Advertisement
gruntfutuk

unscrambling

Apr 23rd, 2018
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.52 KB | None | 0 0
  1. ''' exercise - scramble words randomly from file then find matches '''
  2.  
  3. def Stuart():
  4.    
  5.     from random import shuffle
  6.     from random import choice
  7.     from random import randint
  8.  
  9.     def generate_scrambled_words(quantity=10):
  10.         ''' generate list of scrambled words from randomly selected words from file '''
  11.    
  12.         def scramble_words(word_list, quantity):
  13.             ''' return list of <quantity> scrambled words randomly chosen from <wordlist> '''
  14.    
  15.             def scramble(word):
  16.                 ''' returns string with character order randomly shuffled'''
  17.                 scrambled = list(word)
  18.                 shuffle(scrambled)
  19.                 return ''.join(scrambled)
  20.    
  21.             scrambled_words = []
  22.             for _ in range(quantity + 1):
  23.                 while True:
  24.                     word = choice(word_list)
  25.                     scrambled_word = scramble(word)
  26.                     if scrambled_word not in scrambled_words:
  27.                         break
  28.                 scrambled_words.append(scrambled_word)
  29.             return scrambled_words
  30.    
  31.         def read_words_from_file():
  32.             ''' read file of words '''
  33.             with open('wordlist.txt', 'r') as f:
  34.                 # sorted string versions of words (keys), with original words (values)
  35.                 word_list = [word.strip() for word in f]
  36.             return word_list
  37.    
  38.         word_list = read_words_from_file()
  39.         scrambled_words = scramble_words(word_list, quantity)
  40.         return scrambled_words
  41.    
  42.    
  43.     def solve_scrambled_words(scrambled_words):
  44.         ''' return list of unscrambled words for supplied scrambled words '''
  45.    
  46.         def read_words_from_file():
  47.             ''' read file of words '''
  48.             with open('wordlist.txt', 'r') as f:
  49.                 # sorted string versions of words (keys), with original words (values)
  50.                 word_dict = {}
  51.                 for word in f:
  52.                     sorted_word = ''.join(sorted(word.strip()))
  53.                     if not word_dict.get(sorted_word):
  54.                         word_dict[sorted_word] = word.strip()
  55.             return word_dict
  56.    
  57.         word_dict = read_words_from_file()
  58.    
  59.         unscrambled_words = []
  60.    
  61.         for scrambled in scrambled_words:
  62.             sorted_scrambled = ''.join(sorted(scrambled))
  63.             found = word_dict.get(sorted_scrambled, '** not found **')
  64.             unscrambled_words.append(found)
  65.         return unscrambled_words
  66.  
  67.  
  68.     scrambled_words = generate_scrambled_words(randint(5, 10))
  69.     unscrambled_words = solve_scrambled_words(scrambled_words)
  70.    
  71.     print(f"\nScrambled words are: {', '.join(scrambled_words)}.\n")
  72.     for scrambled, unscrambled in zip(scrambled_words, unscrambled_words):
  73.         print(f'{scrambled} unscrambles to {unscrambled}')
  74.     print()
  75.    
  76.     return scrambled_words, unscrambled_words
  77.  
  78.  
  79. ''' test framework for unscrambling challenge
  80.  
  81.    Copy this, using the raw view (or download), to an editor of your choice
  82.    and insert your function(s) at the top of the code.
  83.    
  84.    Wrap your main code including the two required functions into a function named
  85.    after you that returns the scambled and unscrambles word lists
  86.    and add the function to the list of functions called in the last line below.
  87.  
  88.    Edit the last line, the call to the test function test_funcs() and place
  89.    the name of each function, without its trailing (), in the call to test_funcs,
  90.    with commas between each function name if testing more than one function.
  91. '''
  92.  
  93. def test_funcs(*funcs):
  94.    
  95.     tests = [('Testing using external file', 'Simple comparison')]
  96.    
  97.     import traceback
  98.    
  99.     for func in funcs:
  100.         print(f'\n\nTesting function: {func.__name__}\n')
  101.         print('-----------')
  102.         for test, assertion in tests:
  103.             print(f'Testing: {test}')
  104.  
  105.             try:
  106.                 scrambled_words, unscrambled_words = func()
  107.             except ValueError as errmsg:
  108.                 print(errmsg)
  109.                 break
  110.             except Exception as e:
  111.                 print(f'ERROR: {traceback.format_exc()}')
  112.                 break
  113.  
  114.             try:
  115.                 if not (isinstance(scrambled_words, list) and isinstance(unscrambled_words, list)):
  116.                     raise TypeError('ERROR - failed to return two lists')
  117.                 if not (len(scrambled_words) > 0 and len(scrambled_words) == len(unscrambled_words)):
  118.                     raise ValueError('ERROR - lists are not of equal length with at least one entry')
  119.             except (TypeError, ValueError) as errmsg:
  120.                 print(errmsg)
  121.                 break
  122.                
  123.             #testing
  124.             scrambled_words.append('TESTING FAILURE')
  125.             unscrambled_words.append('CONFIRMED')
  126.        
  127.             for scrambled, unscrambled in zip(scrambled_words, unscrambled_words):
  128.                 try:
  129.                     if not isinstance(scrambled, str):
  130.                         raise TypeError('Scrambled list contains non string entry')
  131.                     if not isinstance(unscrambled, str):
  132.                         raise TypeError('Unscrambled list contains non string entry')
  133.                     assert sorted(scrambled) == sorted(unscrambled)
  134.                 except AssertionError:
  135.                     print(f'ERROR: {scrambled} does not unscramble to {unscrambled}')
  136.                 except TypeError as errmsg:
  137.                     print(errmsg)
  138.  
  139. if __name__ == "__main__":
  140.     test_funcs(Stuart)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement