0

I want to generate lists of four prime numbers in all possible combinations, so that the numbers never repeat themselves in that list.

I do know how to get what I want with this function:

def combinations():
    primeList = [2, 3, 5, 7, 11, 13, 17]
    length = len(primeList)
    for i in range(0, length-3): 
        for j in range(i+1, length-2):
            for k in range(j+1, length-1):
                for h in range(k+1, length):
                    print([primeList[i], primeList[j], primeList[k], primeList[h]])

which returns such lists: http://postimg.org/image/94u3hzgqb/

But I want to use the code constructed like the one below, because I want this particular structure and want to know the reason it does not act the same way as the function I just copy pasted.

def combinations2():
    primeList = [2, 3, 5, 7, 11, 13, 17]
    for i1, i in enumerate(primeList[0: -3]): 
        for i2, j in enumerate(primeList[i1+1: -2]):
            for i3, k in enumerate(primeList[i2+1: -1]):
                for h in primeList[i3+1:]:
                    print([i, j, k, h])

Which returns lists with repeating elements: http://postimg.org/image/y0h0gwfhf/

Apparently I am using the for loop with enumerate the wrong way but can't seem to figure out where I could be wrong. To me, both functions look like they should be doing the same thing.

If you can, please point out the mistake I am making or correct me otherwise.

Larisa
  • 781
  • 1
  • 11
  • 27
  • 5
    Have you considered [itertools.combinations](https://docs.python.org/2/library/itertools.html#itertools.combinations) ? E.g. `itertools.combinations(primeList, 4)` – Chad S. Dec 18 '15 at 22:39
  • Are you really need a loops? Try `itertools.combinations` and answers to [that](http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) question – Anton Protopopov Dec 18 '15 at 22:40

1 Answers1

1

It is because i1, i2, i3 each start from zero. On the first iteration, you have

primeList[i1+1: -2] = [3, 5, 7, 11]
primeList[i2+1: -1] = [3, 5, 7, 11, 13]
primeList[i3+1:]    = [3, 5, 7, 11, 13, 17]

This is the correct function:

def combinations2():
    primeList = [2, 3, 5, 7, 11, 13, 17]
    for i1, i in enumerate(primeList[0: -3]):
        for i2, j in enumerate(primeList[i1+1: -2]):
            for i3, k in enumerate(primeList[i1+i2+2: -1]):
                for h in primeList[i1+i2+i3+3:]:
                    print([i, j, k, h])
Patrick Fournier
  • 600
  • 6
  • 19