Hello, (random) World!

Hello, (random) World!

For reference, see the famous “Hello, World!” program.

# print a string (text)
print('Hello, World!')
Hello, World!
# store a text in a variable
txt = 'Hello, World!'
# print the content of the variable
print(txt)
Hello, World!
# split text into single characters
# store this characters in the same variable
txt = [char for char in txt]
# print the list of single characters
print(txt)
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
# join the single characters to one text and print it
print(''.join(txt))
Hello, World!
# import the built-in module random
import random
# shuffle the list of charaters and print it
random.shuffle(txt)
print(''.join(txt))
, rloWl!odHle
# do the same as above 5 times
for i in range(5):
    random.shuffle(txt)
    print(''.join(txt))
lH oleWrld,!o
olH ,ld!lrWeo
e!lHWlo,orld 
dWlr,lHole!o 
l eoo,lWr!Hld

Recreate the original with random

counter = 0 # count how many iterations are necessary
original = 'Hello, World!'
generated = ''
# Do until original and generated are the same
while generated != original:
    counter += 1
    random.shuffle(txt)
    generated = ''.join(txt)
    
print(f'generated {generated} after {counter} iterations')
generated Hello, World! after 38549263 iterations
import random
counter = 0 # count how many iterations are necessary

original = 'Hello, World!'
# copy the original and split it
generated = [c for c in original]
# shuffle it
random.shuffle(generated)
print('original:', original)
print('first random shuffled:', ''.join(generated))

# Do until original and generated are the same
while ''.join(generated) != original:
    counter += 1
    random.shuffle(generated)
    
print(f'generated {"".join(generated)} after {counter} iterations')
original: Hello, World!
first random shuffled: el!H Wd,lolro
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/tmp/ipykernel_14326/663549123.py in <module>
     13 while ''.join(generated) != original:
     14     counter += 1
---> 15     random.shuffle(generated)
     16 
     17 print(f'generated {"".join(generated)} after {counter} iterations')

~/miniconda3/envs/text/lib/python3.9/random.py in shuffle(self, x, random)
    359             for i in reversed(range(1, len(x))):
    360                 # pick an element in x[:i+1] with which to exchange x[i]
--> 361                 j = randbelow(i + 1)
    362                 x[i], x[j] = x[j], x[i]
    363         else:

KeyboardInterrupt: