[Tutor] Finding more efficient ways

HRK rahn.no.kamikakushi at gmail.com
Tue Jul 9 22:04:00 CEST 2013


Hello,
I'm pretty new to Python so while I can make some basic stuff work, it doesn't look particularly pretty. I wanted to find better ways to solve the following two problems (the current code works, but is clunky.) Any tips or help appreciated. Thanks!

PROBLEM #1

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

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

print(mountain_height({'K2':8611, 'Hekla':1488}, "K2"))
#8611
print(mountain_height({'K2':8611, 'Hekla':1488}, "Hekla  "))
#1488
print(mountain_height({'K2':8611, 'Hekla':1488}, "Port Hills"))
#-1


PROBLEM #2

def is_up_down(values):
    '''Return True if values is an up-down-sequence, otherwise
    return False.
    A sequence [x[0], x[1], x[2], ..., x[n]] is an up-down-sequence
    if there is an index k such that
    x[0] <= x[1] <= x[2] <= ... <= x[k-1] <= x[k] and
    x[k] >= x[k+1] >= x[k+2] >= ... >= x[n-1] >= x[n] hold.
    That is, the first part of the sequence is increasing and the
    second part is decreasing.
    Either part may be empty, so any increasing sequence and any
    decreasing sequence is an up-down-sequence.
    '''
    flip = 0
    value = 0
    for item in values:
        if flip == 2:
            if item > value:
                return False
        elif flip == 1:
            if item < value:
                flip += 1
            value = item
        elif flip == 0:
            if item > value:
                flip += 1
            value = item
    return True

print(is_up_down([2,5,5,7,9,9,8]))
#True
print(is_up_down([2,5,5,7,9,8,9]))
#False
print(is_up_down([9,8]))
#True
print(is_up_down([13]))
#True


More information about the Tutor mailing list