# ReexamPracticeProblemSolutions ```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 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(&quot;Enter the number of pounds: &quot;))
coffee_cost = 10.5*n
shipping_cost = 1.50 + 0.86*n
total = coffee_cost + shipping_cost
print(&quot;Total cost, including shipping: &quot;,total)
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(&quot;Enter a the number of values: &quot;))
sum = 0
for i in range(n):
sum += eval(input(&quot;Next number: &quot;))
print(&quot;sum = &quot;,sum,&quot;; average = &quot;,sum/n,sep='')
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 &quot;random access memory&quot;. 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(&quot;Enter a phrase: &quot;)
words = phrase.split()
acronym = &quot;&quot;
for w in words:
acronym = acronym + w.upper()
4. Numerologists claim to be able to determine a person's character traits based
on the &quot;numeric value&quot; 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, &quot;Tindell&quot;
would have value 20+9+14+4+5+12+12 = 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(&quot;Enter your last name: &quot;)
numval = 0
for ch in name:
if ch.isalpha():
numval += ord(ch.lower())-ord('a')+1
print(&quot;The numerical value of your name is&quot;,numval)
4. Numerologists claim to be able to determine a person's character traits based
on the &quot;numeric value&quot; 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, &quot;Tindell&quot;
would have value 20+9+14+4+5+12+12 = 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 = &quot; abcdefghijklmnopqrstuvwxyz&quot;
name = input(&quot;Enter your last name: &quot;)
numval = 0
for ch in name:
if ch.isalpha():
numval += letters.index(ch.lower())
print(&quot;The numerical value of your name is&quot;,numval)
5. Write a program that counts and prints the number of words in a sentence
entered by the user..
sentence = input(&quot;Enter a sentence: &quot;)
word_count = len(sentence.split())
6. Write a program that computes and prints the average length of the words in a
sentence entered by the user.
sentence = input(&quot;Enter a sentence: &quot;)
word_list = sentence.split()
word_count = len(word_list)
total_len = sum([len(w) for w in word_list])
print(&quot;The average word length is&quot;,total_len/word_count)
7. A common utility on Unix/Linux systems is a small program called wc. This
program analyzes a file to determine the number of lines, words and characters
contained therein. Write your own program to input a filename and print the
three numbers produced by wc. Your program should define a function with
parameter a file name that returns the line count, word count and character
count for the file.
def wc(fname):
with open(fname,'r') as f:
chars = len(S)
words = len(S.split())
lines = len(S.splitlines())
return lines,words,chars
fnom = input(&quot;Enter a file name: &quot;)
l,w,c = wc(fnom)
print(l,&quot;lines,&quot;,w,&quot;words&quot;,c,&quot;characters&quot;)
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)
9. Write and test a function to meet this specification.
sumList(nums)
nums is a list of numbers. Modifies the list by squaring each entry
def sumList(nums):
sum = 0
for item in nums:
sum += item
return sum
# Test
L = [1,2,3,4,5]
print(sumList(L))
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)
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 [x1, x2,…, xn] and
[y1, y2,…, yn] is
x1y1 + x2y2 + … + xnyn
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))
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(&quot;Enter hours worked this week: &quot;))
rate = eval(input(&quot;Enter the hourly rate: &quot;))
if hrs &lt;= 40:
pay = hrs*rate
else:
pay = 40*rate + 1.5*rate*(hrs-40)
print(&quot;Total wages for the week:&quot;,pay)
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(&quot;Enter speed limit: &quot;))
actual = eval(input(&quot;Enter clocked speed: &quot;))
if actual &lt;= limit:
print(&quot;Speed OK, no fine&quot;)
else:
fine = 50+5*(actual-limit)
if actual &gt; 90:
fine += 200
print(&quot;Amount of fine:&quot;,fine)
14. A formula for computing the date of Easter in the years 1982-2048, 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(&quot;Enter a year between 1982 and 2048: &quot;))
if year &lt; 1982 or year &gt; 2048:
print(&quot;Illegal date&quot;)
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(&quot;In year &quot;,year,&quot;, Easter falls on&quot;,sep = &quot;&quot;,end = &quot; &quot;)
if days &lt;= 31:
print(&quot;March &quot; +str(days))
else:
print(&quot;April &quot; + str(days-31))
15. Preceding Easter formula works for range 1900-2099 with the exception that it
is a week later than the actual date for years 1954, 1981, 2049, and 2076. Modify
your program to accept dates between 1900 and 2099.
year = eval(input(&quot;Enter a year between 1900 and 2099: &quot;))
if year &lt; 1900 or year &gt; 2099:
print(&quot;Illegal date&quot;)
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(&quot;In year &quot;,year,&quot;, Easter falls on&quot;,sep = &quot;&quot;,end = &quot; &quot;)
if days &lt;= 31:
print(&quot;March &quot; +str(days))
else:
print(&quot;April &quot; + str(days-31))
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(&quot;Enter a date (month/day/year): &quot;)
m,d,y = (int(k) for k in datestr.split('/'))
if is_leap_year(y):
days_in_month = 29
if m &lt; 1 or m &gt; 12:
print(&quot;Invalid date&quot;)
elif d &gt; days_in_month[m]:
print(&quot;Invalid date&quot;)
else:
print(&quot;Valid date&quot;)
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 &lt; 2*start_amt):
amt = (1+rate)*amt
years += 1
return years
a = float(input(&quot;Enter initial investment: &quot;))
r = float(input(&quot;Enter the yearly interest rate: &quot;))
d = years_to_double(a,r)
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.
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
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
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 =
L =
D =
for
input(&quot;Enter a string: &quot;)
S.split()
prefix_dictionary(L)
A in D:
print(A,':',','.join(D[A]))
```