-
Changing direction issue
I'm running into a weird snag with the challenge "Changing Direction" under the "Home" area.
I have two functions that, if they worked as intended, would increment the global variable "count" by 1 whenever the next item in the list deviates from whether it is less than or greater than the current item. It seems like the problem is that "count" isn't interpreted as a global variable, but a local one, as it spits out "UnboundLocalError: cannot access local variable 'count' where it is not associated with a value":
def changing_direction(elements: list) -> int: # your code here count = 0 def changed_plus(elements): for idx, x in enumerate(elements): if len(elements) - 1 < idx+1: break elif elements[idx+1] >= x: continue elif elements[idx+1] < x: count += 1 changed_minus(elements) def changed_minus(elements): for idx, x in enumerate(elements): if len(elements) - 1 < idx+1: break elif elements[idx+1] <= x: continue elif elements[idx+1] > x: count += 1 changed_plus(elements) if elements[0] <= elements[1]: changed_plus(elements) elif elements[0] > elements[1]: changed_minus(elements) return count print("Example:") print(changing_direction([1, 2, 3, 2, 1])) assert changing_direction([1, 2, 3, 4, 5]) == 0 assert changing_direction([1, 2, 3, 2, 1]) == 1 assert changing_direction([1, 2, 2, 1, 2, 2]) == 2 print("The mission is done! Click 'Check Solution' to earn rewards!")
I thought that a variable would be processed globally if it is defined at the very beginning of your program, but it doesn't. I've even moved it before the default "changing_direction" function before, and get the exact same error. I've also tried explicitly defining "global count" but still get the same in either place I try it...
Even weirder, I can get my code to increment the "count" variable successfully if I just don't specify that second function and call it within the first function... It's just that by design, it doesn't switch to the other function and register that the direction has already changed...
def changing_direction(elements: list) -> int: # your code here count = 0 for idx, x in enumerate(elements): if len(elements) - 1 < idx+1: break elif elements[idx+1] >= x: continue elif elements[idx+1] < x: count += 1 return count print("Example:") print(changing_direction([1, 2, 3, 2, 1])) assert changing_direction([1, 2, 3, 4, 5]) == 0 assert changing_direction([1, 2, 3, 2, 1]) == 1 assert changing_direction([1, 2, 2, 1, 2, 2]) == 2 print("The mission is done! Click 'Check Solution' to earn rewards!")