Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import time
def number_of_sweets(days):
"""
This function assumes the parameter, days, contains a list of integers in ascending order.
optimised function where the
sum_of_sweets counts every odd number and keeps track of the previous calculation.
This function more clearly displays its efficiency for very long lists.
For explanation we look a list of length 3:
if days = [3, 5, 9], we first calculate 3,
sum_of_sweets counts from 1 to 3 and skips every 2nd number
so, sum_of_sweets(1) = 1 + 3 = 4
then we calculate 5,
but we already know the sum_of_sweets from 1 to 3 (which is 4)
therefore, sum_of_sweets counts from 3 to 5 and adds it to the previous calculation
so, sum_of_sweets(2) = sum_of_sweets(1) + 5 = 9
then we calculate 9,
but we already know the sum_of_sweets from 1 to 5 (which is 9)
therefore, sum_of_sweets counts from 5 to 9 and adds it to the previous calculation
so, sum_of_sweets = sum_of_Sweets(2) + 7 + 9 = 25
in comparison, the original solution computed 3 by looping from 1 each time.
for example,
sum_of_sweets = 1 + 3 = 4
then 5 by,
sum_of_sweets = 1 + 3 + 5 = 9
then 9 by,
sum_of_sweets = 1 + 3 + 5 + 7 + 9 = 25
"""
min_day = 1
sum_of_sweets = 0
for day in range(len(days)):
while min_day < days[day] + 1:
sum_of_sweets += min_day
min_day += 2
print(sum_of_sweets)
# end of number_of_sweets
# function submitted in hacker rank test
# (equivalent to java code)
def number_of_sweets_submitted(arr):
for days in range(len(arr)):
sum = 0
for day in range(arr[days] + 1):
if (day % 2 != 0):
sum += day
print(sum)
# end of number_of_sweets_submitted
# List of days in a year, where each element i
# is the number of days.
# For example,
# i = 2, 2 days have past
# i = 5, 5 days have past
day_in_year_list = [1, 2, 5, 10000000]
# We pass the above list into the submitted function
# We also time it to compare with the new function.
# The original function give a time of ~ 1.0 second
# for day_in_year_list (length 4)
t1 = time.time()
number_of_sweets_submitted(day_in_year_list)
t2 = time.time()
# We pass the above list into the optimised function
# We also time it to compare with the old function.
# The optimised function gives a time of ~ 0.60
# for day_in_year_list (length 4)
# Therefore, the optimised functions takes about
# half of the time as the the submitted solution.
t3 = time.time()
number_of_sweets(day_in_year_list)
t4 = time.time()
print("The submitted function takes: " + str(t2-t1))
print("The optimised functions takes: " + str(t4-t3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.