Skip to content
Advertisement

How to create a script that gives me every combination possible of a six digit code

Me and a friend want to create a script that gives us every possible permutation of a six digit code, comprised of 36 alphanumeric characters (0-9, and a-z), in alphabetical order, then be able to see them in a .txt file.

And I want it to use all of the CPU and RAM it can, so that it takes less time to complete the task.

So far, this is the code:

import random
charset = "0123456789abcdefghijklmnopqrstuvwxyz"
links = []
file = open("codes.txt", "a")

for g in range(0, 36**6):
    key = ""
    base = ""
    print(str(g))
    for i in range(0, 6):
        char = random.choice(charset)
        key += char
    base += key
    file.write(base + "n")

file.close()

This code randomly generates the combinations and immediately writes them in a .txt file, while printing the amount of codes it has already created but, it isn’t in alphabetical order (have to do it afterwards), and it takes too long.

How can the code be improved to give the desired outcome?

Thanks to @R0Best for providing the best answer

Advertisement

Answer

The fastest way I can think of is using pypy3 with this code:

import functools
import time
from string import digits, ascii_lowercase


@functools.lru_cache(maxsize=128)
def main():
    cl = []
    cs = digits + ascii_lowercase
    for letter in cs:
        cl.append(letter)
    ct = tuple(cl)
    with open("codes.txt", "w") as file:
        for p1 in ct:
            for p2 in ct:
                for p3 in ct:
                    for p4 in ct:
                        for p5 in ct:
                            for p6 in ct:
                                file.write(f"{p1}{p2}{p3}{p4}{p5}{p6}n")


if __name__ == '__main__':
    start = time.time()
    main()
    print(f"Done!nTook {time.time() - start} seconds!")

It writes at around 10-15MB/s. The total file is around 15GB I believe so it would take like 990-1500 seconds to generate. The results are on a VM of unraid with 1 3.4 ghz core of server CPU, with an old SATA3 SSD. You will probably get better results with an NVME drive and a faster single core CPU.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement