Not sure how else to word the title, but this is what I need:
Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have:
n = 0
x = “hello”
for i in range(20):
print(n, end= ‘’) or print(n 1, end= ‘’) or print(x)
The only problem is that it prints them out in order so that it is always 01hello01hello01hello and so on. I need it to be randomized so that it could print something like 000hello1hello101 or just any random variation of the three variables.
Let me know how :)
CodePudding user response:
import random
choices = [1, 0, "hello"]
for i in range(20):
print(random.choice(choices))
CodePudding user response:
Your question is hard to understand, but I think this will help.
If you want to randomize, then try importing random
import random
my_strings=["foo", "bar", "baz"]
for i in range(10):
print(random.choose(my_strings))
CodePudding user response:
Use random.choice
:
import random
choices = (0, 1, "hello")
print(''.join(str(random.choice(choices)) for _ in range(20)))
CodePudding user response:
The "random" module is very useful for these situations, especially the "shuffle" function.
The "suffle" function allows you to shuffle a list, this function requires the list, and optionally a function that returns a random number between 0 and 1 (by default random.random). This function does not return a list but modifies it.
import random
# Create 20 elements of each vars
vars_0 = ["0"] * 20
vars_1 = ["1"] * 20
vars_2 = ["hello"] * 20
# Join the elements
super_list = vars_0 vars_1 vars_2
# Mix the super list
random.shuffle(super_list)
# Convert the list to a string
print("".join(super_list))
The result
hellohello001hello01hellohello1hello10hello011101hello1101hellohellohello1001hello100001hello101hello00hello0hellohellohellohello1001hello10
I think it is quite readable solution