Skip to content Skip to sidebar Skip to footer

Debugging A Function In Python

I am asked to debug the following function: def buggy_find_max(input): max_val = None for value in input: if max_val is None: max_val = value if

Solution 1:

In the first version you are supposed to be debugging, ignore the base case (max_val is None), because that becomes False on the first value. Look instead at the second check:

ifmax_val>value:max_val=value

Imagine your second value, value == 5. At this point, the maximum so far max_val == 3:

if3>5:# Falsemax_val=value# doesn't happen

Does this seem like the correct behaviour to you?

To comment on your rewritten version (note that, generally, if you are being given a function to debug it won't need to be completely re-tooled):

defbuggy_find_max(input):
    for value ininput:
        max_val = value # just sets max_val to each value in turnif max_val isNone: # this won't be True unless None is in inputprintNoneif max_val > max_val+1: # this can *never* be True
            max_val = max_value+1print max_val

Post a Comment for "Debugging A Function In Python"