0

I want to get permutations for two numbers upto n repetitions in python code.

Example:

a = 10, b = 100 and given n = 3

Now I want output like:

(10, 10, 10),
(10, 10, 100),
(10, 100, 10),
(10, 100, 100),
(100, 10, 10),
(100, 10, 100),
(100, 100, 10),
(100, 100, 100)

I tried itertools permutations but wont helpful. Anyone please give me a solution.

yatu
  • 86,083
  • 12
  • 84
  • 139
  • 2
    If you search in your browser for "Python permutations", you'll find references that can explain this much better than we can manage here. We expect you to do this research before posting. – Prune May 29 '19 at 16:40
  • @Prune Thanks for suggestion. I googled it before posting here. But I got all answers as n is upto the given list only and that no repetitions of same list numbers. So for that reason I posted my query here. Thanks again! – Mohan Kumar sajja moka May 29 '19 at 16:45

2 Answers2

1

You can use itertools:

from itertools import product

nums = [10, 100]
n = 3

ans = list(product(nums, repeat=n))
print(ans)
Perplexabot
  • 1,852
  • 3
  • 19
  • 22
1

You can use itertools.product and set a repeat of 3:

from itertools import product
a, b = 10, 100
n = 3

list(product([a,b], repeat=n))

[(10, 10, 10),
 (10, 10, 100),
 (10, 100, 10),
 (10, 100, 100),
 (100, 10, 10),
 (100, 10, 100),
 (100, 100, 10),
 (100, 100, 100)]
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Thanks @yatu, can we solve this without itertools? If yes what will be the time complexity also. – Mohan Kumar sajja moka May 29 '19 at 16:34
  • 1
    Hi @moka won't be able to share other answers until later. This will be O(n^2), as it is a cartesian product. If you want to avoid imports just take a look at the python code shared in the docs in itertools. – yatu May 29 '19 at 16:40
  • 4
    Please set a better example by voting to close these duplicates in the future. – jpmc26 May 29 '19 at 16:46
  • Yes you're right, this is a clear dupe @jpmc26 – yatu May 29 '19 at 17:02