-4

lets say I have a list [1,1,1,1].

I want to iterate over all the possible combinations while every index of the list must contain a number from 1 to n.

in other words, i want to make a for loop that will go over all the combinations.

like: [n-35, n-5, 1, n], [1, 1, 1, n], [n, 1, n, n-19]. I hope you get the idea.

does anyone has any idea how to do this?

Maor2871
  • 147
  • 1
  • 13

1 Answers1

1

see itertools.combinations_with_replacement. That should do it.

for comb in itertools.combinations_with_replacement(range(1,n+1), 4):
    # comb is (1,1,1,1), then (1,1,1,2), then ...
Chad S.
  • 6,252
  • 15
  • 25
Berserker
  • 1,112
  • 10
  • 26
  • But this is not what i need, i need a loop that will give me an access to check whatever i want to every combination. this is why i have a list. – Maor2871 Aug 28 '15 at 18:15
  • itertools gives you an iterator, that you can iterate over and do whatever logic you want on each iteration. So yes, it is what you need. – Berserker Aug 28 '15 at 18:17
  • this is what i need! thank you polpak! – Maor2871 Aug 28 '15 at 18:20
  • polpak edited, I answered. Feels great to be left out. – Berserker Aug 28 '15 at 18:21
  • you right i'm sorry, thanks Berserker! i was helped by your comment, i didn't get that it actually letting me to iterate through the combinations. polpak just added the range(1, n+1) that was missed. i guess you deserve the main thank. – Maor2871 Aug 28 '15 at 18:29
  • Well the original answer said to use itertools.combinations which wouldn't allow for repeated items, and didn't have an example so.... – Chad S. Aug 28 '15 at 18:40
  • You both really helped me!! :) – Maor2871 Aug 28 '15 at 18:55