Presentation is loading. Please wait.

Presentation is loading. Please wait.

Re-Exam 1 Practice Problems SOLUTIONS. 1. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships at $0.86.

Similar presentations


Presentation on theme: "Re-Exam 1 Practice Problems SOLUTIONS. 1. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships at $0.86."— Presentation transcript:

1 Re-Exam 1 Practice Problems SOLUTIONS

2 1. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships at $0.86 per pound + $1.50 fixed cost for overhead. Write a program that inputs the number of pounds in an order and prints the total cost of the order, including shipping. n = float(input("Enter the number of pounds: ")) coffee_cost = 10.5*n shipping_cost = *n total = coffee_cost + shipping_cost print("Total cost, including shipping: ",total)

3 2. Write a program to compute the sum and average of a series of numbers values entered by the user. The program should first ask the user how many numbers there are. Then it should input the numbers one after another, then print their sum and average value. Your program should use a for loop. n = int(input("Enter a the number of values: ")) sum = 0 for i in range(n): sum += eval(input("Next number: ")) print("sum = ",sum,"; average = ",sum/n,sep='')

4 3. An acronym is a word formed by taking the first letters of the words in a phrase and making a word from them using all capital letters. For example, RAM is an acronym for "random access memory". Note that all the letters of the acronym are capital letters even in the words are lower-case. Write a program that allows the user to enter a phrase and prints the acronym for that phrase. phrase = input("Enter a phrase: ") words = phrase.split() acronym = "" for w in words: acronym = acronym + w[0].upper() print("Acronym for your phrase: ",acronym)

5 4. Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where 'a' is 1, 'b' = 2, …,'z' = 26. Upper- and lower-case letters are treated as equal. For example, "Tindell" would have value = 76, which happens to be a very auspicious number. Write a program that prints the numeric value of a name entered by the user. Solution I: name = input("Enter your last name: ") numval = 0 for ch in name: if ch.isalpha(): numval += ord(ch.lower())-ord('a')+1 print("The numerical value of your name is",numval)

6 4. Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where 'a' is 1, 'b' = 2, …,'z' = 26. Upper- and lower-case letters are treated as equal. For example, "Tindell" would have value = 76, which happens to be a very auspicious number. Write a program that prints the numeric value of a name entered by the user. Solution II: letters = " abcdefghijklmnopqrstuvwxyz" name = input("Enter your last name: ") numval = 0 for ch in name: if ch.isalpha(): numval += letters.index(ch.lower()) print("The numerical value of your name is",numval)

7 5. Write a program that counts and prints the number of words in a sentence entered by the user.. sentence = input("Enter a sentence: ") word_count = len(sentence.split()) print("Your sentence contains",word_count,"words") 6. Write a program that computes and prints the average length of the words in a sentence entered by the user. sentence = input("Enter a sentence: ") word_list = sentence.split() word_count = len(word_list) total_len = sum([len(w) for w in word_list]) print("The average word length is",total_len/word_count)

9 8. Write and test a function to meet this specification. SquareEach(nums) nums is a list of numbers. Modifies the list by squaring each entry def SquareEach(nums): for i in range(len(nums)): nums[i] = nums[i]*nums[i] # Test L = [1,2,3,4,5] print(L) SquareEach(L) print(L)

10 9. Write and test a function to meet this specification. sumList(nums) nums is a list of numbers. Returns the sum of the numbers in nums. def sumList(nums) : sum = 0 for item in nums: sum += item return sum # Test L = [1,2,3,4,5] sum = sumList(L) print(sum9)

11 10. Write and test a function to meet this specification. toNumbers(strList) strList is a list of strings of digit characters. Modifies each entry of the list by converting it to an integer. def toNumbers(strList): for i in range(len(strList)): strList[i] = int(strList[i]) # Test L = ['1','2','3','4','5'] toNumbers(L) print(L)

12 11. Write and test a function innerProd(x,y) that returns the inner product of same-length lists x and y. The inner product of [x 1, x 2,…, x n ] and [y 1, y 2,…, y n ] is x 1 y 1 + x 2 y 2 + … + x n y n def innerProd(x,y): sum = 0 for i in range(len(x)): sum += x[i]*y[i] return sum # Test a = [1,2,3,4,5] b = [5,4,3,2,1] print(innerProd(a,b))

13 12. Most companies pay time and a half for any hours worked above 40 in a given week. Write a program to input the number of hours worked and the hourly rate, then prints the total wages for the week. hrs = eval(input("Enter hours worked this week: ")) rate = eval(input("Enter the hourly rate: ")) if hrs <= 40: pay = hrs*rate else: pay = 40*rate + 1.5*rate*(hrs-40) print("Total wages for the week:",pay)

