0

I Have Code Like this

n = 8
Num = set()
start = 0
end = 10**n

while start < end:
  x = ''.join(['{}'.format(randint(0, 9)) for num in range(0, n)])
  if x not in Num:
    start += 1
    Num.add(x)

Which gave me result like this:

46282449
76709352
92922406

The point of the code above is that I want to produce all combinations of the 8 digit numbers, which means there are about 100 million combinations. My problem is this code takes a lot of time to process (until now this code has taken up to 7 hours more and has not stopped). Can someone give me advice on how to optimize this code?

Hari
  • 23
  • 4
  • If you have working code and you're looking for improvements, you should post your question on https://codereview.stackexchange.com/ instead – Mike Scotty Jul 19 '21 at 06:30
  • You might want to use the `itertools.combinations` [more information](https://www.geeksforgeeks.org/itertools-combinations-module-python-print-possible-combinations/) – Mr. Hobo Jul 19 '21 at 06:30
  • If you are using `randint` then I doubt you are gonna get all possible combinations – PCM Jul 19 '21 at 06:32
  • @PCM You just need unlimited time. – Matthias Jul 19 '21 at 06:32
  • Hint: when there are 99,999,999 combinations in the set already, how many times on average do you think the loop will have to try in order to find the remaining combination? How many times on average do you think it will try (and fail with) an existing combination? Now. Do you *know* what all the combinations are? Can you think of a simple way to generate all of them in order? Now, knowing that, can you think of a simple way using the `random` module to put them in a random order? (If you can't, try reading the documentation.) – Karl Knechtel Jul 19 '21 at 06:34
  • Wait, do you actually want them to be in a random order? ... You do understand that `sets` *don't conceptually have an order*, right? – Karl Knechtel Jul 19 '21 at 06:36
  • That said, what happened when you tried putting `python produce all combinations` into a search engine? – Karl Knechtel Jul 19 '21 at 06:36
  • This isn't even a case for `itertools`. With a given `n` a simple `[f'{i:0{n}d}' for i in range(10 ** n)]` will do - at least until we run out of memory. – Matthias Jul 19 '21 at 08:05

1 Answers1

0

Have a look at itertools.permutations:

itertools.permutations(iterable, r)

This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form.

from itertools import permutations

perm_generator = permutations(range(1, 9), 8)
for p in perm_generator:
    print(p)
Shradha
  • 2,232
  • 1
  • 14
  • 26