Skip to content

Instantly share code, notes, and snippets.

@fulmicoton
Created March 10, 2021 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fulmicoton/f4ac78118f45bdf1c6d0b505968bbf1b to your computer and use it in GitHub Desktop.
Save fulmicoton/f4ac78118f45bdf1c6d0b505968bbf1b to your computer and use it in GitHub Desktop.
# The point of this program is to demonstrate why
# supporting negative indices can be error-prone.
#
# The example was voluntarily made simple.
# Of course this is not the most optimized algorithm to answer
# the question...
#
# Real life example are typically more intricate
# and may occur sporadically.
def longest_stay(hotel_rates, budget):
""" Given the list of hotel rates for the month of august,
return the longest affordable stay ending Sept. 1st.
- hotel_rates: list of length 31
- budget: maximum cost of the stay.
"""
max_so_far = 0
for num_days in range(31):
if sum(hotel_rates[-num_days:]) > budget:
# This is overbudget!
return max_so_far
max_so_far = num_days
# We can afford
return 31
print("result", longest_stay([10] * 31, 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment