I’m trying to add random letters after each letter in a given range, but they aren’t in complete randomness.
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = random.choice(string.ascii_letters) * num
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
some of the results will have the same letter repeating multiple times like "HAAAAeiiiilzzzzlBBBBoSSSS!jjjj". Instead, they should be random.
>Solution :
- You used
*sum, which only generaterandomLetteronce and repeat the result letter forsumtimes. It’s not repeat the random generation. So the result repeated. - It should be a
looporlist-comprehensionto generate mutiplerandomLetter.
fixed code:
import random
import string
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = "".join(random.choice(string.ascii_letters) for _ in range(num))
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
result:
Adding 1 random characters to Hello! -> HNemldlgos!z
Adding 2 random characters to Hello! -> HVTeGYlYLlxdonV!GM
Adding 3 random characters to Hello! -> HqjbeQyOlgfHlAwqoyCj!PRq
Adding 4 random characters to Hello! -> HyFoLeyHUzlExGelVLlAoOhyz!EuzW