Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 30 additions & 8 deletions eating_cookies/eating_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,36 @@
import sys

# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(n, cache=None):
pass


def memoize(func):
memo = {}

def wrapper(val):
if val not in memo:
memo[val] = func(val)
return memo[val]
return wrapper


def eating_cookies(n):
if n == 0:
return 1
elif n < 0:
return 0
else:
return eating_cookies(
n - 1) + eating_cookies(n - 2) + eating_cookies(n - 3)


eating_cookies = memoize(eating_cookies)

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]')
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]')
24 changes: 13 additions & 11 deletions eating_cookies/test_eating_cookies.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import unittest
from eating_cookies import eating_cookies


class Test(unittest.TestCase):

def test_eating_cookies_small_n(self):
self.assertEqual(eating_cookies(0), 1)
self.assertEqual(eating_cookies(1), 1)
self.assertEqual(eating_cookies(2), 2)
self.assertEqual(eating_cookies(5), 13)
self.assertEqual(eating_cookies(10), 274)
def test_eating_cookies_small_n(self):
self.assertEqual(eating_cookies(0), 1)
self.assertEqual(eating_cookies(1), 1)
self.assertEqual(eating_cookies(2), 2)
self.assertEqual(eating_cookies(5), 13)
self.assertEqual(eating_cookies(10), 274)

def test_eating_cookies_large_n(self):
self.assertEqual(eating_cookies(50, [0 for i in range(51)]), 10562230626642)
self.assertEqual(eating_cookies(100, [0 for i in range(101)]), 180396380815100901214157639)
self.assertEqual(eating_cookies(500, [0 for i in range(501)]), 1306186569702186634983475450062372018715120191391192207156664343051610913971927959744519676992404852130396504615663042713312314219527)
def test_eating_cookies_large_n(self):
self.assertEqual(eating_cookies(50), 10562230626642)
self.assertEqual(eating_cookies(100), 180396380815100901214157639)
self.assertEqual(eating_cookies(
500), 1306186569702186634983475450062372018715120191391192207156664343051610913971927959744519676992404852130396504615663042713312314219527)


if __name__ == '__main__':
unittest.main()
unittest.main()
33 changes: 24 additions & 9 deletions making_change/making_change.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
#!/usr/bin/python

import sys
# Here's a general idea: we can initialize a cache as a list (a dictionary would work fine as well) of 0s with a length equal to the amount we're looking to make change for. Each value of the list will represent the number of ways to make i cents, where i are the indices of the list. So cache[10] == 4 from our example above. Since we know there is one way to make 0 cents in change, we'll initialize cache[0] = 1 (you can seed entries for additional values as well, though you don't actually need to).

# Now that we've initialized our cache, we'll start building it up. We have an initial value in our cache, so we'll want to build up subsequent answers in terms of this initial value. So, for a given coin, we can loop through all of the higher amounts between our coin and the amount (i.e., for higher_amount in range(coin, amount + 1)). If we take the difference between the higher amount and the value of our coin, we can start building up the values in our cache.

# To go into a little more detail, let's walk through a small example. If we imagine our coin is a penny, in the first loop iteration, higher_amount is going to be 1 (since it will at first be the same value as our coin). If we take the difference between higher_amount and our coin value, we get 0. We already have a value for 0 in our cache; it's 1. So now we've just figured out 1 way to 1 cent from a penny. Add that answer to our cache.

# Next up, on the next iteration, higher_amount will now be 2. The difference between higher_amount and our coin value now is 1. Well we just figured out an answer for 1, so now we have an answer for 2. Add that to our cache.

def making_change(amount, denominations):
pass

cache = [0] * (amount + 1)
cache[0] = 1
for coin in denominations:
for higher_amount in range(coin, amount+1):
cache[higher_amount] += cache[higher_amount-coin]

return cache[amount]


if __name__ == "__main__":
# Test our your implementation from the command line
# with `python making_change.py [amount]` with different amounts
if len(sys.argv) > 1:
denominations = [1, 5, 10, 25, 50]
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]")
# Test our your implementation from the command line
# with `python making_change.py [amount]` with different amounts
if len(sys.argv) > 1:
denominations = [1, 5, 10, 25, 50]
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]")
31 changes: 24 additions & 7 deletions recipe_batches/recipe_batches.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
#!/usr/bin/python

import math

def recipe_batches(recipe, ingredients):
pass

batches = 0
for item, needed in recipe.items():
# If our recipe includes any ingredient not available, we can't make any batches
if item not in ingredients:
return 0
# The amount we can make is determined by dividing what's on hand by what's needed
amount = ingredients[item] // needed
# If we don't have enough of any ingredient to make even one batch, return 0
if amount == 0:
return 0
# If the amount we can make with the current ingredient is less than a previous one,
# lower the number of batches we can make to the current amount. Or if batches is 0,
# as when we first start, initialize batches to the first amount
elif amount < batches or batches == 0:
batches = amount

return 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))
# 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))
20 changes: 14 additions & 6 deletions rock_paper_scissors/rps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@

import sys


def rock_paper_scissors(n):
pass

def calculate_plays(plays, num):
if len(plays) == n:
return [plays]
else:
return calculate_plays(plays + ['rock'], n - 1) + calculate_plays(plays + ['paper'], n - 1) + calculate_plays(plays + ['scissors'], n - 1)

return calculate_plays([], n)


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]')
if len(sys.argv) > 1:
num_plays = int(sys.argv[1])
print(rock_paper_scissors(num_plays))
else:
print('Usage: rps.py [num_plays]')
24 changes: 18 additions & 6 deletions stock_prices/stock_prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@

import argparse


def find_max_profit(prices):
pass
current_max = 0
current_min = potential_min = prices[0]
for price in prices[1:]:
if price < potential_min:
potential_min = price
if price > current_max:
current_max = price
current_min = potential_min
return current_max - current_min if current_max != current_min else 0 - potential_min


if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
args = parser.parse_args()
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(
description='Find max profit from 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))