Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created August 18, 2020 19:34
Show Gist options
  • Save saintsGrad15/fbb1745887780dbe80e331b231a3ce03 to your computer and use it in GitHub Desktop.
Save saintsGrad15/fbb1745887780dbe80e331b231a3ce03 to your computer and use it in GitHub Desktop.
Given an array that keeps information about Temperature readings for a city, return an array of equal length that tells you, for a given day how many days have passed since a higher temperature occurred.
# Given an array that keeps information about Temperature readings for a city,
# return an array of equal length that tells you, for a given day
# how many days have passed since a higher temperature occurred
temps = [7, 3, 4, 6, 9, 1, 5, 6, 3, 7, 4, 8, 2, 10]
expected_output = [1, 1, 2, 3, 5, 1, 2, 3, 1, 5, 1, 7, 1, 14]
def local_minima_finder_v2(temps):
complexity_counter = 0
output = [1]
highest = temps[0]
for i, temp in enumerate(temps):
# Skip the first element as we know the answer is 1 but maintain the correct indices for the remaining elements...
if i == 0:
continue
complexity_counter += 1
# if temp is the highest we've seen so far
# then we know the distance is the current index + 1 or "past the first element"
# This avoids having to iterate all the way back to the beginning
if temp > highest:
output.append(i + 1)
highest = temp
continue
# Look backwards, intentionally starting with the current element
# The current element with never be > itself.
# Counting it will give us the inclusive behavior we want
for j in range(i, -1, -1):
complexity_counter += 1
# If the backwards-counting element is higher than temp then it is the local minimum
if temps[j] > temp:
output.append(i - j)
break
# A for...else is triggered when the for loop is never broken
else:
output.append(i + 1)
print("Element Encounters: {}".format(complexity_counter))
return output
output = local_minima_finder_v2(temps)
print("Expected: {}".format(expected_output))
print(" Actual: {}".format(output))
print("NAILED IT!" if output == expected_output else "NOPE...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment