About Me
No description provided.
Classes
|
Class status: Established
Role:
Student
|
.
52% complete
|
Submitted Assignments
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 12, HW 1
- Complexity of fact0 is O(n), because recursion have fixed nested level that depends on a "n" and works until n != 1.
- Complexity of fact1 is O(n), because there only one for loop
- If except loop in conditional statement than the complexity equals O(n), because there also one constant loop
- O(n), because there are same one constant loop, and makeSet functions execute only in the first time
#5
def swap0([1], [2]):
assert type(s1) == list and type(s2) == list #True
tmp = s1[:] #[1]
s1 = s2[:] #[2]
s2 = tmp #[1]
return
s1 = [1]
s2 = [2]
swap0(s1, s2) #s1 = 1, s2 = 2
print(s1, s2) #[1] [2]
#6
def swap1(s1, s2):
assert type(s1) == list and type(s2) == list #True
return s2, s1
s1 = [1]
s2 = [2]
s1, s2 = swap1(s1, s2) #s1 = 2, s2 = 1
print(s1, s2) #[2] [1]
#7
def rev([1,2,3]):
assert type(s) == list
for i in range(0,1):
tmp = s[i] #1
s[i] = s[-(i+1)] # [3,2,3]
s[-(i+1)] = tmp #[3,2,1]
rev(s)
print(s) #[3,2,1]
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 11, HW 1
# Problem Set 6: Word Game
# Name: chip
import random
import time
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
HAND_LIMIT = 20
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
WORDLIST_FILENAME = "words.txt"
def get_word_rearrangements(word_list):
rearrange_dict = []
for word in word_list:
rearrange_dict.append("".join(sorted(word)))
return rearrange_dict
def get_frequency_dict(sequence):
freq = {}
for x in sequence:
freq[x] = freq.get(x, 0) + 1
return freq
def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter) # print all on the same line
def deal_hand(n):
hand={}
num_vowels = n // 3
for i in range(num_vowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(num_vowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
def update_hand(hand, word):
new_hand = hand.copy()
for c in word:
if c in new_hand:
new_hand[c] -= 1;
if new_hand[c] == 0:
del new_hand[c]
return new_hand
def is_valid_word(word, hand, word_list):
test_hand = hand.copy()
if word not in word_list:
return False
for c in word:
if c not in test_hand:
return False
else:
if test_hand[c] == 0:
return False
test_hand[c] -= 1
return True
def load_words():
inFile = open(WORDLIST_FILENAME, encoding='utf-8')
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
return wordlist
def get_word_score(word, n):
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES[c]
if len(word) == n:
score += 50
return score
def get_words_to_points(word_list):
points_dict = {}
for word in word_list:
points_dict[word] = get_word_score(word,0)
return points_dict
def pick_best_word(hand, points_dict):
posibilities = {}
for (word, point) in points_dict.items():
posible_word = True
hand_copy = hand.copy()
for ch in word:
if ch not in hand_copy.keys():
posible_word = False
break
else:
del hand_copy[ch]
if posible_word:
posibilities[point] = word
key_vals = posibilities.keys()
sorted(key_vals)
if len(posibilities) == 0:
return "."
else:
return posibilities[max(key_vals)]
def pick_best_word_faster(hand, points_dict, rearrange_dict):
posibilities = {}
sorted_hand = "".join(sorted("".join(hand)))
for (word, point) in points_dict.items():
if sorted_hand in rearrange_dict:
posibilities[point] = word
if len(posibilities) == 0:
return "."
else:
return posibilities[max(posibilities.keys())]
def play_hand(hand, word_list, rearrange_dict):
points_dict = get_words_to_points(word_list)
total_points, time_spend, total_time = 0,0,0
while True:
print("Current hand: ")
display_hand(hand)
start_time = time.time()
print("You have " + str(HAND_LIMIT - total_time) + " seconds ramaining!")
word = pick_best_word_faster(hand, points_dict, rearrange_dict)
# word = input("Enter word, or . to indicate thar you are finished: ")
time_spend += (time.time() - start_time)
total_time += time_spend
if word == ".":
print("Total score: ",total_points)
break
if total_time > HAND_LIMIT:
print("Time limit exceeded!")
break
if not is_valid_word(word, hand, word_list):
print("Ivalid word, please try again!")
continue
points = get_word_score(word, len(hand))
print(("It took {0:2f} seconds to provide an answer.").format(time_spend))
total_points += (points / time_spend)
print(word, "earned", points,"points. Total:",total_points)
hand = update_hand(hand, word)
time_spend = 0
def play_game(word_list, rearrange_dict):
hand = deal_hand(HAND_SIZE)
while True:
cmd = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
if cmd == "n":
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list, rearrange_dict)
print()
elif cmd == "r":
play_hand(hand.copy(), word_list, rearrange_dict)
print()
elif cmd == "e":
break
else:
print("Invalid command.")
word_list = load_words()
rearrange_dict = get_word_rearrangements(word_list)
play_game(word_list, rearrange_dict)
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 2
#Problem Set 5
#Name: chip
WORDLIST_FILENAME = "words.txt"
def load_words():
inFile = open(WORDLIST_FILENAME, encoding='utf-8')
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
return wordlist
word_list = load_words()
def make_turn(player, fragment):
print("Current word fragment:\'",fragment,"\'")
print(player, "turn")
letter = input(player + " says letter: ")
if check_input(letter) != False:
fragment += letter
check_fragment(fragment)
return fragment
def check_input(letter):
if not letter.isalpha() or len(letter) != 1:
return False
return True
def check_fragment(fragment):
fg = fragment.lower().strip()
if fg in word_list and len(fg) > 3:
return fragment + " is a word"
for word in word_list:
indx = word.find(fg)
if indx != -1:
if indx == 0:
return True
return "no words begins with " + fragment;
def play_game():
players = ["Player 1", "Player 2"]
player = 0
fragment = ""
print ("Welcome to Ghost!")
while True:
fragment = make_turn(players[player], fragment)
fragment_check = check_fragment(fragment)
if fragment_check != True:
print("Player", players[player],"loses because",fragment_check)
break
if player + 1 >= len(players):
player = 0
else:
player += 1
print("\n")
play_game()
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 1
# Problem Set 5: 6.00 Word Game
# Name: chip
import random
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
WORDLIST_FILENAME = "words.txt"
def get_frequency_dict(sequence):
freq = {}
for x in sequence:
freq[x] = freq.get(x, 0) + 1
return freq
def display_hand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter) # print all on the same line
def deal_hand(n):
hand={}
num_vowels = n // 3
for i in range(num_vowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(num_vowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
def update_hand(hand, word):
new_hand = hand.copy()
for c in word:
if c in new_hand:
new_hand[c] -= 1;
if new_hand[c] == 0:
del new_hand[c]
return new_hand
def is_valid_word(word, hand, word_list):
test_hand = hand.copy()
if word not in word_list:
return False
for c in word:
if c not in test_hand:
return False
else:
if test_hand[c] == 0:
return False
test_hand[c] -= 1
return True
def load_words():
inFile = open(WORDLIST_FILENAME, encoding='utf-8')
wordlist = []
for line in inFile:
wordlist.append(line.strip().lower())
return wordlist
def get_word_score(word, n):
if word in word_list:
score = 0
for c in word:
score += SCRABBLE_LETTER_VALUES[c]
if len(word) == n:
score += 50
return score
else:
return 0
def play_hand(hand, word_list):
total_points = 0
while True:
print("Current hand: ")
display_hand(hand)
word = input("Enter word, or . to indicate thar you are finished: ")
if word == ".":
print("Total score: ",total_points)
break
if not is_valid_word(word, hand, word_list):
print("Ivalid word, please try again!")
continue
points = get_word_score(word, len(hand))
total_points += points
print(word, "earned", points,"points. Total:",total_points)
hand = update_hand(hand, word)
def play_game(word_list):
hand = deal_hand(HAND_SIZE)
while True:
cmd = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
if cmd == "n":
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
print()
elif cmd == "r":
play_hand(hand.copy(), word_list)
print()
elif cmd == "e":
break
else:
print("Invalid command.")
word_list = load_words()
play_game(word_list)
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1
# Problem Set 4
# Name: chip
# Time: 0:45
#
# Problem 1
#
def nestEggFixed(salary, save, growthRate, years):
assert type(years) == type(1) and years > 0, "Years must integer and > 0"
retirement = [salary * save * 0.01]
startyear = 1
while startyear < years:
retirement.append(retirement[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
startyear += 1
return retirement
#
# Problem 2
#
def nestEggVariable(salary, save, growthRates):
retitement = [salary * save * 0.01]
del growthRates[0]
for rate in growthRates:
retitement.append(retitement[-1] * (1 + 0.01 * rate) + salary * save * 0.01)
return retitement
#
# Problem 3
#
def postRetirement(savings, growthRates, expenses):
retitement = [savings * (1 + 0.01 * growthRates[0]) - expenses]
i = 1
while i < len(growthRates):
retitement.append(retitement[-1] * (1 + 0.01 * growthRates[i]) - expenses)
i += 1
return retitement
#
# Problem 4
#
def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
years = len(preRetireGrowthRates)
savings = nestEggVariable(salary, save, preRetireGrowthRates)[years - 1]
low = 0
height = savings
gues = (height + low) / 2
rest = postRetirement(savings, postRetireGrowthRates, gues)[years - 1]
while abs(rest) > epsilon:
if rest > 0:
low = gues
else:
height = gues
gues = (height + low) / 2
rest = postRetirement(savings, postRetireGrowthRates, gues)[years - 1]
return gues
def testNestEggFixed():
salary = 10000
save = 10
growthRate = 15
years = 5
savingsRecord = nestEggFixed(salary, save, growthRate, years)
print savingsRecord
# Output should have values close to:
# [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]
def testNestEggVariable():
salary = 10000
save = 10
growthRates = [3, 4, 5, 0, 3]
savingsRecord = nestEggVariable(salary, save, growthRates)
print savingsRecord
# Output should have values close to:
# [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]
def testPostRetirement():
savings = 100000
growthRates = [10, 5, 0, 5, 1]
expenses = 30000
savingsRecord = postRetirement(savings, growthRates, expenses)
print savingsRecord
# Output should have values close to:
# [80000.000000000015, 54000.000000000015, 24000.000000000015,
# -4799.9999999999854, -34847.999999999985]
def testFindMaxExpenses():
salary = 10000
save = 10
preRetireGrowthRates = [3, 4, 5, 0, 3]
postRetireGrowthRates = [10, 5, 0, 5, 1]
epsilon = .01
expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
postRetireGrowthRates, epsilon)
print expenses
# Output should have a value close to:
# 1229.95548986
testNestEggFixed()
testNestEggVariable()
testPostRetirement()
testFindMaxExpenses()
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 5, HW 1
#Problem Set 3
#Name: chip
#Time: 0:40
target1 = 'atgacatgcacaagtatgcat'
target2 = 'atgaatgcatggatgtaaatgcag'
key10 = 'a'
key11 = 'atg'
key12 = 'atgc'
key13 = 'atgca'
#Problem 1
def countSubStringMatch(target, key):
result = target.find(key)
count = 0
while result != -1:
count += 1
result = target.find(key, result + 1)
return count
def countSubStringMatchRecursive(target, key):
result = target.find(key)
if result == -1:
return 0;
else:
return 1 + countSubStringMatchRecursive(target[result+len(key):], key)
#Problem 2
def subStringMatchExact(target,key):
result = target.find(key)
index = ()
while result != -1:
index += (result,)
result = target.find(key, result + 1)
return index
#Problem 3
def constrainedMatchPair(firstMatch, secondMatch, length):
matches = ()
for n in firstMatch:
k = n + length + 1
if k in secondMatch:
matches += (n,)
return matches
def subStringMatchOneSub(key,target):
"""search for all locations of key in target, with one substitution"""
allAnswers = ()
for miss in range(0,len(key)):
# miss picks location for missing element
# key1 and key2 are substrings to match
key1 = key[:miss]
key2 = key[miss+1:]
print('breaking key',key,'into',key1,key2)
# match1 and match2 are tuples of locations of start of matches
# for each substring in target
match1 = subStringMatchExact(target,key1)
match2 = subStringMatchExact(target,key2)
# when we get here, we have two tuples of start points
# need to filter pairs to decide which are correct
filtered = constrainedMatchPair(match1,match2,len(key1))
allAnswers = allAnswers + filtered
print('match1',match1)
print('match2',match2)
print('possible matches for',key1,key2,'start at',filtered)
return allAnswers
#Problem 4
def subStringMatchExactlyOneSub(target, key):
return tuple(set(subStringMatchOneSub(key, target)) - set(subStringMatchExact(target, key)))
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1
#Problem Set 2
#Name: chip
#Time: 4:00
#
#Problem 1
region = range(50, 55)
for a in range (0, 20):
for b in range(0,20):
for c in range(0,20):
k = 6 * a + 9 * b + 20 * c;
if k in region:
print("{0:2}*6 + {1}*9 + {2}*20 = {3}".format(a,b,c,k));
# 2*6 + 2*9 + 1*20 = 50
# 5*6 + 1*9 + 0*20 = 51
# 2*6 + 0*9 + 2*20 = 52
# 1*6 + 3*9 + 1*20 = 53
# 9*6 + 0*9 + 0*20 = 54
# 1*6 + 1*9 + 2*20 = 55
#Problem 2
"""
Theorem is true because when we had all x, x+1,..., x+5 all next steps will repeat.
For example if we has 54 nugets we can add 6 and get 60 or 51 + 6 =57.
This works for any x, ..., x+5 values
"""
#Problem 3
def can_buy(n, ax, bx, cx):
for a in range(0,20):
for b in range(0,20):
for c in range(0,20):
k = ax * a + bx * b + cx * c
if k == n:
return True
return False
def solve(a,b,c):
count = 0
for n in range(1,200):
if not can_buy(n,a,b,c):
ans = n
count = 0
else: count += 1
if count == 6: break
print("Given package sizes <{0}>, <{1}>, <{2}>, the largest number of McNuggets that cannot be bought in exact quantity is: {3}".format(a,b,c,ans))
solve(6,9,20)
#Problem 4
solve(10,14,15)
chip
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
#Problem Set 1
#Name: chip
import math
N = 1000
log_sum = math.log(2)
print(2)
for counter in range(3, N, 2):
prime = True
for j in range(3, N - 1, 2):
if counter % j == 0 and counter != j:
prime = False
break
if prime:
log_sum += math.log(counter)
print(counter)
counter += 2;
print("Sum of logs is: ", log_sum)
print("N equals to: ", N)
print("Ration is: ", log_sum / N)
chip
1 year ago
|
 |
|
|
|