python - Trying to use variables outside of a for loop gives a SyntaxError: no binding for nonlocal 'max_' found -
def min_diff(arry_): max_ =0 temp_ =0 in arry_: nonlocal max_ nonlocal temp_ if > max_: nonlocal max_ nonlocal temp_ temp_ = max_ max_ =i return max_-temp_
i want use max_
, temp_
outside loop getting error
syntaxerror: no binding nonlocal 'max_' found
nonlocal
can applied in functions have nested scope. nested scope when define function inside of function.
python doesn't have block scopes; for
loop doesn't create new scope, don't need use nonlocal
in loop. variables available throughout rest of function. drop nonlocal
statements altogether:
def min_diff(arry_): max_ = 0 temp_ = 0 in arry_: if > max_: temp_ = max_ max_ = return max_ - temp_
in python, functions, class definitions , comprehensions (list, set, , dict comprehensions generator expressions) own scope, , functions can act parent scope closures (nonlocal variables).
there bug in code; if pass in list first value maximum value in list, temp_
set 0
, never changes. won't ever find second-highest value in case, because first i
if > max_:
true. you'd need test if i
greater temp_
in case:
def min_diff(arry_): max_ = 0 temp_ = 0 in arry_: if > max_: temp_ = max_ max_ = elif > temp_: temp_ = return max_ - temp_
as side note: don't need use trailing underscores in local variables. of local names used, max_
potentially shadow built-in max()
function, since don't use function @ all, using max_
instead of max
in function not requirement. i'd drop trailing _
underscores names in function. i'd use different names; perhaps highest
, secondhighest
.
last not least, use heapq.nlargest()
function 2 largest values, efficiently:
from heapq import nlargest def min_diff(values): highest, secondhighest = nlargest(2, values) return highest - secondhighest
you may want add length checks there; if len(values) < 2
true, should happen instead?
Comments
Post a Comment