14 13. The speeding ticket fine policy in Podunksville is $50 plus $5 for each mph over the limit plus a penalty of $200 for any speed over 90 mph. Write a program that inputs a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of fine. limit = eval(input("Enter speed limit: ")) actual = eval(input("Enter clocked speed: ")) if actual <= limit: print("Speed OK, no fine") else: fine = 50+5*(actual-limit) if actual > 90: fine += 200 print("Amount of fine:",fine)

15 14. A formula for computing the date of Easter in the years , inclusive, is as follows. Let a = year % 19, b = year%4, c = year%7, d = (19*a + 24)%30, and e = (2*b+4*c+6*d+5)%7. The date of Easter is (d+e) days after March 22 (which could be in April). Write a program that inputs a year, verifies that it is in the proper range, and then prints the date of Easter that year. year = eval(input("Enter a year between 1982 and 2048: ")) if year 2048: print("Illegal date") else: a,b,c = year%19,year%4,year%7 d = (19*a+24)%30 e = (2*b+4*c+6*d+5)%7 days_after = d+e days = 22+days_after print("In year ",year,", Easter falls on",sep = "",end = " ") if days <= 31: print("March " +str(days)) else: print("April " + str(days-31))

16 15. Preceding Easter formula works for range with the exception that it is a week later than the actual date for years 1954, 1981, 2049, and Modify your program to accept dates between 1900 and year = eval(input("Enter a year between 1900 and 2099: ")) if year 2099: print("Illegal date") else: a,b,c = year%19,year%4,year%7 d = (19*a+24)%30 e = (2*b+4*c+6*d+5)%7 days_after = d+e days = 22+days_after if year in [ 1954, 1981, 2049, 2076]: days -= 7 print("In year ",year,", Easter falls on",sep = "",end = " ") if days <= 31: print("March " +str(days)) else: print("April " + str(days-31))

17 16. Write a program that inputs a date in the form month/day/year (all integers) and prints a message indicating whether the date is valid. For example, 5/24/1962 is valid but 9/31/2000 is not (September has only 30 days). def is_leap_year(year): if year%4 != 0 or (year%100 == 0 and year%400 != 0): return False else: return True days_in_month=[0,31,28,31,30,31,30,31,31,30,31,30,31] datestr = input("Enter a date (month/day/year): ") m,d,y = (int(k) for k in datestr.split('/')) if is_leap_year(y): days_in_month[2] = 29 if m 12: print("Invalid date") elif d > days_in_month[m]: print("Invalid date") else: print("Valid date")

18 17. You are to write a Python program that uses a while loop to determine how long it takes to double an initial investment with a fixed annual percentage rate. def years_to_double(start_amt,rate): years = 0 amt = start_amt while(amt < 2*start_amt): amt = (1+rate)*amt years += 1 return years a = float(input("Enter initial investment: ")) r = float(input("Enter the yearly interest rate: ")) d = years_to_double(a,r) print("Years to double your investment:",d)

19 18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. First write a function is_prefix_atom(L,A) that returns True if and only if A is a prefix atom of L. Then write a function prefix_atoms(L) that returns a list of the distinct prefix atoms of L sorted by increasing length. Next write a function prefix_dictionary(L) that returns a dictionary whose keys are the prefix atoms of L; and the value in the dictionary for prefix atom A is a list of the distinct strings in L having A as a prefix. Complete your program by prompting the user for a string and printing, for each prefix atom of the word list of S, the atom, A, the character : and then the list of words of S having A as a prefix. Each atom and list should be on a separate line.

20 18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. First write a function is_prefix_atom(L,A) that returns True if and only if A is a prefix atom of L. Then write a function prefix_atoms(L) that returns a list of the distinct prefix atoms of L sorted by increasing length. def is_prefix_atom(w,L): if w not in L: return False for u in L: if u != w and w.startswith(u): return False return True

21 18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. Next write a function prefix_dictionary(L) that returns a dictionary whose keys are the prefix atoms of L; and the value in the dictionary for prefix atom A is a list of the distinct strings in L having A as a prefix. def prefix_dictionary(L): D = {} X = {w for w in L if is_prefix_atom(w,L)} for w in X: D[w] = {u for u in L if u.startswith(w)} return D

22 18. A prefix atom of a list L of strings is a string A in L such that, for any string W in L, if W is a prefix of A, then W is equal to A. Complete your program by prompting the user for a string and printing, for each prefix atom of the word list of S, the atom, A, the character : and then the list of words of S having A as a prefix. Each atom and list should be on a separate line. S = input("Enter a string: ") L = S.split() D = prefix_dictionary(L) for A in D: print(A,':',','.join(D[A]))


Download ppt "Re-Exam 1 Practice Problems SOLUTIONS. 1. The Konditorei coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships at $0.86."

Similar presentations


Ads by Google