1

Trying to find the smallest number in an array that the user inputs. Here's what I have:

def main():
   numbers = eval(input("Give me an array of numbers: "))
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
      if (numbers[i] < smallest):
         smallest = numbers[i]
         print("The smallest number is: ", smallest)
main()

The result I'm looking for is to be:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is 3

Instead, this is what I am getting:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is:  5
The smallest number is:  3

Can anyone help me figure out where I am messing up? Thanks in advance.

1
  • Since you assigned smallest = numbers[0] you can change the range in the for-loop to start at index 1 rather than 0. Also, the step parameter of range is 1 by default, so not required to specify. Commented Apr 10, 2014 at 6:29

3 Answers 3

6

You can just use min():

print("The smallest number is: ", min(numbers))
Sign up to request clarification or add additional context in comments.

Comments

3

You have to print the output only once after the loop finishes.

def main():
   numbers = eval(input("Give me an array of numbers: "))
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
      if (numbers[i] < smallest):
         smallest = numbers[i]
   print("The smallest number is: ", smallest)
main()

Or use min() as Christian suggested.

3 Comments

Not supposed to use built in functions. Practicing using different patterns, in this case, the extreme pattern.
@user3518112 If you're operating under constraints like that, it always helps to mention them in the question.
off-topic: where possible ast.literal_eval is preferred instead of eval as it only evaluates: 'strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None'
0

Lets assume an array as arr

Method 1: First sorting an array in ascending order & then printing the element of 0 index

arr = [2,5,1,3,0]
arr.sort()
print(arr[0])

Method 2: Using For loop until we get the smallest number then min

arr = [2,5,1,3,0]
min = arr[0]
for i in range (len(arr)):
    if arr[i] < min:
        min = arr[i]
print(min)

1 Comment

Concerning method 1: A) it is an in-place operation, use sort build-in for a new list B) using a sort approach to find only the min/max could be a waste since, depending on the data in the list, it is at worst an n*log(n)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.