Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
All answers explained so I understand solution in Clear category for Changing direction by BootzenKatzen
#This is my solution, which is longer, but still works:
def changing_directions(elements: list[int]) -> int:
dirs = []
changes = 0
for i, j in zip(elements, elements[1:]): #It took me a while to figure out what this did
if i > j: #Zip takes 2 lists and pairs them up 1:1
dirs.append('down') #Then the elements, elements[1:] basically takes your one list
elif i < j: #And turns it into 2 - one offset by 1 number
dirs.append('up') #So you pair 0-1 1-2 etc etc etc
for i, j in zip(dirs, dirs[1:]): #I just used a duplicate logic to compare the dirs list for changes
if i != j:
changes = changes + 1
return changes
#This is their solution:
def changing_direction(elements: list[int]) -> int:
dirs = []
for i, j in zip(elements, elements[1:]):
if j > i and (not dirs or dirs[-1] == '-'):
dirs.append('+')
elif j < i and (not dirs or dirs[-1] == '+'):
dirs.append('-')
return len(dirs) - bool(dirs)
#I didn't understand why they had to subtract bool(dirs) at first
#Then I realized that if there were no changes dirs[] would be empty
#If dirs[] is empty - len(dirs) = false
#So I guess len(dirs) - bool(dirs) = False - False
#And I guess False - False == 0 (?)
#It took me forever to understand this bonus solution:
def changing_direction_bonus(elements: list[int]) -> int:
dir = count = 0
for a, b in zip(elements, elements[1:]):
dir2 = a - b #first set would be 1-2 = -1
if dir2:
if dir2 * dir < 0: #-1 * 0 < 0 so we add to the count
count += 1 # second set is 2-3 or -1 again... but -1 * -1 is 1 which is >0 so no count
dir = dir2 # if the next number was lower instead (changing direction) 3-2 = 1 and 1 * -1 is -1
# and -1 < 0 so the count would go up
return count
#This one essentially does the same thing as above but differently
def changing_direction(e: list[int]) -> int:
d = [x - y for x, y in zip(e, e[1:]) if x != y] # This generates a list based of the results from the math
# so the first example would be [-1, -1, -1, -1]
return sum(x * y < 0 for x, y in zip(d, d[1:])) # Then this multiplies the elements in the same way we did
# the subtraction so we'd end up with [1, 1, 1]
# and none of those are < 0 so our sum of items <0 is 0
# The second assert would be d = [-1, -1, 1, 1]
# So our multiplication would be [1, -1, 1]
# with a sum of 1 value < 0
print("Example:")
print(changing_directions([1, 2, 3, 4, 5]))
# These "asserts" are used for self-checking
assert changing_directions([1, 2, 3, 4, 5]) == 0
assert changing_directions([1, 2, 3, 2, 1]) == 1
assert changing_directions([1, 2, 2, 1, 2, 2]) == 2
print("The mission is done! Click 'Check Solution' to earn rewards!")
March 30, 2023
Comments: