3
\$\begingroup\$

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.

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))
\$\endgroup\$
  • 1
    \$\begingroup\$ You originally tagged the question as python-3.x, but raw_input() is only available in Python 2. \$\endgroup\$ – 200_success May 10 '16 at 21:05
4
\$\begingroup\$

Some suggestions:

  1. 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.
  2. You can iterate directly over lists. So you don't need range(len(target)), you can just do for _ in target.
  3. You should define string.ascii_letters + string.digits + string.punctuation + ' ' as a new variable on a separate line so you can re-use it.
  4. You can use the modulus operator % to keep the index inside the correct bounds.
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

I would also restructure the program a little bit, so make it more comprehensive:

import random
import string

target = raw_input("Enter your target text: ")
CHARS = string.ascii_letters + string.digits + string.punctuation + ' '
current = [random.choice(CHARS) for _ in target]
counter = 0

for index, char in enumerate(target):
    while current[index] != char:
        current[index] = random.choice(CHARS)
        counter += 1
        print ' '.join(current)

print("Done! Match took {0} generations.".format(counter))
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.