'How can I adjust the repetition of for loops?
I wanted to think about this problem personally But I know there are experienced people here who have great solutions. I'm trying to create a code number generator and I will improve that to includes all letter cases. But my problem is that for example, for an 8-letter string, I have to copy the for loop eight times, and I can not say how many strings I want by setting a number. Now I want to ask if there is a solution that prevents for for duplication in the code and can only be achieved by setting a generate number?
myPass = []
print("Calculate started..")
for a in string.digits:
for b in string.digits:
for c in string.digits:
for d in string.digits:
for e in string.digits:
for f in string.digits:
for g in string.digits:
for h in string.digits:
myPass.append(a + b + c + d + e + f + g + h)
print("Calculate finish..")
For example, I want to have a function that performs the above process by just setting a number. This is how I can adjust the number of strings:
def Generate(lettersCount):
print("Generate for loops for 12 times..") # for e.g.
print("12 letters passwords calculated..") # for e.g.
Generate(12) # 12 for loop's generated..
Any ideas and suggestions are accepted here.
Solution 1:[1]
Do you want something like this?
import itertools as it
my_string = '1234'
s = it.permutations(my_string, len(my_string))
print([x for x in s])
Output: [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4'), ('1', '3', '4', '2'), ('1', '4', '2', '3'), ('1', '4', '3', '2'), ('2', '1', '3', '4'), ('2', '1', '4', '3'), ('2', '3', '1', '4'), ('2', '3', '4', '1'), ('2', '4', '1', '3'), ('2', '4', '3', '1'), ('3', '1', '2', '4'), ('3', '1', '4', '2'), ('3', '2', '1', '4'), ('3', '2', '4', '1'), ('3', '4', '1', '2'), ('3', '4', '2', '1'), ('4', '1', '2', '3'), ('4', '1', '3', '2'), ('4', '2', '1', '3'), ('4', '2', '3', '1'), ('4', '3', '1', '2'), ('4', '3', '2', '1')]
Edit: Use print(["".join(x) for x in s]) if you want to add to get strings.
Output: ['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']
Use
import itertools as it
my_string = '1234'
my_list = it.permutations(my_string, len(my_string))
with open('your_file.txt', 'w') as f:
for item in my_list:
f.write("%s\n" % item)
if you want to save the result to a file. If you print a very long result to console, the console usually starts deleting the old lines.
Solution 2:[2]
You can make the recursive function like the following.
class PasswordGenerator():
def __init__(self):
self.password_list = []
def generate_password(self, len, added_string=""):
if len == 0:
self.password_list.append(added_string)
else:
for i in string.digits:
self.generate_rand_with_for(len - 1, i + added_string)
Then you can use this class to get the list of passwords.
password_gen = PasswordGenerator()
password_gen.generate_password(12)
print(password_gen.password_list)
Or you can implement this using the python generator.
import string
from random import choices
def generate_random_string(len):
while True:
yield ''.join(choices(string.ascii_letters + string.digits, k = len))
gen = generate_random_string(12)
Then you can get one string from this generator at any time.
print(next(gen))
Or you can get any number of passwords like the following
number_of_passwords = 100000
for index, item in enumerate(gen_loop):
print(item)
if index == number_of_passwords:
break
Hope it could help.
Solution 3:[3]
In python there is a function called ord(). This function returns the unicode value of a character. Digits from 0 to 9 are also characters. We can view the unicode values of the characters from '0' to '9' as follows...
for c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
print('Character : ', c, ' and Unicode value : ', ord(c))
You will ge a out put like this...
Character : 0 and Unicode value : 48
Character : 1 and Unicode value : 49
Character : 2 and Unicode value : 50
Character : 3 and Unicode value : 51
Character : 4 and Unicode value : 52
Character : 5 and Unicode value : 53
Character : 6 and Unicode value : 54
Character : 7 and Unicode value : 55
Character : 8 and Unicode value : 56
Character : 9 and Unicode value : 57
There is a function in the module "random" called "randint()"
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
Now considering that your paawrod will only contain digits from '0' to '9', you can solve your problem with the code below ()...
def passwordGenerator(password_length):
password = ''
for length in range(password_length):
password += chr(random.randint(48, 57))
return password
print(passwordGenerator(12))
Few examples of the generated passwords are given below...
852501224302
501575191222
271006502875
914595005843
The function chr() in python returns the string representation from the unicode value.
Solution 4:[4]
Are you trying to make a password generator ?
That can be accomplished with the random module and a single for loop
all_symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
import random
def password_gen():
return ''.join(random.choice(all_symbols)for i in range(15))
password = password_gen()
print(f"Secure password - {password}")
Hope this helps :)
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 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 |
