1 / 20

Exam 1 Practice Problems

Exam 1 Practice Problems. SOLUTIONS. 1. Show Output. for i in range(5): print( i * i ) 0 1 4 9 16 for d in [3,1,4,1,5]: print( d,end =' ') 3 1 4 1 5 (c) for i in range(4): print("Hello") Hello Hello Hello Hello. 1. Show Output.

shay
Download Presentation

Exam 1 Practice Problems

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exam 1 Practice Problems SOLUTIONS

  2. 1. Show Output • for i in range(5): print(i*i) 0 1 4 9 16 • for d in [3,1,4,1,5]: print(d,end=' ') 3 1 4 1 5 (c) for i in range(4): print("Hello") Hello Hello Hello Hello

  3. 1. Show Output • for i in range(5): print(i,2**i) 0 1 1 2 2 4 3 8 4 16 • for c in ['g','o','o','d','b','y','e']: print(c,sep='',end='') goodbye (f) D = {'Prof':'Tindell','Dept':'CSE','School':'USF','City':'Tampa'} for k in D.keys(): print(k,'is',D[k]) Prof is TindellDept is CSE School is USF City is Tampa

  4. 1. Show Output (g) L = ['To','be','or','not','to','be'] print(' '.join(L)) To be or not to be (h) L = ['6','12','2012'] print('/'.join(L)) K = L[-1:]+L[:2] print('-'.join(K)) 6/12/20122012-6-12 (i) S = "Elementary my dear Watson" print(S.split()) ['Elementary','my','dear','Watson'] L[-1:] = ['2012']L[:2] = ['6','12'] L[-1:]+ L[:2] = ['2012','6','12']

  5. 1. Show Output ((j) S = """Well, Stanley, isn't this a fine kettle of fish you've gotten me into""" print(S.splitlines()) ["Well, Stanley,","isn'tthis","a fine", "kettle of fish","you've gotten me into"]

  6. 1. Show Output (k) i = input("Enter an integer: ") j = input("Enter another integer: ") print("Adding them together we get",i+j) Suppose the user enters 25 at the first prompt and 10 at the second prompt. Show the output. Adding them together we get 2510 • L = ['to','be','or','not','to','be'] for k in sorted(L):print(k) bebe not or to to

  7. 1. Show Output • print(11/4,11//4,11%4) 2.75 2 3 (n) S = 'To be or not to be'S.replace('be','have been') print(S) To be or not to be (o) names1 = ['Amir','Barry','Charles','Dao'] print(names1[-1][-1]) o (p) names1 = ['Amir','Barry','Charles','Dao'] loc = names1.find("Edward") print(loc) -1 names[-1] = 'Dao''Dao'[-1] = 'o'

  8. 1. Show Output • names1 = ['Amir','Barry','Charles','Dao']names2 = [x.lower() for xin names1] names2 = ['amir','barry','charles','dao'] print(names2[2][0]) c (r) confusion = {} confusion[1] = 1 confusion['1'] = 2 confusion[1] += 1 sum = 0 for k in confusion: sum += confusion[k] print(sum) 4 names2[2]

  9. 1. Show Output (s) name = "snow storm" print(name[6:8]) to (t) name = "snowstorm" name[5] = 'X' print(name) ERROR – OBJECTS OF TYPE str ARE IMMUTABLE (u) for i in range(2): print(i,end=' ') for i in range(4,6): print(i,end=' ') 0 1 4 5

  10. 1. Show Output (v) x = True y = False z = False if x or y and z: print('Yes') else: print('No') ) Yes True or (False and False) = True or False = True

  11. 1. Show Output (w) x = True y = False z = False if not x or y: print(1)elif not x or not y and z: print(2)elif not x or not y or not y and x: print(3) else: print(4) 3 (not True) or False = False or False = False (not True) or ((not False) and False) = False or (True and False) = False or False = False (not True) or (not False) or ((not False) and True) = False or True or (True and True) = True

  12. 1. Show Output (x) L = [3,1,1,5,3,2,2,4] S = set(L) print(len(S)) 5

  13. 2. Suppose we execute the following statemenst D = { } S = 'one' L = ['one','two'] T = ('one','two') For each of the following, indicate whether it is a valid Python statement; if it is not valid, explain why. D[S] = 'bacon' valid D[T] = 'bacon'valid D[L] = 'bacon' invalid – dictionary keys must immutable, lists are mutable D[5] = 'bacon' valid

  14. 3. Write a python code segment that prompts for and inputs positive integers where the user indicates the end of input by entering the value 0; prints out the number of positive integers that were entered, their sum and their average value. number_of_entries= 0 sum = 0 print("Enter a sequence of positive integers, 0 to quit") n = int(input("Enter a postive integer, or 0 to stop: ")) while n != 0: number_of_entries+= 1 sum += n n = int(input("Enter a postive integer, or 0 to stop: ")) average = sum/ number_of_entries print("You entered", number_of_entries,"values") print("Their sum is",sum) print("and their average value is",average)

  15. 4. Write a complete Python program that CHALLENGING • Prompts for and inputs a string named S • prints the total number of alphabetic characters in S • for each alphabetic character that appears in S, prints the character, the number of times that character appears in S and its relative frequence (fraction of the total) Note: upper and lower case versions of a letter are to be considered the same S = input("Enter a string: ") S = S.lower() X = {c for c in set(S) if c.isalpha()} D = {} total = 0 for c in X: D[c] = S.count(c) total += D[c] print("Total number of alphabetic characters: ",total) for c in sorted(D.keys()): print(c,D[c],D[c]/total,sep='\t')

  16. Alternate solution to problem 4 S = input("Enter a string: ") S = S.lower() # X = {c for c in set(S) if c.isalpha()} L = [] for c in S: if c.isalpha() and c not in L:L.append(c) D = {} total = 0 #for c in X: for c in L: D[c] = S.count(c) total += D[c] print("Total number of alphabetic characters: ",total) for c in sorted(D.keys()): print(c,D[c],D[c]/total,sep='\t')

  17. 5. Consider the following function with two parameters, both strings: def mystery(s,p):i = s.find(p) if i == -1: return False while True:old_i = ii = s.find(p,old_i+1) if i == -1: return Falseelifi < old_i+len(p): return True Describe in words what this function does. That is, complete the following sentence: mystery(s,p) returns True if and only if s contains two overlapping substrings equal to p # no substring equal to p # remember previous index # no more substrings equal to p # found overlapping strings

  18. Write a complete Python program that prompts for and inputs a time in 12-hour format, then prints the same time in 24-hour format S = input("Enter a time in twelve-hour format: ") comps = S.split() hourstr, minutestr = comps[0].split(':') hour,minute = int(hourstr),int(minutestr) if comps[1] == 'pm': hour += 12 elif hour == 12: hour = 0 print('Time in 24-hour format: ',hour,':',minute,sep='') hour,minute= [int(k) for k in comps[0].split()] '4:25 pm' comps = ['4:25','pm'] comps[0] = ['4:25'] comps[1] = ['pm'] hourstr = '4' minutestr = '25' hour = 4 minute = 25 hour = 16 Time in 24-hour format: 16:25

  19. 7. Write a complete Python program that prompts for and inputs a time in 24-hour format and prints the same time in 12hour format S = input("Enter a time in twenty-four hour format: ") hourstr, minutestr = S.split(':') hour,minute = int(hourstr),int(minutestr) ampm = "am" if hour < 12 else "pm" if hour > 12: hour -= 12 elif hour == 0: hour = 12 print("Time in 12-hour format: ",hour,':',minute,' ',ampm,sep='')

  20. Write a Python program that inputs a string containing only lower-case letters and spaces, then constructs a dictionary whose keys are the distinct words in the string and whose value for a word is the number of times the word appears in the string. After that, it prints the contents of the dictionary by printing for each word in the string a line containing the word, a tab and the number of times the word appears in the string. You must print the lines in ascending alphabetic order of the words. S = input("Enter a string: ") D = {} L = S.split() for w in L: if w in D: D[w] += 1 else: D[w] = 1 for c in sorted(D.keys()): print(c,D[c],sep='\t') D[w] = L.count(w)

More Related