Programming with Python (lab classes)

Vedran Šego, vsego.org

Content:

  1. Control flow

Important: Make your programs as impervious to crashes as you can.

For example, in the problems where integers need to be loaded, make sure that if anything else is loaded, the program asks again for the same input until it is done right.

However, you should always allow your programs to be interrupted by Ctrl+C, so never use the except: clause without specifying which exception do you want to catch.

Problem 1. Write a program that loads a list of integers until it loads a zero (which does not get added to the list). The program then has to print the sums of all rightmost digits, all the second to rightmost ones, etc.

For example, the list $[ \color{blue}1\color{red}7, \color{blue}1\color{red}9, \color{blue}2\color{red}3, \color{orange}1\color{green}7\color{blue}1\color{red}9, \color{green}1\color{blue}2\color{red}7 ]$ will produce $\color{red}7 + \color{red}9 + \color{red}3 + \color{red}9 + \color{red}7 = 35$, $\color{blue}1 + \color{blue}1 + \color{blue}2 + \color{blue}1 + \color{blue}2 = 7$, $\color{green}7 + \color{green}1 = 8$, $\color{orange}1 = 1$, so the output should be

The sum of the 1. digits from the right: 35
The sum of the 2. digits from the right: 7
The sum of the 3. digits from the right: 8
The sum of the 4. digits from the right: 1

As mentioned above, make sure that the program doesn't crash even if the user inputs floats or some text instead of integers (in which case the same input should be requested again).

Problem 2. Write a program that loads a list of integers as a string (all the numbers are separated by a single comma) and prints the frequency of each digit.

For example, if the list $[\color{red}17, \color{red}19, \color{blue}2\color{green}3, \color{red}17\color{red}19, \color{red}1\color{blue}27]$ is given, then a digit $\color{red}1$ appears $5$ times, a digit $\color{blue}2$ appears $2$ times, a digit $\color{green}3$ appears only once, etc., so the program should print:

A digit 0 has appeared in none of the numbers.
A digit 1 has appeared 5 times.
A digit 2 has appeared 2 times.
A digit 3 has appeared once.
A digit 4 has appeared in none of the numbers.
A digit 5 has appeared in none of the numbers.
A digit 6 has appeared in none of the numbers.
A digit 7 has appeared 3 times.
A digit 8 has appeared in none of the numbers.
A digit 9 has appeared 2 times.

Try to get exactly the same output for this example (notice the difference in the format of the output message for the digits that appeared only once, more than once, or not a single time).

Problem 3. Solve the previous problem, but instead of a list of integers analyze a line of text (i.e., a string) and count the frequencies of all of its characters.

Hint: Instead of counting the frequences in a list (which was convenient for the digits 0,1,...,9) as in the solution of the previous problem, a different data structure might be more useful here.