Search code examples
pythonperlprogramming-languages

I want to nest loop ten times, Is there any better way than this?


Something like this. I want to brute force all characters with word of 10 size

lookup = map(chr, range(32, 127))
for i in lookup:
    for j in lookup:
        for k in lookup:
            for l in lookup:
                for m in lookup:
                    for n in lookup:
                        for o in lookup:
                            for p in lookup:
                                for q in lookup:
                                    for r in lookup:
                                       print(r) # whatever

Here are my questions

1) Is there any better way?

2) One problem with this code is print(any of i j k ... r) not working, can you help me figure out the problem? if I give any string it is working but not the variables

3) I tried same with perl even there not able to print variables in the loop like i, j, .. r


Solution

  • itertools is your friend.

    >>> lookup = map(chr, range(32, 127))
    >>> import itertools
    >>> itertools.permutations(lookup, 10)
    <itertools.permutations object at 0x023C8AE0>
    

    Notice that permutations will give you every word, whereas combinations will give you every group of distinct characters. Note also that there are a lot of ten-letter words.