For fun, I'm trying to write a code in python that associates a random number with a letter of the alphabet or punctuation mark and adds that letter to a list. I then want to have the code keep making new lists of random letters until it outputs "to be or not to be, that is the question." I then want to print that list and see how many evaluations it took. This is what I have so far.
from random import *
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',',',' ','.']
sentence = []
numbers = []
def random(x):
randval = x
return randval
count = 0
for i in range(1000): # trying to place an upper bound on how many times to try
for i in range(41): # the number of characters in the sentence
randomness = random(randint(0,28)) # the number of enteries in the alphabet list
numbers.append(randomness)
for i in numbers:
count += 1
sentence.append(alphabet[i])
if sentence!=['t','o',' ','b','e',' ','o','r',' ','n','o','t',' ','t','o',' ','b','e',',',' ','t','h','a','t',' ','i','s','t','h','e',' ','q','u','e','s','t','i','o','n','.']:
sentence = [] ### This is supposed to empty the list if it gets the wrong order, but doesn't quite do that.
if sentence == ['t','o',' ','b','e',' ','o','r',' ','n','o','t',' ','t','o',' ','b','e',',',' ','t','h','a','t',' ','i','s','t','h','e',' ','q','u','e','s','t','i','o','n','.']:
print sentence
print count
break
new_sentence = ''.join(sentence)
print new_sentence
I'm not sure what I'm doing wrong. The list size keeps blowing up instead of keeping a length of 41. suggestions?
Aucun commentaire:
Enregistrer un commentaire