-1

I want to print the sum of all possible combinations of two items in this list - can you tell me what is wrong with the code below? Nothing happens when I run it.

gammas = [1.0,2.0,6.0,5.0,8.,4.]
for i in range(len(gammas)):
    for j in range(len(gammas)):
        while (j>i):
            print gammas[i]+gammas[j]
        if j==i:
            break  
N Solomons
  • 11
  • 2
  • 3
    `j` is always smaller than or the same as `i`, hence `break` is always triggered first. Even so, `while j > i` will never end because neither `i` nor `j` change inside the `while` loop. It's for the better that it doesn't do anything… – deceze Jul 27 '18 at 13:32
  • Why do you need while loop?? just check it with a condition. other ways just change the value of j inside the while loop. (like j--) – Projesh Bhoumik Jul 27 '18 at 13:37
  • I've written an answer, but after reading your question again, I'm not sure if I actually answer to your expectations. I really think it would be beneficial for you to further explain what is the goal of this code. – scharette Jul 27 '18 at 13:43
  • @tripleee Thank you, yes, I hadn't found that – N Solomons Jul 27 '18 at 14:50

1 Answers1

0

Even though you're code have several little mistakes and to understand why it didn't work see @deceze comment.


But, I think your goal here is interesting (eg.print the sum of all possible combinations of two items in this list).

Let me suggest this way of acheiving it,

import itertools

gammas = [1.0,2.0,6.0,5.0,8.0,4.0]

print([sum(x) for x in itertools.combinations(gammas,2)])

>>>>[3.0, 7.0, 6.0, 9.0, 5.0, 8.0, 7.0, 10.0, 6.0, 11.0, 14.0, 10.0, 13.0, 9.0, 12.0]
scharette
  • 9,437
  • 8
  • 33
  • 67
  • Thanks for your help! The actual code I'm working on is more complicated so I wanted to test this more simple version to find out why it doesn't work, but it's great to know about this tool, so thank you! – N Solomons Jul 27 '18 at 14:18