Search code examples
pythonpython-3.xfor-loopgenerator

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

  • 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.