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
10 changes: 7 additions & 3 deletions applications/expensive_seq/expensive_seq.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# Your code here
cache = {}


def expensive_seq(x, y, z):
# Your code here

if (x, y, z) not in cache:
if x <= 0:
cache[(x, y, z)] = (y + z)
else:
cache[(x, y, z)] = expensive_seq(x-1, y+1, z) + expensive_seq(x-2, y+2, z*2) + expensive_seq(x-3, y+3, z*3)
return cache[(x, y, z)]


if __name__ == "__main__":
Expand Down
4 changes: 4 additions & 0 deletions applications/histo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,17 @@ bow ######
## Hints

Items: `.vgrzf()` zrgubq ba n qvpgvbanel zvtug or hfrshy.
# `.items()` method on a dictionary might be useful

Sorting: vg'f cbffvoyr sbe `.fbeg()` gb fbeg ba zhygvcyr xrlf ng bapr.
# it's possible for `.sort()` to sort on multiple keys at once.

Sorting: artngvirf zvtug uryc jurer `erirefr` jba'g.
# negatives might help where `reverse` won't.

Printing: lbh pna cevag n inevnoyr svryq jvqgu va na s-fgevat jvgu
arfgrq oenprf, yvxr fb `{k:{l}}`
# you can print a variable field width in an f-string with nested braces, like so `{x:{y}}`

(The hints are encrypted with ROT13. Google for `rot13 decoder` to see
them.)
41 changes: 40 additions & 1 deletion applications/histo/histo.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,41 @@
# Your code here
def histo(filename):
# open file
with open(filename, 'r') as f:
# set string text to variable
s = f.read()
# list of characters to ignore
characters_to_ignore = ['"', ":", ";" , ".", "-", "+", "=", "/", "[", "]",
"{", "}", "(", ")", ",", "*", "^", "&", "|", '\\']
# for each character in input string
for character in s:
# if it's in the ignored characters
if character in characters_to_ignore:
# replace the value with whitepsace
s = s.replace(character, ' ')
# now, ready to make string a list by splitting string on whitespace
words = s.split()
# make all words in list lowercase
words = [word.lower() for word in words]
# create an empty dict
word_dict = {}
# for each word in our list of words
for word in words:
# if not already in dict
if word not in word_dict:
# add new key/value pair
word_dict[word] = 1
# if word in dict
else:
# increase the counter
word_dict[word] += 1
# sort the list of tuples by the second key first (counts, descending)
# then by the first key (alphabetical order)
for tup in sorted(word_dict.items(), key=lambda x: (-x[1], x[0])):
# print our word and it's associated word count as a histogram
print(tup[0].ljust(20) + " " + ("#" * tup[1]))


if __name__ == '__main__':

histo('robin.txt')

31 changes: 13 additions & 18 deletions applications/lookup_table/lookup_table.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
# Your code here
# expensive calculation on the fly

import math

def slowfun_too_slow(x, y):
v = math.pow(x, y)
v = math.factorial(v)
v //= (x + y)
v %= 982451653
lookup_table = {}

return v
def inverse_root(n):
return 1/math.sqrt(n)

def slowfun(x, y):
"""
Rewrite slowfun_too_slow() in here so that the program produces the same
output, but completes quickly instead of taking ages to run.
"""
# Your code here
for i in range(1, 1000):
lookup_table[i] = inverse_root(i)


print(lookup_table[995])

# Do not modify below this line!
# rainbow table
## hash common passwords ahead of time
## precomputed table for caching the output of cryptographic hash functions,
# usually for cracking password hashes

for i in range(50000):
x = random.randrange(2, 14)
y = random.randrange(3, 6)
print(f'{i}: {x},{y}: {slowfun(x, y)}')
# hashing function for pws should be slow
56 changes: 52 additions & 4 deletions applications/markov/markov.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,61 @@
import random
import numpy as np

# Read in all the words in one go
with open("input.txt") as f:
words = f.read()
corpus = words.split()

# TODO: analyze which words can follow other words
# Your code here
def get_current_and_next(word_list):
# for each word in our word list
for i in range(len(word_list) - 1):
# iterate over without storing
# can produce a sequence of values
yield (word_list[i], word_list[i+1])

