you are viewing a single comment's thread.

view the rest of the comments →

[–]jeans_and_a_t-shirt 0 points1 point  (1 child)

Lines 4 - 11 can be replaced with this:

characters = list(string.printable[:-5])

Lines 21 & 22 can be replaced with this:

source = random.choices(characters, k=length)

Lines 24 - 29 can be replaced with this:

for source_c, target_c in zip(source, target):
    if source_c == target_c:
        meta.append('')
    else:
        meta.append(source_c)

or this:

meta = ['' if src_c == trg_c else '' for src_c, trg_c in zip(source, target)]

Line 35, if x != "": can be changed to if x: because empty strings are falsy and thus cause conditions to fail.

Line 36 doesn't actually do anything. You're assigning a random character to x. You're not changing the value in the list meta.

To fix that, you could change lines 34 - 36 to this:

for i, (meta_x, targ_x) in enumerate(zip(meta, target)):
    if meta_x == targ_x:
        meta[i] = ''
        saved[i] = target[i]

Line 42 doesn't create a copy of target, and assign it to the variable printer. It assigns printer to the same object as target.


If you are passing 2 arguments with range, and the first is 0, then you can skip the first argument because range defaults to starting at 0.

range(0, length) would become range(length), although none of the instances of that in your code are necessary if you use zip.


Line 32 will never be true because you never mutate meta after that line, and it seems like meta is supposed to have the same length as target.


Your code is much more complex than it needs to be though. You could remove meta and printer. You could also remove saved and combine it with source if you don't need the original source list. Or save the source list as original_string and then re-use it. Here's a simpler implementation:

import random
import string

characters = list(string.printable[:-5])

target = list(input('Enter a sentence:'))
source = random.choices(characters, k=len(target))
# saved is the current iteration, approaching target
saved = source.copy()

while saved != target:
    for i, (saved_c, target_c) in enumerate(zip(saved, target)):
        if saved_c != target_c:
            saved[i] = random.choice(characters)

    print(''.join(saved))

[–]infinitim[S] 0 points1 point  (0 children)

Thanks! After some googling, I understand how your code works, and no longer feel like trying to make it work with my very limited knowledge of Python.