Skip to content
This repository was archived by the owner on Jul 18, 2020. It is now read-only.
26 changes: 24 additions & 2 deletions eating_cookies/eating_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,33 @@
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(n, cache=None):
pass
if cache is None:
cache = [0 for i in range(n + 1)]

count = 0
if n == 0:
# Hard-coded case
return 1
for k in range(1, 4):
# Loop through 1, 2, and 3 (k)
if n > k:
# Eat k cookies
m = n - k
# Check the number of possibilities
# for the remaining cookies
if cache[m] == 0:
value = eating_cookies(m, cache)
count += value
cache[m] = value
else:
count += cache[m]
elif n == k:
count += 1
return count

if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(ways=eating_cookies(num_cookies), n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]')
print('Usage: eating_cookies.py [num_cookies]')
34 changes: 31 additions & 3 deletions knapsack/knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,40 @@

import sys
from collections import namedtuple
from operator import itemgetter

Item = namedtuple('Item', ['index', 'size', 'value'])

def knapsack_solver(items, capacity):
pass

ratios = []
for item in items:
ratio = item[2] / item[1]
ratios.append((item,ratio))
ratios.sort(key = itemgetter(1), reverse = True)

knapsack = []
has_space = True
while has_space:
# repeat until there are no items left
# or there isn't space left for the lightest item
best_value = next((item for item in ratios if item[0][1] <= capacity), None)
if best_value is None:
has_space = False
else:
item = best_value[0]
ratio = best_value[1]
knapsack.append(item)
capacity -= item[1]
ratios.remove(best_value)

knapsack.sort(key = itemgetter(0))

result = {}
result['Value'] = sum([item[2] for item in knapsack])
result['Chosen'] = [item[0] for item in knapsack]

return result


if __name__ == '__main__':
if len(sys.argv) > 1:
Expand All @@ -23,4 +51,4 @@ def knapsack_solver(items, capacity):
file_contents.close()
print(knapsack_solver(items, capacity))
else:
print('Usage: knapsack.py [filename] [capacity]')
print('Usage: knapsack.py [filename] [capacity]')
40 changes: 37 additions & 3 deletions making_change/making_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,42 @@

import sys

def making_change(amount, denominations):
pass
def making_change(amount, denominations, is_sorted = False, cache = None):
if cache is None:
cache = {}

# Should be similar to eating_cookies, but using
# the denominations array instead of range(1, 4)
# The order things are done in doesn't matter here, though

# Sort so you'll always be decreasing in denomination
if not is_sorted:
denominations.sort(reverse=True)

count = 0
if amount == 0:
return 1
for d in denominations:
if d == 1:
# If you reach pennies, you're done with this iteration
count += 1
else:
for i in range(1, int(amount / d) + 1):
if amount > d * i:
newAmount = amount - d * i
newDenoms = [x for x in denominations if x < d]
newDenomsTuple = tuple(newDenoms)
if not newDenomsTuple in cache:
cache[newDenomsTuple] = {}
if newAmount in cache[newDenomsTuple]:
count += cache[newDenomsTuple][newAmount]
else:
value = making_change(newAmount, newDenoms, True, cache)
count += value
cache[newDenomsTuple][newAmount] = value
elif amount == d * i:
count += 1
return count


if __name__ == "__main__":
Expand All @@ -14,4 +48,4 @@ def making_change(amount, denominations):
amount = int(sys.argv[1])
print("There are {ways} ways to make {amount} cents.".format(ways=making_change(amount, denominations), amount=amount))
else:
print("Usage: making_change.py [amount]")
print("Usage: making_change.py [amount]")
13 changes: 11 additions & 2 deletions recipe_batches/recipe_batches.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@
import math

def recipe_batches(recipe, ingredients):
pass
max_batches = None
for key in recipe:
if not key in ingredients:
# if you don't have any of one ingredient,
# then you can't make any
return 0
local_max = ingredients[key] // recipe[key]
if max_batches is None or local_max < max_batches:
max_batches = local_max
return max_batches


if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
17 changes: 15 additions & 2 deletions rock_paper_scissors/rps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@
import sys

def rock_paper_scissors(n):
pass
rps = ['rock', 'paper', 'scissors']

# We need 3^(n-1) arrays starting with each hand
# 3^(n-2) arrays starting with hadn1, hand2
# 3^(n-3) arrays starting with hand1, hand2, hand3
# etc.

if n == 0:
return [[]]
result = []
for hand in rps:
children = rock_paper_scissors(n-1)
result += [[hand] + children[i] for i in range(0, pow(3, n - 1))]
return result


if __name__ == "__main__":
if len(sys.argv) > 1:
num_plays = int(sys.argv[1])
print(rock_paper_scissors(num_plays))
else:
print('Usage: rps.py [num_plays]')
print('Usage: rps.py [num_plays]')
10 changes: 8 additions & 2 deletions stock_prices/stock_prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@
import argparse

def find_max_profit(prices):
pass
max_profit = prices[1] - prices[0]

for i in range(0, len(prices) - 1):
for j in range(i + 1, len(prices) - 1):
if prices[j] - prices[i] > max_profit:
max_profit = prices[j] - prices[i]
return max_profit


if __name__ == '__main__':
Expand All @@ -12,4 +18,4 @@ def find_max_profit(prices):
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
args = parser.parse_args()

print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))
print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))