0

I would like to generate a random series of letters assigned to a list and assign it to a new list. To further explain this question, I will give an example:

I have a list of 5 letters:

letters = ["A", "B", "C", "D", "E"]

And I want to randomly mixed those letters into another list and add it to a .TXT file. Heres an example of what I want the output to be:

["C", "A", "E", "D", "B"]

Or:

["E", "D", "B", "C", "A"]

As you can see, I just want all the letters to be randomly placed WITHOUT repeats. So something like this:

["C", "C", "E", "B", "A"]

Would not work as "C" repeats 2 times.

I would also like to do this in Python

Thanks Daniel

Daniel
  • 83
  • 8

2 Answers2

4

You can use the method random.choice() for giving you random alphabetic values. If you want to write 25 random alphabetic lower-/uppercase letters to a file, I would have done it like this:

import random
import string
with open("filepath", "w+") as file:
    for _ in range(25):
        file.write(f"{random.choice(string.ascii_letters)}\n")

For getting 25 characters below each other.

Edit: I did not quite understand what you meant by having some letters already defined, but if you want to create a map between a letter to a new one, I would recommend using a dictionary.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Martin
  • 66
  • 3
1

The way I can do this is by using the module random. @Dharman's & @Martin J. Nilsen's answer WOULD work, but not for the question I want. I would like NO repeats in the new Generated List and random.choices()/random.choice() will ALWAYs have repeats.

The way I fixed this is by using the random.shuffle() method:

letters = ["A", "B", "C", "D", "E"]

import random

random.shuffle(letters)

print(letters)

>>> ['E', 'A', 'D', 'B', 'C']
>>> ['C', 'E', 'D', 'B', 'A']
>>> ['B', 'E', 'C', 'D', 'A']

If I wanted to add these random lists to a text file, all I would need to add the script above to a medthod:

def ShuffleLetters():
    import random

    letters = ["A", "B", "C", "D", "E"]

    random.shuffle(letters)

    return letters

Then add them to a for loop:

file = open("test.txt", "a")

i = 0

amount_of_shuffles = 10

for i in range(0, (amount_of_shuffles + 1)):
    file.write(str(ShuffleLetters()) + "\n")

file.close()
Daniel
  • 83
  • 8