Find the Max in a List

I'm New and I'm Stuck

Page 1 of 1

3 Replies - 1024 Views - Last Post: 11 March 2010 - 03:01 PM Rate Topic: -----

#1 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Find the Max in a List

Posted 10 March 2010 - 11:05 PM

I want to find the max number in a list....

This is what I have...I know it's wrong, but I need help
def print_max():
  nums = [10,7,9]

  max = 0
  if nums[0] > max:
        max = nums[0]
    if nums[1] > max:
        max = nums[1]
    if nums[2] >  max:
        max = nums[2]
    print max




I started Python today (about 12 hours ago) so be kind... :/

This post has been edited by zim1985: 10 March 2010 - 11:13 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Find the Max in a List

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5832
  • View blog
  • Posts: 12,685
  • Joined: 16-October 07

Re: Find the Max in a List

Posted 11 March 2010 - 05:28 AM

First, be aware there is a built in function for this. Still, let's explore:

>>> nums = [10,7,9] # our list
>>> max(nums) # built in
10
>>> nums[1:] # show a slice; the list without the first one
[7, 9]
>>> # now find max on our own
... 
>>> n = nums[0] # grab the first
>>> for v in nums[1:]: # look at the rest
...     if v>n: n = v
... 
>>> n
10
>>> # not very exciting, let's write a function
... 
>>> def mymax(list):
...     n = list[0]
...     for v in nums[1:]:
...             if v>n:
...                     n=v
...     return n
... 
>>> mymax([3,4,9,7])
9
>>> 



Hope this helps.
Was This Post Helpful? 2
  • +
  • -

#3 lksnyder0  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 22-January 10

Re: Find the Max in a List

Posted 11 March 2010 - 01:20 PM

I like what baavgai said what he wrote is correct. Second zim1985 the indents in your code is off. If I am reading your program right then the if statements need to be at the same indent.
Was This Post Helpful? 0
  • +
  • -

#4 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: Find the Max in a List

Posted 11 March 2010 - 03:01 PM

View Postlksnyder0, on 11 March 2010 - 11:20 AM, said:

I like what baavgai said what he wrote is correct. Second zim1985 the indents in your code is off. If I am reading your program right then the if statements need to be at the same indent.

I'll keep the indent thing in mind. I think it was just when I posted it here that it got messed up. It looks fine on my computer.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1