2
from itertools import product

p = np.random.randint(1,2,2)
p = product(p, repeat=50)

I don't know how to get length of P immediately

Blckknght
  • 100,903
  • 11
  • 120
  • 169
Gavin
  • 33
  • 4
  • Does this answer your question? [How to get the length of an itertools.product?](https://stackoverflow.com/questions/32074543/how-to-get-the-length-of-an-itertools-product) – Georgy Mar 19 '20 at 09:51

2 Answers2

1

This is simple combinatorics, not really programming. There are a**n ways to select any of a values n times (repetition is allowed). In your case, a is len(p) (the original p, the array), or 2 (since you've generated an array with two values), and n is 50, so will get 2**50 or 1125899906842624 results from your product if you have a whole lot of time to iterate over them all.

Now, if you're looking for how many distinct values you get, the answer is even easier (though subtly so). There's only one distinct value ever generated, a tuple with 50 ones. That's because you're taking products from an array that contains only the value 1, never anything else, since numpy.random.randint(1, 2) only ever gives you 1 (the upper bound is excluded).

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • thank you for answering, maybe my question is not clear enough, i want to know if there is any method that can get the length of the itertool.product without converting it into a list regardless of what numbers are in it, thank you – Gavin Mar 19 '20 at 08:46
  • Well, you can do the math on the inputs. Use `len(p)**50`, if you don't know what the length is beforehand. After the call, no, I don't think there's any way to know how long it will run. Maybe the code implementing it could figure it out, but it doesn't expose that anywhere. – Blckknght Mar 19 '20 at 19:49
0

The product iterator will have as many items as the lengths of all iterables you pass in multiplied with each other.
You're passing in one iterable but repeating it 50 times. Therefore you have to multiply the length of p 50 times with each other. That's basically len(p)**50.

swenzel
  • 6,745
  • 3
  • 23
  • 37