patternpythonMinor
Simple 'Evolution of Text' app
Viewed 0 times
textsimpleevolutionapp
Problem
I'm a complete beginner to Python, and wanted to get some feedback on my first app. I tried to make a clone of the 'evolution of text' app found on the Using Python website.
Enter some text, and watch the program 'evolve' the answer. The program just prints a load of random text, but keeps the correct bits each time.
I wrote my program without looking at the solution on the website. My solution is a little different, so I wanted to ask some more experienced developers what they think of it, what might be bad style and what could be improved.
Enter some text, and watch the program 'evolve' the answer. The program just prints a load of random text, but keeps the correct bits each time.
I wrote my program without looking at the solution on the website. My solution is a little different, so I wanted to ask some more experienced developers what they think of it, what might be bad style and what could be improved.
import random
import string
target = list(raw_input("Enter your target text: "))
current = [random.choice(string.ascii_letters + string.digits + string.punctuation + ' ') for n in range(len(target))]
index = 0
counter = 0
while current != target:
if current[index] != target[index]:
current[index] = random.choice(string.ascii_letters + string.digits + string.punctuation + ' ')
counter += 1
print ' '.join(current)
if index == len(target) - 1:
index = 0
else:
index += 1
print("Done! Match took {0} generations.".format(counter))Solution
Some suggestions:
- Your algorithm is not doing the same thing as the original. The original randomizes the entire string each time, except the correct bits, while yours randomizes only one character each time.
- You can iterate directly over lists. So you don't need
range(len(target)), you can just dofor _ in target.
- You should define
string.ascii_letters + string.digits + string.punctuation + ' 'as a new variable on a separate line so you can re-use it.
- You can use the modulus operator
%to keep the index inside the correct bounds.
Context
StackExchange Code Review Q#127979, answer score: 4
Revisions (0)
No revisions yet.