Task: Given a list of prices of a stock on a single day, return a string describing whether the stock increased, stayed the same, or decreased from its starting price.
def daily_change(prices):
first = prices[0]
last = prices[-1]
if first > last:
return 'decrease'
elif first == last:
return 'none'
else:
return 'increase'
# Returns 'increase', since 1 < 4
daily_change([1, 2, 2.5, 3, 3.5, 4])
# Returns 'none', since 3 = 3
daily_change([3, 9, 3])
# Return 'decrease', since 5 > 2
daily_change([5, 4, 3, 4, 5, 4, 3, 2, 2])
Task: Given a list of prices of a stock on a single day, return True
if the stock was strictly increasing, and False
otherwise. A list of numbers is strictly increasing if each one is larger than the previous.
def strictly_increasing(prices):
i = 0
while i < len(prices) - 1:
if ...:
return False
i += 1
return True
# True
# strictly_increasing([1, 2, 5, 8, 10])
# False
# strictly_increasing([2, 3, 9, 7, 11])
# False
# strictly_increasing([2, 3, 4, 4, 5])
def next_day(day):
week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
curr = week.index(day)
return week[(curr + 1) % 7]
next_day('Wednesday')
next_day('Saturday')
def full_prefix(name):
# i and idx are short for "index"
idx = name.index('.')
prefix = name[:idx]
rest = ...
if prefix == 'Dr':
return 'Doctor ' + rest
elif prefix == 'Prof':
return 'Professor ' + rest
elif prefix == 'Gov':
return 'Governor ' + rest
else:
return name
# 'Governor Newsom'
# full_prefix('Gov. Newsom')
# 'Professor Christ'
# full_prefix('Prof. Christ')
# 'Doctor Biden'
# full_prefix('Dr. Biden')
# 'Hon. Caboto'
# full_prefix('Hon. Caboto')
# For now, ignore the code in this cell.
def increase_sort(n):
n_list = list(str(n))
n_list_sorted = sorted(n_list)
n_str_sorted = ''.join(n_list_sorted)
return int(n_str_sorted)
def decrease_sort(n):
n_list = list(str(n))
n_list_sorted = sorted(n_list)[::-1]
n_str_sorted = ''.join(n_list_sorted)
return int(n_str_sorted)
def find_sequence(n):
# Need to keep track of the steps, and the "current" number in our sequence
steps = [n]
curr = n
# As long as our current number isn't 495
# make one more step, and store the current step
while curr != 495:
curr = decrease_sort(curr) - increase_sort(curr)
steps.append(curr)
return steps
find_sequence(813)
find_sequence(215)