Programming with Python

Stefan Güttel, guettel.com

(based on course notes written by Vedran Šego, vsego.org)

Content:

  1. Functions

Reminder: When asked to write a function as a part of a problem, also write a program that lets us test that function. This program should get whatever input is meaningful for testing this function, call it with these arguments, and print (in some form) what it returned.

Problem 1. Write a program that loads a natural number n and then n integers. The program has to compute the sum of the digits of each of these numbers, and then the product of these sums. In the end, the program has to print the sum of the digits of the computed product.

More formally, if $\operatorname{sd}(x)$ denotes the sum of the digits of $x$, and $x_1,x_2,\dots,x_n$ denote the loaded numbers, then the program has to print $$\operatorname{sd}\left(\prod_{k=1}^n \operatorname{sd}(x_k)\right).$$

Problem 2. Write a function sdn takes integer arguments n and r. If $r \le 0$, it returns $n$. If $r > 0$, it returns $$\operatorname{sd}^r(n) := (\underbrace{\operatorname{sd} \circ \operatorname{sd} \circ \cdots \circ \operatorname{sd}}_{r})(n) = \underbrace{\operatorname{sd}(\operatorname{sd}(\dots\operatorname{sd}}_{r}(n)\dots)),$$ where $\operatorname{sd}(n)$ denotes the sum of the digits of $n$.

If r is undefined (i.e., if the function is called with only one argument), the function returns sd(n, r) for the largest r for which it makes sense. In this case, explain your stopping criteria in detail.

Write a program that will allows us to test all the possible inputs.

Problem 3. Write a function get_digit(n, left, right). The function returns

  • d-th digit of n from the left if the function was called as get_digit(n, left=d),
    If the required digit doesn't exist, the function must return -1.
  • d-th digit of n from the right if the function was called as get_digit(n, right=d), or If the required digit doesn't exist, the function must return 0.
  • -1 otherwise, i.e., for get_digit(n) and get_digit(n, left=d1, right=d2).

Problem 4. Write a function rev(n) that returns the value of the integer argument n with its digits order reversed ($1719 \mapsto 9171$). The sign of the number must remain unchanged ($-1719 \mapsto -9171$).

Write a program that loads a natural number n and then n integers. The program has to print which of the numbers (first, second, etc.; you can write $k$-th as number #k) has the largest reversed value.

Hint: We know how to take the last digit $d$ out of a number $x$. However, we can add that digit to the end of a new number $y$ by computing $y = 10y + d$. Doing so for all digits will produce the reversed number.