Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1.  
  2. CS1026 Review/Practice Questions – Quiz 4 – Logic Problems!!
  3.  
  4. 1Some Logic Problems
  5.  
  6. a.  The following program is to read a text file and then organize the words in the text by their starting letter.  This is then used to form a “dictionary” of words in the text.  The program has 3 logic errors.  Find and correct them.  Assume that the file inf has been input and opened correctly.
  7.  
  8. words = {}
  9. for ch in "abcdefghijklmnopqrstuvwxyz" :
  10.    words[ch] = set()
  11.  
  12. # Read all of the lines from the file and add them to the dictionary.
  13. for line in inf:
  14.    parts = line.split(,)
  15.    for word in parts :
  16.       word = word.upper()
  17.       for ch in words :
  18.          if ch == word[0] :
  19.             words[ch].add(ch)
  20.  
  21. # Display the contents of the dictionary.
  22. for ch in sorted(words) :
  23.    print("Words beginning with %s:" % ch.upper())
  24.    for word in sorted(words[ch]) :
  25.       print(" ", word)
  26.  
  27. b.  The following function builds a dictionary of the frequency of letters in a string.  Assume that the string consists only of letters; i.e. all digits and punctuation have been removed.  The function has 2 errors; find and correct them.
  28.  
  29. def charCounts(s) :
  30.    # Count the number of occurrences of each character.
  31.    counts = {}
  32.    for ch in s :
  33.       if ch not in counts :
  34.          counts[ch] = 0
  35.       else :
  36.          counts[ch] = counts[ch] + 1
  37.    return s
  38.  
  39. c.  The following code is supposed to collect only letters (i.e. ‘A’ to ‘Z’ and ‘a’ to ‘z’ inclusively) ignoring all others.  It is supposed to count the number of letters, the number of upper case letters and number of lower case letters.  It contains 4 errors.  Find and correct them
  40. countU = 0
  41. countL = 0
  42. nL = 0
  43.  
  44. aset = set()
  45. for ch in strng :
  46.       if ch > "A" or ch < "Z" :
  47.          aset.add(ch)
  48.          countU = countL + 1
  49.          nL = nL + 1
  50.       elif ch > "a" or ch < "z" :
  51.           aset.add(ch)
  52.           countL = countU + 1
  53.           nL = nL + 1
  54. print(nL, countU, countL)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement