Search code examples
pythonpython-itertools

How to use itertools combinations/permutations to stop only halfway through the list


I have a project in school where we are going to brute force a password, and we have gotten a list of passwords. The password is a combination of two words on the list, so we have to make this list ourselves.

I have tried this, using itertools:

    list_of_letters = open("passwords.txt").readlines()
    for word in itertools.permutations(list_of_letters):
        print(''.join(word))

But I get a file of 18,9 GB, and even that wasn't enough, due to me not having any more space on my device, as it will need space for 1 mill passwords. Therefore I need to split up this into several files, preferably like 3GB each. How can I do this, and still get all of the combination? I was thinking of dividing the original password-file, but then I will not get all of the combinations.


Solution

  • If you check the documentation for itertools.permutations you will find this:

    If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

    Since you did not specify r this means itertools.permutations will generate all permutations with the length(line count) of your password.txt. What you want is to specify r and set it to 2, to only get permutations with a length of 2:

    itertools.permutations(list_of_letters, 2)
    

    In addition, using .readlines() will lead to all strings having newlines so your "password" will have a newline in the middle so thats a bug you might want to fix too.

    The full code for this could look like this:

    import itertools
    
    # Use a context manager to ensure the file is closed once we're done
    with open("passwords.txt") as f:
        # Strip off the `\n` at the end of each line
        list_of_letters = [line.strip() for line in f.readlines()]
    
        for word in itertools.permutations(list_of_letters, 2):
            print(''.join(word))