Scarica Esercizi di Programmazione in Python: Esercizi di esame e più Esercizi in PDF di Programmazione e controllo solo su Docsity!
EXERCISES PYTHON
MIDTERM
- Write a function my_function that, given four integer numbers n, a, b, and k, returns the maximum sum x+y taken among pairs (x,y) such that y is a multiple of 3 strictly smaller than n and strictly larger than 0, x is a number strictly larger than a and strictly smaller than b, and the difference between x and y is at least k (included). Example a = my_function(20,1,21,12) print(a)
Expected Output : 26
def my_function(n, a, b, k): max = 0 for y in range (3, n, 3): for x in range(a+1,b): if x-y >= k: if max < x+y: max = x + y return max print(my_function(20,1,21,12))
- Write a Python program my_function(m,d) that, given two integers m and d representing a month and a day, respectively, returns a string (“Autumn”, “Winter”, “Spring”, “Summer”) with the astronomical season name for that month and day. You can assume that:
- The input parameters are valid, i.e., 1 <= m <= 12, 1 <= d <= 31, and day d exists within month m
- Autumn starts on September 22
- Winter starts on December 21
- Spring starts on March 20
- Summer starts on June 21
- You are not in a leap year (i.e., February has 28 days).
- Months with 30 days are April, June, September, and November Def my_function(m,d): if m<3 or (m == 3 and d<20) or (m == 12 and d>=21): return "Winter" elif (m == 3 and d>=20) or m == 4 or m == 5 or (m == 6 and d<21): return "Spring" elif (m == 6 and d>= 21) or m == 7 or m == 8 or (m == 9 and d<22): return "Summer" elif (m == 9 and d>= 22) or m == 10 or m == 11 or (m == 12 and d<21): return "Autumn"
- You have to compute the sum of numbers 11, 101, 1001, 10001, 100001, and so on, until the value of the sum becomes larger than or equal to n. Write a function my_function that gets an integer value n as input parameter and returns the number of terms in the smallest sum whose value is larger than or equal to n. The sum of 0 terms is equal to 0. Hint: each number in the series is a power of 10 + 1. E.g., 10001 = 10^4+1.
def my_function(n): mysum= 0 exponent = 0 while mysum <= n: exponent += 1 mysum = 1 + 10**exponent return exponent print(my_function(250))
- Write a function my_function that, given as parameters a string S, a string R and another string C of length 1 (i.e., a character), returns a string T that is equal to S except that each occurrence of character C is replaced by string R. def my_function(s, r, c): t = "" for x in range(len(s)): if s[x].lower == c.lower: t += r else: t += s[x] return t print(my_function("I study at Luiss", "REPLACE", "s"))
- Write a function my_function that, given two integer values X and Y and a string S of length 1 (i.e., a character), returns a string with X characters S separated by Y characters ’-’. You can assume that X and Y are larger than or equal to 0. If X=1 no character “-” should be added, independently of the value of Y. Hint: use the * operator to obtain sequences of equal characters (e.g., “x”*7=“xxxxxxx”) Example s1 = my_function(3,2,"A") print(s1)
Expected Output : A--A--A
def my_function(x, y, s): new_s = "" if x>0: if x == 1: new_s = s else: new_s = (s + (y"-"))(x-1) + s return new_s print(my_function(4,6,"T"))
- You have to compute how many numbers divisible by 4 with remainder 1 or 2 you have to sum up until the value of the sum becomes larger than or equal to n. The series of numbers divisible by 4 with remainder 1 or 2 starts with 1,2,5,6,9,10: indeed, when dividing 1 by 4 you get 0 with remainder of 1, when dividing 2 by 4 you get 0 with remainder of 2, when dividing 5 by 4 you get 1 with remainder of 1, and so on. Write a function my_function that gets an integer value n as input parameter and returns the number of terms in the smallest sum whose value is larger than or equal to n. The sum of 0 terms is equal to 0. Example Input: 25 Output: 6 Indeed 1+2+5+6+9=23 < 25 but 1+2+5+6+9+10=33 >= 25
return - print(find([1,4,6,47,9], 4))
- Define the function exercise(list) that adds 100 to all the negative elements of the list and prints the minimum element. def exercise(list): l = len(list) for x in range(l): if list[x] <0: list[x] += 100 return min(list) print(exercise([100, 20, -90, 9]))
- Write a function insert_list(lst, i, v) that, given a list lst, an integer i and a value v, inserts element v in lst at position with index i. a = [4, 10 , 2, 10 , 12] insert_list (a, 1, 18) print (a) insert_list (a, 5, 99) print (a)
[4, 18 , 10 , 2, 10 , 12]
[4, 18 , 10 , 2, 10 , 12 , 99]
def insert_list(list, i, v): for x in range(len(list)): if x == i : list[x] = v return list print (insert_list([1,2,3,4,5], 2, 14))
- Write a function intersection(l1, l2) that takes two lists as input, and returns a new list, containing the common elements of l1 and l2. Assume that all elements of l1 are distinct (i.e., there are no repetitions), and that the same applies to l2. def intersection(l1, l2): l3 = [] for x in l1: for y in l2: if y == x: l3.append(x) return l print (intersection([1,2,3,4,5], [9,6,3,1,8]))
- Write a function square_list(lst) that takes a list of numbers lst as a parameter and return a list, squaring each number of the list. input_list = [1, 2, 3, 4, 5, 6, 7] expected_output = [1, 4, 9, 16, 25, 36, 49] def square_list(l): for x in l:
l[x-1] = x** return l print(square_list([1,2,3,4,5]))
- Write a function vector_sum(list1, list2) that takes two lists of floats list1 and list2, with the same length n, as parameters. The function shall return a new list, whose i-th element is the sum of the i- th elements of list1 and list2 (for every i in {0, 1, ..., n-1}). a = [10, 4, 9] b = [7, 11, 34] c = vector_sum(a, b) print(c) # Expected output: [17, 15, 43] def vector_sum(l1, l2): l3 = [] n = len(l1) for x in range(n): l3.append(l1[x]+l2[x]) return l print(vector_sum([1,2,3], [4,5,6]))
- Write a function pad_with_zeroes(n, lst) whose parameters are an integer n, and a list lst having at most n elements. The function shall return a new list ret with length n, consisting in list lst "filled" with zeroes on its head so that the number of elements is n. More precisely, the last elements of ret shall be the elements of lst, in the same order. The first "padding" elements of ret shall be zeroes. The input list lst shall not be modified by the function. def pad_with_zeroes (n, lst): new_list =[] for x in range(n-len(lst)): new_list.append(0) for y in lst: new_list.append(y) return new_list print(pad_with_zeroes(5, [2,3,4]))
- Write a function halve_even_numbers(lst) that takes a list of integers lst as a parameter. The function shall return a new list, containing the same elements of input list lst, except for even numbers: even numbers shall be halved. The function shall not modify the input list. Example a = [10, 7, 22, 14, 9, 33] b = halve_even_numbers(a) print(b) # Expected output: [5, 7, 11, 7, 9, 33] def halve_even_Numbers(lst): new_list=[] for x in lst: if x %2 == 0: new_list.append(x/2)
def bitonic(lst): maximum = max(lst) index = lst.index(maximum) increasing = 0 decreasing = 0 for x in range(index): if lst[x] < lst[x+1]: increasing = 0 else: increasing = 1 for y in range(index+1, len(lst)): if lst[y] < lst[y-1]: decreasing = 0 else: decreasing = 1 if increasing == 0 and decreasing == 0: return True else: return False print(bitonic([-3,9,11,20,17,5,1]))
- Write a function that check if a list is k-bitonic (k integer given in input) def bitonic(lst, num): maximum = max(lst) index = lst.index(maximum) increasing = 0 decreasing = 0 l2 = [] if num >0: for x in range(index): if lst[x] < lst[x+1]: increasing = 0 else: increasing = 1 for y in range(index+1, len(lst)): if lst[y] < lst[y-1]: decreasing = 0 else: decreasing = 1 if increasing == 0 and decreasing == 0: return True else: return False else: for z in lst: l2.append(z*num)
for x in range(index): if l2[x] < l2[x+1]: increasing = 0 else: increasing = 1 for y in range(index+1, len(lst)): if l2[y] < l2[y-1]: decreasing = 0 else: decreasing = 1 if increasing == 0 and decreasing == 0: return True else: return False print(bitonic([-3,9,11,20,17,5,1], -1))
- Write a function my_function(L) that, given a list L of numbers, returns the sum of the squares of the even numbers contained in L. If there are no items or no even numbers in the list, the function should return 0. Example : my_function([2,13,8,5]) should return 68 = 4 + 64. def my_function(L): mysum = 0 if len(L) == 0: return 0 else: for x in L: if x %2 != 0: mysum += 0 elif x%2 == 0: mysum += x** return mysum
- Write a function my_function (M,i) that is given a list M of lists of numbers and an integer number i such that: M represents a square matrix containing D x D elements: you can assume that all its sublists have the same length and that the number D of rows equals the number D of columns Integer i is a row and column index: it is larger than or equal to 0, and strictly smaller than D. The function should return the sum of the elements in the i-th row and the elements in the i- th column. Element in row i and column i should be counted twice. Example : If M = [[1, 2, 3], [4, 5, 8], [7, 8, 0]] and i=2, should return 7 + 8 + 0 + 3 + 8 + 0 = 26 def my_function(M, i): mysum = 0 for j in range(len(M)): for z in range(len(M)): if j == i: mysum += M[j][z] if z == i: mysum += M[j][z]
- M represents a square matrix containing D × D elements: you can assume that all its sublists (corresponding to rows) have the same length and that the number D of rows equals the number D of columns.
- Integer i is a row index: it is larger than or equal to 0, and strictly smaller than D.
- Integer j is a column index: it is larger than or equal to 0, and strictly smaller than D. Notice that D is not given as input. The function should modify M by replacing the i-th row with the j-th column and should then return the modified matrix. def my_function(M, i, j): new_list = [] new_M = [] for x in range(len(M)): new_list.append(M[x][j]) for x in range(len(M)): if x == i: new_M.append(new_list) else: new_M.append(M[x]) return new_M print(my_function([[1,2,3],[4,5,6], [7,8,9]], 0, 2))
- Write a function my_function(L) that is given a list L of lists of numbers. L represents a square matrix and you can assume that all sublists have the same length and that the number of rows equals the number of columns. The function shall return the sum of items in the top-right to bottom-left diagonal, or 0 if the matrix is empty. def my_function (L) : D= len(L) s= for i in range(D): s = s + L[i][-(i + 1)] return s DICTIONARIES
- Write a function called dictsquares() that: takes an integer number n returns a dictionary where the keys are numbers between 1 and n (both included) and the values are square of keys. def dictsquares(n): d = dict() if n<0: return d else: for i in range(n): d[i+1] = (i+1)** return d
- Write a function called inverter() that: takes as input a dictionary d returns a new dictionary where values and keys are swapped (i.e., keys in d are values in the new dictionary and values in d are keys in the new dictionary).
d = {"monkey":12, "alessia": 3, "giada": 90, "gio":45} def inverter(d): d_new = dict() for k in d.keys(): val = d[k] d_new[val] = k return d_new print(inverter(d))
- Write a function called namehist() that:
- takes as input a list names
- returns a dictionary containing the number of times each name appears in names def namehist(names): count = 0 d = dict() for x in names: count = 1 if x in d: count += 1 d [x] = count return d print(namehist(["ale", "gio", "leo", "ale", "gio"]))
- Write a function called listMapper() that: takes as input two lists L1 and L returns a dictionary where the keys are the items from L1 and the values are the items from L You can assume L1 and L2 having the same length. def listMapper(l1, l2): d = dict() n = len(l1) for x in range(n): d[l1[x]] = l2[x] return d print(listMapper(["red", "blue", "yellow", "green"], [1,26,3,9]))
- Write a function called minMaxVal() that:
- (^) takes as input a dictionary d with numerical values
- (^) returns the minimum and maximum value across d def minMaxVal(d): l = d.values() l = list(l) return min(l), max(l) print(minMaxVal({"x":500, "y":5874, "z": 560}))
- Write a function called adder() that: takes as input two dictionaries d1 and d2 with numerical values
Example keys = ['red', 'green', 'blue'] values = ['# FF0000', '# 008000', '# 0000FF'] returns {'green': '# 008000', 'blue': '# 0000FF', 'red': '# FF0000'} def dictionary(keys, values): dic = dict() for x in range(len(keys)): dic[keys[x]] = values[x] return dic print(dictionary(["red", "green", "blue"],["#F0", "#08", "#00"]))
- Define a function that returns the the most expensive items in a store. The store inventory is represented by a dictionary (given as input) where the keys are the objects and the value their price. def inventory(dictionary): new_list = list(dictionary.items()) max_num = max(list(dictionary.values())) for x, y in new_list: if y == max_num: return x print(inventory({'tomato': 1.05, 'fish': 7, 'redbull': 1.8, 'steak': 4.2, 'biscuits': 2.4}))
- Write a function my_function (wallet, price) that computes the total value inside the wallet in euro. Parameter wallet is a list of tuples (currency, quantity), where currency is a string and quantity is a number: for example, wal let could be [("gbp", 3), ("dollar", 2), ("gbp", 4)]. Parameter price is a dictionary that maps the conversion of different currencies in euro (1 euro) , for example {"krona": 7.44, "dollar": 1.22, "gbp": 0.89, "real": 6.65}. You can assume that the currency in each item in the wallet appears as a key in the price dictionary. The function shall return the total value in euro inside the wallet. If there are no items in the cart, the function should return 0. Example : my_function([("gbp", 2), ("dollar", 2)], {"krona": 7.44, "dollar": 1.22, "gbp": 0.89, "real": 6.65}) should return 4.22 = 20.89 + 21.22. def my_function(wallet, price): sum = 0 for x,y in wallet: if x in price: sum += (price[x])*y return sum
- Write a Python program to check whether all dictionaries in a list are empty or not. def empty_dictionary(l): empty = 0 for dictionary in l: if dictionary == {}: empty = True else: return False return empty
print(empty_dictionary([{},{},{}])) print(empty_dictionary([{1,2},{},{}]))
- Write a Python program to get the top three items in a shopdef top_items(d): new_list = list(d.items()) l2 = [] for x, y in new_list: l2.append(y) l2.sort() first_item = l2[-1] second_item = l2[-2] third_item = l2[-3] for x in new_list: if first_item in x: output_one = x if second_item in x: output_two = x if third_item in x: output_three = x return output_one, output_two, output_three print(top_items({'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}))
- Write a Python program to filter even numbers from a given dictionary values def filter_even(d): new_list = list(d.items()) for sublist in new_list: for x in sublist: if type(x) == str: None else: clone = x[:] for element in clone: if element % 2 != 0: x.remove(element) return d print(filter_even({'V': [1, 4, 6, 10], 'VI': [1, 4, 12], 'VII': [1, 3, 8]}))
- In Italy every driving license holder gets a credit, measured in "points". The initial value for each person is 20 points. When you receive a fine, you will lose some points, depending on the severity of the fine. Write a function my_function(fines) that gets a parameter fines represent- ing a list of fines, where each element of the list is a tuple (name, points): name is the name of a person and points is the number of points lost due to the fine. The function should compute a dictionary that maps each person to his/her number of left points. It should then return the sum of the left points over all persons with at most 5 points left. If there are no items in the list, the function should return 0. def my_function(fines):
- Write a class Stats that computes and returns several statistics over a set of numbers, added one by one. The class shall provide the following methods: ● add_number(x): "tells" the instance that there is another number x to be considered ● get_max(): shall return the maximum over all numbers added so far. ● get_min(): shall return the minimum over all numbers added so far. ● get_sum(): shall return the sum of all numbers added so far. ● get_count(): shall return the quantity of numbers added so far. ● get_average(): shall return the average of all numbers added so far. class Stat: def init(self): self._max = 0 self._min = 10000000 self._sum = 0 self._count = 0 def add_number(self, x): if x > self._max: self.max = x if x < self._min: self._min = x self._sum += x self._count += 1 def get_max(self): return self._max def get_min(self): return self._min def get_sum(self): return self._sum def get_count(self): return self._count def get_average(self): return self._sum/self._count
- Define a class Elevator to represent an elevator installed in a building. The class shall provide the following methods: ● Constructor: takes an input float highest_floor, that represents the number of the highest floor in the building. Elevator starts its service from the ground floor (floor 0). ● go_to_floor(f): when called, the elevator moves to floor f. The method shall return one of the following strings: ○ "up floors", if the elevator goes up k floors ○ "down floors", if the elevator goes down k floors ○ “still", if the elevator does not move class Elevator: def init(self, n): self._highest_floor = n
self._actual_floor = 0 def go_to_floor(self, f): if f > self._highest_floor or f<0: print ("Not allowed") elif f> self._actual_floor: print ("up" + str(f - self._actual_floor) + "floors") self._actual_floor = f elif f == self._actual_floor: print( "still") else: print( "down" + (self._actual_floor-f) + "floors") self._actual_floor = f mf = Elevator(6) print(mf.go_to_floor(3))
- Define a class Student, whose instances represent university students. Each student has a first and a last name, a student id, an email address, and the name of the degree course he/she attends. We also want to represent the exams passed by the student. To this aim, class Student shall provide the following methods and public instance variables: ● constructor, with parameters last_name, first_name, student_id, email, degree_course ● public instance variables first_name, last_name, student_id, email, degree_course ● add_exam(name, grade): called when student passes an exam: parameters represent exam name and grade ● get_average_grade(): shall return the average degree of the exams passed so far ● get_grade(exam_name): shall return the grade of the exam named exam_grade, or None if no such exam has been passed by the student yet ● get_exam_names(): shall return a list with all the names of the exams passed so far by the student class Student: def init(self,last_name, first_name, student_id, email, degree_course): self.last_name = last_name self.first_name = first_name self.student_id = student_id self.email = email self.degree_course = degree_course self.exams = {} def add_exam(self, name, grade): self.exams[name] = grade def get_average_grade(self): number_of_exams = 0 sum_of_grades = 0 for x in self.exams: number_of_exams += 1 sum_of_grades += self.exams[x] return sum_of_grades/number_of_exams def get_grade(self, exam_name):
roman_value = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} for x in range(len(roman)): if roman[x] > roman[x-1]: integer_value += roman_value[roman[x]] - roman_value[roman[x-1]]* else: integer_value += roman_value[roman[x]] return integer_value print(roman_to_integer().converter('XIX'))
- Define a class Match to represent a soccer match. The class shall provide the following methods:
- Constructor: takes two string parameters (home_team, away_team) with the name of playing teams.
- goal(team): called when a team scores a goal. String team shall be the name of the team which scored the goal.
- get_score(): returns the current score, as a tuple with 4 elements: (home_team, home_score, away_team, away_score).
- get_winning(): if a team is winning, return the name of that team. Oth- erwise, return "Tie".class Match: def init(self, home_team, away_team): self.home_team = home_team self.away_team = away_team self.home_score = 0 self.away_score = 0 def goal(self, team): if team == self.home_team: self.home_score+= return self.home_team elif team == self.away_team: self.away_score += return self.away_team def get_score(self): return (self.home_team, self.home_score, self.away_team, self.away_score) def get_winning(self): if self.home_score > self.away_score: return self.home_team elif self.away_score > self.home_score: return self.away_team else: return "Tie"
- Define a class TelephoneAccount to keep track of the phone calls of a subscriber of a telephone line. The class shall provide the following methods.
- Constructor: takes two float parameters (call_setup_fee, per_minute_fee).
- add_call(duration): called when a phone call is performed. If duration is 0, the call is unsuccessful and nothing is charged. Otherwise, duration is the length of the call, in minutes. The subscriber is charged the call setup fee, plus a variable cost, depending on the call duration.
- get_bill(): returns the total price to be paid for all the calls that have been performed so far.
class TelephoneAccount: init(self, call_setup_fee, per_minute_fee): self.call_setup_fee = call_setup_fee self.per_minute_fee = per_minute_fee self.charge = 0 def add_call(self, duration): if duration == 0: pass else: self.charge += self.call_setup_fee + duration*self.per_minute_fee def get_bill(self): return self.charge RECURSION
- Define the function for the factorial of a number def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(6))
- Define a function that checks if a word is palindrome def palindrome(s): if len(s)<=1: return True else: return (s[0] == s[-1]) and palindrome(s[1:-1]) print(palindrome("racecar"))
- Define a function that given an integer n, returns the n-th number in the Fibonacci sequence def fibonacci(n): if n in [0,1]: return n else: return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(5))
- Define a function that sums the elements of a list using recursion def sum_list(a): if len(a) == 0: return 0 else: return a[0] + sum_list(a[1:])