1

I am having a very strange issue, with the following code (removed all irrelevant parts, so the code probably looks like it does nothing):

def get_items(cred, items):
    for i in range(0, len(items)):
        for j in range(0, len(items)):
            if items[i] + items[j] == cred:
                result = [i + 1, j + 1]
                result.sort()
                break
            else:
                result = [None, None]
    return result

def main():
    for idx, val in enumerate(content):
        cred = 200
        items = [150, 24, 79, 50, 88, 345, 3]

        output = get_items(cred, items)

The problem I am having is with the if items[i] + items[j] == cred: line, because it should be true (when i = 0 and j = 3), but it never evaluates to true, depsite the fact that I have tried printing out both items[i] + items[j] and cred right before the if statement, and they both show up as 200. Yet the get_items method returns [None, None].

They are both definitely integers, so I am completely lost as to how this is happening?

user9352220
  • 95
  • 1
  • 8
  • 1
    Somewhat related: https://stackoverflow.com/questions/42913798/searching-array-reports-not-found-even-though-its-found/42913882#42913882 – Barmar Feb 25 '18 at 00:26
  • Did you try putting a `print` statement in the `if` to see if it's evaluating to true? – Barmar Feb 25 '18 at 00:27

2 Answers2

5

You seem to be expecting the break to break both loops. It only breaks the inner loop; the outer loop keeps going, and result gets reset to [None, None]. Just return the result immediately instead of breaking.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

I think you are overriding result on each iteration. try like this:

def get_items(cred, items):
   result= []
   for i in range(0, len(items)):
       for j in range(0, len(items)):
           print(items[i] + items[j], cred)
           if (items[i] + items[j]) == cred:
               result.append([i + 1, j + 1])
               #result.sort()
               break
           else:
               result.append( [None, None])
   print(result)

cred = 200
items = [150, 24, 79, 50, 88, 345, 3]

output = get_items(cred, items)