├── Final_Exam
├── Problem_3.py
├── Problem_4.py
├── Problem_5.py
├── Problem_6.py
├── Problem_6
│ ├── Problem_6-1.py
│ ├── Problem_6-2.py
│ └── Problem_6-3.py
└── Problem_7.py
├── MIT_python.PNG
├── MidTerm_Exam
├── Problem_1.py
├── Problem_2.py
├── Problem_3.py
├── Problem_4.py
├── Problem_5.py
└── Problem_6.py
├── Projects
├── Encrypted_Decrypted_Message
│ ├── ps6.py
│ ├── story.txt
│ └── words.txt
├── Hangman_Game
│ ├── __pycache__
│ │ └── ps3_hangman.cpython-35.pyc
│ ├── ps3_hangman.py
│ └── words.txt
└── Word_Game
│ ├── ps4a.py
│ ├── ps4b.py
│ ├── test_ps4a.py
│ └── words.txt
├── README.md
├── Week_1_Python-Basic
├── Excersice_Happy.py
├── Excersice_Hello_World.py
├── Excersice_vara_verb.py
├── Exercise_for.py
├── Exercise_while.py
└── Problem_Set
│ ├── Problem_1.py
│ ├── Problem_2.py
│ └── Problem_3.py
├── Week_2_Simple_Programs
├── Exercise_Grader.py
├── Exercise_eval_quadratic.py
├── Exercise_fourth_power.py
├── Exercise_gcd_iter.py
├── Exercise_gcd_recur.py
├── Exercise_guess_my_number.py
├── Exercise_is_in.py
├── Exercise_iter_power.py
├── Exercise_odd.py
├── Exercise_power_recur.py
├── Exercise_square.py
└── Problem_set
│ ├── Problem 1_Paying_Debt_off_in_a_Year.py
│ ├── Problem 2_Paying_Debt_off_in_a_Year.py
│ └── Problem 3_Using_Bisection_Search_to_Make_the_Program_Faster.py
├── Week_3_Structured_Types
├── Exercise_apply_to_each_1.py
├── Exercise_biggest.py
├── Exercise_how_many.py
├── Exercise_odd_tuples.py
└── Problem_Set
│ ├── Problem 1_Is_the_Word_Guessed.py
│ ├── Problem_2_Printing_Out_the_User's_Guess.py
│ ├── Problem_3_Printing_Out_all_Available_Letters.py
│ └── Problem_4_The_Game.py
├── Week_4_Good_Programming_Practices
├── Exercise_integer_division.py
├── Exercise_simple_divide.py
└── Problem_Set
│ ├── Problem_1_Word_Scores.py
│ ├── Problem_2_Dealing_with_Hands.py
│ ├── Problem_3_Valid_Words.py
│ ├── Problem_4_Hand_Length.py
│ ├── Problem_5_Playing_a_Hand.py
│ ├── Problem_6_Playing_a_Game.py
│ └── Problem_7_You_and_your_Computer.py
├── Week_5_Object_Oriented_Programming
├── Exercise_coordinate.py
├── Exercise_genPrimes.py
├── Exercise_hand.py
├── Exercise_int_set.py
└── Problem_Set
│ ├── Problem_1_Build_the_Shift_Dictionary_and_Apply_Shift.py
│ ├── Problem_2_PlaintextMessage.py
│ ├── Problem_3_CiphertextMessage.py
│ └── Problem_4_Decrypt_a_Story.py
└── _config.yml
/Final_Exam/Problem_3.py:
--------------------------------------------------------------------------------
1 | # Problem 3
2 | # 10/10 points (graded)
3 | # Numbers in Mandarin follow 3 simple rules.
4 |
5 | # There are words for each of the digits from 0 to 10.
6 | # For numbers 11-19, the number is pronounced as "ten digit", so for example, 16 would be pronounced (using Mandarin) as "ten six".
7 | # For numbers between 20 and 99, the number is pronounced as “digit ten digit”, so for example, 37 would be pronounced (using Mandarin) as
8 | # "three ten seven". If the digit is a zero, it is not included.
9 | # Here is a simple Python dictionary that captures the numbers between 0 and 10.
10 | # trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'}
11 |
12 | # We want to write a procedure that converts an American number (between 0 and 99), written as a string, into the equivalent Mandarin.
13 |
14 | # Example Usage
15 | # convert_to_mandarin('36') will return san shi liu
16 | # convert_to_mandarin('20') will return er shi
17 | # convert_to_mandarin('16') will return shi liu
18 |
19 | # Paste your function here
20 | def convert_to_mandarin(us_num):
21 | '''
22 | us_num, a string representing a US number 0 to 99
23 | returns the string mandarin representation of us_num
24 | '''
25 | # FILL IN YOUR CODE HERE
26 | trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si',
27 | '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'}
28 |
29 | if int(us_num) <= 10:
30 | return trans[us_num]
31 |
32 | elif int(us_num) <=19:
33 | return 'shi ' + trans[us_num[1]]
34 |
35 | elif int(us_num[1]) == 0:
36 | return trans[us_num[0]] + ' shi'
37 | else:
38 | return trans[us_num[0]] + ' shi ' + trans[us_num[1]]
39 |
--------------------------------------------------------------------------------
/Final_Exam/Problem_4.py:
--------------------------------------------------------------------------------
1 | # Problem 4
2 | # 15.0/15.0 points (graded)
3 | # Write a Python function that creates and returns a list of prime numbers between 2 and N, inclusive, sorted in increasing order. A prime number is a number that is divisible only by 1 and itself. This function takes in an integer and returns a list of integers.
4 |
5 |
6 | def primes_list(N):
7 | '''
8 | N: an integer
9 | '''
10 | # Your code here
11 | primes_no = []
12 | for i in range(2, N+1):
13 | for j in range(2, i):
14 | if i % j == 0:
15 | break
16 | else:
17 | primes_no.append(i)
18 |
19 | primes_no.sort()
20 | return primes_no
21 |
22 |
23 | print(primes_list(20))
--------------------------------------------------------------------------------
/Final_Exam/Problem_5.py:
--------------------------------------------------------------------------------
1 | # Problem 5
2 | # 20.0/20.0 points (graded)
3 | # Assume you are given two dictionaries d1 and d2, each with integer keys and integer values. You are also given a function f, that takes in two integers, performs an unknown operation on them, and returns a value.
4 |
5 | # Write a function called dict_interdiff that takes in two dictionaries (d1 and d2). The function will return a tuple of two dictionaries: a dictionary of the intersect of d1 and d2 and a dictionary of the difference of d1 and d2, calculated as follows:
6 |
7 | # intersect: The keys to the intersect dictionary are keys that are common in both d1 and d2. To get the values of the intersect dictionary, look at the common keys in d1 and d2 and apply the function f to these keys' values -- the value of the common key in d1 is the first parameter to the function and the value of the common key in d2 is the second parameter to the function. Do not implement f inside your dict_interdiff code -- assume it is defined outside.
8 | # difference: a key-value pair in the difference dictionary is (a) every key-value pair in d1 whose key appears only in d1 and not in d2 and (b) every key-value pair in d2 whose key appears only in d2 and not in d1.
9 |
10 | # Here are two examples:
11 |
12 | # If f(a, b) returns a + b
13 | # d1 = {1:30, 2:20, 3:30, 5:80}
14 | # d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
15 | # then dict_interdiff(d1, d2) returns ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
16 | # If f(a, b) returns a > b
17 | # d1 = {1:30, 2:20, 3:30}
18 | # d2 = {1:40, 2:50, 3:60}
19 | # then dict_interdiff(d1, d2) returns ({1: False, 2: False, 3: False}, {})
20 |
21 | def dict_interdiff(d1, d2):
22 | '''
23 | d1, d2: dicts whose keys and values are integers
24 | Returns a tuple of dictionaries according to the instructions above
25 | '''
26 | # Your code here
27 | intersect = {}
28 | difference = {}
29 | for i in d1.keys():
30 | if i not in d2.keys():
31 | difference[i] = d1[i]
32 | else:
33 | intersect[i] = f(d1[i], d2[i])
34 |
35 | for i in d2.keys():
36 | if i not in d1.keys():
37 | difference[i] = d2[i]
38 |
39 | return (intersect, difference)
--------------------------------------------------------------------------------
/Final_Exam/Problem_6.py:
--------------------------------------------------------------------------------
1 | # Problem 6
2 | # 20.0/20.0 points (graded)
3 | # In this problem, you will implement a class according to the specifications in the template file usresident.py. The file contains a Person class similar to what you have seen in lecture and a USResident class (a subclass of Person). Person is already implemented for you and you will have to implement two methods of USResident.
4 |
5 | # For example, the following code:
6 |
7 | # a = USResident('Tim Beaver', 'citizen')
8 | # print(a.getStatus())
9 | # b = USResident('Tim Horton', 'non-resident')
10 | # will print out:
11 |
12 | # citizen
13 |
14 | # ## will show that a ValueError was raised at a particular line
15 |
16 |
17 | ## DO NOT MODIFY THE IMPLEMENTATION OF THE Person CLASS ##
18 | class Person(object):
19 | def __init__(self, name):
20 | #create a person with name name
21 | self.name = name
22 | try:
23 | firstBlank = name.rindex(' ')
24 | self.lastName = name[firstBlank+1:]
25 | except:
26 | self.lastName = name
27 | self.age = None
28 | def getLastName(self):
29 | #return self's last name
30 | return self.lastName
31 | def setAge(self, age):
32 | #assumes age is an int greater than 0
33 | #sets self's age to age (in years)
34 | self.age = age
35 | def getAge(self):
36 | #assumes that self's age has been set
37 | #returns self's current age in years
38 | if self.age == None:
39 | raise ValueError
40 | return self.age
41 | def __lt__(self, other):
42 | #return True if self's name is lexicographically less
43 | #than other's name, and False otherwise
44 | if self.lastName == other.lastName:
45 | return self.name < other.name
46 | return self.lastName < other.lastName
47 | def __str__(self):
48 | #return self's name
49 | return self.name
50 |
51 | class USResident(Person):
52 | """
53 | A Person who resides in the US.
54 | """
55 | def __init__(self, name, status):
56 | """
57 | Initializes a Person object. A USResident object inherits
58 | from Person and has one additional attribute:
59 | status: a string, one of "citizen", "legal_resident", "illegal_resident"
60 | Raises a ValueError if status is not one of those 3 strings
61 | """
62 | # Write your code here
63 | Person.__init__(self, name)
64 | if status == "citizen" or status == "legal_resident" or status == "illegal_resident":
65 | self.status = status
66 | else:
67 | raise ValueError ('non-resident')
68 |
69 |
70 | def getStatus(self):
71 | """
72 | Returns the status
73 | """
74 | # Write your code here
75 | return self.status
--------------------------------------------------------------------------------
/Final_Exam/Problem_6/Problem_6-1.py:
--------------------------------------------------------------------------------
1 | # Problem 6-1
2 | # 10.0/10.0 points (graded)
3 | # This question has 3 parts
4 |
5 | # Consider the following hierarchy of classes:
6 |
7 | class Person(object):
8 | def __init__(self, name):
9 | self.name = name
10 | def say(self, stuff):
11 | return self.name + ' says: ' + stuff
12 | def __str__(self):
13 | return self.name
14 |
15 | class Lecturer(Person):
16 | def lecture(self, stuff):
17 | return 'I believe that ' + Person.say(self, stuff)
18 |
19 | class Professor(Lecturer):
20 | def say(self, stuff):
21 | return self.name + ' says: ' + self.lecture(stuff)
22 |
23 | class ArrogantProfessor(Professor):
24 | def say(self, stuff):
25 | return 'It is obvious that ' + self.say(stuff)
26 |
27 | # As written, this code leads to an infinite loop when using the Arrogant Professor class.
28 |
29 | # Change the definition of ArrogantProfessor so that the following behavior is achieved:
30 |
31 | # e = Person('eric')
32 | # le = Lecturer('eric')
33 | # pe = Professor('eric')
34 | # ae = ArrogantProfessor('eric')
35 |
36 | # >>> e.say('the sky is blue')
37 | # eric says: the sky is blue
38 |
39 | # >>> le.say('the sky is blue')
40 | # eric says: the sky is blue
41 |
42 | # >>> le.lecture('the sky is blue')
43 | # I believe that eric says: the sky is blue
44 |
45 | # >>> pe.say('the sky is blue')
46 | # eric says: I believe that eric says: the sky is blue
47 |
48 | # >>> pe.lecture('the sky is blue')
49 | # I believe that eric says: the sky is blue
50 |
51 | # >>> ae.say('the sky is blue')
52 | # eric says: It is obvious that eric says: the sky is blue
53 |
54 | # >>> ae.lecture('the sky is blue')
55 | # It is obvious that eric says: the sky is blue
56 |
57 | # For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own
58 | # test cases.
59 |
60 |
61 | # Paste your class here
62 | class ArrogantProfessor(Person):
63 | def say(self, stuff):
64 | return self.name + ' says: ' + 'It is obvious that ' + self.name + ' says: ' + stuff
65 | def lecture(self, stuff):
66 | return 'It is obvious that ' + self.name + ' says: ' + stuff
67 |
68 | # Correct
69 |
--------------------------------------------------------------------------------
/Final_Exam/Problem_6/Problem_6-2.py:
--------------------------------------------------------------------------------
1 | # Problem 6-2
2 | # 10.0/10.0 points (graded)
3 | # You change your mind, and now want the behavior as described in Part 1, except that you want:
4 |
5 | # >>> ae.say('the sky is blue')
6 | # eric says: It is obvious that I believe that eric says: the sky is blue
7 |
8 | # >>> ae.lecture('the sky is blue')
9 | # It is obvious that I believe that eric says: the sky is blue
10 |
11 | # Change the definition of ArrogantProfessor so that the behavior described above is achieved.
12 |
13 | # Paste ONLY your ArrogantProfessor class in the box below. Do not leave any debugging print statements.
14 |
15 | # For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own test
16 | # cases.
17 |
18 |
19 | # Paste your class here
20 | class ArrogantProfessor(Person):
21 | def say(self, stuff):
22 | return self.name + ' says: ' + 'It is obvious that I believe that ' + self.name + ' says: ' + stuff
23 | def lecture(self, stuff):
24 | return 'It is obvious that I believe that ' + self.name + ' says: ' + stuff
25 |
26 | # Correct
27 |
--------------------------------------------------------------------------------
/Final_Exam/Problem_6/Problem_6-3.py:
--------------------------------------------------------------------------------
1 | # Problem 6-3
2 | # 15.0/15.0 points (graded)
3 | # You change your mind once more. You want to keep the behavior from Part 2, but now you would like:
4 |
5 | # >>> pe.say('the sky is blue')
6 | # Prof. eric says: I believe that eric says: the sky is blue
7 |
8 | # >>> ae.say('the sky is blue')
9 | # Prof. eric says: It is obvious that I believe that eric says: the sky is blue
10 |
11 | # Change the Professor class definition in order to achieve this. You may have to modify your implmentation for a previous part to get
12 | # this to work.
13 |
14 | # Paste ONLY the Professor class in the box below. Do not leave any debugging print statements.
15 |
16 | # For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own test
17 | # cases.
18 |
19 |
20 | # Paste your class here
21 | class Professor(Lecturer):
22 | def say(self, stuff):
23 | return 'Prof. ' + self.name + ' says: ' + self.lecture(stuff)
24 |
25 | # Correct
26 |
--------------------------------------------------------------------------------
/Final_Exam/Problem_7.py:
--------------------------------------------------------------------------------
1 | # Problem 7
2 | # 20.0/20.0 points (graded)
3 | # Implement the class myDict with the methods below, which will represent a dictionary without using a dictionary object. The methods you implement below should have the same behavior as a dict object, including raising appropriate exceptions. Your code does not have to be efficient. Any code that uses a Python dictionary object will receive 0.
4 |
5 | # For example:
6 |
7 | # With a dict: | With a myDict:
8 | # -------------------------------------------------------------------------------
9 | # d = {} md = myDict() # initialize a new object using
10 | # your choice of implementation
11 |
12 | # d[1] = 2 md.assign(1,2) # use assign method to add a key,value pair
13 |
14 | # print(d[1]) print(md.getval(1)) # use getval method to get value stored for key 1
15 |
16 | # del(d[1]) md.delete(1) # use delete method to remove
17 | # key,value pair associated with key 1
18 | # class myDict(object):
19 | # """ Implements a dictionary without using a dictionary """
20 | # def __init__(self):
21 | # """ initialization of your representation """
22 | # #FILL THIS IN
23 |
24 | # def assign(self, k, v):
25 | # """ k (the key) and v (the value), immutable objects """
26 | # #FILL THIS IN
27 |
28 | # def getval(self, k):
29 | # """ k, immutable object """
30 | # #FILL THIS IN
31 |
32 | # def delete(self, k):
33 | # """ k, immutable object """
34 | # #FILL THIS IN
35 |
36 |
37 |
38 |
39 | class myDict(object):
40 | """ Implements a dictionary without using a dictionary """
41 |
42 | def __init__(self):
43 | """ initialization of your representation """
44 | #FILL THIS IN
45 | self.aDict = {}
46 |
47 | def assign(self, k, v):
48 | """ k (the key) and v (the value), immutable objects """
49 | #FILL THIS IN
50 | self.k = k
51 | self.v = v
52 | if self.k not in self.aDict:
53 | self.aDict[self.k] = self.v
54 | else:
55 | self.aDict[self.k] = self.v
56 |
57 | def getval(self, k):
58 | """ k, immutable object """
59 | #FILL THIS IN
60 |
61 | if k in self.aDict:
62 | return self.aDict[k]
63 | else:
64 | raise KeyError ('KeyError successfully raised')
65 |
66 | # return self.aDict[k]
67 |
68 | def delete(self, k):
69 | """ k, immutable object """
70 | #FILL THIS IN
71 | if k in self.aDict.keys():
72 |
73 | del self.aDict[k]
74 | else:
75 | raise KeyError('KeyError successfully raised')
76 |
77 |
--------------------------------------------------------------------------------
/MIT_python.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codenigma1/MITx-6.00.1x_Introduction-to-Computer-Science-and-Programming-Using-Python/ccf123a93956c2254d6c3e0d6d87d81536e8adc1/MIT_python.PNG
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_1.py:
--------------------------------------------------------------------------------
1 | # Problem 3
2 | # 10.0/10.0 points (graded)
3 | # Implement a function called closest_power that meets the specifications below.
4 |
5 | # For example,
6 |
7 | # closest_power(3,12) returns 2
8 | # closest_power(4,12) returns 2
9 | # closest_power(4,1) returns 0
10 |
11 | def closest_power(base, num):
12 | '''
13 | base: base of the exponential, integer > 1
14 | num: number you want to be closest to, integer > 0
15 | Find the integer exponent such that base**exponent is closest to num.
16 | Note that the base**exponent may be either greater or smaller than num.
17 | In case of a tie, return the smaller value.
18 | Returns the exponent.
19 | '''
20 | # Your code here
21 | cls_pwr = 0
22 | if base > num:
23 | cls_pwr = 0
24 | elif base == num:
25 | cls_pwr = 1
26 | else:
27 | for i in range(1, int(num)):
28 | if abs(base**i - num) <= abs(base**(i + 1) - num):
29 | cls_pwr = i
30 | break
31 | return cls_pwr
32 |
33 |
34 | print(closest_power(2, 9))
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_2.py:
--------------------------------------------------------------------------------
1 | # Problem 4
2 | # 15.0/15.0 points (graded)
3 | # Write a function called getSublists, which takes as parameters a list of integers named L and an integer named n.
4 |
5 | # assume L is not empty
6 | # assume 0 < n <= len(L)
7 | # This function returns a list of all possible sublists in L of length n without skipping elements in L. The sublists in the returned list should be ordered in the way they appear in L, with those sublists starting from a smaller index being at the front of the list.
8 |
9 | # Example 1, if L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2] and n = 4 then your function should return the list [[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4], [8, 3, 4, 5], [3, 4, 5, 7], [4, 5, 7, 7], [5, 7, 7, 2]]
10 |
11 | # Example 2, if L = [1, 1, 1, 1, 4] and n = 2 then your function should return the list [[1, 1], [1, 1], [1, 1], [1, 4]]
12 |
13 |
14 | # Your function does not have to be recursive. Do not leave any debugging print statements when you paste your code in the box.
15 |
16 | # Code Editor
17 |
18 | def getSublists(L, n):
19 | sublist = []
20 | for srt_lst in range(len(L)-n+1):
21 | sublist.append(L[srt_lst:srt_lst+n])
22 | return sublist
23 |
24 | L = [1, 1, 1, 1, 4]
25 | print(getSublists(L, 2))
26 |
27 |
28 | # Correct
29 |
30 |
31 |
32 |
33 | # def getSublists(L, n):
34 | # list_of_sublists = []
35 | # for i in range(len(L)-n+1):
36 | # list_of_sublists.append(L[i:i+n])
37 | # #create sublists of length n for every i and adds this sublist to master sublist
38 | # return list_of_sublists
39 |
40 | # L = [1, 1, 1, 1, 4]
41 | # print(getSublists(L, 2))
42 |
43 | # def longestRun(L):
44 | # for i in range(len(L),0,-1):
45 | # for list in getSublists(L,i):
46 | # if all(x<=y for x, y in zip(list, list[1:])) == True: #checks to see if list is monotonic
47 | # return i
48 |
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_3.py:
--------------------------------------------------------------------------------
1 | # Problem 5
2 | # 20.0/20.0 points (graded)
3 | # Write a Python function that returns a list of keys in aDict with the value target. The list of keys you return should be sorted in increasing order. The keys and values in aDict are both integers. (If aDict does not contain the value target, you should return an empty list.)
4 |
5 | # This function takes in a dictionary and an integer and returns a list.
6 | # This is trick problem you should figure out how it is!
7 |
8 | def keysWithValue(aDict, target):
9 | result_list = []
10 | '''
11 | aDict: a dictionary
12 | target: an integer
13 | '''
14 | # Your code here
15 | for i in aDict:
16 | if aDict[i] == target:
17 |
18 | result_list.append(i)
19 | result_list.sort()
20 |
21 | return result_list
22 |
23 | aDict = {5 : 1, 3: 90, 4: 90, 12: 90, 22: 90, 21: 100}
24 | print(keysWithValue(aDict, 90))
25 |
26 | # Correct
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_4.py:
--------------------------------------------------------------------------------
1 | # Problem 6
2 | # 20.0/20.0 points (graded)
3 | # Write a recursive Python function, given a non-negative integer N, to calculate and return the sum of its digits.
4 |
5 | # Hint: Mod (%) by 10 gives you the rightmost digit (126 % 10 is 6), while doing integer division by 10 removes the rightmost digit (126 // 10 is 12).
6 |
7 | # This function has to be recursive; you may not use loops!
8 |
9 | # This function takes in one integer and returns one integer.
10 |
11 |
12 | # Paste your function here
13 | def sumDigits(N):
14 | '''
15 | N: a non-negative integer
16 | '''
17 | # Your code here
18 | if N == 0:
19 | return 0
20 | else:
21 | return N%10 + sumDigits(N//10)
22 |
23 | print(sumDigits(12))
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_5.py:
--------------------------------------------------------------------------------
1 | # Problem 6
2 | # 20.0/20.0 points (graded)
3 | # Write a function called gcd that calculates the greatest common divisor of two positive integers. The gcd of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder.
4 |
5 | # One way is recursively, where the greatest common denominator of a and b can be calculated as gcd(a, b) = gcd(b, a mod b). Hint: remember the mod symbol is % in Python. Do not import anything.
6 |
7 | # For example, the greatest common divisor (gcd) between a = 20 and b = 12 is:
8 | # gcd(20,12) is the same as gcd(12, 20 mod 12) = gcd(12,8)
9 | # gcd(12,8) is the same as gcd(8, 12 mod 8) = gcd(8,4)
10 | # gcd(8,4) is the same as gcd(4, 8 mod 4) = gcd(4,0)
11 | # The gcd is found (and the gcd is equal to a) when we reach 0 for b.
12 |
13 | def gcd(a, b):
14 | """
15 | a, b: two positive integers
16 | Returns the greatest common divisor of a and b
17 | """
18 | #YOUR CODE HERE
19 | if b == 0:
20 | return a
21 | else:
22 | return gcd(b, a%b)
23 |
24 | print(gcd(20, 12))
25 |
26 | # Correct
--------------------------------------------------------------------------------
/MidTerm_Exam/Problem_6.py:
--------------------------------------------------------------------------------
1 | # Problem 7
2 | # 20.0/20.0 points (graded)
3 | # Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because 1∗103+2∗102+3∗101+4∗100 .
4 |
5 |
6 | def general_poly (L):
7 | """ L, a list of numbers (n0, n1, n2, ... nk)
8 | Returns a function, which when applied to a value x, returns the value
9 | n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
10 | #YOUR CODE HERE
11 | def calculate(x):
12 | k = 0
13 | for i in L:
14 | k = x*k + i
15 | return k
16 | return calculate
17 |
18 |
19 | # If you are getting "exception thrown", you should read the specification CAREFULLY for what you need to return.
--------------------------------------------------------------------------------
/Projects/Encrypted_Decrypted_Message/ps6.py:
--------------------------------------------------------------------------------
1 | import string
2 |
3 | ### DO NOT MODIFY THIS FUNCTION ###
4 | def load_words(file_name):
5 | '''
6 | file_name (string): the name of the file containing
7 | the list of words to load
8 |
9 | Returns: a list of valid words. Words are strings of lowercase letters.
10 |
11 | Depending on the size of the word list, this function may
12 | take a while to finish.
13 | '''
14 | print('Loading word list from file...')
15 | # inFile: file
16 | in_file = open(file_name, 'r')
17 | # line: string
18 | line = in_file.readline()
19 | # word_list: list of strings
20 | word_list = line.split()
21 | print(' ', len(word_list), 'words loaded.')
22 | in_file.close()
23 | return word_list
24 |
25 | ### DO NOT MODIFY THIS FUNCTION ###
26 | def is_word(word_list, word):
27 | '''
28 | Determines if word is a valid word, ignoring
29 | capitalization and punctuation
30 |
31 | word_list (list): list of words in the dictionary.
32 | word (string): a possible word.
33 |
34 | Returns: True if word is in word_list, False otherwise
35 |
36 | Example:
37 | >>> is_word(word_list, 'bat') returns
38 | True
39 | >>> is_word(word_list, 'asdf') returns
40 | False
41 | '''
42 | word = word.lower()
43 | word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
44 | return word in word_list
45 |
46 | ### DO NOT MODIFY THIS FUNCTION ###
47 | def get_story_string():
48 | """
49 | Returns: a joke in encrypted text.
50 | """
51 | f = open("story.txt", "r")
52 | story = str(f.read())
53 | f.close()
54 | return story
55 |
56 | WORDLIST_FILENAME = 'words.txt'
57 |
58 | class Message(object):
59 | ### DO NOT MODIFY THIS METHOD ###
60 | def __init__(self, text):
61 | '''
62 | Initializes a Message object
63 |
64 | text (string): the message's text
65 |
66 | a Message object has two attributes:
67 | self.message_text (string, determined by input text(When user give input))
68 | self.valid_words (list, determined using helper function load_words
69 | '''
70 | self.message_text = text
71 | self.valid_words = load_words(WORDLIST_FILENAME)
72 |
73 | ### DO NOT MODIFY THIS METHOD ###
74 | def get_message_text(self):
75 | '''
76 | Used to safely access self.message_text outside of the class
77 |
78 | Returns: self.message_text
79 | '''
80 | return self.message_text
81 |
82 | ### DO NOT MODIFY THIS METHOD ###
83 | def get_valid_words(self):
84 | '''
85 | Used to safely access a copy of self.valid_words outside of the class
86 |
87 | Returns: a COPY of self.valid_words
88 | '''
89 | return self.valid_words[:]
90 |
91 | def build_shift_dict(self, shift):
92 | '''
93 | Creates a dictionary that can be used to apply a cipher to a letter.
94 | The dictionary maps every uppercase and lowercase letter to a
95 | character shifted down the alphabet by the input shift. The dictionary
96 | should have 52 keys of all the uppercase letters and all the lowercase
97 | letters only.
98 |
99 | shift (integer): the amount by which to shift every letter of the
100 | alphabet. 0 <= shift < 26
101 |
102 | Returns: a dictionary mapping a letter (string) to
103 | another letter (string).
104 | '''
105 | # Code Here #
106 | lower_keys = list(string.ascii_lowercase)
107 | lower_values = list(string.ascii_lowercase)
108 | lower_shift_values = lower_keys[shift:] + lower_values[:shift]
109 |
110 | upper_keys = list(string.ascii_uppercase)
111 | upper_values = list(string.ascii_uppercase)
112 | upper_shift_values = upper_keys[shift:] + upper_values[:shift]
113 |
114 | combine_keys = lower_keys + upper_keys
115 | shift_combine_keys = lower_shift_values + upper_shift_values
116 |
117 | self.shift_dict = dict(zip(combine_keys, shift_combine_keys))
118 | return self.shift_dict
119 |
120 |
121 | def apply_shift(self, shift):
122 | '''
123 | Applies the Caesar Cipher to self.message_text with the input shift.
124 | Creates a new string that is self.message_text shifted down the
125 | alphabet by some number of characters determined by the input shift
126 | or put it into new string.
127 |
128 | shift (integer): the shift with which to encrypt the message.
129 | 0 <= shift < 26
130 |
131 | Returns: the message text (string) in which every character is shifted
132 | down the alphabet by the input shift
133 | '''
134 | #delete this line and replace with your code here
135 |
136 | new_text = []
137 | for i in self.message_text:
138 | if i not in self.build_shift_dict(shift).keys():
139 | new_text.append(i)
140 | else:
141 | new_text.append(self.build_shift_dict(shift)[i])
142 | return "".join(new_text)
143 |
144 |
145 | # m = Message("vaibhav")
146 | # print(m.apply_shift(2))
147 |
148 |
149 | class PlaintextMessage(Message):
150 | def __init__(self, text, shift):
151 | '''
152 | Initializes a PlaintextMessage object
153 |
154 | text (string): the message's text
155 | shift (integer): the shift associated with this message
156 |
157 | A PlaintextMessage object inherits from Message and has five attributes:
158 | self.message_text (string, determined by input text)
159 | self.valid_words (list, determined using helper function load_words)
160 | self.shift (integer, determined by input shift)
161 | self.encrypting_dict (dictionary, built using shift)
162 | self.message_text_encrypted (string, created using shift)
163 |
164 | Hint: consider using the parent class constructor so less
165 | code is repeated
166 | '''
167 | #delete this line and replace with your code here
168 | self.message_text = text
169 | self.valid_words = load_words(WORDLIST_FILENAME)
170 | self.shift = shift
171 | self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift)
172 | self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift)
173 |
174 |
175 |
176 | def get_shift(self):
177 | '''
178 | Used to safely access self.shift outside of the class
179 |
180 | Returns: self.shift
181 | '''
182 | #delete this line and replace with your code here
183 | return self.shift
184 |
185 | def get_encrypting_dict(self):
186 | '''
187 | Used to safely access a copy self.encrypting_dict outside of the class
188 |
189 | Returns: a COPY of self.encrypting_dict
190 | '''
191 | #delete this line and replace with your code here
192 | x_self.encrypting_dict = self.encrypting_dict.copy()
193 | return x_self.encrypting_dict
194 |
195 | def get_message_text_encrypted(self):
196 | '''
197 | Used to safely access self.message_text_encrypted outside of the class
198 |
199 | Returns: self.message_text_encrypted
200 | '''
201 | #delete this line and replace with your code here
202 | return self.message_text_encrypted
203 |
204 | def change_shift(self, shift):
205 | '''
206 | Changes self.shift of the PlaintextMessage and updates other
207 | attributes determined by shift (ie. self.encrypting_dict and
208 | message_text_encrypted).
209 |
210 | shift (integer): the new shift that should be associated with this message.
211 | 0 <= shift < 26
212 |
213 | Returns: nothing
214 | '''
215 | #delete this line and replace with your code here
216 | self.shift = shift
217 | self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift)
218 | self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift)
219 |
220 |
221 | class CiphertextMessage(Message):
222 | def __init__(self, text):
223 | '''
224 | Initializes a CiphertextMessage object
225 |
226 | text (string): the message's text
227 |
228 | a CiphertextMessage object has two attributes:
229 | self.message_text (string, determined by input text)
230 | self.valid_words (list, determined using helper function load_words)
231 | '''
232 | #delete this line and replace with your code here
233 | self.message_text = text
234 | self.valid_words = load_words(WORDLIST_FILENAME)
235 |
236 |
237 | def decrypt_message(self):
238 | '''
239 | Decrypt self.message_text by trying every possible shift value
240 | and find the "best" one. We will define "best" as the shift that
241 | creates the maximum number of real words when we use apply_shift(shift)
242 | on the message text. If s is the original shift value used to encrypt
243 | the message, then we would expect 26 - s to be the best shift value
244 | for decrypting it.
245 |
246 | Note: if multiple shifts are equally good such that they all create
247 | the maximum number of you may choose any of those shifts (and their
248 | corresponding decrypted messages) to return
249 |
250 | Returns: a tuple of the best shift value used to decrypt the message
251 | and the decrypted message text using that shift value
252 | '''
253 | #delete this line and replace with your code here
254 | word_no = 0
255 | high_no = 0
256 | for i in range(26):
257 | for ch in list(super(CiphertextMessage, self).apply_shift(i).split(" ")):
258 | if is_word(self.valid_words, ch):
259 | word_no += 1
260 | if word_no > high_no:
261 | high_no = word_no
262 | best_shift_value = i
263 | dec_msg = super(CiphertextMessage, self).apply_shift(i)
264 |
265 | return (best_shift_value, dec_msg)
266 |
267 |
268 | def decrypt_story():
269 | joke = (CiphertextMessage(get_story_string()))
270 | decStory = joke.decrypt_message()
271 | return decStory
272 |
273 |
274 | s = decrypt_story()
275 | print(s)
276 |
277 |
278 | #Example test case (PlaintextMessage)
279 | plaintext = input('Enter the message or words from word.txt that you want to be encrypt: ')
280 | encrypt_msg = PlaintextMessage(plaintext, 2)
281 | # print('Expected Output: Pqpugpug yqtfu')
282 | # print('"Nonsense words" now is encrypting......')
283 | print('Loading........')
284 | print('Encrypted output of the plaintext that you have enter above:', encrypt_msg.get_message_text_encrypted())
285 |
286 | # Example test case (CiphertextMessage)
287 | print('')
288 | print('Decryption function is running')
289 | ciphertext = input('Copy the above ciphertext and convert into the plain message: ')
290 | decrypt_msg = CiphertextMessage(ciphertext)
291 | # print('Expected Output:', (24, 'Nonsense words'))
292 | print('Output of encrypted message into the plaintext:', decrypt_msg.decrypt_message())
293 |
--------------------------------------------------------------------------------
/Projects/Encrypted_Decrypted_Message/story.txt:
--------------------------------------------------------------------------------
1 | Tkmu Pvyboi sc k widrsmkv mrkbkmdob mbokdon yx dro czeb yp k wywoxd dy rovz myfob kx sxceppsmsoxdvi zvkxxon rkmu. Ro rkc loox boqscdobon pyb mvkccoc kd WSD dgsmo lopybo, led rkc bozybdonvi xofob zkccon k mvkcc. Sd rkc loox dro dbknsdsyx yp dro bocsnoxdc yp Okcd Mkwzec dy lomywo Tkmu Pvyboi pyb k pog xsqrdc okmr iokb dy onemkdo sxmywsxq cdenoxdc sx dro gkic, wokxc, kxn odrsmc yp rkmusxq.
--------------------------------------------------------------------------------
/Projects/Hangman_Game/__pycache__/ps3_hangman.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/codenigma1/MITx-6.00.1x_Introduction-to-Computer-Science-and-Programming-Using-Python/ccf123a93956c2254d6c3e0d6d87d81536e8adc1/Projects/Hangman_Game/__pycache__/ps3_hangman.cpython-35.pyc
--------------------------------------------------------------------------------
/Projects/Hangman_Game/ps3_hangman.py:
--------------------------------------------------------------------------------
1 | # Hangman game
2 | #
3 |
4 | # -----------------------------------
5 | # Helper code
6 | # You don't need to understand this helper code,
7 | # but you will have to know how to use the functions
8 | # (so be sure to read the docstrings!)
9 |
10 | import random
11 |
12 | WORDLIST_FILENAME = "words.txt"
13 |
14 | def loadWords():
15 | """
16 | Returns a list of valid words. Words are strings of lowercase letters.
17 |
18 | Depending on the size of the word list, this function may
19 | take a while to finish.
20 | """
21 | print("Loading word list from file...")
22 | # inFile: file
23 | inFile = open(WORDLIST_FILENAME, 'r')
24 | # line: string
25 | line = inFile.readline()
26 | # wordlist: list of strings
27 | wordlist = line.split()
28 | print(" ", len(wordlist), "words loaded.")
29 | return wordlist
30 |
31 | def chooseWord(wordlist):
32 | """
33 | wordlist (list): list of words (strings)
34 |
35 | Returns a word from wordlist at random
36 | """
37 | return random.choice(wordlist)
38 |
39 | # end of helper code
40 | # -----------------------------------
41 |
42 | # Load the list of words into the variable wordlist
43 | # so that it can be accessed from anywhere in the program
44 | wordlist = loadWords()
45 |
46 | def isWordGuessed(secretWord, lettersGuessed):
47 | '''
48 | secretWord: string, the word the user is guessing
49 | lettersGuessed: list, what letters have been guessed so far
50 | returns: boolean, True if all the letters of secretWord are in lettersGuessed;
51 | False otherwise
52 | '''
53 | # FILL IN YOUR CODE HERE...
54 | for i in secretWord:
55 | if i not in lettersGuessed:
56 | return False;
57 | return True;
58 |
59 |
60 | def getGuessedWord(secretWord, lettersGuessed):
61 | '''
62 | secretWord: string, the word the user is guessing
63 | lettersGuessed: list, what letters have been guessed so far
64 | returns: string, comprised of letters and underscores that represents
65 | what letters in secretWord have been guessed so far.
66 | '''
67 | # FILL IN YOUR CODE HERE...
68 | result = '';
69 | for i in secretWord:
70 | if i in lettersGuessed:
71 | result += i;
72 | else:
73 | result += '_ ';
74 | return result;
75 |
76 |
77 | def getAvailableLetters(lettersGuessed):
78 | '''
79 | lettersGuessed: list, what letters have been guessed so far
80 | returns: string, comprised of letters that represents what letters have not
81 | yet been guessed.
82 | '''
83 | # In this function I just converted string into the list, then removing existing string. Finaly, it back to converted into the string because string is immutable...
84 |
85 | # FILL IN YOUR CODE HERE...
86 | import string
87 | alpha = (string.ascii_lowercase)
88 | lst_alpha = list(alpha)
89 | for i in lettersGuessed:
90 | if i in lst_alpha:
91 | # print(i)
92 | lst_alpha.remove(i)
93 |
94 | lst_alpha = ''.join(lst_alpha)
95 | return lst_alpha
96 |
97 |
98 | def hangman(secretWord):
99 | '''
100 | secretWord: string, the secret word to guess.
101 |
102 | Starts up an interactive game of Hangman.
103 |
104 | * At the start of the game, let the user know how many
105 | letters the secretWord contains.
106 |
107 | * Ask the user to supply one guess (i.e. letter) per round.
108 |
109 | * The user should receive feedback immediately after each guess
110 | about whether their guess appears in the computers word.
111 |
112 | * After each round, you should also display to the user the
113 | partially guessed word so far, as well as letters that the
114 | user has not yet guessed.
115 |
116 | Follows the other limitations detailed in the problem write-up.
117 | '''
118 | # FILL IN YOUR CODE HERE...
119 |
120 | lettersGuessed = '';
121 | j = 8;
122 | print('Welcome to the game, Hangman!')
123 | print('I am thinking of a word that is', len(secretWord), 'letters long. Please guess that word what I have just thought')
124 | print('-------------')
125 | print('Instruction: ')
126 | print('* Please put the letter at a time!')
127 | print('* Putting correct and repeat letter are not reduce from your guess limit')
128 | print('-------------')
129 | while j >= 1:
130 | # if lettersGuessed == secretWord:
131 | # print('------------')
132 | # return 'Congratulations, you won!'
133 | if isWordGuessed(secretWord, lettersGuessed) == True:
134 | print('Congratulations, you won!')
135 | break
136 | else:
137 |
138 | print('You have', j, 'guesses left.')
139 | print('Available Letters:', getAvailableLetters(lettersGuessed))
140 | guess = input('Please guess a letter: ', ).lower()
141 |
142 | if guess in secretWord and guess not in lettersGuessed:
143 | lettersGuessed = lettersGuessed + guess
144 | print('Good guess:', getGuessedWord(secretWord, lettersGuessed))
145 | print('-------------')
146 | if lettersGuessed != secretWord:
147 | continue
148 |
149 | elif guess in lettersGuessed:
150 | print("Oops! You've already guessed that letter:", getGuessedWord(secretWord, lettersGuessed))
151 | print('-------------')
152 | continue
153 | elif guess not in secretWord:
154 | print('Oops! That letter is not in my word:', getGuessedWord(secretWord, lettersGuessed))
155 | print('-------------')
156 | lettersGuessed = lettersGuessed + guess
157 | if j == 1:
158 | print('Sorry, you ran out of guesses. The word was else', secretWord)
159 | j = j - 1;
160 |
161 |
162 |
163 | # When you've completed your hangman function, uncomment these two lines
164 | # and run this file to test! (hint: you might want to pick your own
165 | # secretWord while you're testing)
166 | secretWord = chooseWord(wordlist).lower()
167 | hangman(secretWord)
168 |
--------------------------------------------------------------------------------
/Projects/Word_Game/ps4a.py:
--------------------------------------------------------------------------------
1 | # The 6.00 Word Game
2 |
3 | import random
4 | import string
5 |
6 | VOWELS = 'aeiou'
7 | CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
8 | HAND_SIZE = 10
9 |
10 | SCRABBLE_LETTER_VALUES = {
11 | '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
12 | }
13 |
14 | # -----------------------------------
15 | # Helper code
16 | # (you don't need to understand this helper code)
17 |
18 | WORDLIST_FILENAME = "words.txt"
19 |
20 | def loadWords():
21 | """
22 | Returns a list of valid words. Words are strings of lowercase letters.
23 |
24 | Depending on the size of the word list, this function may
25 | take a while to finish.
26 | """
27 | print("Instruction for making better points: ")
28 | print("1) Make the best possible word from the given character")
29 | print("2) Make sure you will get maximum point if you used them all. That means at the end you do not have any word to create new word")
30 | print(" ")
31 | print("Loading word list from file...")
32 | # inFile: file
33 | inFile = open(WORDLIST_FILENAME, 'r')
34 | # wordList: list of strings
35 | wordList = []
36 | for line in inFile:
37 | wordList.append(line.strip().lower())
38 | print(" ", len(wordList), "words loaded.")
39 | return wordList
40 |
41 | def getFrequencyDict(sequence):
42 | """
43 | Returns a dictionary where the keys are elements of the sequence
44 | and the values are integer counts, for the number of times that
45 | an element is repeated in the sequence.
46 |
47 | sequence: string or list
48 | return: dictionary
49 | """
50 | # freqs: dictionary (element_type -> int)
51 | freq = {}
52 | for x in sequence:
53 | freq[x] = freq.get(x,0) + 1
54 | return freq
55 |
56 |
57 | # (end of helper code)
58 | # -----------------------------------
59 |
60 | #
61 | # Problem #1: Scoring a word
62 | #
63 | def getWordScore(word, n):
64 | """
65 | Returns the score for a word. Assumes the word is a valid word.
66 |
67 | The score for a word is the sum of the points for letters in the
68 | word, multiplied by the length of the word, PLUS 50 points if all n
69 | letters are used on the first turn.
70 |
71 | Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
72 | worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
73 |
74 | word: string (lowercase letters)
75 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
76 | returns: int >= 0
77 | """
78 | # TO DO ... <-- Remove this comment when you code this function
79 | score = 0
80 | for i in word:
81 | score += SCRABBLE_LETTER_VALUES[i]
82 | score *= len(word)
83 | if len(word) == n:
84 | score += 50
85 | return score
86 | else:
87 | return score
88 |
89 |
90 | #
91 | # Problem #2: Make sure you understand how this function works and what it does!
92 | #
93 | def displayHand(hand):
94 | """
95 | Displays the letters currently in the hand.
96 |
97 | For example:
98 | >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
99 | Should print out something like:
100 | a x x l l l e
101 | The order of the letters is unimportant.
102 |
103 | hand: dictionary (string -> int)
104 | """
105 | for letter in hand.keys():
106 | for j in range(hand[letter]):
107 | print(letter,end=" ") # print all on the same line
108 | print() # print an empty line
109 |
110 | #
111 | # Problem #2: Make sure you understand how this function works and what it does!
112 | #
113 | def dealHand(n):
114 | """
115 | Returns a random hand containing n lowercase letters.
116 | At least n/3 the letters in the hand should be VOWELS.
117 |
118 | Hands are represented as dictionaries. The keys are
119 | letters and the values are the number of times the
120 | particular letter is repeated in that hand.
121 |
122 | n: int >= 0
123 | returns: dictionary (string -> int)
124 | """
125 | hand={}
126 | numVowels = n // 3
127 |
128 | for i in range(numVowels):
129 | x = VOWELS[random.randrange(0,len(VOWELS))]
130 | hand[x] = hand.get(x, 0) + 1
131 |
132 | for i in range(numVowels, n):
133 | x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
134 | hand[x] = hand.get(x, 0) + 1
135 |
136 | return hand
137 |
138 | #
139 | # Problem #2: Update a hand by removing letters
140 | #
141 | def updateHand(hand, word):
142 | """
143 | Assumes that 'hand' has all the letters in word.
144 | In other words, this assumes that however many times
145 | a letter appears in 'word', 'hand' has at least as
146 | many of that letter in it.
147 |
148 | Updates the hand: uses up the letters in the given word
149 | and returns the new hand, without those letters in it.
150 |
151 | Has no side effects: does not modify hand.
152 |
153 | word: string
154 | hand: dictionary (string -> int)
155 | returns: dictionary (string -> int)
156 | """
157 | hand_1 = hand.copy()
158 | for i in word:
159 | if i in hand_1.keys():
160 | hand_1[i] = hand_1.get(i, 0) -1
161 | return hand_1
162 |
163 |
164 |
165 | #
166 | # Problem #3: Test word validity
167 | #
168 | def isValidWord(word, hand, wordList):
169 | """
170 | Returns True if word is in the wordList and is entirely
171 | composed of letters in the hand. Otherwise, returns False.
172 |
173 | Does not mutate hand or wordList.
174 |
175 | word: string
176 | hand: dictionary (string -> int)
177 | wordList: list of lowercase strings
178 | """
179 | hand_1 = hand.copy()
180 | word_check = False
181 | if word in wordList:
182 | word_check = True
183 |
184 | if set(list(word)) <= set(hand_1.keys()): # set() watch the video this new concept
185 | letter_check = True
186 | else:
187 | letter_check = False
188 |
189 | for i in word:
190 | if i in hand_1.keys():
191 | hand_1[i] = hand_1.get(i, 0) -1
192 |
193 | values_check = all(i >= 0 for i in hand_1.values())
194 |
195 | if word_check == True and letter_check == True and values_check == True:
196 | return True
197 | else:
198 | return False
199 |
200 | # output = hand.copy()
201 | # word_check = False
202 | # if word in wordList:
203 | # word_check = True
204 |
205 | # letter_check = set(list(word)) <= set(output.keys())
206 |
207 | # for letter in word:
208 | # if letter in output.keys():
209 | # output[letter] -= 1
210 |
211 | # value_check = all(i >= 0 for i in output.values())
212 |
213 | # if word_check == True and letter_check == True and value_check == True:
214 | # return True
215 | # else:
216 | # return False
217 |
218 | #
219 | # Problem #4: Playing a hand
220 | #
221 |
222 | def calculateHandlen(hand):
223 | """
224 | Returns the length (number of letters) in the current hand.
225 |
226 | hand: dictionary (string-> int)
227 | returns: integer
228 | """
229 | hand_1 = hand.copy()
230 | length = []
231 | for i in hand_1.values():
232 | if i != 0:
233 | length.append(i)
234 | return sum(length)
235 |
236 | def playHand(hand, wordList, n):
237 | """
238 | Allows the user to play the given hand, as follows:
239 |
240 | * The hand is displayed.
241 | * The user may input a word or a single period (the string ".")
242 | to indicate they're done playing
243 | * Invalid words are rejected, and a message is displayed asking
244 | the user to choose another word until they enter a valid word or "."
245 | * When a valid word is entered, it uses up letters from the hand.
246 | * After every valid word: the score for that word is displayed,
247 | the remaining letters in the hand are displayed, and the user
248 | is asked to input another word.
249 | * The sum of the word scores is displayed when the hand finishes.
250 | * The hand finishes when there are no more unused letters or the user
251 | inputs a "."
252 |
253 | hand: dictionary (string -> int)
254 | wordList: list of lowercase strings
255 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
256 |
257 | """
258 | # BEGIN PSEUDOCODE (download ps4a.py to see)
259 | score = 0
260 | # As long as there are still letters left in the hand:
261 | while calculateHandlen(hand) > 0:
262 |
263 | # Display the hand
264 | print("Current hand:", end = " ")
265 | displayHand(hand)
266 |
267 | # Ask user for input
268 | inp = input("Enter word, or a '.' to indicate that you are finished: ", )
269 |
270 | # If the input is a single period:
271 | if inp == ".":
272 |
273 | # End the game (break out of the loop)
274 | break
275 |
276 | # Otherwise (the input is not a single period):
277 |
278 | else:
279 |
280 | # If the word is not valid:
281 | if isValidWord(inp, hand, wordList) == False:
282 | print("Invalid word, please try again.")
283 | print(" ")
284 |
285 | # Reject invalid word (print a message followed by a blank line)
286 |
287 | # Otherwise (the word is valid):
288 | else:
289 | score += getWordScore(inp, n)
290 |
291 | # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
292 |
293 | print(inp, "earned", getWordScore(inp, n), "points.", "Total: ", score)
294 | print(" ")
295 |
296 | # Update the hand
297 | hand = updateHand(hand, inp)
298 |
299 |
300 | # Game is over (user entered a '.' or ran out of letters), so tell user the total score
301 | if inp == ".":
302 | print("Goodbye! Total score: ", score, "point")
303 | else:
304 | print("Run out of letters. Total score: ", score, "points.")
305 |
306 | #
307 | # Problem #5: Playing a game
308 | #
309 |
310 | def playGame(wordList):
311 | """
312 | Allow the user to play an arbitrary number of hands.
313 |
314 | 1) Asks the user to input 'n' or 'r' or 'e'.
315 | * If the user inputs 'n', let the user play a new (random) hand.
316 | * If the user inputs 'r', let the user play the last hand again.
317 | * If the user inputs 'e', exit the game.
318 | * If the user inputs anything else, tell them their input was invalid.
319 |
320 | 2) When done playing the hand, repeat from step 1
321 | """
322 | # TO DO ... <-- Remove this comment when you code this function
323 | hand ={}
324 | while True:
325 |
326 | user_inp = input("Enter n to deal a new hand, r to replay the last hand, or e to end game:")
327 | if user_inp == 'e':
328 | break
329 | elif user_inp == 'n':
330 | hand = dealHand(HAND_SIZE)
331 | playHand(hand, wordList, HAND_SIZE)
332 | elif user_inp == 'r':
333 | if len(hand)>0:
334 | playHand(hand, wordList, HAND_SIZE)
335 | else:
336 | print("You have not played a hand yet. Please play a new hand first!")
337 | else:
338 | print("Invalid command.")
339 |
340 |
341 | #
342 | # Build data structures used for entire session and play game
343 | #
344 | if __name__ == '__main__':
345 | wordList = loadWords()
346 | playGame(wordList)
347 |
--------------------------------------------------------------------------------
/Projects/Word_Game/ps4b.py:
--------------------------------------------------------------------------------
1 | from ps4a import *
2 | import time
3 |
4 |
5 | #
6 | #
7 | # Computer chooses a word
8 | #
9 | #
10 | def compChooseWord(hand, wordList, n):
11 | """
12 | Given a hand and a wordList, find the word that gives
13 | the maximum value score, and return it.
14 |
15 | This word should be calculated by considering all the words
16 | in the wordList.
17 |
18 | If no words in the wordList can be made from the hand, return None.
19 |
20 | hand: dictionary (string -> int)
21 | wordList: list (string)
22 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
23 |
24 | returns: string or None
25 | """
26 | # Create a new variable to store the maximum score seen so far (initially 0)
27 | bestScore = 0
28 | # Create a new variable to store the best word seen so far (initially None)
29 | bestWord = None
30 | # For each word in the wordList
31 | for word in wordList:
32 | # If you can construct the word from your hand
33 | if isValidWord(word, hand, wordList):
34 | # find out how much making that word is worth
35 | score = getWordScore(word, n)
36 | # If the score for that word is higher than your best score
37 | if (score > bestScore):
38 | # update your best score, and best word accordingly
39 | bestScore = score
40 | bestWord = word
41 | # return the best word you found.
42 | return bestWord
43 |
44 | #
45 | # Computer plays a hand
46 | #
47 | def compPlayHand(hand, wordList, n):
48 | """
49 | Allows the computer to play the given hand, following the same procedure
50 | as playHand, except instead of the user choosing a word, the computer
51 | chooses it.
52 |
53 | 1) The hand is displayed.
54 | 2) The computer chooses a word.
55 | 3) After every valid word: the word and the score for that word is
56 | displayed, the remaining letters in the hand are displayed, and the
57 | computer chooses another word.
58 | 4) The sum of the word scores is displayed when the hand finishes.
59 | 5) The hand finishes when the computer has exhausted its possible
60 | choices (i.e. compChooseWord returns None).
61 |
62 | hand: dictionary (string -> int)
63 | wordList: list (string)
64 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
65 | """
66 | # Keep track of the total score
67 | totalScore = 0
68 | # As long as there are still letters left in the hand:
69 | while (calculateHandlen(hand) > 0) :
70 | # Display the hand
71 | print("Current Hand: ", end=' ')
72 | displayHand(hand)
73 | # computer's word
74 | word = compChooseWord(hand, wordList, n)
75 | # If the input is a single period:
76 | if word == None:
77 | # End the game (break out of the loop)
78 | break
79 |
80 | # Otherwise (the input is not a single period):
81 | else :
82 | # If the word is not valid:
83 | if (not isValidWord(word, hand, wordList)) :
84 | print('This is a terrible error! I need to check my own code!')
85 | break
86 | # Otherwise (the word is valid):
87 | else :
88 | # Tell the user how many points the word earned, and the updated total score
89 | score = getWordScore(word, n)
90 | totalScore += score
91 | print('"' + word + '" earned ' + str(score) + ' points. Total: ' + str(totalScore) + ' points')
92 | # Update hand and show the updated hand to the user
93 | hand = updateHand(hand, word)
94 | print()
95 | # Game is over (user entered a '.' or ran out of letters), so tell user the total score
96 | print('Total score: ' + str(totalScore) + ' points.')
97 |
98 |
99 | #
100 | # Problem #6: Playing a game
101 | #
102 | #
103 | def playGame(wordList):
104 | """
105 | Allow the user to play an arbitrary number of hands.
106 |
107 | 1) Asks the user to input 'n' or 'r' or 'e'.
108 | * If the user inputs 'e', immediately exit the game.
109 | * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again.
110 |
111 | 2) Asks the user to input a 'u' or a 'c'.
112 | * If the user inputs anything that's not 'c' or 'u', keep asking them again.
113 |
114 | 3) Switch functionality based on the above choices:
115 | * If the user inputted 'n', play a new (random) hand.
116 | * Else, if the user inputted 'r', play the last hand again.
117 |
118 | * If the user inputted 'u', let the user play the game
119 | with the selected hand, using playHand.
120 | * If the user inputted 'c', let the computer play the
121 | game with the selected hand, using compPlayHand.
122 |
123 | 4) After the computer or user has played the hand, repeat from step 1
124 |
125 | wordList: list (string)
126 | """
127 | # TO DO... <-- Remove this comment when you code this function
128 |
129 | while True:
130 | user_input = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ", )
131 | if user_input == 'e':
132 | break
133 | elif user_input == 'n':
134 | while True:
135 |
136 | if user_input == 'n':
137 | inp = input("Enter u to have yourself play, c to have the computer play: ", )
138 |
139 | if inp == 'u':
140 |
141 | hand = dealHand(HAND_SIZE)
142 | playHand(hand, wordList, HAND_SIZE)
143 | break
144 |
145 | elif inp == 'c':
146 |
147 | hand = dealHand(HAND_SIZE)
148 | compPlayHand(hand, wordList, HAND_SIZE)
149 | break
150 |
151 | else:
152 | print("Invalid command.")
153 |
154 | elif user_input == 'r':
155 | try:
156 | hand
157 | inp = input("Enter u to have yourself play, c to have the computer play: ", )
158 |
159 | if inp == 'u':
160 | playHand(hand, wordList, HAND_SIZE)
161 |
162 | elif inp == 'c':
163 | compPlayHand(hand, wordList, HAND_SIZE)
164 |
165 | else:
166 | print("Invalid command.")
167 | except:
168 | print("You have not played a hand yet. Please play a new hand first!")
169 | else:
170 | print("Invalid command.")
171 |
172 | #
173 | # Build data structures used for entire session and play game
174 | #
175 | if __name__ == '__main__':
176 | wordList = loadWords()
177 | playGame(wordList)
178 |
179 |
180 |
--------------------------------------------------------------------------------
/Projects/Word_Game/test_ps4a.py:
--------------------------------------------------------------------------------
1 | from ps4a import *
2 |
3 | #
4 | # Test code
5 | # You don't need to understand how this test code works (but feel free to look it over!)
6 |
7 | # To run these tests, simply run this file (open up in your IDE, then run the file as normal)
8 |
9 | def test_getWordScore():
10 | """
11 | Unit test for getWordScore
12 | """
13 | failure=False
14 | # dictionary of words and scores
15 | words = {("", 7):0, ("it", 7):4, ("was", 7):18, ("scored", 7):54, ("waybill", 7):155, ("outgnaw", 7):127, ("fork", 7):44, ("fork", 4):94}
16 | for (word, n) in words.keys():
17 | score = getWordScore(word, n)
18 | if score != words[(word, n)]:
19 | print("FAILURE: test_getWordScore()")
20 | print("\tExpected", words[(word, n)], "points but got '" + str(score) + "' for word '" + word + "', n=" + str(n))
21 | failure=True
22 | if not failure:
23 | print("SUCCESS: test_getWordScore()")
24 |
25 | # end of test_getWordScore
26 |
27 |
28 | def test_updateHand():
29 | """
30 | Unit test for updateHand
31 | """
32 | # test 1
33 | handOrig = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
34 | handCopy = handOrig.copy()
35 | word = "quail"
36 |
37 | hand2 = updateHand(handCopy, word)
38 | expectedHand1 = {'l':1, 'm':1}
39 | expectedHand2 = {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
40 | if hand2 != expectedHand1 and hand2 != expectedHand2:
41 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
42 | print("\tReturned: ", hand2, "\n\t-- but expected:", expectedHand1, "or", expectedHand2)
43 |
44 | return # exit function
45 | if handCopy != handOrig:
46 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
47 | print("\tOriginal hand was", handOrig)
48 | print("\tbut implementation of updateHand mutated the original hand!")
49 | print("\tNow the hand looks like this:", handCopy)
50 |
51 | return # exit function
52 |
53 | # test 2
54 | handOrig = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
55 | handCopy = handOrig.copy()
56 | word = "evil"
57 |
58 | hand2 = updateHand(handCopy, word)
59 | expectedHand1 = {'v':1, 'n':1, 'l':1}
60 | expectedHand2 = {'e':0, 'v':1, 'n':1, 'i':0, 'l':1}
61 | if hand2 != expectedHand1 and hand2 != expectedHand2:
62 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
63 | print("\tReturned: ", hand2, "\n\t-- but expected:", expectedHand1, "or", expectedHand2)
64 |
65 | return # exit function
66 |
67 | if handCopy != handOrig:
68 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
69 | print("\tOriginal hand was", handOrig)
70 | print("\tbut implementation of updateHand mutated the original hand!")
71 | print("\tNow the hand looks like this:", handCopy)
72 |
73 | return # exit function
74 |
75 | # test 3
76 | handOrig = {'h': 1, 'e': 1, 'l': 2, 'o': 1}
77 | handCopy = handOrig.copy()
78 | word = "hello"
79 |
80 | hand2 = updateHand(handCopy, word)
81 | expectedHand1 = {}
82 | expectedHand2 = {'h': 0, 'e': 0, 'l': 0, 'o': 0}
83 | if hand2 != expectedHand1 and hand2 != expectedHand2:
84 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
85 | print("\tReturned: ", hand2, "\n\t-- but expected:", expectedHand1, "or", expectedHand2)
86 |
87 | return # exit function
88 |
89 | if handCopy != handOrig:
90 | print("FAILURE: test_updateHand('"+ word +"', " + str(handOrig) + ")")
91 | print("\tOriginal hand was", handOrig)
92 | print("\tbut implementation of updateHand mutated the original hand!")
93 | print("\tNow the hand looks like this:", handCopy)
94 |
95 | return # exit function
96 |
97 | print("SUCCESS: test_updateHand()")
98 |
99 | # end of test_updateHand
100 |
101 | def test_isValidWord(wordList):
102 | """
103 | Unit test for isValidWord
104 | """
105 | failure=False
106 | # test 1
107 | word = "hello"
108 | handOrig = getFrequencyDict(word)
109 | handCopy = handOrig.copy()
110 |
111 | if not isValidWord(word, handCopy, wordList):
112 | print("FAILURE: test_isValidWord()")
113 | print("\tExpected True, but got False for word: '" + word + "' and hand:", handOrig)
114 |
115 | failure = True
116 |
117 | # Test a second time to see if wordList or hand has been modified
118 | if not isValidWord(word, handCopy, wordList):
119 | print("FAILURE: test_isValidWord()")
120 |
121 | if handCopy != handOrig:
122 | print("\tTesting word", word, "for a second time - be sure you're not modifying hand.")
123 | print("\tAt this point, hand ought to be", handOrig, "but it is", handCopy)
124 |
125 | else:
126 | print("\tTesting word", word, "for a second time - have you modified wordList?")
127 | wordInWL = word in wordList
128 | print("The word", word, "should be in wordList - is it?", wordInWL)
129 |
130 | print("\tExpected True, but got False for word: '" + word + "' and hand:", handCopy)
131 |
132 | failure = True
133 |
134 |
135 | # test 2
136 | hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
137 | word = "rapture"
138 |
139 | if isValidWord(word, hand, wordList):
140 | print("FAILURE: test_isValidWord()")
141 | print("\tExpected False, but got True for word: '" + word + "' and hand:", hand)
142 |
143 | failure = True
144 |
145 | # test 3
146 | hand = {'n': 1, 'h': 1, 'o': 1, 'y': 1, 'd':1, 'w':1, 'e': 2}
147 | word = "honey"
148 |
149 | if not isValidWord(word, hand, wordList):
150 | print("FAILURE: test_isValidWord()")
151 | print("\tExpected True, but got False for word: '"+ word +"' and hand:", hand)
152 |
153 | failure = True
154 |
155 | # test 4
156 | hand = {'r': 1, 'a': 3, 'p': 2, 't': 1, 'u':2}
157 | word = "honey"
158 |
159 | if isValidWord(word, hand, wordList):
160 | print("FAILURE: test_isValidWord()")
161 | print("\tExpected False, but got True for word: '" + word + "' and hand:", hand)
162 |
163 | failure = True
164 |
165 | # test 5
166 | hand = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
167 | word = "evil"
168 |
169 | if not isValidWord(word, hand, wordList):
170 | print("FAILURE: test_isValidWord()")
171 | print("\tExpected True, but got False for word: '" + word + "' and hand:", hand)
172 |
173 | failure = True
174 |
175 | # test 6
176 | word = "even"
177 |
178 | if isValidWord(word, hand, wordList):
179 | print("FAILURE: test_isValidWord()")
180 | print("\tExpected False, but got True for word: '" + word + "' and hand:", hand)
181 | print("\t(If this is the only failure, make sure isValidWord() isn't mutating its inputs)")
182 |
183 | failure = True
184 |
185 | if not failure:
186 | print("SUCCESS: test_isValidWord()")
187 |
188 |
189 | wordList = loadWords()
190 | print("----------------------------------------------------------------------")
191 | print("Testing getWordScore...")
192 | test_getWordScore()
193 | print("----------------------------------------------------------------------")
194 | print("Testing updateHand...")
195 | test_updateHand()
196 | print("----------------------------------------------------------------------")
197 | print("Testing isValidWord...")
198 | test_isValidWord(wordList)
199 | print("----------------------------------------------------------------------")
200 | print("All done!")
201 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
2 | "**[Introduction to Computer Science and Programming Using Python](https://courses.edx.org/certificates/153ba01cd1be42488525544ed5925f4f)**," is 3 credits course from MITx on the edX platform. In this course provide basic to hard excercise and problem sets. So, the user get gradually understanding in python.
3 |
4 |
5 |
6 | # Projects:
7 | 1. [Hangman](https://repl.it/@codenigma1/UltimateDescriptiveFlashdrive-1): If you have dare, beat the computer.
8 | 2. [WordGame](https://repl.it/@codenigma1/OnerlookedDifferentVariable): Create the word with possible letter. It build both version, first play the game by yourself, then repeat the same game with computer and see who make highest score.
9 | 3. [Encryption and Decryption messages](https://repl.it/@codenigma1/CheapAdventurousLogic): This basic encryption and decryption message. it remind me Alan Turing enigma machine.
10 |
11 | # Couse Syllabus:
12 | # Week 1
13 | Lecture 1 – Introduction to Python:
14 | • Knowledge
15 | • Machines
16 | • Languages
17 | • Types
18 | • Variables
19 | • Operators and Branching
20 |
21 | Lecture 2 – Core elements of programs
22 | • Bindings
23 | • Strings
24 | • Input/output
25 | • IDEs
26 | • Control Flow
27 | • Iteration
28 | • Guess and Check
29 |
30 | # Week 2:
31 | Lecture 3 – Simple Programs:
32 | • Approximate Solutions
33 | • Bisection Search
34 | • Floats and Fractions
35 | • Newton-Raphson
36 |
37 | Lecture 4 – Functions:
38 | • Decomposition and Abstraction
39 | • Functions and Scope
40 | • Keyword Arguments
41 | • Specifications
42 | • Iteration vs Recursion
43 | • Inductive Reasoning
44 | • Towers of Hanoi
45 | • Fibonacci
46 | • Recursion on non-numerics
47 | • Files
48 |
49 | # Week 3
50 | Lecture 5 – Tuples and Lists:
51 | • Tuples
52 | • Lists
53 | • List Operations
54 | • Mutation, Aliasing, Cloning
55 |
56 | Lecture 6 – Dictionaries:
57 | • Functions as Objects
58 | • Dictionaries
59 | • Example with a Dictionary
60 | • Fibonacci and Dictionaries
61 | • Global Variables
62 |
63 | # MidTerm Exam ((8 hours’ time limits))
64 |
65 | # Week 4
66 | Lecture 7 – Debugging:
67 | • Programming Challenges
68 | • Classes of Tests
69 | • Bugs
70 | • Debugging
71 | • Debugging Examples
72 |
73 | Lecture 8 – Assertions and Exceptions
74 | • Assertions
75 | • Exceptions
76 | • Exception Examples
77 |
78 | # Week 5
79 | Lecture 9 – Classes and Inheritance:
80 | • Object Oriented Programming
81 | • Class Instances
82 | • Methods
83 | • Classes Examples
84 | • Why OOP
85 | • Hierarchies
86 | • Your Own Types
87 |
88 | Lecture 10 – An Extended Example:
89 | • Building a Class
90 | • Viualizing the Hierarchy
91 | • Adding another Class
92 | • Using Inherited Methods
93 | • Gradebook Example
94 | • Generators
95 |
96 | # Week 6
97 | Lecture 11 – Computational Complexity:
98 | • Program Efficiency
99 | • Big Oh Notation
100 | • Complexity Classes
101 | • Analyzing Complexity
102 |
103 | Lecture 12 – Searching and Sorting Algorithms:
104 | • Indirection
105 | • Linear Search
106 | • Bisection Search
107 | • Bogo and Bubble Sort
108 | • Selection Sort
109 | • Merge Sort
110 |
111 | # Week 7
112 | Lecture 13 – Visualization of Data:
113 | • Visualizing Results
114 | • Overlapping Displays
115 | • Adding More Documentation
116 | • Changing Data Display
117 | • An Example
118 | Lecture 14 – Summary
119 |
120 |
121 | # Final Exam (8 hours time limits)
122 |
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Excersice_Happy.py:
--------------------------------------------------------------------------------
1 | # Exercise: happy
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 3 minutes
4 |
5 | # Write a piece of Python code that prints out the string 'hello world' if the value of an integer variable, happy, is strictly greater than 2.
6 |
7 | None
8 | if happy > 2:
9 | print ('hello world')
10 |
11 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Excersice_Hello_World.py:
--------------------------------------------------------------------------------
1 | # Exercise: hello world
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 2 minutes
4 |
5 | # Write a piece of Python code that prints out the string hello world
6 |
7 | h = 'hello world'
8 | print (h)
9 |
10 | #Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Excersice_vara_verb.py:
--------------------------------------------------------------------------------
1 | # Exercise: vara varb
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # Assume that two variables, varA and varB, are assigned values, either numbers or strings.
6 |
7 | # Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
8 |
9 | # "string involved" if either varA or varB are strings
10 |
11 | # "bigger" if varA is larger than varB
12 |
13 | # "equal" if varA is equal to varB
14 |
15 | # "smaller" if varA is smaller than varB
16 |
17 | # Assume that variables are defined for you by our grader code. Simply write code assuming you know the values of the variables.
18 |
19 | if type(varA) == str or type(varB) == str:
20 | print('string involved')
21 | elif varA > varB:
22 | print('bigger')
23 | elif varA == varB:
24 | print('equal')
25 | elif varA < varB:
26 | print('smaller')
27 |
28 |
29 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Exercise_for.py:
--------------------------------------------------------------------------------
1 | # Exercise: while exercise 1
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # In this problem you'll be given a chance to practice writing some while loops.
6 |
7 | # 1. Convert the following into code that uses a while loop.
8 |
9 | # print 2
10 | # prints 4
11 | # prints 6
12 | # prints 8
13 | # prints 10
14 | # prints Goodbye!
15 |
16 | num = [2, 4, 6, 8, 10]
17 | for i in num:
18 | print (i)
19 | print ('Goodbye!')
20 |
21 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Exercise_while.py:
--------------------------------------------------------------------------------
1 | # Exercise: while exercise 1
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # In this problem you'll be given a chance to practice writing some while loops.
6 |
7 | # 1. Convert the following into code that uses a while loop.
8 |
9 | # print 2
10 | # prints 4
11 | # prints 6
12 | # prints 8
13 | # prints 10
14 | # prints Goodbye!
15 |
16 | num = 2
17 | while num <= 10:
18 | print (num)
19 | num = num + 2
20 | print ('Goodbye!')
21 |
22 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Problem_Set/Problem_1.py:
--------------------------------------------------------------------------------
1 | # Problem 1
2 | # 10.0/10.0 points (graded)
3 | # Assume s is a string of lower case characters.
4 |
5 | # Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:
6 |
7 | # Number of vowels: 5
8 |
9 | count = 0
10 | for vow in s:
11 | if vow == "a" or vow == "e" or vow == "i" or vow == "o" or vow == "u":
12 | count = count + 1
13 | print("Number of vowels: " + str(count))
14 |
15 |
16 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Problem_Set/Problem_2.py:
--------------------------------------------------------------------------------
1 | # Problem 2
2 | # 10.0/10.0 points (graded)
3 | # Assume s is a string of lower case characters.
4 |
5 | # Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
6 | # Number of times bob occurs is: 2
7 |
8 |
9 | # Paste your code into this box
10 | count = 0
11 | for b in range(len(s)):
12 | if s[b:].startswith('bob'):
13 | count = count + 1
14 | print ('Number of times bob occurs is:', count)
15 |
16 | # Correct
--------------------------------------------------------------------------------
/Week_1_Python-Basic/Problem_Set/Problem_3.py:
--------------------------------------------------------------------------------
1 | # Problem 3
2 | # 15.0/15.0 points (graded)
3 | # Assume s is a string of lower case characters.
4 |
5 | # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print:
6 |
7 | # Longest substring in alphabetical order is: beggh
8 |
9 | # In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print:
10 | # Longest substring in alphabetical order is: abc
11 |
12 | # Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.
13 |
14 |
15 | morelength=0
16 | present=s[0]
17 | longest=s[0]
18 | for i in range(len(s) - 1):
19 | # print (i)
20 | if s[i + 1] >= s[i]:
21 | # print (s[i + 1])
22 | present = present + s[i + 1]
23 | # print (present)
24 | if len(present) > morelength:
25 | morelength = len(present)
26 | longest = present
27 | # print (longest)
28 | else:
29 | present=s[i + 1]
30 | # print (present)
31 | print ('Longest substring in alphabetical order is: ', longest)
32 |
33 |
34 | # Correct
35 |
36 |
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_Grader.py:
--------------------------------------------------------------------------------
1 | # Grader
2 | # 10.0/10.0 points (ungraded)
3 | # A regular polygon has n number of sides. Each side has length s.
4 |
5 | # The area of a regular polygon is: abs(0.25*n*s**2)/(math.tan(math.pi/n))
6 | # The perimeter of a polygon is: length of the boundary of the polygon
7 | # Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places.
8 |
9 | # Hint: What to import?
10 | # Which library should you be importing at the beginning of your code in order to call the tan function and to get the pi constant?
11 |
12 | # This is an optional exercise, but great for extra practice!
13 |
14 | import math
15 | def polysum(n, s):
16 | area = abs(0.25*n*s**2)/(math.tan(math.pi/n))
17 | perimeter = (n*s)**2
18 | return round((area + perimeter), 4)
19 |
20 |
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_eval_quadratic.py:
--------------------------------------------------------------------------------
1 | # Exercise: eval quadratic
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # Write a Python function, evalQuadratic(a, b, c, x), that returns the value of the quadratic a*x^2 + b*c + c.
6 |
7 | # This function takes in four numbers and returns a single number.
8 |
9 | def evalQuadratic(a, b, c, x):
10 | '''
11 | a, b, c: numerical values for the coefficients of a quadratic equation
12 | x: numerical value at which to evaluate the quadratic.
13 | '''
14 | return ((a*(x*x)) + (b*x) + c)
15 |
16 | print (evalQuadratic (1, 2, 3, 4))
17 |
18 |
19 | # Correct
20 |
21 |
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_fourth_power.py:
--------------------------------------------------------------------------------
1 | # Exercise: fourth power
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 2 minutes
4 |
5 | # Write a Python function, fourthPower, that takes in one number and returns that value raised to the fourth power.
6 |
7 | # You should use the square procedure that you defined in an earlier exercise (you don't need to redefine square in this box; when you call square, the grader will use our definition).
8 |
9 | # This function takes in one number and returns one number.
10 |
11 | def fourthPower(x):
12 | '''
13 | x: int or float.
14 | '''
15 | # Your code here
16 | return square(square(x))
17 |
18 |
19 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_gcd_iter.py:
--------------------------------------------------------------------------------
1 | # Exercise: gcd iter
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example,
6 |
7 | # gcd(2, 12) = 2
8 |
9 | # gcd(6, 12) = 6
10 |
11 | # gcd(9, 12) = 3
12 |
13 | # gcd(17, 12) = 1
14 |
15 | # Write an iterative function, gcdIter(a, b), that implements this idea. One easy way to do this is to begin with a test value equal to the smaller of the two input arguments, and iteratively reduce this test value by 1 until you either reach a case where the test divides both a and b without remainder, or you reach 1.
16 |
17 | def gcdIter(a, b):
18 | '''
19 | a, b: positive integers
20 |
21 | returns: a positive integer, the greatest common divisor of a & b.
22 | '''
23 | # Your code here
24 | divisor = b;
25 | result = 0;
26 | while 1 <= divisor :
27 | if a%divisor == 0 and b%divisor == 0:
28 | if divisor >= result :
29 | result = divisor;
30 | return result;
31 | else :
32 | result = result;
33 | else :
34 | result = 0;
35 | divisor -=1;
36 | # return result;
37 |
38 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_gcd_recur.py:
--------------------------------------------------------------------------------
1 | # Exercise: gcd recur
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 6 minutes
4 |
5 | # The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example,
6 |
7 | # gcd(2, 12) = 2
8 |
9 | # gcd(6, 12) = 6
10 |
11 | # gcd(9, 12) = 3
12 |
13 | # gcd(17, 12) = 1
14 |
15 | # A clever mathematical trick (due to Euclid) makes it easy to find greatest common divisors. Suppose that a and b are two positive integers:
16 |
17 | # If b = 0, then the answer is a
18 |
19 | # Otherwise, gcd(a, b) is the same as gcd(b, a % b)
20 |
21 | # See this website for an example of Euclid's algorithm being used to find the gcd.
22 |
23 | # Write a function gcdRecur(a, b) that implements this idea recursively. This function takes in two positive integers and returns one integer.
24 |
25 | def gcdRecur(a, b):
26 | '''
27 | a, b: positive integers
28 |
29 | returns: a positive integer, the greatest common divisor of a & b.
30 | '''
31 | # Your code here
32 | if b == 0:
33 | return a;
34 | else :
35 | return gcdRecur(b, a%b)
36 |
37 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_guess_my_number.py:
--------------------------------------------------------------------------------
1 | # Exercise: guess my number
2 | # 10.0/10.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 15 minutes
4 |
5 | # In this problem, you'll create a program that guesses a secret number!
6 |
7 | # The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number!
8 |
9 | # Here is a transcript of an example session:
10 |
11 | # Please think of a number between 0 and 100!
12 | # Is your secret number 50?
13 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
14 | # Is your secret number 75?
15 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
16 | # Is your secret number 87?
17 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
18 | # Is your secret number 81?
19 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
20 | # Is your secret number 84?
21 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
22 | # Is your secret number 82?
23 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
24 | # Is your secret number 83?
25 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
26 | # Game over. Your secret number was: 83
27 |
28 |
29 | # Important
30 | # Hint: Endpoints
31 | # ** Your program should use bisection search. So think carefully what that means. What will the first guess always be? How should you calculate subsequent guesses?
32 |
33 | # ** Your initial endpoints should be 0 and 100. Do not optimize your subsequent endpoints by making them be the halfway point plus or minus 1. Rather, just make them be the halfway point.
34 |
35 | # Python Trick: Printing on the same line
36 | # Try the following in your console:
37 |
38 | # # Notice how if we have two print statements
39 | # print("Hi")
40 | # print("there")
41 |
42 | # # The output will have each string on a separate line:
43 | # Hi
44 | # there
45 |
46 | # # Now try adding the following:
47 | # print("Hi",end='')
48 | # print("there")
49 | # print("Hi",end='*')
50 | # print("there")
51 |
52 | # # The output will place the subsequent string on the same line
53 | # # and will connect the two prints with the character given by end
54 | # Hithere
55 | # Hi*there
56 |
57 | # Click to See Test Cases
58 | # Test Cases to Test Your Code With. Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
59 |
60 | # Test case 1. Secret guess = 42
61 |
62 | # Please think of a number between 0 and 100!
63 | # Is your secret number 50?
64 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
65 | # Is your secret number 25?
66 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
67 | # Is your secret number 37?
68 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
69 | # Is your secret number 43?
70 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
71 | # Is your secret number 40?
72 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
73 | # Is your secret number 41?
74 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
75 | # Is your secret number 42?
76 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
77 | # Game over. Your secret number was: 42
78 | # Test case 2. Secret guess = 91
79 |
80 | # Please think of a number between 0 and 100!
81 | # Is your secret number 50?
82 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
83 | # Is your secret number 75?
84 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
85 | # Is your secret number 87?
86 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
87 | # Is your secret number 93?
88 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
89 | # Is your secret number 90?
90 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
91 | # Is your secret number 91?
92 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. y
93 | # Sorry, I did not understand your input.
94 | # Is your secret number 91?
95 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
96 | # Game over. Your secret number was: 91
97 |
98 | # Note: your program should use input to obtain the user's input! Be sure to handle the case when the user's input is not one of h, l, or c.
99 |
100 | # When the user enters something invalid, you should print out a message to the user explaining you did not understand their input. Then, you should re-ask the question, and prompt again for input. For example:
101 |
102 | # Is your secret number 91?
103 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. y
104 | # Sorry, I did not understand your input.
105 | # Is your secret number 91?
106 | # Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
107 |
108 |
109 | low = 0
110 | high = 100
111 | print ('Please think of a number between 0 and 100!')
112 | while True:
113 | ans = (high + low)//2
114 | print ('Is your secret number', ans, '?')
115 | inp = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
116 | if inp == 'h':
117 | high = ans
118 | elif inp == 'l':
119 | low = ans
120 | elif inp == 'c':
121 | print ('Game over. Your secret number was:', ans)
122 | break
123 | else :
124 | print ('Sorry, I did not understand your input.')
125 |
126 |
127 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_is_in.py:
--------------------------------------------------------------------------------
1 | # Exercise: is in
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 18 minutes
4 |
5 | # We can use the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.
6 |
7 | # First, test the middle character of a string against the character you're looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
8 |
9 | # If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string. (Note that you can compare characters using Python's < function.)
10 |
11 | # Implement the function isIn(char, aStr) which implements the above idea recursively to test if char is in aStr. char will be a single character and aStr will be a string that is in alphabetical order. The function should return a boolean value.
12 |
13 | # As you design the function, think very carefully about what the base cases should be.
14 |
15 | def isIn(char, aStr):
16 | '''
17 | char: a single character
18 | aStr: an alphabetized string
19 |
20 | returns: True if char is in aStr; False otherwise
21 | '''
22 | # Your code here
23 | if aStr == "":
24 | return False;
25 | elif len(aStr) == 1 and aStr!= char:
26 | return False;
27 | elif len(aStr) == 1 and aStr == char:
28 | return True;
29 | elif aStr[(len(aStr)//2)] == char:
30 | return True;
31 | else:
32 | # if char < aStr[(len(aStr)//2)]:
33 | return isIn(char, aStr[:(len(aStr)//2)]) or isIn(char, aStr[(len(aStr)//2):])
34 |
35 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_iter_power.py:
--------------------------------------------------------------------------------
1 | # Exercise: iter power
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 6 minutes
4 |
5 | # Write an iterative function iterPower(base, exp) that calculates the exponential base^exp by simply using successive multiplication. For example, iterPower(base, exp) should compute base^exp by multiplying base times itself exp times. Write such a function below.
6 |
7 | # This function should take in two values - base can be a float or an integer; exp will be an integer 0. It should return one numerical value. Your code must be iterative - use of the ** operator is not allowed.
8 |
9 |
10 | def iterPower(base, exp):
11 | '''
12 | base: int or float.
13 | exp: int >= 0
14 |
15 | returns: int or float, base^exp
16 | '''
17 | # Your code here
18 | total = 1;
19 | while exp > 0:
20 | total = total * base;
21 | exp -= 1;
22 | return total;
23 |
24 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_odd.py:
--------------------------------------------------------------------------------
1 | # Exercise: odd
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 3 minutes
4 |
5 | # Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise.
6 |
7 | # You should use the % (mod) operator, not if.
8 |
9 | # This function takes in one number and returns a boolean.
10 |
11 | def odd(x):
12 | '''
13 | x: int
14 |
15 | returns: True if x is odd, False otherwise
16 | '''
17 | # Your code here
18 | return x%2 != 0
19 |
20 |
21 |
22 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_power_recur.py:
--------------------------------------------------------------------------------
1 | # Exercise: power recur
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 7 minutes
4 |
5 | # In Problem 1, we computed an exponential by iteratively executing successive multiplications. We can use the same idea, but in a recursive function.
6 |
7 | # Write a function recurPower(base, exp) which computes base^exp by recursively calling itself to solve a smaller version of the same problem, and then multiplying the result by base to solve the initial problem.
8 |
9 | # This function should take in two values - base can be a float or an integer; exp will be an integer . It should return one numerical value. Your code must be recursive - use of the ** operator or looping constructs is not allowed.
10 |
11 | def recurPower(base, exp):
12 | '''
13 | base: int or float.
14 | exp: int >= 0
15 |
16 | returns: int or float, base^exp
17 | '''
18 | # Your code here
19 | if exp == 0:
20 | return 1;
21 | else :
22 | return base * recurPower(base, exp - 1);
23 |
24 |
25 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Exercise_square.py:
--------------------------------------------------------------------------------
1 | # Exercise: square
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 3 minutes
4 |
5 | # Write a Python function, square, that takes in one number and returns the square of that number.
6 |
7 | # This function takes in one number and returns one number.
8 |
9 | def square(x):
10 | '''
11 | x: int or float.
12 | '''
13 | return x*x
14 |
15 | print (square (4))
16 |
17 | # Correct
18 |
19 |
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Problem_set/Problem 1_Paying_Debt_off_in_a_Year.py:
--------------------------------------------------------------------------------
1 | # Problem 1 - Paying Debt off in a Year
2 | # 10.0/10.0 points (graded)
3 | # Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
4 |
5 | # The following variables contain values as described below:
6 |
7 | # balance - the outstanding balance on the credit card
8 |
9 | # annualInterestRate - annual interest rate as a decimal
10 |
11 | # monthlyPaymentRate - minimum monthly payment rate as a decimal
12 |
13 | # For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print
14 |
15 | # Remaining balance: 813.41
16 | # instead of
17 |
18 | # Remaining balance: 813.4141998135
19 | # So your program only prints out one thing: the remaining balance at the end of the year in the format:
20 |
21 | # Remaining balance: 4784.0
22 | # A summary of the required math is found below:
23 |
24 | # Monthly interest rate= (Annual interest rate) / 12.0
25 | # Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
26 | # Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
27 | # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
28 |
29 | # We provide sample test cases below. We suggest you develop your code on your own machine, and make sure your code passes the sample test cases, before you paste it into the box below.
30 |
31 |
32 | # Test Cases to Test Your Code With. Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
33 |
34 | # Click to See Problem 1 Test Cases
35 | # Note: Depending on where you round in this problem, your answers may be off by a few cents in either direction. Do not worry if your solution is within +/- 0.05 of the correct answer. Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
36 |
37 | # Test Cases:
38 |
39 | # # Test Case 1:
40 | # balance = 42
41 | # annualInterestRate = 0.2
42 | # monthlyPaymentRate = 0.04
43 |
44 | # # Result Your Code Should Generate Below:
45 | # Remaining balance: 31.38
46 |
47 | # # To make sure you are doing calculation correctly, this is the
48 | # # remaining balance you should be getting at each month for this example
49 | # Month 1 Remaining balance: 40.99
50 | # Month 2 Remaining balance: 40.01
51 | # Month 3 Remaining balance: 39.05
52 | # Month 4 Remaining balance: 38.11
53 | # Month 5 Remaining balance: 37.2
54 | # Month 6 Remaining balance: 36.3
55 | # Month 7 Remaining balance: 35.43
56 | # Month 8 Remaining balance: 34.58
57 | # Month 9 Remaining balance: 33.75
58 | # Month 10 Remaining balance: 32.94
59 | # Month 11 Remaining balance: 32.15
60 | # Month 12 Remaining balance: 31.38
61 |
62 |
63 |
64 | # Test Case 2:
65 | # balance = 484
66 | # annualInterestRate = 0.2
67 | # monthlyPaymentRate = 0.04
68 |
69 | # Result Your Code Should Generate Below:
70 | # Remaining balance: 361.61
71 |
72 |
73 | # Paste your code into this box
74 | i = 1;
75 | while i <= 12:
76 | balance = balance - (balance * monthlyPaymentRate);
77 | balance = balance + (balance * annualInterestRate/12.0)
78 | # print ("Month", i, "Remaining balance: ", round(balance, 2));
79 | i = i + 1;
80 | print("Remaining balance:", round(balance, 2))
81 |
82 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Problem_set/Problem 2_Paying_Debt_off_in_a_Year.py:
--------------------------------------------------------------------------------
1 | # Problem 2 - Paying Debt Off in a Year
2 | # 15.0/15.0 points (graded)
3 | # Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
4 |
5 | # In this problem, we will not be dealing with a minimum monthly payment rate.
6 |
7 | # The following variables contain values as described below:
8 |
9 | # balance - the outstanding balance on the credit card
10 |
11 | # annualInterestRate - annual interest rate as a decimal
12 |
13 | # The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
14 |
15 | # Lowest Payment: 180
16 | # Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
17 |
18 | # Monthly interest rate = (Annual interest rate) / 12.0
19 | # Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
20 | # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
21 |
22 | # Test Cases to Test Your Code With. Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
23 |
24 | # Click to See Problem 2 Test Cases
25 | # Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
26 |
27 | # Test Cases:
28 |
29 |
30 | # Test Case 1:
31 | # balance = 3329
32 | # annualInterestRate = 0.2
33 |
34 | # Result Your Code Should Generate:
35 | # -------------------
36 | # Lowest Payment: 310
37 |
38 |
39 |
40 | # Test Case 2:
41 | # balance = 4773
42 | # annualInterestRate = 0.2
43 |
44 | # Result Your Code Should Generate:
45 | # -------------------
46 | # Lowest Payment: 440
47 |
48 |
49 |
50 | # Test Case 3:
51 | # balance = 3926
52 | # annualInterestRate = 0.2
53 |
54 | # Result Your Code Should Generate:
55 | # -------------------
56 | # Lowest Payment: 360
57 |
58 |
59 | # Paste your code into this box
60 | monthlyInterestRate = annualInterestRate/12.0;
61 | FixMonthPay = 0;
62 | init_balance = balance;
63 | # count = 0
64 |
65 | while balance > 0:
66 | for i in range(12):
67 |
68 | balance = balance - FixMonthPay + ((balance - FixMonthPay) * monthlyInterestRate)
69 | # count = count + 1;
70 | # print (balance, count)
71 |
72 | if balance > 0:
73 | FixMonthPay = FixMonthPay + 10;
74 | balance = init_balance;
75 |
76 | elif balance < 0:
77 | break;
78 |
79 | print("Lowest Payment: ", FixMonthPay)
80 |
81 |
82 | # Correct
--------------------------------------------------------------------------------
/Week_2_Simple_Programs/Problem_set/Problem 3_Using_Bisection_Search_to_Make_the_Program_Faster.py:
--------------------------------------------------------------------------------
1 | # Problem 3 - Using Bisection Search to Make the Program Faster
2 | # 20.0/20.0 points (graded)
3 | # You'll notice that in Problem 2, your monthly payment had to be a multiple of $10. Why did we make it that way? You can try running your code locally so that the payment can be any dollar and cent amount (in other words, the monthly payment is a multiple of $0.01). Does your code still work? It should, but you may notice that your code runs more slowly, especially in cases with very large balances and interest rates. (Note: when your code is running on our servers, there are limits on the amount of computing time each submission is allowed, so your observations from running this experiment on the grading system might be limited to an error message complaining about too much time taken.)
4 |
5 | # Well then, how can we calculate a more accurate fixed monthly payment than we did in Problem 2 without running into the problem of slow code? We can make this program run faster using a technique introduced in lecture - bisection search!
6 |
7 | # The following variables contain values as described below:
8 |
9 | # balance - the outstanding balance on the credit card
10 |
11 | # annualInterestRate - annual interest rate as a decimal
12 |
13 | # To recap the problem: we are searching for the smallest monthly payment such that we can pay off the entire balance within a year. What is a reasonable lower bound for this payment value? $0 is the obvious anwer, but you can do better than that. If there was no interest, the debt can be paid off by monthly payments of one-twelfth of the original balance, so we must pay at least this much every month. One-twelfth of the original balance is a good lower bound.
14 |
15 | # What is a good upper bound? Imagine that instead of paying monthly, we paid off the entire balance at the end of the year. What we ultimately pay must be greater than what we would've paid in monthly installments, because the interest was compounded on the balance we didn't pay off each month. So a good upper bound for the monthly payment would be one-twelfth of the balance, after having its interest compounded monthly for an entire year.
16 |
17 | # In short:
18 |
19 | # Monthly interest rate = (Annual interest rate) / 12.0
20 | # Monthly payment lower bound = Balance / 12
21 | # Monthly payment upper bound = (Balance x (1 + Monthly interest rate)12) / 12.0
22 |
23 | # Write a program that uses these bounds and bisection search (for more info check out the Wikipedia page on bisection search) to find the smallest monthly payment to the cent (no more multiples of $10) such that we can pay off the debt within a year. Try it out with large inputs, and notice how fast it is (try the same large inputs in your solution to Problem 2 to compare!). Produce the same return value as you did in Problem 2.
24 |
25 | # Note that if you do not use bisection search, your code will not run - your code only has 30 seconds to run on our servers.
26 |
27 | # Test Cases to Test Your Code With. Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
28 |
29 | # Click to See Problem 3 Test Cases
30 | # Note: The automated tests are leinient - if your answers are off by a few cents in either direction, your code is OK.
31 |
32 | # Be sure to test these on your own machine - and that you get the same output! - before running your code on this webpage!
33 |
34 | # Test Cases:
35 |
36 |
37 | # Test Case 1:
38 | # balance = 320000
39 | # annualInterestRate = 0.2
40 |
41 | # Result Your Code Should Generate:
42 | # -------------------
43 | # Lowest Payment: 29157.09
44 |
45 |
46 |
47 | # Test Case 2:
48 | # balance = 999999
49 | # annualInterestRate = 0.18
50 |
51 | # Result Your Code Should Generate:
52 | # -------------------
53 | # Lowest Payment: 90325.03
54 |
55 |
56 | # balance = 999999;
57 | init_balance = balance;
58 | # annualInterestRate = 0.18;
59 | monthlyInterestRate = annualInterestRate/12.0;
60 | low = init_balance/12;
61 | high = (init_balance * (1 + monthlyInterestRate)**12)/12.0;
62 | epsilon = 0.03;
63 | # count = 0
64 |
65 | while abs(balance) > epsilon:
66 | monthlyPaymentRate = (high + low)/2.0;
67 | balance = init_balance;
68 | for i in range(12):
69 | balance = balance - monthlyPaymentRate + ((balance - monthlyPaymentRate)* monthlyInterestRate)
70 | # count = count + 1;
71 | # print ("balance: ", balance, count)
72 | if balance > epsilon:
73 | low = monthlyPaymentRate;
74 | elif balance < -epsilon:
75 | high = monthlyPaymentRate;
76 | else :
77 | break;
78 | print("Lowest Payment: ", round(monthlyPaymentRate, 2))
79 |
80 |
81 | # Correct
82 |
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Exercise_apply_to_each_1.py:
--------------------------------------------------------------------------------
1 | # Exercise: apply to each 1
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 2 minutes
4 |
5 | # Here is the code for a function applyToEach:
6 |
7 | # def applyToEach(L, f):
8 | # for i in range(len(L)):
9 | # L[i] = f(L[i])
10 | # Assume that
11 |
12 | # testList = [1, -4, 8, -9]
13 | # For each of the following questions (which you may assume is evaluated independently of the previous questions, so that testList has the value indicated above), provide an expression using applyToEach, so that after evaluation testList has the indicated value. You may need to write a simple procedure in each question to help with this process.
14 |
15 | # Example Question:
16 |
17 | # >>> print(testList)
18 | # [5, -20, 40, -45]
19 | # Solution to Example Question
20 | # >>> print(testList)
21 | # [1, 4, 8, 9]
22 |
23 |
24 | # Your Code Here
25 | def applyToEach(L, f):
26 | for i in range(len(L)):
27 | L[i] = f(L[i])
28 | return L
29 |
30 | #testList = [1, -4, 8, -9]
31 |
32 | print(applyToEach(testList, abs))
33 |
34 | # Correct
35 |
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Exercise_biggest.py:
--------------------------------------------------------------------------------
1 | # Exercise: biggest
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 7 minutes
4 |
5 | # Consider the following sequence of expressions:
6 |
7 | # animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
8 |
9 | # animals['d'] = ['donkey']
10 | # animals['d'].append('dog')
11 | # animals['d'].append('dingo')
12 | # We want to write some simple procedures that work on dictionaries to return information.
13 |
14 | # This time, write a procedure, called biggest, which returns the key corresponding to the entry with the largest number of values associated with it. If there is more than one such entry, return any one of the matching keys.
15 |
16 | # Example usage:
17 |
18 | # >>> biggest(animals)
19 | # 'd'
20 | # If there are no values in the dictionary, biggest should return None.
21 |
22 |
23 | def biggest(aDict):
24 | '''
25 | aDict: A dictionary, where all the values are lists.
26 |
27 | returns: The key with the largest number of values associated with it
28 | '''
29 | # Your Code Here
30 |
31 | values = aDict.values()
32 | big = max(values)
33 | result = "";
34 | # print(big)
35 | for read in aDict:
36 | if aDict[read] == big:
37 | result = read;
38 | return result;
39 |
40 |
41 | # Correct
42 | # Important: If you are getting a message Incorrect: Something went wrong: tests don't match up. please click Check until you get a different error message or you get the green Correct. We apologize for the inconvenience.
43 |
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Exercise_how_many.py:
--------------------------------------------------------------------------------
1 | # Exercise: how many
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 6 minutes
4 |
5 | # Consider the following sequence of expressions:
6 |
7 | # animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
8 |
9 | # animals['d'] = ['donkey']
10 | # animals['d'].append('dog')
11 | # animals['d'].append('dingo')
12 | # We want to write some simple procedures that work on dictionaries to return information.
13 |
14 | # First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary. For example:
15 | # >>> print(how_many(animals))
16 | # 6
17 |
18 | def how_many(aDict):
19 | '''
20 | aDict: A dictionary, where all the values are lists.
21 |
22 | returns: int, how many values are in the dictionary.
23 |
24 | '''
25 | a = 0;
26 | for i in aDict:
27 | a+= len(aDict[i]);
28 | return a;
29 |
30 |
31 | # Correct
32 | # Important: If you are getting a message Incorrect: Something went wrong: tests don't match up. please click Check until you get a different error message or you get the green Correct. We apologize for the inconvenience.
33 |
34 |
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Exercise_odd_tuples.py:
--------------------------------------------------------------------------------
1 | # Exercise: odd tuples
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 5 minutes
4 |
5 | # Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple')
6 |
7 | def oddTuples(aTup):
8 | '''
9 | aTup: a tuple
10 |
11 | returns: tuple, every other element of aTup.
12 | '''
13 | # Your Code Here
14 | return aTup[::2]
15 |
16 | # Correct
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Problem_Set/Problem 1_Is_the_Word_Guessed.py:
--------------------------------------------------------------------------------
1 | # Note: Do not be intimidated by this problem! It's actually easier than it looks. We will 'scaffold' this problem, guiding you through the creation of helper functions before you implement the actual game.
2 |
3 | # For this problem, you will implement a variation of the classic wordgame Hangman. For those of you who are unfamiliar with the rules, you may read all about it here. In this problem, the second player will always be the computer, who will be picking a word at random.
4 |
5 | # In this problem, you will implement a function, called hangman, that will start up and carry out an interactive Hangman game between a player and the computer. Before we get to this function, we'll first implement a few helper functions to get you going.
6 |
7 | # For this problem, you will need the code files ps3_hangman.py and words.txt. Right-click on each and hit "Save Link As". Be sure to save them in same directory. Open and run the file ps3_hangman.py without making any modifications to it, in order to ensure that everything is set up correctly. By "open and run" we mean do the following:
8 |
9 | # Go to your IDE. From the File menu, choose "Open".
10 | # Find the file ps3_hangman.py and choose it.
11 | # The template ps3_hangman.py file should now be open. Run the file.
12 | # The code we have given you loads in a list of words from a file. If everything is working okay, after a small delay, you should see the following printed out:
13 |
14 |
15 | # Loading word list from file...
16 | # 55909 words loaded.
17 | # If you see an IOError instead (e.g., "No such file or directory"), you should change the value of the WORDLIST_FILENAME constant (defined near the top of the file) to the complete pathname for the file words.txt (This will vary based on where you saved the file). Windows users, change the backslashes to forward slashes, like below.
18 |
19 | # For example, if you saved ps3_hangman.py and words.txt in the directory "C:/Users/Ana/" change the line:
20 |
21 | # WORDLIST_FILENAME = "words.txt" to something like
22 |
23 | # WORDLIST_FILENAME = "C:/Users/Ana/words.txt"
24 |
25 | # This folder will vary depending on where you saved the files.
26 |
27 | # The file ps3_hangman.py has a number of already implemented functions you can use while writing up your solution. You can ignore the code between the following comments, though you should read and understand how to use each helper function by reading the docstrings:
28 |
29 |
30 |
31 | # # -----------------------------------
32 | # # Helper code
33 | # # You don't need to understand this helper code,
34 | # # but you will have to know how to use the functions
35 | # # (so be sure to read the docstrings!)
36 | # .
37 | # .
38 | # .
39 | # # (end of helper code)
40 | # # -----------------------------------
41 |
42 | # You will want to do all of your coding for this problem within this file as well because you will be writing a program that depends on each function you write.
43 |
44 | # Requirements
45 | # Here are the requirements for your game:
46 |
47 | # The computer must select a word at random from the list of available words that was provided in words.txt. The functions for loading the word list and selecting a random word have already been provided for you in ps3_hangman.py.
48 |
49 | # The game must be interactive; the flow of the game should go as follows:
50 |
51 | # At the start of the game, let the user know how many letters the computer's word contains.
52 |
53 | # Ask the user to supply one guess (i.e. letter) per round.
54 |
55 | # The user should receive feedback immediately after each guess about whether their guess appears in the computer's word.
56 |
57 | # After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.
58 |
59 | # Some additional rules of the game:
60 | # A user is allowed 8 guesses. Make sure to remind the user of how many guesses s/he has left after each round. Assume that players will only ever submit one character at a time (A-Z).
61 |
62 | # A user loses a guess only when s/he guesses incorrectly.
63 |
64 | # If the user guesses the same letter twice, do not take away a guess - instead, print a message letting them know they've already guessed that letter and ask them to try again.
65 |
66 | # The game should end when the user constructs the full word or runs out of guesses. If the player runs out of guesses (s/he "loses"), reveal the word to the user when the game ends.
67 |
68 | # Sample Output
69 | # The output of a winning game should look like this...
70 |
71 | # Loading word list from file...
72 | # 55900 words loaded.
73 | # Welcome to the game, Hangman!
74 | # I am thinking of a word that is 4 letters long.
75 | # -------------
76 | # You have 8 guesses left.
77 | # Available letters: abcdefghijklmnopqrstuvwxyz
78 | # Please guess a letter: a
79 | # Good guess: _ a_ _
80 | # ------------
81 | # You have 8 guesses left.
82 | # Available letters: bcdefghijklmnopqrstuvwxyz
83 | # Please guess a letter: a
84 | # Oops! You've already guessed that letter: _ a_ _
85 | # ------------
86 | # You have 8 guesses left.
87 | # Available letters: bcdefghijklmnopqrstuvwxyz
88 | # Please guess a letter: s
89 | # Oops! That letter is not in my word: _ a_ _
90 | # ------------
91 | # You have 7 guesses left.
92 | # Available letters: bcdefghijklmnopqrtuvwxyz
93 | # Please guess a letter: t
94 | # Good guess: ta_ t
95 | # ------------
96 | # You have 7 guesses left.
97 | # Available letters: bcdefghijklmnopqruvwxyz
98 | # Please guess a letter: r
99 | # Oops! That letter is not in my word: ta_ t
100 | # ------------
101 | # You have 6 guesses left.
102 | # Available letters: bcdefghijklmnopquvwxyz
103 | # Please guess a letter: m
104 | # Oops! That letter is not in my word: ta_ t
105 | # ------------
106 | # You have 5 guesses left.
107 | # Available letters: bcdefghijklnopquvwxyz
108 | # Please guess a letter: c
109 | # Good guess: tact
110 | # ------------
111 | # Congratulations, you won!
112 |
113 |
114 | # And the output of a losing game should look like this...
115 |
116 | # Loading word list from file...
117 | # 55900 words loaded.
118 | # Welcome to the game Hangman!
119 | # I am thinking of a word that is 4 letters long
120 | # -----------
121 | # You have 8 guesses left
122 | # Available Letters: abcdefghijklmnopqrstuvwxyz
123 | # Please guess a letter: a
124 | # Oops! That letter is not in my word: _ _ _ _
125 | # -----------
126 | # You have 7 guesses left
127 | # Available Letters: bcdefghijklmnopqrstuvwxyz
128 | # Please guess a letter: b
129 | # Oops! That letter is not in my word: _ _ _ _
130 | # -----------
131 | # You have 6 guesses left
132 | # Available Letters: cdefghijklmnopqrstuvwxyz
133 | # Please guess a letter: c
134 | # Oops! That letter is not in my word: _ _ _ _
135 | # -----------
136 | # You have 5 guesses left
137 | # Available Letters: defghijklmnopqrstuvwxyz
138 | # Please guess a letter: d
139 | # Oops! That letter is not in my word: _ _ _ _
140 | # -----------
141 | # You have 4 guesses left
142 | # Available Letters: efghijklmnopqrstuvwxyz
143 | # Please guess a letter: e
144 | # Good guess: e_ _ e
145 | # -----------
146 | # You have 4 guesses left
147 | # Available Letters: fghijklmnopqrstuvwxyz
148 | # Please guess a letter: f
149 | # Oops! That letter is not in my word: e_ _ e
150 | # -----------
151 | # You have 3 guesses left
152 | # Available Letters: ghijklmnopqrstuvwxyz
153 | # Please guess a letter: g
154 | # Oops! That letter is not in my word: e_ _ e
155 | # -----------
156 | # You have 2 guesses left
157 | # Available Letters: hijklmnopqrstuvwxyz
158 | # Please guess a letter: h
159 | # Oops! That letter is not in my word: e_ _ e
160 | # -----------
161 | # You have 1 guesses left
162 | # Available Letters: ijklmnopqrstuvwxyz
163 | # Please guess a letter: i
164 | # Oops! That letter is not in my word: e_ _ e
165 | # -----------
166 | # Sorry, you ran out of guesses. The word was else.
167 | #
168 |
169 | # Problem 1 - Is the Word Guessed
170 | # 10.0/10.0 points (graded)
171 | # Please read the Hangman Introduction before starting this problem. We'll start by writing 3 simple functions that will help us easily code the Hangman problem. First, implement the function isWordGuessed that takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed. This function returns a boolean - True if secretWord has been guessed (ie, all the letters of secretWord are in lettersGuessed) and False otherwise.
172 |
173 | # Example Usage:
174 |
175 | # >>> secretWord = 'apple'
176 | # >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
177 | # >>> print(isWordGuessed(secretWord, lettersGuessed))
178 | # False
179 | # For this function, you may assume that all the letters in secretWord and lettersGuessed are lowercase
180 |
181 | def isWordGuessed(secretWord, lettersGuessed):
182 | '''
183 | secretWord: string, the word the user is guessing
184 | lettersGuessed: list, what letters have been guessed so far
185 | returns: boolean, True if all the letters of secretWord are in lettersGuessed;
186 | False otherwise
187 | '''
188 | # FILL IN YOUR CODE HERE...
189 | for i in secretWord:
190 | if i not in lettersGuessed:
191 | return False;
192 | return True;
193 |
194 | # Correct
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Problem_Set/Problem_2_Printing_Out_the_User's_Guess.py:
--------------------------------------------------------------------------------
1 | # Problem 2 - Printing Out the User's Guess
2 | # 10.0/10.0 points (graded)
3 | # Next, implement the function getGuessedWord that takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed. This function returns a string that is comprised of letters and underscores, based on what letters in lettersGuessed are in secretWord. This shouldn't be too different from isWordGuessed!
4 |
5 | # Example Usage:
6 |
7 | # >>> secretWord = 'apple'
8 | # >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
9 | # >>> print(getGuessedWord(secretWord, lettersGuessed))
10 | # '_ pp_ e'
11 | # When inserting underscores into your string, it's a good idea to add at least a space after each one, so it's clear to the user how many unguessed letters are left in the string (compare the readability of ____ with _ _ _ _ ). This is called usability - it's very important, when programming, to consider the usability of your program. If users find your program difficult to understand or operate, they won't use it!
12 |
13 | # For this problem, you are free to use spacing in any way you wish - our grader will only check that the letters and underscores are in the proper order; it will not look at spacing. We do encourage you to think about usability when designing.
14 |
15 | # For this function, you may assume that all the letters in secretWord and lettersGuessed are lowercase.
16 |
17 | def getGuessedWord(secretWord, lettersGuessed):
18 | '''
19 | secretWord: string, the word the user is guessing
20 | lettersGuessed: list, what letters have been guessed so far
21 | returns: string, comprised of letters and underscores that represents
22 | what letters in secretWord have been guessed so far.
23 | '''
24 | # FILL IN YOUR CODE HERE...
25 | result = '';
26 | for i in secretWord:
27 | if i in lettersGuessed:
28 | result += i;
29 | else:
30 | result += '_';
31 | return result;
32 |
33 | print(getGuessedWord('apple', ['e', 'i', 'k', 'p', 'r', 's']))
34 |
35 | # Correct
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Problem_Set/Problem_3_Printing_Out_all_Available_Letters.py:
--------------------------------------------------------------------------------
1 | # Problem 3 - Printing Out all Available Letters
2 | # 10.0/10.0 points (graded)
3 | # Next, implement the function getAvailableLetters that takes in one parameter - a list of letters, lettersGuessed. This function returns a string that is comprised of lowercase English letters - all lowercase English letters that are not in lettersGuessed.
4 |
5 | # Example Usage:
6 |
7 | # >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
8 | # >>> print(getAvailableLetters(lettersGuessed))
9 | # abcdfghjlmnoqtuvwxyz
10 | # Note that this function should return the letters in alphabetical order, as in the example above.
11 |
12 | # For this function, you may assume that all the letters in lettersGuessed are lowercase.
13 |
14 | # Hint: You might consider using string.ascii_lowercase, which is a string comprised of all lowercase letters:
15 |
16 | # >>> import string
17 | # >>> print(string.ascii_lowercase)
18 | # abcdefghijklmnopqrstuvwxyz
19 |
20 | def getAvailableLetters(lettersGuessed):
21 | '''
22 | lettersGuessed: list, what letters have been guessed so far
23 | returns: string, comprised of letters that represents what letters have not
24 | yet been guessed.
25 | '''
26 | # FILL IN YOUR CODE HERE...
27 | import string
28 | alpha = (string.ascii_lowercase)
29 | lst_alpha = list(alpha)
30 | for i in lettersGuessed:
31 | if i in lst_alpha:
32 | # print(i)
33 | lst_alpha.remove(i)
34 |
35 | lst_alpha = ''.join(lst_alpha)
36 | return lst_alpha
37 |
38 |
39 | # Correct
--------------------------------------------------------------------------------
/Week_3_Structured_Types/Problem_Set/Problem_4_The_Game.py:
--------------------------------------------------------------------------------
1 | # Problem 4 - The Game
2 | # 15.0/15.0 points (graded)
3 | # Now you will implement the function hangman, which takes one parameter - the secretWord the user is to guess. This starts up an interactive game of Hangman between the user and the computer. Be sure you take advantage of the three helper functions, isWordGuessed, getGuessedWord, and getAvailableLetters, that you've defined in the previous part.
4 |
5 | # Hints:
6 | # You should start by noticing where we're using the provided functions (at the top of ps3_hangman.py) to load the words and pick a random one. Note that the functions loadWords and chooseWord should only be used on your local machine, not in the tutor. When you enter in your solution in the tutor, you only need to give your hangman function.
7 |
8 | # Consider using lower() to convert user input to lower case. For example:
9 |
10 | # guess = 'A'
11 | # guessInLowerCase = guess.lower()
12 | # Consider writing additional helper functions if you need them!
13 |
14 | # There are four important pieces of information you may wish to store:
15 |
16 | # secretWord: The word to guess.
17 | # lettersGuessed: The letters that have been guessed so far.
18 | # mistakesMade: The number of incorrect guesses made so far.
19 | # availableLetters: The letters that may still be guessed. Every time a player guesses a letter, the guessed letter must be removed from availableLetters (and if they guess a letter that is not in availableLetters, you should print a message telling them they've already guessed that - so try again!).
20 | # Sample Output
21 | # The output of a winning game should look like this...
22 | # And the output of a losing game should look like this...
23 |
24 | # Note that if you choose to use the helper functions isWordGuessed, getGuessedWord, or getAvailableLetters, you do not need to paste your definitions in the box. We have supplied our implementations of these functions for your use in this part of the problem. If you use additional helper functions, you will need to paste those definitions here.
25 |
26 | # Your function should include calls to input to get the user's guess.
27 |
28 | # Why does my Output Have None at Various Places?
29 | # None is a keyword and it comes from the fact that you are printing the result of a function that does not return anything. For example:
30 |
31 | # def foo(x):
32 | # print(x)
33 |
34 | # If you just call the function with foo(3), you will see output:
35 | # 3 #-- because the function printed the variable
36 |
37 | # However, if you do print(foo(3)), you will see output:
38 | # 3 #-- because the function printed the variable
39 | # None #-- because you printed the function (and hence the return)
40 |
41 | # All functions return something. If a function you write does not return anything (and just prints something to the console), then the default action in Python is to return None
42 |
43 | def hangman(secretWord):
44 | '''
45 | secretWord: string, the secret word to guess.
46 |
47 | Starts up an interactive game of Hangman.
48 |
49 | * At the start of the game, let the user know how many
50 | letters the secretWord contains.
51 |
52 | * Ask the user to supply one guess (i.e. letter) per round.
53 |
54 | * The user should receive feedback immediately after each guess
55 | about whether their guess appears in the computers word.
56 |
57 | * After each round, you should also display to the user the
58 | partially guessed word so far, as well as letters that the
59 | user has not yet guessed.
60 |
61 | Follows the other limitations detailed in the problem write-up.
62 | '''
63 | # FILL IN YOUR CODE HERE...
64 | lettersGuessed = '';
65 | j = 8;
66 | print('Welcome to the game, Hangman!')
67 | print('I am thinking of a word that is', len(secretWord), 'letters long.')
68 | print('-------------')
69 | while j >= 1:
70 | # if lettersGuessed == secretWord:
71 | # print('------------')
72 | # return 'Congratulations, you won!'
73 | if isWordGuessed(secretWord, lettersGuessed) == True:
74 | print('Congratulations, you won!')
75 | break
76 | else:
77 |
78 | print('You have', j, 'guesses left.')
79 | print('Available Letters:', getAvailableLetters(lettersGuessed))
80 | guess = input('Please guess a letter: ', ).lower()
81 |
82 | if guess in secretWord and guess not in lettersGuessed:
83 | lettersGuessed = lettersGuessed + guess
84 | print('Good guess:', getGuessedWord(secretWord, lettersGuessed))
85 | print('-------------')
86 | if lettersGuessed != secretWord:
87 | continue
88 |
89 | elif guess in lettersGuessed:
90 | print("Oops! You've already guessed that letter:", getGuessedWord(secretWord, lettersGuessed))
91 | print('-------------')
92 | continue
93 | elif guess not in secretWord:
94 | print('Oops! That letter is not in my word:', getGuessedWord(secretWord, lettersGuessed))
95 | print('-------------')
96 | lettersGuessed = lettersGuessed + guess
97 | if j == 1:
98 | print('Sorry, you ran out of guesses. The word was else', secretWord)
99 | j = j - 1;
100 |
101 |
102 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Exercise_integer_division.py:
--------------------------------------------------------------------------------
1 | # Exercise: integer division
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 4 minutes
4 |
5 | # Consider the following function definition:
6 |
7 | # def integerDivision(x, a):
8 | # """
9 | # x: a non-negative integer argument
10 | # a: a positive integer argument
11 |
12 | # returns: integer, the integer division of x divided by a.
13 | # """
14 | # while x >= a:
15 | # count += 1
16 | # x = x - a
17 | # return count
18 | # When we call
19 |
20 | # print(integerDivision(5, 3))
21 | # we get the following error message:
22 |
23 | # File "temp.py", line 9, in integerDivision
24 | # count += 1
25 | # UnboundLocalError: local variable 'count' referenced before assignment
26 | # Your task is to modify the code for integerDivision so that this error does not occur.
27 |
28 | def integerDivision(x, a):
29 | """
30 | x: a non-negative integer argument
31 | a: a positive integer argument
32 |
33 | returns: integer, the integer division of x divided by a.
34 | """
35 | count = 0
36 | while x >= a:
37 | count += 1
38 | x = x - a
39 | return count
40 |
41 |
42 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Exercise_simple_divide.py:
--------------------------------------------------------------------------------
1 | # Exercise: simple divide
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 4 minutes
4 |
5 | # Suppose we rewrite the FancyDivide function to use a helper function.
6 |
7 | # def fancy_divide(list_of_numbers, index):
8 | # denom = list_of_numbers[index]
9 | # return [simple_divide(item, denom) for item in list_of_numbers]
10 |
11 |
12 | # def simple_divide(item, denom):
13 | # return item / denom
14 |
15 |
16 | # This code raises a ZeroDivisionError exception for the following call: fancy_divide([0, 2, 4], 0)
17 |
18 | # Your task is to change the definition of simple_divide so that the call does not raise an exception. When dividing by 0, fancy_divide should return a list with all 0 elements. Any other error cases should still raise exceptions. You should only handle the ZeroDivisionError.
19 |
20 | #define the simple_divide function here
21 | def fancy_divide(list_of_numbers, index):
22 | result = []
23 | denom = list_of_numbers[index]
24 | for i in range(len(list_of_numbers)):
25 | result.append(simple_divide(list_of_numbers[i], denom))
26 | return result
27 |
28 |
29 |
30 | def simple_divide(item, denom):
31 | try:
32 | return item / denom
33 | except ZeroDivisionError:
34 | return 0
35 |
36 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_1_Word_Scores.py:
--------------------------------------------------------------------------------
1 | # In this problem set, you'll implement two versions of a wordgame!
2 |
3 | # Don't be intimidated by the length of this problem set. There is a lot of reading, but it can be done with a reasonable amount of thinking and coding. It'll be helpful if you start this problem set a few days before it is due!
4 |
5 | # Let's begin by describing the 6.00 wordgame: This game is a lot like Scrabble or Words With Friends, if you've played those. Letters are dealt to players, who then construct one or more words out of their letters. Each valid word receives a score, based on the length of the word and the letters in that word.
6 |
7 | # The rules of the game are as follows:
8 |
9 | # Dealing
10 | # A player is dealt a hand of n letters chosen at random (assume n=7 for now).
11 |
12 | # The player arranges the hand into as many words as they want out of the letters, using each letter at most once.
13 |
14 | # Some letters may remain unused (these won't be scored).
15 |
16 | # Scoring
17 | # The score for the hand is the sum of the scores for each word formed.
18 |
19 | # The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, plus 50 points if all n letters are used on the first word created.
20 |
21 | # Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. We have defined the dictionary SCRABBLE_LETTER_VALUES that maps each lowercase letter to its Scrabble letter value.
22 |
23 | # For example, 'weed' would be worth 32 points ((4+1+1+2) for the four letters, then multiply by len('weed') to get (4+1+1+2)*4 = 32). Be sure to check that the hand actually has 1 'w', 2 'e's, and 1 'd' before scoring the word!
24 |
25 | # As another example, if n=7 and you make the word 'waybill' on the first try, it would be worth 155 points (the base score for 'waybill' is (4+1+4+3+1+1+1)*7=105, plus an additional 50 point bonus for using all n letters).
26 |
27 | # Sample Output
28 | # Here is how the game output will look!
29 |
30 | # Loading word list from file...
31 | # 83667 words loaded.
32 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
33 | # Current Hand: p z u t t t o
34 | # Enter word, or a "." to indicate that you are finished: tot
35 | # "tot" earned 9 points. Total: 9 points
36 | # Current Hand: p z u t
37 | # Enter word, or a "." to indicate that you are finished: .
38 | # Total score: 9 points.
39 |
40 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: r
41 | # Current Hand: p z u t t t o
42 | # Enter word, or a "." to indicate that you are finished: top
43 | # "top" earned 15 points. Total: 15 points
44 | # Current Hand: z u t t
45 | # Enter word, or a "." to indicate that you are finished: tu
46 | # Invalid word, please try again.
47 | # Current Hand: z u t t
48 | # Enter word, or a "." to indicate that you are finished: .
49 | # Total score: 15 points.
50 |
51 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
52 | # Current Hand: a q w f f i p
53 | # Enter word, or a "." to indicate that you are finished: paw
54 | # "paw" earned 24 points. Total: 24 points
55 | # Current Hand: q f f i
56 | # Enter word, or a "." to indicate that you are finished: qi
57 | # "qi" earned 22 points. Total: 46 points
58 | # Current Hand: f f
59 | # Enter word, or a "." to indicate that you are finished: .
60 | # Total score: 46 points.
61 |
62 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
63 | # Current Hand: a r e t i i n
64 | # Enter word, or a "." to indicate that you are finished: inertia
65 | # "inertia" earned 99 points. Total: 99 points
66 | # Run out of letters. Total score: 99 points.
67 |
68 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: e
69 |
70 | ##################################################################################################
71 |
72 | # Download and save Problem Set 4, a zip file of all the skeleton code you'll be filling in. Extract the files from the zip folder and make sure to save all the files - ps4a.py, ps4b.py, test_ps4a.py and words.txt - in the same folder. We recommend creating a folder in your Documents folder called 6001x, and inside the 6001x folder, creating a separate folder for each problem set. If you don't follow this instruction, you may end up with issues because the files for this problem set depend on one another.
73 |
74 | # Run the file ps4a.py, without making any modifications to it, in order to ensure that everything is set up correctly (this means, open the file in IDLE, and use the Run command to load the file into the interpreter). The code we have given you loads a list of valid words from a file and then calls the playGame function. You will implement the functions it needs in order to work. If everything is okay, after a small delay, you should see the following printed out:
75 |
76 |
77 | # Loading word list from file...
78 | # 83667 words loaded.
79 | # playGame not yet implemented.
80 |
81 | # If you see an IOError instead (e.g., "No such file or directory"), you should change the value of the WORDLIST_FILENAME constant (defined near the top of the file) to the complete pathname for the file words.txt (This will vary based on where you saved the files).
82 |
83 | # For example, if you saved all the files including this words.txt in the directory "C:/Users/Ana/6001x/PS4" change the line:
84 |
85 | # WORDLIST_FILENAME = "words.txt" to something like
86 | # WORDLIST_FILENAME = "C:/Users/Ana/6001x/PS4/words.txt"
87 | # Windows users, if you are copying the file path from Windows Explorer, you will have to change the backslashes to forward slashes.
88 |
89 | # The file ps4a.py has a number of already implemented functions you can use while writing up your solution. You can ignore the code between the following comments, though you should read and understand how to use each helper function by reading the docstrings:
90 |
91 | # # -----------------------------------
92 | # # Helper code
93 | # # You don't need to understand this helper code,
94 | # # but you will have to know how to use the functions
95 | # # (so be sure to read the docstrings!)
96 | # .
97 | # .
98 | # .
99 | # # (end of helper code)
100 | # # -----------------------------------
101 |
102 | # This problem set is structured so that you will write a number of modular functions and then glue them together to form the complete word playing game. Instead of waiting until the entire game is ready, you should test each function you write, individually, before moving on. This approach is known as unit testing, and it will help you debug your code.
103 |
104 | # We have provided several test functions to get you started. After you've written each new function, unit test by running the file test_ps4a.py to check your work.
105 |
106 | # If your code passes the unit tests you will see a SUCCESS message; otherwise you will see a FAILURE message. These tests aren't exhaustive. You will want to test your code in other ways too.
107 |
108 | # Try running test_ps4a.py now (before you modify the ps4a.py skeleton). You should see that all the tests fail, because nothing has been implemented yet.
109 |
110 | # These are the provided test functions:
111 |
112 | # test_getWordScore()
113 | # Test the getWordScore() implementation.
114 |
115 | # test_updateHand()
116 | # Test the updateHand() implementation.
117 |
118 | # test_isValidWord()
119 | # Test the isValidWord() implementation.
120 |
121 |
122 | # Problem 1 - Word Scores
123 | # 10.0/10.0 points (graded)
124 | # The first step is to implement some code that allows us to calculate the score for a single word. The function getWordScore should accept as input a string of lowercase letters (a word) and return the integer score for that word, using the game's scoring rules.
125 |
126 | # A Reminder of the Scoring Rules
127 | # Scoring
128 | # The score for the hand is the sum of the scores for each word formed.
129 |
130 | # The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, plus 50 points if all n letters are used on the first word created.
131 |
132 | # Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. We have defined the dictionary SCRABBLE_LETTER_VALUES that maps each lowercase letter to its Scrabble letter value.
133 |
134 | # For example, 'weed' would be worth 32 points ((4+1+1+2) for the four letters, then multiply by len('weed') to get (4+1+1+2)*4 = 32). Be sure to check that the hand actually has 1 'w', 2 'e's, and 1 'd' before scoring the word!
135 |
136 | # As another example, if n=7 and you make the word 'waybill' on the first try, it would be worth 155 points (the base score for 'waybill' is (4+1+4+3+1+1+1)*7=105, plus an additional 50 point bonus for using all n letters).
137 |
138 |
139 | # Hints
140 | # You may assume that the input word is always either a string of lowercase letters, or the empty string "".
141 | # You will want to use the SCRABBLE_LETTER_VALUES dictionary defined at the top of ps4a.py. You should not change its value.
142 | # Do not assume that there are always 7 letters in a hand! The parameter n is the number of letters required for a bonus score (the maximum number of letters in the hand). Our goal is to keep the code modular - if you want to try playing your word game with n=10 or n=4, you will be able to do it by simply changing the value of HAND_SIZE!
143 | # Testing: If this function is implemented properly, and you run test_ps4a.py, you should see that the test_getWordScore() tests pass. Also test your implementation of getWordScore, using some reasonable English words.
144 | # Fill in the code for getWordScore in ps4a.py and be sure you've passed the appropriate tests in test_ps4a.py before pasting your function definition here.
145 |
146 |
147 | def getWordScore(word, n):
148 | """
149 | Returns the score for a word. Assumes the word is a valid word.
150 |
151 | The score for a word is the sum of the points for letters in the
152 | word, multiplied by the length of the word, PLUS 50 points if all n
153 | letters are used on the first turn.
154 |
155 | Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
156 | worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
157 |
158 | word: string (lowercase letters)
159 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
160 | returns: int >= 0
161 | """
162 | score = 0
163 | add = 0
164 | length = 0
165 | myDict = []
166 | for i in word:
167 | myDict.append(SCRABBLE_LETTER_VALUES[i])
168 | add = sum(myDict)
169 | length = len(myDict)
170 | score = add*length
171 | if len(word) == n:
172 | score += 50
173 | return score
174 | else:
175 | return score
176 |
177 |
178 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_2_Dealing_with_Hands.py:
--------------------------------------------------------------------------------
1 | # Problem 2 - Dealing with Hands
2 | # 10.0/10.0 points (graded)
3 | # **Please read this problem entirely!!** The majority of this problem consists of learning how to read code, which is an incredibly useful and important skill. At the end, you will implement a short function. Be sure to take your time on this problem - it may seem easy, but reading someone else's code can be challenging and this is an important exercise.
4 |
5 |
6 | # Representing hands
7 | # A hand is the set of letters held by a player during the game. The player is initially dealt a set of random letters. For example, the player could start out with the following hand: a, q, l, m, u, i, l. In our program, a hand will be represented as a dictionary: the keys are (lowercase) letters and the values are the number of times the particular letter is repeated in that hand. For example, the above hand would be represented as:
8 |
9 | # hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
10 | # Notice how the repeated letter 'l' is represented. Remember that with a dictionary, the usual way to access a value is hand['a'], where 'a' is the key we want to find. However, this only works if the key is in the dictionary; otherwise, we get a KeyError. To avoid this, we can use the call hand.get('a',0). This is the "safe" way to access a value if we are not sure the key is in the dictionary. d.get(key,default) returns the value for key if key is in the dictionary d, else default. If default is not given, it returns None, so that this method never raises a KeyError. For example:
11 |
12 | # >>> hand['e']
13 | # Traceback (most recent call last):
14 | # File "", line 1, in
15 | # KeyError: 'e'
16 | # >>> hand.get('e', 0)
17 | # 0
18 | # Converting words into dictionary representation
19 | # One useful function we've defined for you is getFrequencyDict, defined near the top of ps4a.py. When given a string of letters as an input, it returns a dictionary where the keys are letters and the values are the number of times that letter is represented in the input string. For example:
20 |
21 | # >>> getFrequencyDict("hello")
22 | # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
23 | # As you can see, this is the same kind of dictionary we use to represent hands.
24 |
25 | # Displaying a hand
26 | # Given a hand represented as a dictionary, we want to display it in a user-friendly way. We have provided the implementation for this in the displayHand function. Take a few minutes right now to read through this function carefully and understand what it does and how it works.
27 |
28 | # Generating a random hand
29 | # The hand a player is dealt is a set of letters chosen at random. We provide you with the implementation of a function that generates this random hand, dealHand. The function takes as input a positive integer n, and returns a new object, a hand containing n lowercase letters. Again, take a few minutes (right now!) to read through this function carefully and understand what it does and how it works.
30 |
31 | # Removing letters from a hand (you implement this)
32 | # The player starts with a hand, a set of letters. As the player spells out words, letters from this set are used up. For example, the player could start out with the following hand: a, q, l, m, u, i, l. The player could choose to spell the word quail . This would leave the following letters in the player's hand: l, m. Your task is to implement the function updateHand, which takes in two inputs - a hand and a word (string). updateHand uses letters from the hand to spell the word, and then returns a copy of the hand, containing only the letters remaining. For example:
33 |
34 | # >>> hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
35 | # >>> displayHand(hand) # Implemented for you
36 | # a q l l m u i
37 | # >>> hand = updateHand(hand, 'quail') # You implement this function!
38 | # >>> hand
39 | # {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
40 | # >>> displayHand(hand)
41 | # l m
42 | # Implement the updateHand function. Make sure this function has no side effects: i.e., it must not mutate the hand passed in. Before pasting your function definition here, be sure you've passed the appropriate tests in test_ps4a.py.
43 |
44 | # Hints
45 | # Testing
46 | # Testing: Make sure the test_updateHand() tests pass. You will also want to test your implementation of updateHand with some reasonable inputs.
47 |
48 | # Copying Dictionaries
49 | # You may wish to review the ".copy" method of Python dictionaries (review this and other Python dictionary methods here).
50 |
51 |
52 | # Your implementation of updateHand should be short (ours is 4 lines of code). It does not need to call any helper functions.
53 |
54 | def updateHand(hand, word):
55 | """
56 | Assumes that 'hand' has all the letters in word.
57 | In other words, this assumes that however many times
58 | a letter appears in 'word', 'hand' has at least as
59 | many of that letter in it.
60 |
61 | Updates the hand: uses up the letters in the given word
62 | and returns the new hand, without those letters in it.
63 |
64 | Has no side effects: does not modify hand.
65 |
66 | word: string
67 | hand: dictionary (string -> int)
68 | returns: dictionary (string -> int)
69 | """
70 | hand_1 = hand.copy()
71 | for i in word:
72 | if i in hand_1.keys():
73 | hand_1[i]= hand_1.get(i, 0) -1
74 | return hand_1
75 |
76 |
77 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_3_Valid_Words.py:
--------------------------------------------------------------------------------
1 | # Problem 3 - Valid Words
2 | # 10.0/10.0 points (graded)
3 | # At this point, we have written code to generate a random hand and display that hand to the user. We can also ask the user for a word (Python's input) and score the word (using your getWordScore). However, at this point we have not written any code to verify that a word given by a player obeys the rules of the game. A valid word is in the word list; and it is composed entirely of letters from the current hand. Implement the isValidWord function.
4 |
5 | # Testing: Make sure the test_isValidWord tests pass. In addition, you will want to test your implementation by calling it multiple times on the same hand - what should the correct behavior be? Additionally, the empty string ('') is not a valid word - if you code this function correctly, you shouldn't need an additional check for this condition.
6 |
7 | # Fill in the code for isValidWord in ps4a.py and be sure you've passed the appropriate tests in test_ps4a.py before pasting your function definition here.
8 |
9 | def isValidWord(word, hand, wordList):
10 | """
11 | Returns True if word is in the wordList and is entirely
12 | composed of letters in the hand. Otherwise, returns False.
13 |
14 | Does not mutate hand or wordList.
15 |
16 | word: string
17 | hand: dictionary (string -> int)
18 | wordList: list of lowercase strings
19 | """
20 | hand_1 = hand.copy()
21 | word_check = False
22 | if word in wordList:
23 | word_check = True
24 |
25 | if set(list(word)) <= set(hand_1.keys()):
26 | letter_check = True
27 | else:
28 | letter_check = False
29 |
30 | for i in word:
31 | if i in hand_1.keys():
32 | hand_1[i] = hand_1.get(i, 0) -1
33 |
34 | values_check = all(i >= 0 for i in hand_1.values())
35 |
36 | if word_check == True and letter_check == True and values_check == True:
37 | return True
38 | else:
39 | return False
40 |
41 |
42 | # Correct
43 |
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_4_Hand_Length.py:
--------------------------------------------------------------------------------
1 | # Problem 4 - Hand Length
2 | # 10.0/10.0 points (graded)
3 | # We are now ready to begin writing the code that interacts with the player. We'll be implementing the playHand function. This function allows the user to play out a single hand. First, though, you'll need to implement the helper calculateHandlen function, which can be done in under five lines of code.
4 |
5 |
6 | def calculateHandlen(hand):
7 | """
8 | Returns the length (number of letters) in the current hand.
9 |
10 | hand: dictionary (string int)
11 | returns: integer
12 | """
13 | hand_1 = hand.copy()
14 | length = []
15 | for i in hand_1.values():
16 | if i != 0:
17 | length.append(i)
18 | return sum(length)
19 |
20 | # Correct
21 |
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_5_Playing_a_Hand.py:
--------------------------------------------------------------------------------
1 | # Problem 5 - Playing a Hand
2 | # 10.0/10.0 points (graded)
3 | # In ps4a.py, note that in the function playHand, there is a bunch of pseudocode. This pseudocode is provided to help guide you in writing your function. Check out the Why Pseudocode? resource to learn more about the What and Why of Pseudocode before you start coding your solution.
4 |
5 | # Note: Do not assume that there will always be 7 letters in a hand! The parameter n represents the size of the hand.
6 |
7 | # Testing: Before testing your code in the answer box, try out your implementation as if you were playing the game. Here is some example output of playHand:
8 |
9 | # Test Cases
10 | # Case #1
11 | # Function Call:
12 | # wordList = loadWords()
13 | # playHand({'h':1, 'i':1, 'c':1, 'z':1, 'm':2, 'a':1}, wordList, 7)
14 | # Output:
15 | # Current Hand: a c i h m m z
16 | # Enter word, or a "." to indicate that you are finished: him
17 | # "him" earned 24 points. Total: 24 points
18 |
19 | # Current Hand: a c m z
20 | # Enter word, or a "." to indicate that you are finished: cam
21 | # "cam" earned 21 points. Total: 45 points
22 |
23 | # Current Hand: z
24 | # Enter word, or a "." to indicate that you are finished: .
25 | # Goodbye! Total score: 45 points.
26 | # Case #2
27 | # Function Call:
28 | # wordList = loadWords()
29 | # playHand({'w':1, 's':1, 't':2, 'a':1, 'o':1, 'f':1}, wordList, 7)
30 | # Output:
31 | # Current Hand: a s t t w f o
32 | # Enter word, or a "." to indicate that you are finished: tow
33 | # "tow" earned 18 points. Total: 18 points
34 |
35 | # Current Hand: a s t f
36 | # Enter word, or a "." to indicate that you are finished: tasf
37 | # Invalid word, please try again.
38 |
39 | # Current Hand: a s t f
40 | # Enter word, or a "." to indicate that you are finished: fast
41 | # "fast" earned 28 points. Total: 46 points
42 |
43 | # Run out of letters. Total score: 46 points.
44 | # Case #3
45 | # Function Call:
46 | # wordList = loadWords()
47 | # playHand({'n':1, 'e':1, 't':1, 'a':1, 'r':1, 'i':2}, wordList, 7)
48 | # Output:
49 | # Current Hand: a r e t i i n
50 | # Enter word, or a "." to indicate that you are finished: inertia
51 | # "inertia" earned 99 points. Total: 99 points
52 |
53 | # Run out of letters. Total score: 99 points.
54 | # Additional Testing
55 | # Be sure that, in addition to the listed tests, you test the same basic test conditions with varying values of n. n will never be smaller than the number of letters in the hand.
56 |
57 |
58 | def playHand(hand, wordList, n):
59 | """
60 | Allows the user to play the given hand, as follows:
61 |
62 | * The hand is displayed.
63 | * The user may input a word or a single period (the string ".")
64 | to indicate they're done playing
65 | * Invalid words are rejected, and a message is displayed asking
66 | the user to choose another word until they enter a valid word or "."
67 | * When a valid word is entered, it uses up letters from the hand.
68 | * After every valid word: the score for that word is displayed,
69 | the remaining letters in the hand are displayed, and the user
70 | is asked to input another word.
71 | * The sum of the word scores is displayed when the hand finishes.
72 | * The hand finishes when there are no more unused letters or the user
73 | inputs a "."
74 |
75 | hand: dictionary (string -> int)
76 | wordList: list of lowercase strings
77 | n: integer (HAND_SIZE; i.e., hand size required for additional points)
78 |
79 | """
80 | # BEGIN PSEUDOCODE (download ps4a.py to see)
81 | score = 0
82 | # As long as there are still letters left in the hand:
83 | while calculateHandlen(hand) > 0:
84 |
85 | # Display the hand
86 | print("Current hand:", end = " ")
87 | displayHand(hand)
88 |
89 | # Ask user for input
90 | inp = input("Enter word, or a '.' to indicate that you are finished: ", )
91 |
92 | # If the input is a single period:
93 | if inp == ".":
94 |
95 | # End the game (break out of the loop)
96 | break
97 |
98 | # Otherwise (the input is not a single period):
99 |
100 | else:
101 |
102 | # If the word is not valid:
103 | if isValidWord(inp, hand, wordList) == False:
104 | print("Invalid word, please try again.")
105 | print(" ")
106 |
107 | # Reject invalid word (print a message followed by a blank line)
108 |
109 | # Otherwise (the word is valid):
110 | else:
111 | score += getWordScore(inp, n)
112 |
113 | # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
114 |
115 | print(inp, "earned", getWordScore(inp, n), "points.", "Total: ", score)
116 | print(" ")
117 |
118 | # Update the hand
119 | hand = updateHand(hand, inp)
120 |
121 |
122 | # Game is over (user entered a '.' or ran out of letters), so tell user the total score
123 | if inp == ".":
124 | print("Goodbye! Total score: ", score, "point")
125 | else:
126 | print("Run out of letters. Total score: ", score, "points.")
127 |
128 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_6_Playing_a_Game.py:
--------------------------------------------------------------------------------
1 | # Problem 6 - Playing a Game
2 | # 15.0/15.0 points (graded)
3 | # A game consists of playing multiple hands. We need to implement one final function to complete our word-game program. Write the code that implements the playGame function. You should remove the code that is currently uncommented in the playGame body. Read through the specification and make sure you understand what this function accomplishes. For the game, you should use the HAND_SIZE constant to determine the number of cards in a hand.
4 |
5 | # Testing: Try out this implementation as if you were playing the game. Try out different values for HAND_SIZE with your program, and be sure that you can play the wordgame with different hand sizes by modifying only the variable HAND_SIZE.
6 |
7 | # Sample Output
8 | # Here is how the game output should look...
9 |
10 | # Loading word list from file...
11 | # 83667 words loaded.
12 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: r
13 | # You have not played a hand yet. Please play a new hand first!
14 |
15 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
16 | # Current Hand: p z u t t t o
17 | # Enter word, or a "." to indicate that you are finished: tot
18 | # "tot" earned 9 points. Total: 9 points
19 |
20 | # Current Hand: p z u t
21 | # Enter word, or a "." to indicate that you are finished: .
22 | # Goodbye! Total score: 9 points.
23 |
24 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: r
25 | # Current Hand: p z u t t t o
26 | # Enter word, or a "." to indicate that you are finished: top
27 | # "top" earned 15 points. Total: 15 points
28 |
29 | # Current Hand: z u t t
30 | # Enter word, or a "." to indicate that you are finished: tu
31 | # Invalid word, please try again.
32 |
33 | # Current Hand: z u t t
34 | # Enter word, or a "." to indicate that you are finished: .
35 | # Goodbye! Total score: 15 points.
36 |
37 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
38 | # Current Hand: a q w f f i p
39 | # Enter word, or a "." to indicate that you are finished: paw
40 | # "paw" earned 24 points. Total: 24 points
41 |
42 | # Current Hand: q f f i
43 | # Enter word, or a "." to indicate that you are finished: qi
44 | # "qi" earned 22 points. Total: 46 points
45 |
46 | # Current Hand: f f
47 | # Enter word, or a "." to indicate that you are finished: .
48 | # Goodbye! Total score: 46 points.
49 |
50 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
51 | # Current Hand: a r e t i i n
52 | # Enter word, or a "." to indicate that you are finished: inertia
53 | # "inertia" earned 99 points. Total: 99 points.
54 |
55 | # Run out of letters. Total score: 99 points.
56 |
57 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: x
58 | # Invalid command.
59 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: e
60 |
61 |
62 | # Hints about the output
63 | # Be sure to inspect the above sample output carefully - very little is actually printed out in this function specifically. Most of the printed output actually comes from the code you wrote in playHand - be sure that your code is modular and uses function calls to the playHand helper function!
64 |
65 | # You should also make calls to the dealHand helper function. You shouldn't make calls to any other helper function that we've written so far - in fact, this function can be written in about 15-20 lines of code.
66 |
67 | # Here is the above output, with the output from playHand obscured:
68 |
69 |
70 | # Loading word list from file...
71 | # 83667 words loaded.
72 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: r
73 | # You have not played a hand yet. Please play a new hand first!
74 |
75 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
76 | #
77 |
78 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
79 | #
80 |
81 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: n
82 | #
83 |
84 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: x
85 | # Invalid command.
86 | # Enter n to deal a new hand, r to replay the last hand, or e to end game: e
87 |
88 |
89 | # Hopefully this hint makes the problem seem a bit more approachable.
90 |
91 | # Entering Your Code
92 | # Be sure to only paste your definition for playGame in the following box. Do not include any other function definitions.
93 |
94 | # A Cool Trick about 'print'
95 | # A cool trick about print: you can make two or more print statements print to the same line! Try out the following code. It will separate the first and second line with a space, and the second and third line with a "?" rather than putting each on a new line.
96 |
97 | # print('Hello', end = " ")
98 | # print('world', end="?")
99 | # print('!')
100 |
101 |
102 | def playGame(wordList):
103 | """
104 | Allow the user to play an arbitrary number of hands.
105 |
106 | 1) Asks the user to input 'n' or 'r' or 'e'.
107 | * If the user inputs 'n', let the user play a new (random) hand.
108 | * If the user inputs 'r', let the user play the last hand again.
109 | * If the user inputs 'e', exit the game.
110 | * If the user inputs anything else, tell them their input was invalid.
111 |
112 | 2) When done playing the hand, repeat from step 1
113 | """
114 | while True:
115 | game_inp = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ", ).lower()
116 | if game_inp == 'e':
117 | break
118 | elif game_inp == 'n':
119 | hand = dealHand(HAND_SIZE)
120 | playHand(hand, wordList, HAND_SIZE)
121 | elif game_inp == 'r':
122 | try:
123 | playHand(hand, wordList, HAND_SIZE)
124 | except:
125 | print("You have not played a hand yet. Please play a new hand first!")
126 | else:
127 | print("Invalid command.")
128 |
129 | # Correct
--------------------------------------------------------------------------------
/Week_4_Good_Programming_Practices/Problem_Set/Problem_7_You_and_your_Computer.py:
--------------------------------------------------------------------------------
1 | # **Part B is dependent on your functions from ps4a.py, so be sure to complete ps4a.py before working on ps4b.py**
2 | # Now that you have completed your word game code, you decide that you would like to enable your computer (SkyNet) to play the game (your hidden agenda is to prove once and for all that computers are inferior to human intellect!) In this part, you will be able to compare how you as a user succeed in the game compared to the computer's performance.
3 |
4 | # You should look at the following two functions: compChooseWord and compPlayHand, before moving on to Problem 7 on the next page.
5 |
6 | # compChooseWord
7 | # If you follow the pseudocode for compChooseWord, you'll see that the code creates a computer player that is legal, but not always the best. Try to walk through and understand our implementation.
8 |
9 | # A Note On Runtime: You may notice that things run a bit slowly when the computer plays. This is to be expected - the wordList has 83667 words, after all!
10 |
11 | # Test Cases to Understand the Code:
12 | # >>> compChooseWord({'a': 1, 'p': 2, 's': 1, 'e': 1, 'l': 1}, wordList, 6)
13 | # appels
14 | # >>> compChooseWord({'a': 2, 'c': 1, 'b': 1, 't': 1}, wordList, 5)
15 | # acta
16 | # >>> compChooseWord({'a': 2, 'e': 2, 'i': 2, 'm': 2, 'n': 2, 't': 2}, wordList, 12)
17 | # immanent
18 | # >>> compChooseWord({'x': 2, 'z': 2, 'q': 2, 'n': 2, 't': 2}, wordList, 12)
19 | # None
20 | # compPlayHand
21 | # Now that we have the ability to let the computer choose a word, we need to set up a function to allow the computer to play a hand - in a manner very similar to Part A's playHand function. This function allows the computer to play a given hand and is very similar to the earlier version in which a user selected the word, although deciding when it is done playing a particular hand is different.
22 |
23 | # Test Cases to Understand the Code:
24 |
25 | # compPlayHand({'a': 1, 'p': 2, 's': 1, 'e': 1, 'l': 1}, wordList, 6)
26 | # Current Hand: a p p s e l
27 | # "appels" earned 110 points. Total: 110 points
28 | # Total score: 110 points.
29 |
30 | # compPlayHand({'a': 2, 'c': 1, 'b': 1, 't': 1}, wordList, 5)
31 | # Current Hand: a a c b t "acta"
32 | # earned 24 points. Total: 24 points
33 | # Current Hand: b Total score: 24 points.
34 |
35 | # compPlayHand({'a': 2, 'e': 2, 'i': 2, 'm': 2, 'n': 2, 't': 2}, wordList, 12)
36 | # Current Hand: a a e e i i m m n n t t
37 | # "immanent" earned 96 points. Total: 96 points
38 | # Current Hand: a e t i
39 | # "ait" earned 9 points. Total: 105 points
40 | # Current Hand: e
41 | # Total score: 105 points.
42 |
43 |
44 | # Problem 7 - You and your Computer
45 | # 20.0/20.0 points (graded)
46 | # Now that your computer can choose a word, you need to give the computer the option to play. Write the code that re-implements the playGame function. You will modify the function to behave as described below in the function's comments. As before, you should use the HAND_SIZE constant to determine the number of cards in a hand. Be sure to try out different values for HAND_SIZE with your program.
47 |
48 | # Sample Output and Hints
49 | # Here is how the game output should look...
50 |
51 | # Hints about the output
52 |
53 | # A Note On Runtime
54 | # You may notice that things run slowly when the computer plays. This is to be expected. If you want (totally optional!), feel free to investigate ways of making the computer's turn go faster - one way is to preprocess the word list into a dictionary (string -> int) so looking up the score of a word becomes much faster in the compChooseWord function.
55 |
56 | # Be careful though - you only want to do this preprocessing one time - probably right after we generate the wordList for you (at the bottom of the file). If you choose to do this, you'll have to modify what inputs your functions take (they'll probably take a word dictionary instead of a word list, for example).
57 |
58 | # IMPORTANT:Don't worry about this issue when running your code in the checker below! We load a very small sample wordList (much smaller than 83667 words!) to avoid having your code time out. Your code will work even if you don't implement a form of pre-processing as described.
59 |
60 | # Entering Your Code
61 | # Be sure to only paste your definition for playGame from ps4b.py in the following box. Do not include any other function definitions.
62 |
63 | def playGame(wordList):
64 | """
65 | Allow the user to play an arbitrary number of hands.
66 |
67 | 1) Asks the user to input 'n' or 'r' or 'e'.
68 | * If the user inputs 'e', immediately exit the game.
69 | * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again.
70 |
71 | 2) Asks the user to input a 'u' or a 'c'.
72 | * If the user inputs anything that's not 'c' or 'u', keep asking them again.
73 |
74 | 3) Switch functionality based on the above choices:
75 | * If the user inputted 'n', play a new (random) hand.
76 | * Else, if the user inputted 'r', play the last hand again.
77 |
78 | * If the user inputted 'u', let the user play the game
79 | with the selected hand, using playHand.
80 | * If the user inputted 'c', let the computer play the
81 | game with the selected hand, using compPlayHand.
82 |
83 | 4) After the computer or user has played the hand, repeat from step 1
84 |
85 | wordList: list (string)
86 | """
87 | # TO DO... <-- Remove this comment when you code this function
88 |
89 | while True:
90 | user_input = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ", )
91 | if user_input == 'e':
92 | break
93 | elif user_input == 'n':
94 | while True:
95 |
96 | if user_input == 'n':
97 | inp = input("Enter u to have yourself play, c to have the computer play: ", )
98 |
99 | if inp == 'u':
100 |
101 | hand = dealHand(HAND_SIZE)
102 | playHand(hand, wordList, HAND_SIZE)
103 | break
104 |
105 | elif inp == 'c':
106 |
107 | hand = dealHand(HAND_SIZE)
108 | compPlayHand(hand, wordList, HAND_SIZE)
109 | break
110 |
111 | else:
112 | print("Invalid command.")
113 |
114 | elif user_input == 'r':
115 | try:
116 | hand
117 | inp = input("Enter u to have yourself play, c to have the computer play: ", )
118 |
119 | if inp == 'u':
120 | playHand(hand, wordList, HAND_SIZE)
121 |
122 | elif inp == 'c':
123 | compPlayHand(hand, wordList, HAND_SIZE)
124 |
125 | else:
126 | print("Invalid command.")
127 | except:
128 | print("You have not played a hand yet. Please play a new hand first!")
129 | else:
130 | print("Invalid command.")
131 |
132 |
133 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Exercise_coordinate.py:
--------------------------------------------------------------------------------
1 | # Exercise: coordinate
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 7 minutes
4 |
5 | # Consider the following code from the last lecture video:
6 |
7 | # class Coordinate(object):
8 | # def __init__(self, x, y):
9 | # self.x = x
10 | # self.y = y
11 |
12 | # def getX(self):
13 | # # Getter method for a Coordinate object's x coordinate.
14 | # # Getter methods are better practice than just accessing an attribute directly
15 | # return self.x
16 |
17 | # def getY(self):
18 | # # Getter method for a Coordinate object's y coordinate
19 | # return self.y
20 |
21 | # def __str__(self):
22 | # return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
23 | # Your task is to define the following two methods for the Coordinate class:
24 |
25 | # Add an __eq__ method that returns True if coordinates refer to same point in the plane (i.e., have the same x and y coordinate).
26 |
27 | # Define __repr__, a special method that returns a string that looks like a valid Python expression that could be used to recreate an object with the same value. In other words, eval(repr(c)) == c given the definition of __eq__ from part 1.
28 |
29 | # For more on __repr__, see this SO post
30 |
31 | class Coordinate(object):
32 | def __init__(self,x,y):
33 | self.x = x
34 | self.y = y
35 |
36 | def getX(self):
37 | # Getter method for a Coordinate object's x coordinate.
38 | # Getter methods are better practice than just accessing an attribute directly
39 | return self.x
40 |
41 | def getY(self):
42 | # Getter method for a Coordinate object's y coordinate
43 | return self.y
44 |
45 | def __str__(self):
46 | return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
47 |
48 | def __eq__(self, other):
49 | if self.getX() == other.getX() and self.getY() == other.getY():
50 | return True
51 | else:
52 | return False
53 | def __repr__(self):
54 | return "Coordinate"+ "("+ (str(self.x)) + "," + (str(self.y)) + ")"
55 |
56 |
57 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Exercise_genPrimes.py:
--------------------------------------------------------------------------------
1 | # Exercise: genPrimes
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 10 minutes
4 |
5 | # Write a generator, genPrimes, that returns the sequence of prime numbers on successive calls to its next() method: 2, 3, 5, 7, 11, ...
6 |
7 | # Hints
8 | # Ideas about the problem
9 | # Have the generator keep a list of the primes it's generated. A candidate number x is prime if (x % p) != 0 for all earlier primes p.
10 |
11 |
12 | def genPrimes():
13 | num = 2
14 | def isPrime(x):
15 |
16 | if x > 1:
17 | for i in range(2, x):
18 | if (x % i) == 0:
19 | return False
20 | else:
21 | return True
22 | while True:
23 | if isPrime(num)==True:
24 | yield num
25 | num += 1
26 |
27 |
28 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Exercise_hand.py:
--------------------------------------------------------------------------------
1 | # Exercise: hand
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 14 minutes
4 |
5 | # In this problem, you'll be asked to read through an object-oriented implementation of the hand from the word game problem of Problem Set 4. You'll then be asked to implement one of its methods. Note that the implementation of the object-oriented version of the hand is a bit different than how we did things with the functional implementation; pay close attention to doc strings and read through the implementation carefully.
6 |
7 | # To begin: Download hand.py and read through the file. Be sure to understand what's going on in the file. Make a few instances of the Hand class, and play around with the existing methods.
8 |
9 | # When you have completed reading through the file, implement the update method.
10 |
11 | # Paste the entire Hand class in the box below.
12 |
13 | # The __str__ method is this:
14 |
15 | # def __str__(self):
16 | # '''
17 | # Display a string representation of the hand.
18 | # '''
19 | # output = ''
20 | # hand_keys = self.hand.keys()
21 | # hand_keys.sort()
22 | # for letter in hand_keys:
23 | # for j in range(self.hand[letter]):
24 | # output += letter
25 | # return output
26 | # A more concise version of this code might be
27 |
28 | # def __str__(self):
29 | # '''
30 | # Display a string representation of the hand.
31 | # '''
32 | # output = ''
33 | # for letter in sorted(self.hand.keys()):
34 | # output += letter * self.hand[letter]
35 | # return output
36 | # Use whichever __str__ method you like. This will make sure the grading of the hand's display is consistent.
37 |
38 |
39 | import random
40 |
41 | class Hand(object):
42 | def __init__(self, n):
43 | '''
44 | Initialize a Hand.
45 |
46 | n: integer, the size of the hand.
47 | '''
48 | assert type(n) == int
49 | self.HAND_SIZE = n
50 | self.VOWELS = 'aeiou'
51 | self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
52 |
53 | # Deal a new hand
54 | self.dealNewHand()
55 |
56 | def dealNewHand(self):
57 | '''
58 | Deals a new hand, and sets the hand attribute to the new hand.
59 | '''
60 | # Set self.hand to a new, empty dictionary
61 | self.hand = {}
62 |
63 | # Build the hand
64 | numVowels = self.HAND_SIZE // 3
65 |
66 | for i in range(numVowels):
67 | x = self.VOWELS[random.randrange(0,len(self.VOWELS))]
68 | self.hand[x] = self.hand.get(x, 0) + 1
69 |
70 | for i in range(numVowels, self.HAND_SIZE):
71 | x = self.CONSONANTS[random.randrange(0,len(self.CONSONANTS))]
72 | self.hand[x] = self.hand.get(x, 0) + 1
73 |
74 | def setDummyHand(self, handString):
75 | '''
76 | Allows you to set a dummy hand. Useful for testing your implementation.
77 |
78 | handString: A string of letters you wish to be in the hand. Length of this
79 | string must be equal to self.HAND_SIZE.
80 |
81 | This method converts sets the hand attribute to a dictionary
82 | containing the letters of handString.
83 | '''
84 | assert len(handString) == self.HAND_SIZE, "Length of handString ({0}) must equal length of HAND_SIZE ({1})".format(len(handString), self.HAND_SIZE)
85 | self.hand = {}
86 | for char in handString:
87 | self.hand[char] = self.hand.get(char, 0) + 1
88 |
89 |
90 | def calculateLen(self):
91 | '''
92 | Calculate the length of the hand.
93 | '''
94 | ans = 0
95 | for k in self.hand:
96 | ans += self.hand[k] # it is return value of the dictionary
97 | return ans
98 |
99 | def __str__(self):
100 | '''
101 | Display a string representation of the hand.
102 | '''
103 | output = ''
104 | hand_keys = sorted(self.hand.keys())
105 | for letter in hand_keys:
106 | for j in range(self.hand[letter]):
107 | output += letter
108 | return output
109 |
110 | def update(self, word):
111 | """
112 | Does not assume that self.hand has all the letters in word.
113 |
114 | Updates the hand: if self.hand does have all the letters to make
115 | the word, modifies self.hand by using up the letters in the given word.
116 |
117 | Returns True if the word was able to be made with the letter in
118 | the hand; False otherwise.
119 |
120 | word: string
121 | returns: Boolean (if the word was or was not made)
122 | """
123 | # Your code here
124 |
125 | """
126 | Displays the letters currently in the hand.
127 |
128 | For example:
129 | >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
130 | Should print out something like:
131 | a x x l l l e
132 | The order of the letters is unimportant.
133 |
134 | hand: dictionary (string -> int)
135 | """
136 |
137 | hand_letter_list = []
138 | for letter in self.hand.keys():
139 | for j in range(self.hand[letter]):
140 | hand_letter_list.append(letter)
141 |
142 | # for i in word:
143 | # if i in self.hand.keys():
144 | # self.hand[i] = self.hand.get(i, 0) -1
145 | # return self.hand
146 |
147 | def isValidWord(word):
148 | """
149 | Returns True if word is in the wordList and is entirely
150 | composed of letters in the hand. Otherwise, returns False.
151 |
152 | Does not mutate hand or wordList.
153 |
154 | word: string
155 | hand: dictionary (string -> int)
156 | wordList: list of lowercase strings
157 | """
158 | hand_1 = self.hand.copy()
159 | letter_check = set(list(word)) <= set(hand_1.keys())
160 | # letter_check = True
161 | # else:
162 | # letter_check = False
163 |
164 | for i in word:
165 | if i in hand_1.keys():
166 | hand_1[i] = hand_1.get(i, 0) -1
167 |
168 | valueCheck = all(i >= 0 for i in hand_1.values())
169 |
170 | if letter_check == True and valueCheck == True:
171 | return True
172 | else:
173 | return False
174 |
175 | if isValidWord(word) == True:
176 | word_list = list(word)
177 | hand_1 = self.hand.copy()
178 | for letter in word_list:
179 | if letter in hand_1.keys():
180 | hand_1[letter] = hand_1.get(letter, 0) -1
181 | self.hand = {k: hand_1[k] for k in hand_1 if hand_1[k] != 0}
182 | return True
183 | else:
184 | return False
185 |
186 |
187 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Exercise_int_set.py:
--------------------------------------------------------------------------------
1 | # Exercise: int set
2 | # 5.0/5.0 points (graded)
3 | # ESTIMATED TIME TO COMPLETE: 10 minutes
4 |
5 | # Consider the following code from the last lecture video:
6 |
7 | # class intSet(object):
8 | # """An intSet is a set of integers
9 | # The value is represented by a list of ints, self.vals.
10 | # Each int in the set occurs in self.vals exactly once."""
11 |
12 | # def __init__(self):
13 | # """Create an empty set of integers"""
14 | # self.vals = []
15 |
16 | # def insert(self, e):
17 | # """Assumes e is an integer and inserts e into self"""
18 | # if not e in self.vals:
19 | # self.vals.append(e)
20 |
21 | # def member(self, e):
22 | # """Assumes e is an integer
23 | # Returns True if e is in self, and False otherwise"""
24 | # return e in self.vals
25 |
26 | # def remove(self, e):
27 | # """Assumes e is an integer and removes e from self
28 | # Raises ValueError if e is not in self"""
29 | # try:
30 | # self.vals.remove(e)
31 | # except:
32 | # raise ValueError(str(e) + ' not found')
33 |
34 | # def __str__(self):
35 | # """Returns a string representation of self"""
36 | # self.vals.sort()
37 | # return '{' + ','.join([str(e) for e in self.vals]) + '}'
38 | # Your task is to define the following two methods for the intSet class:
39 |
40 | # Define an intersect method that returns a new intSet containing elements that appear in both sets. In other words,
41 |
42 | # s1.intersect(s2)
43 | # would return a new intSet of integers that appear in both s1 and s2. Think carefully - what should happen if s1 and s2 have no elements in common?
44 |
45 | # Add the appropriate method(s) so that len(s) returns the number of elements in s.
46 |
47 | # Hint: look through the Python docs to figure out what you'll need to solve this problem.
48 |
49 |
50 | class intSet(object):
51 | """An intSet is a set of integers
52 | The value is represented by a list of ints, self.vals.
53 | Each int in the set occurs in self.vals exactly once."""
54 |
55 | def __init__(self):
56 | """Create an empty set of integers"""
57 | self.vals = []
58 |
59 | def insert(self, e):
60 | """Assumes e is an integer and inserts e into self"""
61 | if not e in self.vals:
62 | self.vals.append(e)
63 |
64 | def member(self, e):
65 | """Assumes e is an integer
66 | Returns True if e is in self, and False otherwise"""
67 | return e in self.vals
68 |
69 | def remove(self, e):
70 | """Assumes e is an integer and removes e from self
71 | Raises ValueError if e is not in self"""
72 | try:
73 | self.vals.remove(e)
74 | except:
75 | raise ValueError(str(e) + ' not found')
76 |
77 | def __str__(self):
78 | """Returns a string representation of self"""
79 | self.vals.sort()
80 | return '{' + ','.join([str(e) for e in self.vals]) + '}'
81 | def intersect(self, other):
82 | self.store = []
83 | for i in self.vals:
84 | if i in other.vals:
85 | self.store.append(i)
86 | return '{' + ','.join([str(i) for i in self.store]) + '}'
87 | def __len__(self):
88 | return len(self.vals)
89 |
90 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Problem_Set/Problem_1_Build_the_Shift_Dictionary_and_Apply_Shift.py:
--------------------------------------------------------------------------------
1 | # Encryption is the process of obscuring information to make it unreadable without special knowledge. For centuries, people have devised schemes to encrypt messages - some better than others - but the advent of the computer and the Internet revolutionized the field. These days, it's hard not to encounter some sort of encryption, whether you are buying something online or logging into a shared computer system. Encryption lets you share information with other trusted people, without fear of disclosure.
2 |
3 | # A cipher is an algorithm for performing encryption (and the reverse, decryption). The original information is called plaintext. After it is encrypted, it is called ciphertext. The ciphertext message contains all the information of the plaintext message, but it is not in a format readable by a human or computer without the proper mechanism to decrypt it; it should resemble random gibberish to those for whom it is not intended.
4 |
5 | # A cipher usually depends on a piece of auxiliary information, called a key. The key is incorporated into the encryption process; the same plaintext encrypted with two different keys should have two different ciphertexts. Without the key, it should be difficult to decrypt the resulting ciphertext into readable plaintext.
6 |
7 | # This assignment will deal with a well-known (though not very secure) encryption method called the Caesar cipher. Some vocabulary to get you started on this problem:
8 |
9 | # Encryption - the process of obscuring or encoding messages to make them unreadable until they are decrypted
10 | # Decryption - making encrypted messages readable again by decoding them
11 | # Cipher - algorithm for performing encryption and decryption
12 | # Plaintext - the original message
13 | # Ciphertext - the encrypted message. Note: a ciphertext still contains all of the original message information, even if it looks like gibberish.
14 | # The Caesar Cipher
15 |
16 | # The idea of the Caesar Cipher is to pick an integer and shift every letter of your message by that integer. In other words, suppose the shift is k . Then, all instances of the i-th letter of the alphabet that appear in the plaintext should become the (i+k)-th letter of the alphabet in the ciphertext. You will need to be careful with the case in which i + k > 26 (the length of the alphabet). Here is what the whole alphabet looks like shifted three spots to the right:
17 |
18 | # Original: a b c d e f g h i j k l m n o p q r s t u v w x y z
19 | # 3-shift: d e f g h i j k l m n o p q r s t u v w x y z a b c
20 | # Using the above key, we can quickly translate the message "happy" to "kdssb" (note how the 3-shifted alphabet wraps around at the end, so x -> a, y -> b, and z -> c).
21 |
22 | # Note!! We are using the English alphabet for this problem - that is, the following letters in the following order:
23 |
24 | # >>> import string
25 | # >>> print string.ascii_lowercase
26 | # abcdefghijklmnopqrstuvwxyz
27 | # We will treat uppercase and lowercase letters individually, so that uppercase letters are always mapped to an uppercase letter, and lowercase letters are always mapped to a lowercase letter. If an uppercase letter maps to "A", then the same lowercase letter should map to "a". Punctuation and spaces should be retained and not changed. For example, a plaintext message with a comma should have a corresponding ciphertext with a comma in the same position.
28 |
29 | # | plaintext | shift | ciphertext |
30 | # | ----------------|-----------|------------------|
31 | # | 'abcdef' | 2 | 'cdefgh' |
32 | # | 'Hello, World!' | 5 | 'Mjqqt, Btwqi!' |
33 | # | '' | any value | '' |
34 | # We implemented for you two helper functions: load_words and is_word. You may use these in your solution and you do not need to understand them completely, but should read the associated comments. You should read and understand the helper code in the rest of the file and use it to guide your solutions.
35 |
36 | # Getting Started
37 |
38 | # To get started, download the ps6.zip file. Extract it to your working directory. The files inside are:
39 |
40 | # ps6.py - a file containing three classes that you will have to implement.
41 | # words.txt - a file containing valid English words (should be in the same folder as your ps6..py file).
42 | # story.txt - a file containing an encrypted message that you will have to decode (should be in the same folder as your ps6..py file).
43 | # This will be your first experience coding with classes! We will have a Message class with two subclasses PlaintextMessage and CiphertextMessage .
44 |
45 | ######################################################################################################
46 |
47 | # Problem 1 - Build the Shift Dictionary and Apply Shift
48 | # 20.0/20.0 points (graded)
49 | # The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action).
50 |
51 | # In the next two questions, you will fill in the methods of the Message class found in ps6.py according to the specifications in the docstrings. The methods in the Message class already filled in are:
52 |
53 | # __init__(self, text)
54 | # The getter method get_message_text(self)
55 | # The getter method get_valid_words(self), notice that this one returns a copy of self.valid_words to prevent someone from mutating the original list.
56 | # In this problem, you will fill in two methods:
57 |
58 | # Fill in the build_shift_dict(self, shift) method of the Message class. Be sure that your dictionary includes both lower and upper case letters, but that the shifted character for a lower case letter and its uppercase version are lower and upper case instances of the same letter. What this means is that if the original letter is "a" and its shifted value is "c", the letter "A" should shift to the letter "C".
59 |
60 | # If you are unfamiliar with the ordering or characters of the English alphabet, we will be following the letter ordering displayed by string.ascii_lowercase and string.ascii_uppercase:
61 |
62 | # >>> import string
63 | # >>> print(string.ascii_lowercase)
64 | # abcdefghijklmnopqrstuvwxyz
65 | # >>> print(string.ascii_uppercase)
66 | # ABCDEFGHIJKLMNOPQRSTUVWXYZ
67 | # A reminder from the introduction page - characters such as the space character, commas, periods, exclamation points, etc will not be encrypted by this cipher - basically, all the characters within string.punctuation, plus the space (' ') and all numerical characters (0 - 9) found in string.digits.
68 |
69 | # Fill in the apply_shift(self, shift) method of the Message class. You may find it easier to use build_shift_dict(self, shift). Remember that spaces and punctuation should not be changed by the cipher.
70 |
71 | # Paste your implementation of the Message class in the box below.
72 |
73 |
74 | class Message(object):
75 | ### DO NOT MODIFY THIS METHOD ###
76 | def __init__(self, text):
77 | '''
78 | Initializes a Message object
79 |
80 | text (string): the message's text
81 |
82 | a Message object has two attributes:
83 | self.message_text (string, determined by input text)
84 | self.valid_words (list, determined using helper function load_words
85 | '''
86 | self.message_text = text
87 | self.valid_words = load_words(WORDLIST_FILENAME)
88 |
89 | ### DO NOT MODIFY THIS METHOD ###
90 | def get_message_text(self):
91 | '''
92 | Used to safely access self.message_text outside of the class
93 |
94 | Returns: self.message_text
95 | '''
96 | return self.message_text
97 |
98 | ### DO NOT MODIFY THIS METHOD ###
99 | def get_valid_words(self):
100 | '''
101 | Used to safely access a copy of self.valid_words outside of the class
102 |
103 | Returns: a COPY of self.valid_words
104 | '''
105 | return self.valid_words[:]
106 |
107 | def build_shift_dict(self, shift):
108 | '''
109 | Creates a dictionary that can be used to apply a cipher to a letter.
110 | The dictionary maps every uppercase and lowercase letter to a
111 | character shifted down the alphabet by the input shift. The dictionary
112 | should have 52 keys of all the uppercase letters and all the lowercase
113 | letters only.
114 |
115 | shift (integer): the amount by which to shift every letter of the
116 | alphabet. 0 <= shift < 26
117 |
118 | Returns: a dictionary mapping a letter (string) to
119 | another letter (string).
120 | '''
121 | # Code Here #
122 | lower_keys = list(string.ascii_lowercase)
123 | lower_values = list(string.ascii_lowercase)
124 | lower_shift_values = lower_keys[shift:] + lower_values[:shift]
125 |
126 | upper_keys = list(string.ascii_uppercase)
127 | upper_values = list(string.ascii_uppercase)
128 | upper_shift_values = upper_keys[shift:] + upper_values[:shift]
129 |
130 | combine_keys = lower_keys + upper_keys
131 | shift_combine_keys = lower_shift_values + upper_shift_values
132 |
133 | self.shift_dict = dict(zip(combine_keys, shift_combine_keys))
134 | return self.shift_dict
135 |
136 |
137 | def apply_shift(self, shift):
138 | '''
139 | Applies the Caesar Cipher to self.message_text with the input shift.
140 | Creates a new string that is self.message_text shifted down the
141 | alphabet by some number of characters determined by the input shift
142 |
143 | shift (integer): the shift with which to encrypt the message.
144 | 0 <= shift < 26
145 |
146 | Returns: the message text (string) in which every character is shifted
147 | down the alphabet by the input shift
148 | '''
149 | #delete this line and replace with your code here
150 |
151 | new_text = []
152 | for i in self.message_text:
153 | if i not in self.build_shift_dict(shift).keys():
154 | new_text.append(i)
155 | else:
156 | new_text.append(self.build_shift_dict(shift)[i])
157 | return "".join(new_text)
158 |
159 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Problem_Set/Problem_2_PlaintextMessage.py:
--------------------------------------------------------------------------------
1 | # Problem 2 - PlaintextMessage
2 | # 15.0/15.0 points (graded)
3 | # For this problem, the graders will use our implementation of the Message class, so don't worry if you did not get the previous parts correct.
4 |
5 | # PlaintextMessage is a subclass of Message and has methods to encode a string using a specified shift value. Our class will always create an encoded version of the message, and will have methods for changing the encoding.
6 |
7 | # Implement the methods in the class PlaintextMessage according to the specifications in ps6.py. The methods you should fill in are:
8 |
9 | # __init__(self, text, shift): Use the parent class constructor to make your code more concise.
10 | # The getter method get_shift(self)
11 | # The getter method get_encrypting_dict(self): This should return a COPY of self.encrypting_dict to prevent someone from mutating the original dictionary.
12 | # The getter method get_message_text_encrypted(self)
13 | # change_shift(self, shift): Think about what other methods you can use to make this easier. It shouldn’t take more than a couple lines of code.
14 | # Paste your implementation of the entire PlaintextMessage class in the box below.
15 |
16 | class PlaintextMessage(Message):
17 | def __init__(self, text, shift):
18 | '''
19 | Initializes a PlaintextMessage object
20 |
21 | text (string): the message's text
22 | shift (integer): the shift associated with this message
23 |
24 | A PlaintextMessage object inherits from Message and has five attributes:
25 | self.message_text (string, determined by input text)
26 | self.valid_words (list, determined using helper function load_words)
27 | self.shift (integer, determined by input shift)
28 | self.encrypting_dict (dictionary, built using shift)
29 | self.message_text_encrypted (string, created using shift)
30 |
31 | Hint: consider using the parent class constructor so less
32 | code is repeated
33 | '''
34 | #delete this line and replace with your code here
35 | self.message_text = text
36 | self.valid_words = load_words(WORDLIST_FILENAME)
37 | self.shift = shift
38 | self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift)
39 | self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift)
40 |
41 |
42 |
43 | def get_shift(self):
44 | '''
45 | Used to safely access self.shift outside of the class
46 |
47 | Returns: self.shift
48 | '''
49 | #delete this line and replace with your code here
50 | return self.shift
51 |
52 | def get_encrypting_dict(self):
53 | '''
54 | Used to safely access a copy self.encrypting_dict outside of the class
55 |
56 | Returns: a COPY of self.encrypting_dict
57 | '''
58 | #delete this line and replace with your code here
59 | x_self_encrypting_dict = self.encrypting_dict.copy()
60 | return x_self_encrypting_dict
61 |
62 | def get_message_text_encrypted(self):
63 | '''
64 | Used to safely access self.message_text_encrypted outside of the class
65 |
66 | Returns: self.message_text_encrypted
67 | '''
68 | #delete this line and replace with your code here
69 | return self.message_text_encrypted
70 |
71 | def change_shift(self, shift):
72 | '''
73 | Changes self.shift of the PlaintextMessage and updates other
74 | attributes determined by shift (ie. self.encrypting_dict and
75 | message_text_encrypted).
76 |
77 | shift (integer): the new shift that should be associated with this message.
78 | 0 <= shift < 26
79 |
80 | Returns: nothing
81 | '''
82 | #delete this line and replace with your code here
83 | self.shift = shift
84 | self.encrypting_dict = super(PlaintextMessage, self).build_shift_dict(shift)
85 | self.message_text_encrypted = super(PlaintextMessage, self).apply_shift(shift)
86 |
87 |
88 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Problem_Set/Problem_3_CiphertextMessage.py:
--------------------------------------------------------------------------------
1 | # Problem 3 - CiphertextMessage
2 | # 15.0/15.0 points (graded)
3 | # For this problem, the graders will use our implementation of the Message and PlaintextMessage classes, so don't worry if you did not get the previous parts correct.
4 |
5 | # Given an encrypted message, if you know the shift used to encode the message, decoding it is trivial. If message is the encrypted message, and s is the shift used to encrypt the message, then apply_shift(message, 26-s) gives you the original plaintext message. Do you see why?
6 |
7 | # The problem, of course, is that you don’t know the shift. But our encryption method only has 26 distinct possible values for the shift! We know English is the main language of these emails, so if we can write a program that tries each shift and maximizes the number of English words in the decoded message, we can decrypt their cipher! A simple indication of whether or not the correct shift has been found is if most of the words obtained after a shift are valid words. Note that this only means that most of the words obtained are actual words. It is possible to have a message that can be decoded by two separate shifts into different sets of words. While there are various strategies for deciding between ambiguous decryptions, for this problem we are only looking for a simple solution.
8 |
9 | # Fill in the methods in the class CiphertextMessage acording to the specifications in ps6.py. The methods you should fill in are:
10 |
11 | # __init__(self, text): Use the parent class constructor to make your code more concise.
12 | # decrypt_message(self): You may find the helper function is_word(wordlist, word) and the string method split() useful. Note that is_word will ignore punctuation and other special characters when considering whether a word is valid.
13 | # Hints
14 | # Using string.split
15 | # You may find the function string.split useful for dividing the text up into words.
16 |
17 | # >>> 'Hello world!'.split('o')
18 | # ['Hell', ' w', 'rld!']
19 | # >>> '6.00.1x is pretty fun'.split(' ')
20 | # ['6.00.1x', 'is', 'pretty', 'fun']
21 |
22 |
23 | class CiphertextMessage(Message):
24 | def __init__(self, text):
25 | '''
26 | Initializes a CiphertextMessage object
27 |
28 | text (string): the message's text
29 |
30 | a CiphertextMessage object has two attributes:
31 | self.message_text (string, determined by input text)
32 | self.valid_words (list, determined using helper function load_words)
33 | '''
34 | #delete this line and replace with your code here
35 | self.message_text = text
36 | self.valid_words = load_words(WORDLIST_FILENAME)
37 |
38 |
39 | def decrypt_message(self):
40 | '''
41 | Decrypt self.message_text by trying every possible shift value
42 | and find the "best" one. We will define "best" as the shift that
43 | creates the maximum number of real words when we use apply_shift(shift)
44 | on the message text. If s is the original shift value used to encrypt
45 | the message, then we would expect 26 - s to be the best shift value
46 | for decrypting it.
47 |
48 | Note: if multiple shifts are equally good such that they all create
49 | the maximum number of you may choose any of those shifts (and their
50 | corresponding decrypted messages) to return
51 |
52 | Returns: a tuple of the best shift value used to decrypt the message
53 | and the decrypted message text using that shift value
54 | '''
55 | #delete this line and replace with your code here
56 | word_no = 0
57 | high_no = 0
58 | for i in range(26):
59 | for ch in list(super(CiphertextMessage, self).apply_shift(i).split(" ")):
60 | if is_word(self.valid_words, ch):
61 | word_no += 1
62 | if word_no > high_no:
63 | high_no = word_no
64 | best_shift_value = i
65 | dec_msg = super(CiphertextMessage, self).apply_shift(i)
66 |
67 | return (best_shift_value, dec_msg)
68 |
69 |
70 | # Correct
--------------------------------------------------------------------------------
/Week_5_Object_Oriented_Programming/Problem_Set/Problem_4_Decrypt_a_Story.py:
--------------------------------------------------------------------------------
1 | # Problem 4 - Decrypt a Story
2 | # 5.0/5.0 points (graded)
3 | # For this problem, the graders will use our implementation of the Message, PlaintextMessage, and CiphertextMessage classes, so don't worry if you did not get the previous parts correct.
4 |
5 | # Now that you have all the pieces to the puzzle, please use them to decode the file story.txt. The file ps6.py contains a helper function get_story_string() that returns the encrypted version of the story as a string. Create a CiphertextMessage object using the story string and use decrypt_message to return the appropriate shift value and unencrypted story string.
6 |
7 | # Paste your function decrypt_story() in the box below.
8 |
9 | def decrypt_story():
10 | joke = CiphertextMessage(get_story_string())
11 | decStory = joke.decrypt_message()
12 | return decStory
13 |
14 |
15 | # Correct
16 |
17 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-time-machine
--------------------------------------------------------------------------------