



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Lecture notes Python provides numerous data structures that can be used to store objects in an efficient way with respect to some specific tasks. One of the most fundamental of those types is the list one. Lists are used to store values in a specific order. A list object can evolve by storing/removing values. In addition Python provides several advanced list oriented constructions. A list object can be specified by putting objects into brackets, as follows
ml = [1, 5, True, 'foo'] print(type(ml)) print(ml) print(len(ml))
This program prints (as expected)
[1, 5, True, 'foo'] 4
Lists are iterable and therefore can be used in for loops, as in the following example
ml = [1, 5, True, 'foo'] for k in ml: print(k)
which prints
1 5 True foo
Exercise 1 (Iterating over a list)
Write a program that first create a list of integers (with specific values given in the program itself) and then computes with a for loop the minimal, maximal and average value of those integers. Do not use the built in Python functions min, max and sum. Solution
x = [1, -2, 4, -5, 12, 1, 0, -3]
my_sum = 0 my_max = x[0] my_min = x[0] for val in x: my_sum = my_sum + val if val > my_max: my_max = val elif val < my_min: my_min = val print('Stats for the list', x) print('max: ', my_max) print('min: ', my_min) print('sum: ', my_sum) print('average: ', my_sum/len(x))
Lecture notes One can grow a list by appending objects to it, as in the following example
ml = [ ] # empty list for k in range(5): ml.append(k) # adding k at the end of the list print(ml)
which prints
[0, 1, 2, 3, 4]
Notice that append is a method with no (meaningful) return value.
Exercise 2 (Appending to a list)
Question 1 Using a for loop and list appending, write a program that asks to the user a number n and then asks to the user n strings to be stored in a list. Print the content of the list at the end of the program. Solution
n = int(input("n= ")) text_list = [] for k in range(n): text_list.append(input("Your text= ")) print(text_list)
Question 2 Using a while loop and list appending, write a program that asks to the user to type in integer values until he/she gives a negative or null value. The program must store all the positive values in a list and print it before exiting.
goal is to show case some list operations. Python provides a sum function which computes the sum of the values contained in the parameter list (iterable).
Question 1 Using only this function and lists (no loops), write a program that calculates the following values, where n is given by the user:
∑^ n
k=
k = 1 + 2 +... + n
∑^ n
k=
(2k + 1) = 1 + 3 + 5 +... + (2n + 1)
Solution
n = int(input("n= ")) print(sum(range(1, n+1))) # or print(sum(list(range(1, n+1)))) print(sum(range(1, 2 * n + 2, 2)))
Question 2 Can this technique be extended to compute e.g.
∑n k=
(−1)k k? Solution Short answer: no. When range is used, it produces only integers whereas the sum above needs decimal numbers.
Lecture notes The most advanced list creation tool in Python is the list comprehension. It combines a for loop with a list syntax as in the following example
ml = [ x for x in range(4) ] print(ml)
which prints
[0, 1, 2, 3]
The general syntax of a (simple) list comprehension is
[ expression for variable in iterable ]
which is interpreted as follows: built a list of the values of expression obtained by setting in order variable to all the values of iterable. In other words,
ml = [ expression for variable in iterable ]
is roughly equivalent to
ml = [ ] for variable in iterable: ml.append(expression)
Thus this program
print([ x + 1 for x in range(1, 6, 2)]) print([ a for a in 'a text']) print([ 2 * y + 1 for y in [1, -2, 4, 5]])
prints
[2, 4, 6] ['a', ' ', 't', 'e', 'x', 't'] [3, -3, 9, 11]
Exercise 4 (List comprehensions)
Warning: this exercise does not provide an efficient way for computing the values specified below. The goal is to demonstrate some list operations. Using only the function sum and lists (no loops), write a program that calculates the following values, where n is given by the user:
∑^ n
k=
(−1)k k
(−1)n n ∑^ n
k=
(2k + 1)^2 = 1 + 3^2 + 5^2 +... + (2n + 1)^2
Solution
n = int(input("n= ")) print(sum([((-1)k)/k for k in range(1, n+1)])) print(sum([(2k+1)*2 for k in range(n+1)]))
Lecture notes In addition to being iterable, Python lists are also indexable and sliceable, which means that this index operation [] and the associated slices [::] can be used on lists as in the following example
ml = list(range(1,6)) print(ml) print(ml[-2]) print(ml[2]) ml2 = ml[1:3] print(ml2)
which prints
Each value corresponds to one of the possible sums and the stars on its right corresponds to the number of rolls. In the above example, 12 was obtained 5 times, while 7 was rolled 13 times.
Solution
import random n = int(input("n= ")) p = int(input("p= ")) counts = [0] * (6 * p + 1) for i in range(n): somme = 0 for k in range(p): somme += random.randint(1, 6) counts[somme] += 1 for val in range(p, len(counts)): if counts[val] > 0: print(repr(val).rjust(3), ""counts[val]) else: print(repr(val).rjust(3))