Reputation: 3002
import random
def random_letters():
x = random.randrange(0, 28)
for i in range (1,29):
n = ["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z"]
print (n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x])
random_letters()
The above is my attempt to print a random shuffling of letters each time the random_letters() method is called, though it does not work. What approach can I use to generate this effect?
Upvotes: 1
Views: 139
Reputation: 6518
What you wrote doesn't work because x = random.randrange(0, 28)
returns a single random number, when you print n[x]
it's always going to be the same character. Even if you declared x = random.randrange(0, 28)
inside the for
loop, it wouldn't be enough to assure every character is different, simply because it would have to generate all different numbers in all loops, which is highly unprobable.
A workaround is creating a range list with the same length as your characters' list, then shuffling it with random.shuffle
and printing the characters' list using the indexes of the shuffled list:
from random import shuffle
def random_letters(length):
n = ["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z"]
list1 = list(range(len(n)))
shuffle(list1) # Try printing list1 after this step
for i in range(length):
print(n[list1[i]],end="") # The end paramater is here to "concatenate" the characters
>>> random_letters(6)
grmöçd
>>> random_letters(10)
mbzfeıjkgş
Upvotes: 1
Reputation: 780
import random
import numpy as np
n = np.array(["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z"])
nLength = np.arange(len(n)) #Generate an array from 0 to the length of n
np.random.shuffle(nLength) #Randomly shuffle that array
def random_letters():
m = n[nLength] #Set m equal to a reordered n according to nLength
print (m)
random_letters()
@coldspeed's method works rather well also, just make it a np.array as above for my method to work.
If you decide you only want it to return the same randomized string each time, set
np.random.seed(*some number*)
above the shuffle method.
Upvotes: 0