Home > Mobile >  Why does this work? Shouldn't it return the smallest value?
Why does this work? Shouldn't it return the smallest value?

Time:07-12

I have this loop that I wrote to find the smallest number in an arbutrary list:

arbitrary=[44,999,20,55,13,21]
smallest=None
for i in arbitrary:
 if smallest is None:
   smallest=i
 elif smallest>i:
   smallest=i
print(smallest)

When I run the code, it gives me the correct value. However, shouldn't it be:

elif smallest<i:
  smallest=i

When it checks to see if the next value is the smallest, it should be checking to see if i is smaller than the current i value. But running elif smallest <i gives me the largest value, 999

I think I'm missing something obvious about how the loop is iterating over arbitrary, but it's just not clicking. What am I missing, and why does the original code work?

CodePudding user response:

In plain english what your elif statement is saying is that IF the smallest number in that iteration of the loop is BIGGER than the i-value then it is no longer the smallest number. This gets replaced by the i value. using a print statement in the loop can help you troubleshoot to understand what's happening.

arbitrary=[44,999,20,55,13,21]
smallest=None
for i in arbitrary:
 print(smallest)
 if smallest is None:
   smallest=i
 elif smallest>i:
   smallest=i
print(smallest)

the output of this code

None
44
44
20
20
13
13

CodePudding user response:

The logic is right. Saying smallest > i is the same as saying i < smallest, what makes sense: when i is lower than the smallest value, the smallest turns to be i.

CodePudding user response:

In order for smallest to be the smallest element in arbitrary, at the end the loop smallest <= x where x is any element in arbitrary.

So, as you're looping through the list, you need to update smallest if this condition is not true.

So what your code should do is the following

if not smallest <= x:
    smallest = x

Some basic algebra shows that not smallest <= x is the same as smallest > x which is faster (since it's a single operation as logical comparisons are implemented in hardware) and cleaner to write in code (fewer symbols to read).

  • Related