[Tutor] Finding more efficient ways

Alan Gauld alan.gauld at btinternet.com
Wed Jul 10 19:50:46 CEST 2013


On 09/07/13 21:04, HRK wrote:

> PROBLEM #1
>
> heights = {"Mount Everest": 8848, "Mount Cook": 3754, "K2": 8611,
> "Ben Nevis": 1344, "Hekla": 1488}

Since you already have a dict of heights why do you pass one in to the 
function each time? Why not just pass this one in? Or use it as a global?

> def mountain_height(heights, mountain):
>      '''Return the height of the mountain.
>      If the mountain isn't in the dictionary, the
>      height returned should be -1.
>      The search should ignore any spaces before or after the name.
>      >>> mountain_height({'K2':8611, 'Hekla':1488}, "K2")
>      8611
>      >>> mountain_height({'K2':8611, 'Hekla':1488}, "Hekla  ")
>      1488
>      >>> mountain_height({'K2':8611, 'Hekla':1488}, "Port Hills")
>      -1
>      '''
>      if mountain.strip() in heights:
>          return heights[mountain.strip()]
>      else:
>          return -1

The last 4 lines can be replaced by heights.get(.....)

Check the dict documentation.

> print(mountain_height({'K2':8611, 'Hekla':1488}, "K2"))
> #8611


print( mountain_height(heights, 'K2') )

> PROBLEM #2
>
> def is_up_down(values):
>      '''Return True if values is an up-down-sequence, otherwise
>      return False.

This is more complex and I'm about to get busy, I might post a reply
if I get time later and nobody else has...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list