current_and_next = get_current_and_next(corpus)

# TODO: construct 5 random sentences
# Your code here
d = {}

# grab the two values from the gen obj
for current_word, next_word in current_and_next:
# if current word is already a key
if current_word in d.keys():
# add another 'next' word
d[current_word].append(next_word)
else:
# create a key where value is a list of next words
d[current_word] = [next_word]

num_of_words = 100

# generate a start word
start_word = np.random.choice(corpus)
# create the first word of the chain
markov_chain = [start_word]
for i in range(num_of_words):
# access the values from the latest word's key in the dict
newest_word_choices = d[markov_chain[-1]]
# add a new word to the chain by grabbing one of the possible values
markov_chain.append(np.random.choice(newest_word_choices))
print(' '.join(markov_chain))


# sentences:

"""
last to see how she began writing for him, and down on her sister, who was far as our fire in time without fifty dinners at me!"
she held the black kitten's fault entirely.
For the window with great curiosity to look as if we were playing just the poor King was in the King, so wide open!
All the boys getting larger and then she was nearly sure they had got all knots and had
"""

# with 100 words

"""
running after its face this led to know you know, I turned cold to find one.
"Blew--me--up," panted the King and fields, that there was all your feelings!"
There was so cold, and Alice said, because the tail just now, as she called out to wind blows--
oh, that's very first thing down among the door of use, and, as different as soon as soon as if you're not been reduced at once!
Well, I can only two and then she could find that she went on the old nurse by the kitten had been rolling it was--'and if the King took
"""
17 changes: 16 additions & 1 deletion applications/no_dups/no_dups.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
def no_dups(s):
# Your code here
# split string into list of words
words = s.split()
# create an empty dict
word_dict = {}
# create an empty list for unique words
unique_words = []
# for each word in list
for word in words:
# if it isn't in our dict
if word not in word_dict:
# add key/value pair
word_dict[word] = '_'
# append the new word to the list of unique ones
unique_words.append(word)
# return a str output of the unique words
return ' '.join(unique_words)



Expand Down
50 changes: 50 additions & 0 deletions applications/word_count/letter_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@


# given a string, count how many times each letter occurs in it
# print by descending order, from the most common letter to the least common

our_string = 'supercalifragilisticexpialidocious'


# UPER
# Understand
# What about spaces and special chars?
# ignore for now, just count alphabet letters

# Plan
# loop and place in a dict
# use our Python list sorting methods to sort by descending order of the values not keys

# E

def letter_count(s):
our_dict = {}

for letter in s:
if letter in our_dict:
our_dict[letter] += 1

else:
# ignore non-alphabetic characters
if letter.isalpha():
our_dict[letter] = 1

return our_dict

count_dict = letter_count(our_string)

list_dict = list(count_dict.items())

list_dict.sort(reverse=True, key=lambda pair: pair[1])
# sorted()

v_set = set()
for k, v in list_dict:
if v not in v_set:
print(v, k)
v_set.add(v)
else:
print(' ', k)

# stretch goal from Omid: print each v only once
# or do we want them all on one line, comma-separated?
28 changes: 27 additions & 1 deletion applications/word_count/word_count.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
def word_count(s):
# Your code here
'''A function that takes in a string and returns a
dictionary of words and their counts'''
characters_to_ignore = ['"', ":", ";" , ".", "-", "+", "=", "/", "[", "]",
"{", "}", "(", ")", ",", "*", "^", "&", "|", '\\']
# for each character in input string
for character in s:
# if it's in the ignored characters
if character in characters_to_ignore:
# replace the value with whitepsace
s = s.replace(character, ' ')
# now, ready to make string a list by splitting string on whitespace
words = s.split()
# make all words in list lowercase
words = [word.lower() for word in words]
# create an empty dict
word_dict = {}
# for each word in our list of words
for word in words:
# if the word is already in the dict
if word in word_dict:
# increase the word count by 1
word_dict[word] += 1
# if the word isn't in dict
else:
# add it the dict
word_dict[word] = 1
return word_dict



Expand Down
Loading