Advertisement
skotoseme

dawkins weasel program

May 9th, 2014
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. # This is a weasel constructor.
  2. # Cf. The Blind Watchmaker, Richard Dawkins, Chapter 3
  3.  
  4. from random import choice
  5.  
  6. ##
  7. # Weasel constructor
  8.  
  9. def weasel(target='METHINKS IT IS LIKE A WEASEL',
  10. characters='default', mode=0):
  11. """mode 0: single step selection; mode 1: cumulative selection"""
  12. if characters == 'default':
  13. characters = [chr(ascii_code) for ascii_code in range(65,91)] # 'A'-'Z'
  14. characters += ' '
  15. working_string = ''
  16. tries = 0
  17. if mode == 0: # = single step selection mode
  18. while working_string != target:
  19. # run until target found (potentially a very long time)
  20. working_string = ''
  21. for position in range(len(target)):
  22. working_string += choice(characters)
  23. # fill working_string with random characters to len of target
  24. print working_string
  25. tries += 1
  26. if mode == 1: # cumulative selection mode
  27. for character in range(len(target)):
  28. working_string += choice(characters)
  29. tries += 1
  30. while working_string != target:
  31. for index_position in range(len(target)):
  32. if working_string[index_position] == target[index_position]:
  33. pass
  34. else:
  35. working_string = working_string[0:index_position] + choice(characters) + working_string[index_position+1:]
  36. print working_string
  37. tries += 1
  38. print "Total tries:",tries
  39. return working_string, tries
  40.  
  41. weasel(target='METHINKS IT IS LIKE A WEASEL', mode=1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement