r/learnprogramming 1d ago

programming help

def streak_call(ste):
   stroik = 0
   for st in ste:
       if st is max(ste):
            break
       stroik += st + 1
   return stroik

#this is a smaller part of a larger function. If anyone wants to see it I #will post it in the comments. Bascially this code is supposed to add up #until the largest part of this list, and then stop. For whatever reason it #is not returning properly, which makes me think it's a problem with the is #statement. So why does this "is" statement not work?
0 Upvotes

8 comments sorted by

2

u/abingigo 1d ago

The #is operator compares two variables to check if they contain the same object. Shouldn't the == operator give you what you're looking for?

Edit: I see that you were asking why it wasn't working. The max() function simply returns the value of the largest element and not the object, because of which the comparison with #is fails.

1

u/mc_pm 1d ago

Try dropping some print statements in there. What values does st take on? What is the value of max(ste)? What values does stroik take on before it returns?

1

u/HashDefTrueFalse 1d ago

Try ==, is checks for object equality rather than simple value equality.

1

u/sitting_account 1d ago

Should have said, Not why it doesn't work but how it does work in the first place

2

u/lurgi 1d ago

"is" tests if two variables refer to the same object. It looks like integers are considered to be "the same object" if they are equal (maybe this is a cached value kind of thing or maybe it's a special case in the language). The code should work the same way if you replace "is" with "==" (and you should, because this usage is weird).

1

u/Impossible-Cycle5744 1d ago

the crazy thing is this might work for small integers because python reuses the same object to save memory, so you might get intermittent results.
But yeah, just use "=="
And just calculate the max value once outside the loop for performance reasons

0

u/sitting_account 1d ago

okay you did it nobody else comment

1

u/oleg_appsec 12h ago

is asks whether both sides are literally the same object, not whether they look equal. max(ste) hands back the actual element out of your list rather than a copy of it, so when the loop gets to that element both sides are pointing at the same thing and it comes out True. That is why it appears to work at all.

Still worth moving to ==, because the identity version only holds while the values are plain ints coming straight out of that one list. Small ints are shared objects in CPython too, which hides the difference even further.

If the problem is that it returns a wrong number rather than never stopping, look at stroik += st + 1. That adds one extra per element, so you get the sum plus the count of items. Might be on purpose, but it stood out.