In this example, we will create a python function which will take in a list of numbers and then return the smallest value. The solution to this problem is first to create a place holder for the first number within the list, then compares that number with other numbers within the same list in the loop. If the program found a number which is smaller than the one in the place holder, then the smaller number will be assigned to that place holder.

def find_smallest_int(arr): smallest = None for elem in arr: if(smallest == None or smallest > elem): smallest = elem return smallest

If you have a better solution then kindly leave your comment below this post.

[Total: 0 Average: 0]

Please follow and like us:

“Better” – using what measurement?

This might take longer to run, but it’s shorter:

def find_smallest_elem(arr):

return sorted(arr)[0]

It is arguably also easier to read.

(It does, however, behave slightly different when passed an empty list).

This is trivial, you don’t need a function:

sorted(arr)[0] if arr else None

You can also use the built-in MIN function

>>> min([2,3,6,3,5])

2

>>> min([3,6,3,5])

3