'How do I create a random letter generator that loops
So I´m very new to python and just trying to create a letter generator.
The output should be like this: aaa aab abb bbb aac acc ccc ...
No uppercase letters, no digits, no double outputs, just a 3 letter long random letter loop.
Hope Someone can help me, Greetings
Edit: I´ve now created a working code that generates a 3 letter long word but now I have the problem that they are getting generated several times. I know the loop function looks weird but I mean it works.
import string, random
count = 0
while count < 1:
randomLetter1 = random.choice(
string.ascii_lowercase
)
randomLetter2 = random.choice(
string.ascii_lowercase
)
randomLetter3 = random.choice(
string.ascii_lowercase
)
print(randomLetter1 + randomLetter2 + randomLetter3)
Solution 1:[1]
The example you posted (aaa, aab, abb, etc.) does not seem like a random letter generator to me, but here's the method I would use to randomly generate 3-letter strings:
# choice allows us to randomly choose an element from a list
from random import choice
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
randomString = ''
for i in range(3):
randomString += choice(letters)
If you want to create a list of these strings, then just loop the last 3 lines several times and add the results to a list like this:
charList = []
for i in range(x):
randomString = ''
for i in range(3):
randomString += choice(letters)
charList.append(randomString)
where x is the number of strings you want to generate. There are definitely many other ways to do something like this, but as you mentioned you're a beginner this would probably be the easiest method.
EDIT: As for the new problem you posted, you've simply forgotten to increment the count variable, which leads to the while loop running infinitely. In general, should you see a loop continue infinitely you should immediate check to see if the exit condition ever becomes true.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
