├── Chapter1.General Introduction └── formulas.py ├── Chapter10. Files ├── afile.py ├── file.py ├── formulas.py ├── grade.csv ├── olympians.py ├── olympics.txt └── reduced_olympics.csv ├── Chapter11. Dictionaries ├── dict.py ├── formulas.py ├── max_value.py └── min_value.py ├── Chapter12. Functions ├── Common_letter.py ├── def_name.py ├── def_sumofsquares.py ├── def_turtle.py ├── difficult.py └── formulas.py ├── Chapter13. Tuple Packing and Unpacking ├── formulas.py ├── rough.py └── tuple.py ├── Chapter14. More About Iteration ├── even.py ├── formulas.py ├── sum_of_list.py ├── whileloop.py └── whileloop_ass.py ├── Chapter15. Advanced Functions ├── ass.py ├── formulas.py └── lambda.py ├── Chapter16. Sorting ├── ass.py ├── course2project.py ├── formulas.py ├── hig-low_nums.py ├── project │ ├── course2project1.py │ ├── negative_words.txt │ ├── positive_words.txt │ └── project_twitter_data.csv ├── sort.py └── sorted_key.py ├── Chapter17. Nested Data and Nested Iteration ├── copy_inner.py ├── course_3_assessment_1.py └── formulas.py ├── Chapter18. Test Cases ├── count.py ├── distance.py ├── formulas.py ├── intro.py ├── reverse.py └── testcase.py ├── Chapter19. Exceptions ├── formulas.py └── try.py ├── Chapter2. Variables, Statements, and Expressions ├── 2.10. Statements and Expressions.py ├── 2.13. Updating Variables.py ├── 2.2.Values and Data types.py ├── 2.3.Operaors and Operands.py ├── 2.4.Functions calls.py ├── 2.6. Type conversion functions.py ├── 2.7. Variables.py ├── hardcoding.py ├── input.py └── rougy.py ├── Chapter20. Defining your own Classes └── formulas.py ├── Chapter21. Building Programs └── formulas.py ├── Chapter22. Inheritance ├── 1 │ ├── 3.py │ ├── Pet.py │ └── Pet1.py ├── 2 │ ├── 1.py │ └── 2.py ├── 3 │ ├── 1.py │ ├── 2.py │ └── 3.py ├── 4 │ └── Tamagotchi.py └── formulas.py ├── Chapter23. More on Accumulation: Map, Filter, List Comprehension, and Zip ├── course_3_assessment_2.py ├── formulas.py └── zip.py ├── Chapter24. Internet APIs ├── Apple_com.py ├── Fetching_a_page.py ├── RestAPI_intro.py ├── flicker.py ├── formulas.py ├── read&write_file.py └── requests_with_caching.py ├── Chapter3. Debugging └── formulas.py ├── Chapter4. Python Modules ├── formulas.py ├── randommodule.py └── randon.py ├── Chapter5. Python Turtle ├── 2stars.py ├── crossarrow.py ├── forloop.py ├── loop&turtle.py ├── proj.py ├── sq_tr_hex_oct.py ├── star.py ├── turtle-shape.py ├── turtle.py ├── turtle.pyc └── turtle_forwar_back.py ├── Chapter6. Sequences ├── 1.py ├── count.py ├── formulas.py ├── index.py ├── listslices.py ├── split.py ├── str&list&tuples.py ├── str&lists.py └── str.py ├── Chapter7. Iteration ├── RGB.py ├── accumulator.py ├── assg.py ├── forloop_byindex.py ├── formulas.py ├── loop.py └── reverse_str.py ├── Chapter8. Conditionals ├── ass.py ├── danger.py ├── formulas.py ├── in_notin.py ├── kirakassignment.py ├── rough.py └── turtleexample.py ├── Chapter9. Transforming Sequences ├── __pycache__ │ └── imp.cpython-37.pyc ├── formulas.py ├── imp.py ├── is.py ├── mutability.py └── rough.py ├── README.md ├── course_1_assessment_10.py ├── course_1_assessment_11.py ├── course_1_assessment_12.py ├── course_1_assessment_2.py ├── course_1_assessment_5.py ├── course_1_assessment_6.py ├── course_1_assessment_7.py ├── course_1_assessment_9.py ├── course_2_assessment_1.py ├── course_2_assessment_2.py ├── course_2_assessment_3.PY ├── course_2_assessment_4.PY ├── course_2_assessment_5.PY ├── course_2_assessment_6.py ├── course_2_assessment_7.py ├── course_2_assessment_8.py ├── course_2_project.py ├── course_3_assessment_1.py ├── course_3_assessment_2.py ├── course_3_project.py ├── course_4_assessment_1.py ├── course_4_assessment_2.py ├── course_4_project.py ├── formulas.py ├── list.py └── rough.py /Chapter1.General Introduction/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter10. Files/afile.py: -------------------------------------------------------------------------------- 1 | fileconnection = open("olympics.txt", 'r') 2 | lines = fileconnection.readlines() 3 | header = lines[0] 4 | field_names = header.strip().split(',') 5 | print(field_names) 6 | for row in lines[1:]: 7 | vals = row.strip().split(',') 8 | if vals[5] != "NA": 9 | print("{}: {}; {}".format( 10 | vals[0], 11 | vals[4], 12 | vals[5])) 13 | -------------------------------------------------------------------------------- /Chapter10. Files/file.py: -------------------------------------------------------------------------------- 1 | fileref = open("olympics.txt","r") 2 | line = fileref.readlines() 3 | 4 | for i in line[:4]: 5 | print(i) 6 | fileref.close() -------------------------------------------------------------------------------- /Chapter10. Files/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter10. Files/grade.csv: -------------------------------------------------------------------------------- 1 | Name, Subject, Grade 2 | Mujju, Maths, A 3 | Salman, Eng, A 4 | Thuss, lol, F 5 | -------------------------------------------------------------------------------- /Chapter10. Files/olympians.py: -------------------------------------------------------------------------------- 1 | olympians = [("John Aalberg", 31, "Cross Country Skiing"), 2 | ("Minna Maarit Aalto", 30, "Sailing"), 3 | ("Win Valdemar Aaltonen", 54, "Art Competitions"), 4 | ("Wakako Abe", 18, "Cycling")] 5 | 6 | outfile = open("reduced_olympics.csv","w") 7 | # output the header row 8 | outfile.write('Name,Age,Sport') 9 | outfile.write('\n') 10 | # output each of the rows: 11 | for olympian in olympians: 12 | row_string = '{},{},{}'.format(olympian[0], olympian[1], olympian[2]) 13 | outfile.write(row_string) 14 | outfile.write('\n') 15 | outfile.close() 16 | -------------------------------------------------------------------------------- /Chapter10. Files/olympics.txt: -------------------------------------------------------------------------------- 1 | Name,Sex,Age,Team,Event,Medal 2 | A Dijiang,M,24,China,Basketball,NA 3 | A Lamusi,M,23,China,Judo,NA 4 | Gunnar Nielsen Aaby,M,24,Denmark,Football,NA 5 | Edgar Lindenau Aabye,M,34,Denmark/Sweden,Tug-Of-War,Gold 6 | Christine Jacoba Aaftink,F,21,Netherlands,Speed Skating,NA 7 | Christine Jacoba Aaftink,F,21,Netherlands,Speed Skating,NA 8 | Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA 9 | Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA 10 | Christine Jacoba Aaftink,F,27,Netherlands,Speed Skating,NA 11 | Christine Jacoba Aaftink,F,27,Netherlands,Speed Skating,NA 12 | Per Knut Aaland,M,31,United States,Cross Country Skiing,NA 13 | Per Knut Aaland,M,31,United States,Cross Country Skiing,NA 14 | Per Knut Aaland,M,31,United States,Cross Country Skiing,NA 15 | Per Knut Aaland,M,31,United States,Cross Country Skiing,NA 16 | Per Knut Aaland,M,33,United States,Cross Country Skiing,NA 17 | Per Knut Aaland,M,33,United States,Cross Country Skiing,NA 18 | Per Knut Aaland,M,33,United States,Cross Country Skiing,NA 19 | Per Knut Aaland,M,33,United States,Cross Country Skiing,NA 20 | John Aalberg,M,31,United States,Cross Country Skiing,NA 21 | John Aalberg,M,31,United States,Cross Country Skiing,NA 22 | John Aalberg,M,31,United States,Cross Country Skiing,NA 23 | John Aalberg,M,31,United States,Cross Country Skiing,NA 24 | John Aalberg,M,33,United States,Cross Country Skiing,NA 25 | John Aalberg,M,33,United States,Cross Country Skiing,NA 26 | John Aalberg,M,33,United States,Cross Country Skiing,NA 27 | John Aalberg,M,33,United States,Cross Country Skiing,NA 28 | "Cornelia ""Cor"" Aalten (-Strannood)",F,18,Netherlands,Athletics,NA 29 | "Cornelia ""Cor"" Aalten (-Strannood)",F,18,Netherlands,Athletics,NA 30 | Antti Sami Aalto,M,26,Finland,Ice Hockey,NA 31 | "Einar Ferdinand ""Einari"" Aalto",M,26,Finland,Swimming,NA 32 | Jorma Ilmari Aalto,M,22,Finland,Cross Country Skiing,NA 33 | Jyri Tapani Aalto,M,31,Finland,Badminton,NA 34 | Minna Maarit Aalto,F,30,Finland,Sailing,NA 35 | Minna Maarit Aalto,F,34,Finland,Sailing,NA 36 | Pirjo Hannele Aalto (Mattila-),F,32,Finland,Biathlon,NA 37 | Arvo Ossian Aaltonen,M,22,Finland,Swimming,NA 38 | Arvo Ossian Aaltonen,M,22,Finland,Swimming,NA 39 | Arvo Ossian Aaltonen,M,30,Finland,Swimming,Bronze 40 | Arvo Ossian Aaltonen,M,30,Finland,Swimming,Bronze 41 | Arvo Ossian Aaltonen,M,34,Finland,Swimming,NA 42 | Juhamatti Tapio Aaltonen,M,28,Finland,Ice Hockey,Bronze 43 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,Bronze 44 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,Gold 45 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,NA 46 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,Gold 47 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,NA 48 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,NA 49 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,NA 50 | Paavo Johannes Aaltonen,M,28,Finland,Gymnastics,Gold 51 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 52 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,Bronze 53 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 54 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 55 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 56 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 57 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 58 | Paavo Johannes Aaltonen,M,32,Finland,Gymnastics,NA 59 | Timo Antero Aaltonen,M,31,Finland,Athletics,NA 60 | Win Valdemar Aaltonen,M,54,Finland,Art Competitions,NA -------------------------------------------------------------------------------- /Chapter10. Files/reduced_olympics.csv: -------------------------------------------------------------------------------- 1 | Name,Age,Sport 2 | John Aalberg,31,Cross Country Skiing 3 | Minna Maarit Aalto,30,Sailing 4 | Win Valdemar Aaltonen,54,Art Competitions 5 | Wakako Abe,18,Cycling 6 | -------------------------------------------------------------------------------- /Chapter11. Dictionaries/dict.py: -------------------------------------------------------------------------------- 1 | f = open('scarlet2.txt', 'r') 2 | txt = f.read() 3 | # now txt is one long string containing all the characters 4 | x = {} # start with an empty dictionary 5 | for c in txt: 6 | if c not in x: 7 | # we have not seen this character before, so initialize a counter for it 8 | x[c] = 0 9 | 10 | #whether we've seen it before or not, increment its counter 11 | x[c] = x[c] + 1 12 | 13 | letter_values = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f':4, 'g': 2, 'h':4, 'i':1, 'j':8, 'k':5, 'l':1, 'm':3, 'n':1, 'o':1, 'p':3, 'q':10, 'r':1, 's':1, 't':1, 'u':1, 'v':8, 'w':4, 'x':8, 'y':4, 'z':10} 14 | 15 | tot = 0 16 | for y in x: 17 | if y in letter_values: 18 | tot = tot + letter_values[y] * x[y] 19 | 20 | print(tot) 21 | -------------------------------------------------------------------------------- /Chapter11. Dictionaries/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter11. Dictionaries/max_value.py: -------------------------------------------------------------------------------- 1 | product = "iphone and android phones" 2 | lett_d = {} 3 | for char in product: 4 | if char not in lett_d: 5 | lett_d[char] = 0 6 | lett_d[char] = lett_d[char] +1 7 | print(lett_d) 8 | ks = lett_d.keys() 9 | 10 | max_value = list(ks)[0] 11 | for k in ks: 12 | print(k) 13 | if lett_d[k] > lett_d[max_value]: 14 | max_value = k 15 | print(max_value) -------------------------------------------------------------------------------- /Chapter11. Dictionaries/min_value.py: -------------------------------------------------------------------------------- 1 | placement = "Beaches are cool places to visit in spring however the Mackinaw Bridge is near. Most people visit Mackinaw later since the island is a cool place to explore." 2 | d ={} 3 | for char in placement: 4 | if char not in d: 5 | d[char] = 0 6 | d[char] = d[char] + 1 7 | print(d) 8 | ks = d.keys() 9 | min_value = list(ks)[0] 10 | 11 | for k in ks: 12 | if d[k] < min_value: 13 | min_value = k 14 | print("key " + min_value + " has the min_value value, " + str(d[min_value])) 15 | -------------------------------------------------------------------------------- /Chapter12. Functions/Common_letter.py: -------------------------------------------------------------------------------- 1 | def most_common_letter(s): 2 | frequencies = count_freqs(s) 3 | return best_key(frequencies) 4 | 5 | def count_freqs(st): 6 | d = {} 7 | for c in st: 8 | if c not in d: 9 | d[c] = 0 10 | d[c] = d[c] + 1 11 | return d 12 | 13 | def best_key(dictionary): 14 | ks = dictionary.keys() 15 | best_key_so_far = list(ks)[0] # Have to turn ks into a real list before using [] to select an item 16 | for k in ks: 17 | if dictionary[k] > dictionary[best_key_so_far]: 18 | best_key_so_far = k 19 | return best_key_so_far 20 | 21 | print(most_common_letter("abbbbbbbbbbbccccddddd")) 22 | -------------------------------------------------------------------------------- /Chapter12. Functions/def_name.py: -------------------------------------------------------------------------------- 1 | # answer = raw_input("Enter Becky only:") 2 | # def intro(string): 3 | # print("Hello, my name is", string ," and I love SI 106.") 4 | # return 5 | # intro(answer) 6 | 7 | def s_change(str): 8 | print(str,'for fun.') 9 | s_change('mujju') -------------------------------------------------------------------------------- /Chapter12. Functions/def_sumofsquares.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | y = x * x 3 | return y 4 | 5 | def sum_of_squares(x,y,z): 6 | a = square(x) 7 | b = square(y) 8 | c = square(z) 9 | 10 | return a+b+c 11 | 12 | a = -5 13 | b = 2 14 | c = 10 15 | result = sum_of_squares(a,b,c) 16 | print(result) -------------------------------------------------------------------------------- /Chapter12. Functions/def_turtle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def drawSquare(t, sz): 4 | """Make turtle t draw a square of with side sz.""" 5 | 6 | for i in range(4): 7 | t.forward(sz) 8 | t.left(90) 9 | 10 | 11 | wn = turtle.Screen() # Set up the window and its attributes 12 | wn.bgcolor("lightgreen") 13 | 14 | alex = turtle.Turtle() # create alex 15 | drawSquare(alex, 50) # Call the function to draw the square passing the actual turtle and the actual side size 16 | 17 | wn.exitonclick() 18 | -------------------------------------------------------------------------------- /Chapter12. Functions/difficult.py: -------------------------------------------------------------------------------- 1 | name = input("Enter a number") 2 | def addit(num): 3 | i = int(num) + 5 4 | return i 5 | yo0 = addit(name) 6 | 7 | def mult(numbers): 8 | result = (int(numbers) * int(name)) + int(numbers) 9 | return result 10 | 11 | 12 | result = mult(yo0) 13 | print(result) 14 | print(yo0) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter12. Functions/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter13. Tuple Packing and Unpacking/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter13. Tuple Packing and Unpacking/rough.py: -------------------------------------------------------------------------------- 1 | print("Hello, World!") -------------------------------------------------------------------------------- /Chapter13. Tuple Packing and Unpacking/tuple.py: -------------------------------------------------------------------------------- 1 | name = input("Enter your Name") 2 | age = input("Enter your Age") 3 | birth_year = input("Enter your birth_year") 4 | year_in_college = input("Enter your year_in_college") 5 | hometown = input("Enter your hometown") 6 | 7 | def info(name,age,birth_year,year_in_college,hometown): 8 | x = name 9 | s = age 10 | y = birth_year 11 | z = year_in_college 12 | a = hometown 13 | return x, s, y, z, a 14 | print(info(name,age,birth_year,year_in_college,hometown)) 15 | 16 | -------------------------------------------------------------------------------- /Chapter14. More About Iteration/even.py: -------------------------------------------------------------------------------- 1 | eve_nums = [] 2 | i=0 3 | while i < 15: 4 | if ( i % 2==0): 5 | print(i) 6 | eve_nums.append(i) 7 | i+=2 8 | 9 | print(eve_nums) -------------------------------------------------------------------------------- /Chapter14. More About Iteration/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter14. More About Iteration/sum_of_list.py: -------------------------------------------------------------------------------- 1 | 2 | list1 = [8, 3, 4, 5, 6, 7, 9] 3 | accum = 0 4 | i = 0 5 | while i < len(list1): 6 | accum = accum + list1[i] 7 | i = i + 1 8 | 9 | -------------------------------------------------------------------------------- /Chapter14. More About Iteration/whileloop.py: -------------------------------------------------------------------------------- 1 | def SumTo(n_num): 2 | sum = 0 3 | num = 1 4 | while num <= n_num: 5 | sum = sum + num 6 | num = num + 1 7 | return sum 8 | 9 | 10 | print(SumTo(4)) -------------------------------------------------------------------------------- /Chapter14. More About Iteration/whileloop_ass.py: -------------------------------------------------------------------------------- 1 | def sublist(x): 2 | sub = [] 3 | x = (num for num in x) 4 | num = next(x, 5) 5 | while num != 5: 6 | sub.append(num) 7 | num = next(x, 5) 8 | return sub 9 | 10 | x = [1, 3, 4, 5, 6, 7, 3] 11 | print(sublist(x)) 12 | 13 | 14 | ##################################### 15 | 16 | def check_nums(x): 17 | sub = [] 18 | x = (num for num in x) 19 | num = next(x, 7) 20 | while num != 7: 21 | sub.append(num) 22 | num = next(x, 7) 23 | return sub 24 | 25 | x = [1, 3, 4, 5, 6, 7, 3] 26 | print(check_nums(x)) 27 | 28 | ####################################### 29 | def sublist(list): 30 | i = 0 31 | while i < len(list): 32 | 33 | if (list[i] == 'STOP'): 34 | return list[0:i] 35 | i+=1 36 | return list[0:i] 37 | print(sublist(['mujju','salman','yo','STOP'])) 38 | -------------------------------------------------------------------------------- /Chapter15. Advanced Functions/ass.py: -------------------------------------------------------------------------------- 1 | # 1. Create a function called mult that has two parameters, the first is required and should be an integer, 2 | # the second is an optional parameter that can either be a number or a string but whose default is 6. 3 | # The function should return the first parameter multiplied by the second. 4 | 5 | def mult(a, b=6): 6 | return a * b 7 | 8 | # 2. The following function, greeting, does not work. Please fix the code so that it runs without error. 9 | # This only requires one change in the definition of the function. 10 | 11 | def greeting(name, greeting="Hello ", excl="!"): 12 | return greeting + name + excl 13 | 14 | print(greeting("Bob")) 15 | print(greeting("")) 16 | print(greeting("Bob", excl="!!!")) 17 | 18 | # 3. Below is a function, sum, that does not work. Change the function definition so the code works. 19 | # The function should still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5. 20 | 21 | def sum(intx, intz=5): 22 | return intz + intx 23 | 24 | # 4. Write a function, test, that takes in three parameters: a required integer, 25 | # an optional boolean whose default value is True, and an optional dictionary, 26 | # called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, 27 | # the function should test to see if the integer is a key in the dictionary. 28 | # The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”. 29 | 30 | def test(x, abool = True, dict1 = {2:3, 4:5, 6:8}): 31 | return abool and dict1.get(x, False) 32 | 33 | # 5. Write a function called checkingIfIn that takes three parameters. 34 | # The first is a required parameter, which should be a string. 35 | # The second is an optional parameter called direction with a default value of True. 36 | # The third is an optional parameter called d that has a default value of 37 | # {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}. 38 | # Write the function checkingIfIn so that when the second parameter is True, 39 | # it checks to see if the first parameter is a key in the third parameter; 40 | # if it is, return True, otherwise return False. 41 | 42 | # But if the second paramter is False, then the function should check to see if the first parameter is not a key of the third.' 43 | # If it’s not, the function should return True in this case, and if it is, it should return False. 44 | 45 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 46 | if direction == True: 47 | if a in d: 48 | return True 49 | else: 50 | return False 51 | else: 52 | if a not in d: 53 | return True 54 | else: 55 | return False 56 | 57 | # 6. We have provided the function checkingIfIn such that if the first input parameter is in the third, 58 | # dictionary, input parameter, then the function returns that value, and otherwise, it returns False. 59 | # Follow the instructions in the active code window for specific variable assignmemts. 60 | 61 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 62 | if direction == True: 63 | if a in d: 64 | return d[a] 65 | else: 66 | return False 67 | else: 68 | if a not in d: 69 | return True 70 | else: 71 | return d[a] 72 | 73 | # Call the function so that it returns False and assign that function call to the variable c_false 74 | c_false = checkingIfIn('peas') 75 | # Call the fucntion so that it returns True and assign it to the variable c_true 76 | c_true = checkingIfIn('apples', False, {'carrots': 1, 'peas': 9, 'potatos': 8, 'corn': 32, 'beans': 1}) 77 | # Call the function so that the value of fruit is assigned to the variable fruit_ans 78 | fruit_ans= checkingIfIn('fruit') 79 | # Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check 80 | param_check = checkingIfIn('potatos', False, {'carrots': 1, 'peas': 9, 'potatos': 8, 'corn': 32, 'beans': 1}) -------------------------------------------------------------------------------- /Chapter15. Advanced Functions/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter15. Advanced Functions/lambda.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | return x - 1 3 | 4 | print(f) 5 | print(f(3)) 6 | 7 | 8 | yoo = lambda x: x-2 9 | print(yoo(3)) 10 | print((lambda x: x-2 )(6)) -------------------------------------------------------------------------------- /Chapter16. Sorting/ass.py: -------------------------------------------------------------------------------- 1 | top_three = [] 2 | medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} 3 | def g(k,d): 4 | return d[k] 5 | ks = medals.keys() 6 | top_three = sorted(ks,key=lambda x : g(x,medals),reverse = True)[:3] 7 | 8 | 9 | ########################### 10 | 11 | most_needed = [] 12 | groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9} 13 | def g(k,d): 14 | return d[k] 15 | ks = groceries.keys() 16 | most_needed = sorted(ks, key=lambda x:g(x,groceries), reverse = True) 17 | print(most_needed) 18 | 19 | #################################### 20 | 21 | ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] 22 | 23 | def last_four(x): 24 | 25 | return (str(x)[-4:]) 26 | last_four(ids) 27 | 28 | sorted_ids = sorted(ids, key=lambda x: str(x)[-4:]) 29 | print(sorted_ids) 30 | 31 | ######################################### -------------------------------------------------------------------------------- /Chapter16. Sorting/course2project.py: -------------------------------------------------------------------------------- 1 | # We have provided some synthetic (fake, semi-randomly generated) twitter data in a csv file named project_twitter_data.csv which has the text of a tweet, 2 | # the number of retweets of that tweet, and the number of replies to that tweet. We have also words that express positive sentiment and negative sentiment, 3 | # in the files positive_words.txt and negative_words.txt. 4 | # Your task is to build a sentiment classifier, which will detect how positive or negative each tweet is. You will create a csv file, 5 | # which contains columns for the Number of Retweets, Number of Replies, Positive Score (which is how many happy words are in the tweet), 6 | # Negative Score (which is how many angry words are in the tweet), and the Net Score for each tweet. At the end, you upload the csv file to Excel or Google Sheets, 7 | # and produce a graph of the Net Score vs Number of Retweets. 8 | # To start, define a function called strip_punctuation which takes one parameter, a string which represents a word, 9 | # and removes characters considered punctuation from everywhere in the word. (Hint: remember the .replace() method for strings.) 10 | 11 | #Answer 12 | projectTwitterDataFile = open("project_twitter_data.csv","r") 13 | resultingDataFile = open("resulting_data.csv","w") 14 | 15 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 16 | # lists of words to use 17 | positive_words = [] 18 | with open("positive_words.txt") as pos_f: 19 | for lin in pos_f: 20 | if lin[0] != ';' and lin[0] != '\n': 21 | positive_words.append(lin.strip()) 22 | 23 | def get_pos(strSentences): 24 | strSentences = strip_punctuation(strSentences) 25 | listStrSentences= strSentences.split() 26 | 27 | count=0 28 | for word in listStrSentences: 29 | for positiveWord in positive_words: 30 | if word == positiveWord: 31 | count+=1 32 | return count 33 | 34 | negative_words = [] 35 | with open("negative_words.txt") as pos_f: 36 | for lin in pos_f: 37 | if lin[0] != ';' and lin[0] != '\n': 38 | negative_words.append(lin.strip()) 39 | 40 | 41 | def get_neg(strSentences): 42 | strSentences = strip_punctuation(strSentences) 43 | listStrSentences = strSentences.split() 44 | 45 | count=0 46 | for word in listStrSentences: 47 | for negativeWord in negative_words: 48 | if word == negativeWord: 49 | count+=1 50 | return count 51 | 52 | 53 | def strip_punctuation(strWord): 54 | for charPunct in punctuation_chars: 55 | strWord = strWord.replace(charPunct, "") 56 | return strWord 57 | 58 | 59 | def writeInDataFile(resultingDataFile): 60 | resultingDataFile.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score") 61 | resultingDataFile.write("\n") 62 | 63 | linesPTDF = projectTwitterDataFile.readlines() 64 | headerDontUsed= linesPTDF.pop(0) 65 | for linesTD in linesPTDF: 66 | listTD = linesTD.strip().split(',') 67 | resultingDataFile.write("{}, {}, {}, {}, {}".format(listTD[1], listTD[2], get_pos(listTD[0]), get_neg(listTD[0]), (get_pos(listTD[0])-get_neg(listTD[0])))) 68 | resultingDataFile.write("\n") 69 | 70 | 71 | 72 | writeInDataFile(resultingDataFile) 73 | projectTwitterDataFile.close() 74 | resultingDataFile.close() 75 | 76 | ########################################################################################### 77 | # Next, copy in your strip_punctuation function and define a function called get_pos which takes one parameter, a string which represents a one or more sentences, 78 | # and calculates how many words in the string are considered positive words. Use the list, positive_words to determine what words will count as positive. 79 | # The function should return a positive integer - how many occurances there are of positive words in the text. 80 | #Answer 81 | 82 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 83 | # list of positive words to use 84 | positive_words = [] 85 | with open("positive_words.txt") as pos_f: 86 | for lin in pos_f: 87 | if lin[0] != ';' and lin[0] != '\n': 88 | positive_words.append(lin.strip()) 89 | 90 | def get_pos(strSentences): 91 | strSentences = strip_punctuation(strSentences) 92 | listStrSentences= strSentences.split() 93 | 94 | count=0 95 | for word in listStrSentences: 96 | for positiveWord in positive_words: 97 | if word == positiveWord: 98 | count+=1 99 | return count 100 | 101 | 102 | def strip_punctuation(strWord): 103 | for charPunct in punctuation_chars: 104 | strWord = strWord.replace(charPunct, "") 105 | return strWord 106 | 107 | ####################################################################################33 108 | 109 | # Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter, a string which represents a one or more sentences, 110 | # and calculates how many words in the string are considered negative words. Use the list, negative_words to determine what words will count as negative. 111 | # The function should return a positive integer - how many occurances there are of negative words in the text. 112 | 113 | 114 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 115 | 116 | negative_words = [] 117 | with open("negative_words.txt") as pos_f: 118 | for lin in pos_f: 119 | if lin[0] != ';' and lin[0] != '\n': 120 | negative_words.append(lin.strip()) 121 | 122 | def get_neg(strSentences): 123 | strSentences = strip_punctuation(strSentences) 124 | listStrSentences = strSentences.split() 125 | 126 | count=0 127 | for word in listStrSentences: 128 | for negativeWord in negative_words: 129 | if word == negativeWord: 130 | count+=1 131 | return count 132 | 133 | 134 | def strip_punctuation(strWord): 135 | for charPunct in punctuation_chars: 136 | strWord = strWord.replace(charPunct, "") 137 | return strWord 138 | 139 | 140 | -------------------------------------------------------------------------------- /Chapter16. Sorting/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter16. Sorting/hig-low_nums.py: -------------------------------------------------------------------------------- 1 | nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] 2 | 3 | def last_char(nums): 4 | return nums[-1] 5 | nums_sorted = sorted(nums, key=last_char, reverse=True) 6 | print(nums_sorted) 7 | 8 | ##########LAMBDA ############## 9 | 10 | 11 | nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] 12 | yo = lambda nums: nums[-1] 13 | nums_sorted_lambda = sorted(nums, key=yo , reverse=True) 14 | 15 | -------------------------------------------------------------------------------- /Chapter16. Sorting/project/course2project1.py: -------------------------------------------------------------------------------- 1 | projectTwitterDataFile = open("project_twitter_data.csv","r") 2 | resultingDataFile = open("resulting_data.csv","w") 3 | 4 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 5 | # lists of words to use 6 | positive_words = [] 7 | with open("positive_words.txt") as pos_f: 8 | for lin in pos_f: 9 | if lin[0] != ';' and lin[0] != '\n': 10 | positive_words.append(lin.strip()) 11 | 12 | def get_pos(strSentences): 13 | strSentences = strip_punctuation(strSentences) 14 | listStrSentences= strSentences.split() 15 | 16 | count=0 17 | for word in listStrSentences: 18 | for positiveWord in positive_words: 19 | if word == positiveWord: 20 | count+=1 21 | return count 22 | 23 | negative_words = [] 24 | with open("negative_words.txt") as pos_f: 25 | for lin in pos_f: 26 | if lin[0] != ';' and lin[0] != '\n': 27 | negative_words.append(lin.strip()) 28 | 29 | 30 | def get_neg(strSentences): 31 | strSentences = strip_punctuation(strSentences) 32 | listStrSentences = strSentences.split() 33 | 34 | count=0 35 | for word in listStrSentences: 36 | for negativeWord in negative_words: 37 | if word == negativeWord: 38 | count+=1 39 | return count 40 | 41 | 42 | def strip_punctuation(strWord): 43 | for charPunct in punctuation_chars: 44 | strWord = strWord.replace(charPunct, "") 45 | return strWord 46 | 47 | 48 | def writeInDataFile(resultingDataFile): 49 | resultingDataFile.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score") 50 | resultingDataFile.write("\n") 51 | 52 | linesPTDF = projectTwitterDataFile.readlines() 53 | headerDontUsed= linesPTDF.pop(0) 54 | for linesTD in linesPTDF: 55 | listTD = linesTD.strip().split(',') 56 | resultingDataFile.write("{}, {}, {}, {}, {}".format(listTD[1], listTD[2], get_pos(listTD[0]), get_neg(listTD[0]), (get_pos(listTD[0])-get_neg(listTD[0])))) 57 | resultingDataFile.write("\n") 58 | 59 | 60 | 61 | writeInDataFile(resultingDataFile) 62 | projectTwitterDataFile.close() 63 | resultingDataFile.close() -------------------------------------------------------------------------------- /Chapter16. Sorting/project/positive_words.txt: -------------------------------------------------------------------------------- 1 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 2 | ; 3 | ; Opinion Lexicon: Positive 4 | ; 5 | ; This file contains a list of POSITIVE opinion words (or sentiment words). 6 | ; 7 | ; This file and the papers can all be downloaded from 8 | ; http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html 9 | ; 10 | ; If you use this list, please cite one of the following two papers: 11 | ; 12 | ; Minqing Hu and Bing Liu. "Mining and Summarizing Customer Reviews." 13 | ; Proceedings of the ACM SIGKDD International Conference on Knowledge 14 | ; Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, 15 | ; Washington, USA, 16 | ; Bing Liu, Minqing Hu and Junsheng Cheng. "Opinion Observer: Analyzing 17 | ; and Comparing Opinions on the Web." Proceedings of the 14th 18 | ; International World Wide Web conference (WWW-2005), May 10-14, 19 | ; 2005, Chiba, Japan. 20 | ; 21 | ; Notes: 22 | ; 1. The appearance of an opinion word in a sentence does not necessarily 23 | ; mean that the sentence expresses a positive or negative opinion. 24 | ; See the paper below: 25 | ; 26 | ; Bing Liu. "Sentiment Analysis and Subjectivity." An chapter in 27 | ; Handbook of Natural Language Processing, Second Edition, 28 | ; (editors: N. Indurkhya and F. J. Damerau), 2010. 29 | ; 30 | ; 2. You will notice many misspelled words in the list. They are not 31 | ; mistakes. They are included as these misspelled words appear 32 | ; frequently in social media content. 33 | ; 34 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 35 | 36 | a+ 37 | abound 38 | abounds 39 | abundance 40 | abundant 41 | accessable 42 | accessible 43 | acclaim 44 | acclaimed 45 | acclamation 46 | accolade 47 | accolades 48 | accommodative 49 | accomodative 50 | accomplish 51 | accomplished 52 | accomplishment 53 | accomplishments 54 | accurate 55 | accurately 56 | achievable 57 | achievement 58 | achievements 59 | achievible 60 | acumen 61 | adaptable 62 | adaptive 63 | adequate 64 | adjustable 65 | admirable 66 | admirably 67 | admiration 68 | admire 69 | admirer 70 | admiring 71 | admiringly 72 | adorable 73 | adore 74 | adored 75 | adorer 76 | adoring 77 | adoringly 78 | adroit 79 | adroitly 80 | adulate 81 | adulation 82 | adulatory 83 | advanced 84 | advantage 85 | advantageous 86 | advantageously 87 | advantages 88 | adventuresome 89 | adventurous 90 | advocate 91 | advocated 92 | advocates 93 | affability 94 | affable 95 | affably 96 | affectation 97 | affection 98 | affectionate 99 | affinity 100 | affirm 101 | affirmation 102 | affirmative 103 | affluence 104 | affluent 105 | afford 106 | affordable 107 | affordably 108 | afordable 109 | agile 110 | agilely 111 | agility 112 | agreeable 113 | agreeableness 114 | agreeably 115 | all-around 116 | alluring 117 | alluringly 118 | altruistic 119 | altruistically 120 | amaze 121 | amazed 122 | amazement 123 | amazes 124 | amazing 125 | amazingly 126 | ambitious 127 | ambitiously 128 | ameliorate 129 | amenable 130 | amenity 131 | amiability 132 | amiabily 133 | amiable 134 | amicability 135 | amicable 136 | amicably 137 | amity 138 | ample 139 | amply 140 | amuse 141 | amusing 142 | amusingly 143 | angel 144 | angelic 145 | apotheosis 146 | appeal 147 | appealing 148 | applaud 149 | appreciable 150 | appreciate 151 | appreciated 152 | appreciates 153 | appreciative 154 | appreciatively 155 | appropriate 156 | approval 157 | approve 158 | ardent 159 | ardently 160 | ardor 161 | articulate 162 | aspiration 163 | aspirations 164 | aspire 165 | assurance 166 | assurances 167 | assure 168 | assuredly 169 | assuring 170 | astonish 171 | astonished 172 | astonishing 173 | astonishingly 174 | astonishment 175 | astound 176 | astounded 177 | astounding 178 | astoundingly 179 | astutely 180 | attentive 181 | attraction 182 | attractive 183 | attractively 184 | attune 185 | audible 186 | audibly 187 | auspicious 188 | authentic 189 | authoritative 190 | autonomous 191 | available 192 | aver 193 | avid 194 | avidly 195 | award 196 | awarded 197 | awards 198 | awe 199 | awed 200 | awesome 201 | awesomely 202 | awesomeness 203 | awestruck 204 | awsome 205 | backbone 206 | balanced 207 | bargain 208 | beauteous 209 | beautiful 210 | beautifullly 211 | beautifully 212 | beautify 213 | beauty 214 | beckon 215 | beckoned 216 | beckoning 217 | beckons 218 | believable 219 | believeable 220 | beloved 221 | benefactor 222 | beneficent 223 | beneficial 224 | beneficially 225 | beneficiary 226 | benefit 227 | benefits 228 | benevolence 229 | benevolent 230 | benifits 231 | best 232 | best-known 233 | best-performing 234 | best-selling 235 | better 236 | better-known 237 | better-than-expected 238 | beutifully 239 | blameless 240 | bless 241 | blessing 242 | bliss 243 | blissful 244 | blissfully 245 | blithe 246 | blockbuster 247 | bloom 248 | blossom 249 | bolster 250 | bonny 251 | bonus 252 | bonuses 253 | boom 254 | booming 255 | boost 256 | boundless 257 | bountiful 258 | brainiest 259 | brainy 260 | brand-new 261 | brave 262 | bravery 263 | bravo 264 | breakthrough 265 | breakthroughs 266 | breathlessness 267 | breathtaking 268 | breathtakingly 269 | breeze 270 | bright 271 | brighten 272 | brighter 273 | brightest 274 | brilliance 275 | brilliances 276 | brilliant 277 | brilliantly 278 | brisk 279 | brotherly 280 | bullish 281 | buoyant 282 | cajole 283 | calm 284 | calming 285 | calmness 286 | capability 287 | capable 288 | capably 289 | captivate 290 | captivating 291 | carefree 292 | cashback 293 | cashbacks 294 | catchy 295 | celebrate 296 | celebrated 297 | celebration 298 | celebratory 299 | champ 300 | champion 301 | charisma 302 | charismatic 303 | charitable 304 | charm 305 | charming 306 | charmingly 307 | chaste 308 | cheaper 309 | cheapest 310 | cheer 311 | cheerful 312 | cheery 313 | cherish 314 | cherished 315 | cherub 316 | chic 317 | chivalrous 318 | chivalry 319 | civility 320 | civilize 321 | clarity 322 | classic 323 | classy 324 | clean 325 | cleaner 326 | cleanest 327 | cleanliness 328 | cleanly 329 | clear 330 | clear-cut 331 | cleared 332 | clearer 333 | clearly 334 | clears 335 | clever 336 | cleverly 337 | cohere 338 | coherence 339 | coherent 340 | cohesive 341 | colorful 342 | comely 343 | comfort 344 | comfortable 345 | comfortably 346 | comforting 347 | comfy 348 | commend 349 | commendable 350 | commendably 351 | commitment 352 | commodious 353 | compact 354 | compactly 355 | compassion 356 | compassionate 357 | compatible 358 | competitive 359 | complement 360 | complementary 361 | complemented 362 | complements 363 | compliant 364 | compliment 365 | complimentary 366 | comprehensive 367 | conciliate 368 | conciliatory 369 | concise 370 | confidence 371 | confident 372 | congenial 373 | congratulate 374 | congratulation 375 | congratulations 376 | congratulatory 377 | conscientious 378 | considerate 379 | consistent 380 | consistently 381 | constructive 382 | consummate 383 | contentment 384 | continuity 385 | contrasty 386 | contribution 387 | convenience 388 | convenient 389 | conveniently 390 | convience 391 | convienient 392 | convient 393 | convincing 394 | convincingly 395 | cool 396 | coolest 397 | cooperative 398 | cooperatively 399 | cornerstone 400 | correct 401 | correctly 402 | cost-effective 403 | cost-saving 404 | counter-attack 405 | counter-attacks 406 | courage 407 | courageous 408 | courageously 409 | courageousness 410 | courteous 411 | courtly 412 | covenant 413 | cozy 414 | creative 415 | credence 416 | credible 417 | crisp 418 | crisper 419 | cure 420 | cure-all 421 | cushy 422 | cute 423 | cuteness 424 | danke 425 | danken 426 | daring 427 | daringly 428 | darling 429 | dashing 430 | dauntless 431 | dawn 432 | dazzle 433 | dazzled 434 | dazzling 435 | dead-cheap 436 | dead-on 437 | decency 438 | decent 439 | decisive 440 | decisiveness 441 | dedicated 442 | defeat 443 | defeated 444 | defeating 445 | defeats 446 | defender 447 | deference 448 | deft 449 | deginified 450 | delectable 451 | delicacy 452 | delicate 453 | delicious 454 | delight 455 | delighted 456 | delightful 457 | delightfully 458 | delightfulness 459 | dependable 460 | dependably 461 | deservedly 462 | deserving 463 | desirable 464 | desiring 465 | desirous 466 | destiny 467 | detachable 468 | devout 469 | dexterous 470 | dexterously 471 | dextrous 472 | dignified 473 | dignify 474 | dignity 475 | diligence 476 | diligent 477 | diligently 478 | diplomatic 479 | dirt-cheap 480 | distinction 481 | distinctive 482 | distinguished 483 | diversified 484 | divine 485 | divinely 486 | dominate 487 | dominated 488 | dominates 489 | dote 490 | dotingly 491 | doubtless 492 | dreamland 493 | dumbfounded 494 | dumbfounding 495 | dummy-proof 496 | durable 497 | dynamic 498 | eager 499 | eagerly 500 | eagerness 501 | earnest 502 | earnestly 503 | earnestness 504 | ease 505 | eased 506 | eases 507 | easier 508 | easiest 509 | easiness 510 | easing 511 | easy 512 | easy-to-use 513 | easygoing 514 | ebullience 515 | ebullient 516 | ebulliently 517 | ecenomical 518 | economical 519 | ecstasies 520 | ecstasy 521 | ecstatic 522 | ecstatically 523 | edify 524 | educated 525 | effective 526 | effectively 527 | effectiveness 528 | effectual 529 | efficacious 530 | efficient 531 | efficiently 532 | effortless 533 | effortlessly 534 | effusion 535 | effusive 536 | effusively 537 | effusiveness 538 | elan 539 | elate 540 | elated 541 | elatedly 542 | elation 543 | electrify 544 | elegance 545 | elegant 546 | elegantly 547 | elevate 548 | elite 549 | eloquence 550 | eloquent 551 | eloquently 552 | embolden 553 | eminence 554 | eminent 555 | empathize 556 | empathy 557 | empower 558 | empowerment 559 | enchant 560 | enchanted 561 | enchanting 562 | enchantingly 563 | encourage 564 | encouragement 565 | encouraging 566 | encouragingly 567 | endear 568 | endearing 569 | endorse 570 | endorsed 571 | endorsement 572 | endorses 573 | endorsing 574 | energetic 575 | energize 576 | energy-efficient 577 | energy-saving 578 | engaging 579 | engrossing 580 | enhance 581 | enhanced 582 | enhancement 583 | enhances 584 | enjoy 585 | enjoyable 586 | enjoyably 587 | enjoyed 588 | enjoying 589 | enjoyment 590 | enjoys 591 | enlighten 592 | enlightenment 593 | enliven 594 | ennoble 595 | enough 596 | enrapt 597 | enrapture 598 | enraptured 599 | enrich 600 | enrichment 601 | enterprising 602 | entertain 603 | entertaining 604 | entertains 605 | enthral 606 | enthrall 607 | enthralled 608 | enthuse 609 | enthusiasm 610 | enthusiast 611 | enthusiastic 612 | enthusiastically 613 | entice 614 | enticed 615 | enticing 616 | enticingly 617 | entranced 618 | entrancing 619 | entrust 620 | enviable 621 | enviably 622 | envious 623 | enviously 624 | enviousness 625 | envy 626 | equitable 627 | ergonomical 628 | err-free 629 | erudite 630 | ethical 631 | eulogize 632 | euphoria 633 | euphoric 634 | euphorically 635 | evaluative 636 | evenly 637 | eventful 638 | everlasting 639 | evocative 640 | exalt 641 | exaltation 642 | exalted 643 | exaltedly 644 | exalting 645 | exaltingly 646 | examplar 647 | examplary 648 | excallent 649 | exceed 650 | exceeded 651 | exceeding 652 | exceedingly 653 | exceeds 654 | excel 655 | exceled 656 | excelent 657 | excellant 658 | excelled 659 | excellence 660 | excellency 661 | excellent 662 | excellently 663 | excels 664 | exceptional 665 | exceptionally 666 | excite 667 | excited 668 | excitedly 669 | excitedness 670 | excitement 671 | excites 672 | exciting 673 | excitingly 674 | exellent 675 | exemplar 676 | exemplary 677 | exhilarate 678 | exhilarating 679 | exhilaratingly 680 | exhilaration 681 | exonerate 682 | expansive 683 | expeditiously 684 | expertly 685 | exquisite 686 | exquisitely 687 | extol 688 | extoll 689 | extraordinarily 690 | extraordinary 691 | exuberance 692 | exuberant 693 | exuberantly 694 | exult 695 | exultant 696 | exultation 697 | exultingly 698 | eye-catch 699 | eye-catching 700 | eyecatch 701 | eyecatching 702 | fabulous 703 | fabulously 704 | facilitate 705 | fair 706 | fairly 707 | fairness 708 | faith 709 | faithful 710 | faithfully 711 | faithfulness 712 | fame 713 | famed 714 | famous 715 | famously 716 | fancier 717 | fancinating 718 | fancy 719 | fanfare 720 | fans 721 | fantastic 722 | fantastically 723 | fascinate 724 | fascinating 725 | fascinatingly 726 | fascination 727 | fashionable 728 | fashionably 729 | fast 730 | fast-growing 731 | fast-paced 732 | faster 733 | fastest 734 | fastest-growing 735 | faultless 736 | fav 737 | fave 738 | favor 739 | favorable 740 | favored 741 | favorite 742 | favorited 743 | favour 744 | fearless 745 | fearlessly 746 | feasible 747 | feasibly 748 | feat 749 | feature-rich 750 | fecilitous 751 | feisty 752 | felicitate 753 | felicitous 754 | felicity 755 | fertile 756 | fervent 757 | fervently 758 | fervid 759 | fervidly 760 | fervor 761 | festive 762 | fidelity 763 | fiery 764 | fine 765 | fine-looking 766 | finely 767 | finer 768 | finest 769 | firmer 770 | first-class 771 | first-in-class 772 | first-rate 773 | flashy 774 | flatter 775 | flattering 776 | flatteringly 777 | flawless 778 | flawlessly 779 | flexibility 780 | flexible 781 | flourish 782 | flourishing 783 | fluent 784 | flutter 785 | fond 786 | fondly 787 | fondness 788 | foolproof 789 | foremost 790 | foresight 791 | formidable 792 | fortitude 793 | fortuitous 794 | fortuitously 795 | fortunate 796 | fortunately 797 | fortune 798 | fragrant 799 | free 800 | freed 801 | freedom 802 | freedoms 803 | fresh 804 | fresher 805 | freshest 806 | friendliness 807 | friendly 808 | frolic 809 | frugal 810 | fruitful 811 | ftw 812 | fulfillment 813 | fun 814 | futurestic 815 | futuristic 816 | gaiety 817 | gaily 818 | gain 819 | gained 820 | gainful 821 | gainfully 822 | gaining 823 | gains 824 | gallant 825 | gallantly 826 | galore 827 | geekier 828 | geeky 829 | gem 830 | gems 831 | generosity 832 | generous 833 | generously 834 | genial 835 | genius 836 | gentle 837 | gentlest 838 | genuine 839 | gifted 840 | glad 841 | gladden 842 | gladly 843 | gladness 844 | glamorous 845 | glee 846 | gleeful 847 | gleefully 848 | glimmer 849 | glimmering 850 | glisten 851 | glistening 852 | glitter 853 | glitz 854 | glorify 855 | glorious 856 | gloriously 857 | glory 858 | glow 859 | glowing 860 | glowingly 861 | god-given 862 | god-send 863 | godlike 864 | godsend 865 | gold 866 | golden 867 | good 868 | goodly 869 | goodness 870 | goodwill 871 | goood 872 | gooood 873 | gorgeous 874 | gorgeously 875 | grace 876 | graceful 877 | gracefully 878 | gracious 879 | graciously 880 | graciousness 881 | grand 882 | grandeur 883 | grateful 884 | gratefully 885 | gratification 886 | gratified 887 | gratifies 888 | gratify 889 | gratifying 890 | gratifyingly 891 | gratitude 892 | great 893 | greatest 894 | greatness 895 | grin 896 | groundbreaking 897 | guarantee 898 | guidance 899 | guiltless 900 | gumption 901 | gush 902 | gusto 903 | gutsy 904 | hail 905 | halcyon 906 | hale 907 | hallmark 908 | hallmarks 909 | hallowed 910 | handier 911 | handily 912 | hands-down 913 | handsome 914 | handsomely 915 | handy 916 | happier 917 | happily 918 | happiness 919 | happy 920 | hard-working 921 | hardier 922 | hardy 923 | harmless 924 | harmonious 925 | harmoniously 926 | harmonize 927 | harmony 928 | headway 929 | heal 930 | healthful 931 | healthy 932 | hearten 933 | heartening 934 | heartfelt 935 | heartily 936 | heartwarming 937 | heaven 938 | heavenly 939 | helped 940 | helpful 941 | helping 942 | hero 943 | heroic 944 | heroically 945 | heroine 946 | heroize 947 | heros 948 | high-quality 949 | high-spirited 950 | hilarious 951 | holy 952 | homage 953 | honest 954 | honesty 955 | honor 956 | honorable 957 | honored 958 | honoring 959 | hooray 960 | hopeful 961 | hospitable 962 | hot 963 | hotcake 964 | hotcakes 965 | hottest 966 | hug 967 | humane 968 | humble 969 | humility 970 | humor 971 | humorous 972 | humorously 973 | humour 974 | humourous 975 | ideal 976 | idealize 977 | ideally 978 | idol 979 | idolize 980 | idolized 981 | idyllic 982 | illuminate 983 | illuminati 984 | illuminating 985 | illumine 986 | illustrious 987 | ilu 988 | imaculate 989 | imaginative 990 | immaculate 991 | immaculately 992 | immense 993 | impartial 994 | impartiality 995 | impartially 996 | impassioned 997 | impeccable 998 | impeccably 999 | important 1000 | impress 1001 | impressed 1002 | impresses 1003 | impressive 1004 | impressively 1005 | impressiveness 1006 | improve 1007 | improved 1008 | improvement 1009 | improvements 1010 | improves 1011 | improving 1012 | incredible 1013 | incredibly 1014 | indebted 1015 | individualized 1016 | indulgence 1017 | indulgent 1018 | industrious 1019 | inestimable 1020 | inestimably 1021 | inexpensive 1022 | infallibility 1023 | infallible 1024 | infallibly 1025 | influential 1026 | ingenious 1027 | ingeniously 1028 | ingenuity 1029 | ingenuous 1030 | ingenuously 1031 | innocuous 1032 | innovation 1033 | innovative 1034 | inpressed 1035 | insightful 1036 | insightfully 1037 | inspiration 1038 | inspirational 1039 | inspire 1040 | inspiring 1041 | instantly 1042 | instructive 1043 | instrumental 1044 | integral 1045 | integrated 1046 | intelligence 1047 | intelligent 1048 | intelligible 1049 | interesting 1050 | interests 1051 | intimacy 1052 | intimate 1053 | intricate 1054 | intrigue 1055 | intriguing 1056 | intriguingly 1057 | intuitive 1058 | invaluable 1059 | invaluablely 1060 | inventive 1061 | invigorate 1062 | invigorating 1063 | invincibility 1064 | invincible 1065 | inviolable 1066 | inviolate 1067 | invulnerable 1068 | irreplaceable 1069 | irreproachable 1070 | irresistible 1071 | irresistibly 1072 | issue-free 1073 | jaw-droping 1074 | jaw-dropping 1075 | jollify 1076 | jolly 1077 | jovial 1078 | joy 1079 | joyful 1080 | joyfully 1081 | joyous 1082 | joyously 1083 | jubilant 1084 | jubilantly 1085 | jubilate 1086 | jubilation 1087 | jubiliant 1088 | judicious 1089 | justly 1090 | keen 1091 | keenly 1092 | keenness 1093 | kid-friendly 1094 | kindliness 1095 | kindly 1096 | kindness 1097 | knowledgeable 1098 | kudos 1099 | large-capacity 1100 | laud 1101 | laudable 1102 | laudably 1103 | lavish 1104 | lavishly 1105 | law-abiding 1106 | lawful 1107 | lawfully 1108 | lead 1109 | leading 1110 | leads 1111 | lean 1112 | led 1113 | legendary 1114 | leverage 1115 | levity 1116 | liberate 1117 | liberation 1118 | liberty 1119 | lifesaver 1120 | light-hearted 1121 | lighter 1122 | likable 1123 | like 1124 | liked 1125 | likes 1126 | liking 1127 | lionhearted 1128 | lively 1129 | logical 1130 | long-lasting 1131 | lovable 1132 | lovably 1133 | love 1134 | loved 1135 | loveliness 1136 | lovely 1137 | lover 1138 | loves 1139 | loving 1140 | low-cost 1141 | low-price 1142 | low-priced 1143 | low-risk 1144 | lower-priced 1145 | loyal 1146 | loyalty 1147 | lucid 1148 | lucidly 1149 | luck 1150 | luckier 1151 | luckiest 1152 | luckiness 1153 | lucky 1154 | lucrative 1155 | luminous 1156 | lush 1157 | luster 1158 | lustrous 1159 | luxuriant 1160 | luxuriate 1161 | luxurious 1162 | luxuriously 1163 | luxury 1164 | lyrical 1165 | magic 1166 | magical 1167 | magnanimous 1168 | magnanimously 1169 | magnificence 1170 | magnificent 1171 | magnificently 1172 | majestic 1173 | majesty 1174 | manageable 1175 | maneuverable 1176 | marvel 1177 | marveled 1178 | marvelled 1179 | marvellous 1180 | marvelous 1181 | marvelously 1182 | marvelousness 1183 | marvels 1184 | master 1185 | masterful 1186 | masterfully 1187 | masterpiece 1188 | masterpieces 1189 | masters 1190 | mastery 1191 | matchless 1192 | mature 1193 | maturely 1194 | maturity 1195 | meaningful 1196 | memorable 1197 | merciful 1198 | mercifully 1199 | mercy 1200 | merit 1201 | meritorious 1202 | merrily 1203 | merriment 1204 | merriness 1205 | merry 1206 | mesmerize 1207 | mesmerized 1208 | mesmerizes 1209 | mesmerizing 1210 | mesmerizingly 1211 | meticulous 1212 | meticulously 1213 | mightily 1214 | mighty 1215 | mind-blowing 1216 | miracle 1217 | miracles 1218 | miraculous 1219 | miraculously 1220 | miraculousness 1221 | modern 1222 | modest 1223 | modesty 1224 | momentous 1225 | monumental 1226 | monumentally 1227 | morality 1228 | motivated 1229 | multi-purpose 1230 | navigable 1231 | neat 1232 | neatest 1233 | neatly 1234 | nice 1235 | nicely 1236 | nicer 1237 | nicest 1238 | nifty 1239 | nimble 1240 | noble 1241 | nobly 1242 | noiseless 1243 | non-violence 1244 | non-violent 1245 | notably 1246 | noteworthy 1247 | nourish 1248 | nourishing 1249 | nourishment 1250 | novelty 1251 | nurturing 1252 | oasis 1253 | obsession 1254 | obsessions 1255 | obtainable 1256 | openly 1257 | openness 1258 | optimal 1259 | optimism 1260 | optimistic 1261 | opulent 1262 | orderly 1263 | originality 1264 | outdo 1265 | outdone 1266 | outperform 1267 | outperformed 1268 | outperforming 1269 | outperforms 1270 | outshine 1271 | outshone 1272 | outsmart 1273 | outstanding 1274 | outstandingly 1275 | outstrip 1276 | outwit 1277 | ovation 1278 | overjoyed 1279 | overtake 1280 | overtaken 1281 | overtakes 1282 | overtaking 1283 | overtook 1284 | overture 1285 | pain-free 1286 | painless 1287 | painlessly 1288 | palatial 1289 | pamper 1290 | pampered 1291 | pamperedly 1292 | pamperedness 1293 | pampers 1294 | panoramic 1295 | paradise 1296 | paramount 1297 | pardon 1298 | passion 1299 | passionate 1300 | passionately 1301 | patience 1302 | patient 1303 | patiently 1304 | patriot 1305 | patriotic 1306 | peace 1307 | peaceable 1308 | peaceful 1309 | peacefully 1310 | peacekeepers 1311 | peach 1312 | peerless 1313 | pep 1314 | pepped 1315 | pepping 1316 | peppy 1317 | peps 1318 | perfect 1319 | perfection 1320 | perfectly 1321 | permissible 1322 | perseverance 1323 | persevere 1324 | personages 1325 | personalized 1326 | phenomenal 1327 | phenomenally 1328 | picturesque 1329 | piety 1330 | pinnacle 1331 | playful 1332 | playfully 1333 | pleasant 1334 | pleasantly 1335 | pleased 1336 | pleases 1337 | pleasing 1338 | pleasingly 1339 | pleasurable 1340 | pleasurably 1341 | pleasure 1342 | plentiful 1343 | pluses 1344 | plush 1345 | plusses 1346 | poetic 1347 | poeticize 1348 | poignant 1349 | poise 1350 | poised 1351 | polished 1352 | polite 1353 | politeness 1354 | popular 1355 | portable 1356 | posh 1357 | positive 1358 | positively 1359 | positives 1360 | powerful 1361 | powerfully 1362 | praise 1363 | praiseworthy 1364 | praising 1365 | pre-eminent 1366 | precious 1367 | precise 1368 | precisely 1369 | preeminent 1370 | prefer 1371 | preferable 1372 | preferably 1373 | prefered 1374 | preferes 1375 | preferring 1376 | prefers 1377 | premier 1378 | prestige 1379 | prestigious 1380 | prettily 1381 | pretty 1382 | priceless 1383 | pride 1384 | principled 1385 | privilege 1386 | privileged 1387 | prize 1388 | proactive 1389 | problem-free 1390 | problem-solver 1391 | prodigious 1392 | prodigiously 1393 | prodigy 1394 | productive 1395 | productively 1396 | proficient 1397 | proficiently 1398 | profound 1399 | profoundly 1400 | profuse 1401 | profusion 1402 | progress 1403 | progressive 1404 | prolific 1405 | prominence 1406 | prominent 1407 | promise 1408 | promised 1409 | promises 1410 | promising 1411 | promoter 1412 | prompt 1413 | promptly 1414 | proper 1415 | properly 1416 | propitious 1417 | propitiously 1418 | pros 1419 | prosper 1420 | prosperity 1421 | prosperous 1422 | prospros 1423 | protect 1424 | protection 1425 | protective 1426 | proud 1427 | proven 1428 | proves 1429 | providence 1430 | proving 1431 | prowess 1432 | prudence 1433 | prudent 1434 | prudently 1435 | punctual 1436 | pure 1437 | purify 1438 | purposeful 1439 | quaint 1440 | qualified 1441 | qualify 1442 | quicker 1443 | quiet 1444 | quieter 1445 | radiance 1446 | radiant 1447 | rapid 1448 | rapport 1449 | rapt 1450 | rapture 1451 | raptureous 1452 | raptureously 1453 | rapturous 1454 | rapturously 1455 | rational 1456 | razor-sharp 1457 | reachable 1458 | readable 1459 | readily 1460 | ready 1461 | reaffirm 1462 | reaffirmation 1463 | realistic 1464 | realizable 1465 | reasonable 1466 | reasonably 1467 | reasoned 1468 | reassurance 1469 | reassure 1470 | receptive 1471 | reclaim 1472 | recomend 1473 | recommend 1474 | recommendation 1475 | recommendations 1476 | recommended 1477 | reconcile 1478 | reconciliation 1479 | record-setting 1480 | recover 1481 | recovery 1482 | rectification 1483 | rectify 1484 | rectifying 1485 | redeem 1486 | redeeming 1487 | redemption 1488 | refine 1489 | refined 1490 | refinement 1491 | reform 1492 | reformed 1493 | reforming 1494 | reforms 1495 | refresh 1496 | refreshed 1497 | refreshing 1498 | refund 1499 | refunded 1500 | regal 1501 | regally 1502 | regard 1503 | rejoice 1504 | rejoicing 1505 | rejoicingly 1506 | rejuvenate 1507 | rejuvenated 1508 | rejuvenating 1509 | relaxed 1510 | relent 1511 | reliable 1512 | reliably 1513 | relief 1514 | relish 1515 | remarkable 1516 | remarkably 1517 | remedy 1518 | remission 1519 | remunerate 1520 | renaissance 1521 | renewed 1522 | renown 1523 | renowned 1524 | replaceable 1525 | reputable 1526 | reputation 1527 | resilient 1528 | resolute 1529 | resound 1530 | resounding 1531 | resourceful 1532 | resourcefulness 1533 | respect 1534 | respectable 1535 | respectful 1536 | respectfully 1537 | respite 1538 | resplendent 1539 | responsibly 1540 | responsive 1541 | restful 1542 | restored 1543 | restructure 1544 | restructured 1545 | restructuring 1546 | retractable 1547 | revel 1548 | revelation 1549 | revere 1550 | reverence 1551 | reverent 1552 | reverently 1553 | revitalize 1554 | revival 1555 | revive 1556 | revives 1557 | revolutionary 1558 | revolutionize 1559 | revolutionized 1560 | revolutionizes 1561 | reward 1562 | rewarding 1563 | rewardingly 1564 | rich 1565 | richer 1566 | richly 1567 | richness 1568 | right 1569 | righten 1570 | righteous 1571 | righteously 1572 | righteousness 1573 | rightful 1574 | rightfully 1575 | rightly 1576 | rightness 1577 | risk-free 1578 | robust 1579 | rock-star 1580 | rock-stars 1581 | rockstar 1582 | rockstars 1583 | romantic 1584 | romantically 1585 | romanticize 1586 | roomier 1587 | roomy 1588 | rosy 1589 | safe 1590 | safely 1591 | sagacity 1592 | sagely 1593 | saint 1594 | saintliness 1595 | saintly 1596 | salutary 1597 | salute 1598 | sane 1599 | satisfactorily 1600 | satisfactory 1601 | satisfied 1602 | satisfies 1603 | satisfy 1604 | satisfying 1605 | satisified 1606 | saver 1607 | savings 1608 | savior 1609 | savvy 1610 | scenic 1611 | seamless 1612 | seasoned 1613 | secure 1614 | securely 1615 | selective 1616 | self-determination 1617 | self-respect 1618 | self-satisfaction 1619 | self-sufficiency 1620 | self-sufficient 1621 | sensation 1622 | sensational 1623 | sensationally 1624 | sensations 1625 | sensible 1626 | sensibly 1627 | sensitive 1628 | serene 1629 | serenity 1630 | sexy 1631 | sharp 1632 | sharper 1633 | sharpest 1634 | shimmering 1635 | shimmeringly 1636 | shine 1637 | shiny 1638 | significant 1639 | silent 1640 | simpler 1641 | simplest 1642 | simplified 1643 | simplifies 1644 | simplify 1645 | simplifying 1646 | sincere 1647 | sincerely 1648 | sincerity 1649 | skill 1650 | skilled 1651 | skillful 1652 | skillfully 1653 | slammin 1654 | sleek 1655 | slick 1656 | smart 1657 | smarter 1658 | smartest 1659 | smartly 1660 | smile 1661 | smiles 1662 | smiling 1663 | smilingly 1664 | smitten 1665 | smooth 1666 | smoother 1667 | smoothes 1668 | smoothest 1669 | smoothly 1670 | snappy 1671 | snazzy 1672 | sociable 1673 | soft 1674 | softer 1675 | solace 1676 | solicitous 1677 | solicitously 1678 | solid 1679 | solidarity 1680 | soothe 1681 | soothingly 1682 | sophisticated 1683 | soulful 1684 | soundly 1685 | soundness 1686 | spacious 1687 | sparkle 1688 | sparkling 1689 | spectacular 1690 | spectacularly 1691 | speedily 1692 | speedy 1693 | spellbind 1694 | spellbinding 1695 | spellbindingly 1696 | spellbound 1697 | spirited 1698 | spiritual 1699 | splendid 1700 | splendidly 1701 | splendor 1702 | spontaneous 1703 | sporty 1704 | spotless 1705 | sprightly 1706 | stability 1707 | stabilize 1708 | stable 1709 | stainless 1710 | standout 1711 | state-of-the-art 1712 | stately 1713 | statuesque 1714 | staunch 1715 | staunchly 1716 | staunchness 1717 | steadfast 1718 | steadfastly 1719 | steadfastness 1720 | steadiest 1721 | steadiness 1722 | steady 1723 | stellar 1724 | stellarly 1725 | stimulate 1726 | stimulates 1727 | stimulating 1728 | stimulative 1729 | stirringly 1730 | straighten 1731 | straightforward 1732 | streamlined 1733 | striking 1734 | strikingly 1735 | striving 1736 | strong 1737 | stronger 1738 | strongest 1739 | stunned 1740 | stunning 1741 | stunningly 1742 | stupendous 1743 | stupendously 1744 | sturdier 1745 | sturdy 1746 | stylish 1747 | stylishly 1748 | stylized 1749 | suave 1750 | suavely 1751 | sublime 1752 | subsidize 1753 | subsidized 1754 | subsidizes 1755 | subsidizing 1756 | substantive 1757 | succeed 1758 | succeeded 1759 | succeeding 1760 | succeeds 1761 | succes 1762 | success 1763 | successes 1764 | successful 1765 | successfully 1766 | suffice 1767 | sufficed 1768 | suffices 1769 | sufficient 1770 | sufficiently 1771 | suitable 1772 | sumptuous 1773 | sumptuously 1774 | sumptuousness 1775 | super 1776 | superb 1777 | superbly 1778 | superior 1779 | superiority 1780 | supple 1781 | support 1782 | supported 1783 | supporter 1784 | supporting 1785 | supportive 1786 | supports 1787 | supremacy 1788 | supreme 1789 | supremely 1790 | supurb 1791 | supurbly 1792 | surmount 1793 | surpass 1794 | surreal 1795 | survival 1796 | survivor 1797 | sustainability 1798 | sustainable 1799 | swank 1800 | swankier 1801 | swankiest 1802 | swanky 1803 | sweeping 1804 | sweet 1805 | sweeten 1806 | sweetheart 1807 | sweetly 1808 | sweetness 1809 | swift 1810 | swiftness 1811 | talent 1812 | talented 1813 | talents 1814 | tantalize 1815 | tantalizing 1816 | tantalizingly 1817 | tempt 1818 | tempting 1819 | temptingly 1820 | tenacious 1821 | tenaciously 1822 | tenacity 1823 | tender 1824 | tenderly 1825 | terrific 1826 | terrifically 1827 | thank 1828 | thankful 1829 | thinner 1830 | thoughtful 1831 | thoughtfully 1832 | thoughtfulness 1833 | thrift 1834 | thrifty 1835 | thrill 1836 | thrilled 1837 | thrilling 1838 | thrillingly 1839 | thrills 1840 | thrive 1841 | thriving 1842 | thumb-up 1843 | thumbs-up 1844 | tickle 1845 | tidy 1846 | time-honored 1847 | timely 1848 | tingle 1849 | titillate 1850 | titillating 1851 | titillatingly 1852 | togetherness 1853 | tolerable 1854 | toll-free 1855 | top 1856 | top-notch 1857 | top-quality 1858 | topnotch 1859 | tops 1860 | tough 1861 | tougher 1862 | toughest 1863 | traction 1864 | tranquil 1865 | tranquility 1866 | transparent 1867 | treasure 1868 | tremendously 1869 | trendy 1870 | triumph 1871 | triumphal 1872 | triumphant 1873 | triumphantly 1874 | trivially 1875 | trophy 1876 | trouble-free 1877 | trump 1878 | trumpet 1879 | trust 1880 | trusted 1881 | trusting 1882 | trustingly 1883 | trustworthiness 1884 | trustworthy 1885 | trusty 1886 | truthful 1887 | truthfully 1888 | truthfulness 1889 | twinkly 1890 | ultra-crisp 1891 | unabashed 1892 | unabashedly 1893 | unaffected 1894 | unassailable 1895 | unbeatable 1896 | unbiased 1897 | unbound 1898 | uncomplicated 1899 | unconditional 1900 | undamaged 1901 | undaunted 1902 | understandable 1903 | undisputable 1904 | undisputably 1905 | undisputed 1906 | unencumbered 1907 | unequivocal 1908 | unequivocally 1909 | unfazed 1910 | unfettered 1911 | unforgettable 1912 | unity 1913 | unlimited 1914 | unmatched 1915 | unparalleled 1916 | unquestionable 1917 | unquestionably 1918 | unreal 1919 | unrestricted 1920 | unrivaled 1921 | unselfish 1922 | unwavering 1923 | upbeat 1924 | upgradable 1925 | upgradeable 1926 | upgraded 1927 | upheld 1928 | uphold 1929 | uplift 1930 | uplifting 1931 | upliftingly 1932 | upliftment 1933 | upscale 1934 | usable 1935 | useable 1936 | useful 1937 | user-friendly 1938 | user-replaceable 1939 | valiant 1940 | valiantly 1941 | valor 1942 | valuable 1943 | variety 1944 | venerate 1945 | verifiable 1946 | veritable 1947 | versatile 1948 | versatility 1949 | vibrant 1950 | vibrantly 1951 | victorious 1952 | victory 1953 | viewable 1954 | vigilance 1955 | vigilant 1956 | virtue 1957 | virtuous 1958 | virtuously 1959 | visionary 1960 | vivacious 1961 | vivid 1962 | vouch 1963 | vouchsafe 1964 | warm 1965 | warmer 1966 | warmhearted 1967 | warmly 1968 | warmth 1969 | wealthy 1970 | welcome 1971 | well 1972 | well-backlit 1973 | well-balanced 1974 | well-behaved 1975 | well-being 1976 | well-bred 1977 | well-connected 1978 | well-educated 1979 | well-established 1980 | well-informed 1981 | well-intentioned 1982 | well-known 1983 | well-made 1984 | well-managed 1985 | well-mannered 1986 | well-positioned 1987 | well-received 1988 | well-regarded 1989 | well-rounded 1990 | well-run 1991 | well-wishers 1992 | wellbeing 1993 | whoa 1994 | wholeheartedly 1995 | wholesome 1996 | whooa 1997 | whoooa 1998 | wieldy 1999 | willing 2000 | willingly 2001 | willingness 2002 | win 2003 | windfall 2004 | winnable 2005 | winner 2006 | winners 2007 | winning 2008 | wins 2009 | wisdom 2010 | wise 2011 | wisely 2012 | witty 2013 | won 2014 | wonder 2015 | wonderful 2016 | wonderfully 2017 | wonderous 2018 | wonderously 2019 | wonders 2020 | wondrous 2021 | woo 2022 | work 2023 | workable 2024 | worked 2025 | works 2026 | world-famous 2027 | worth 2028 | worth-while 2029 | worthiness 2030 | worthwhile 2031 | worthy 2032 | wow 2033 | wowed 2034 | wowing 2035 | wows 2036 | yay 2037 | youthful 2038 | zeal 2039 | zenith 2040 | zest 2041 | zippy -------------------------------------------------------------------------------- /Chapter16. Sorting/project/project_twitter_data.csv: -------------------------------------------------------------------------------- 1 | tweet_text,retweet_count,reply_count 2 | @twitteruser: On now - @Fusion scores first points #FirstFinals @overwatchleague @umich @umsi Michigan Athletics made out of emojis. #GoBlue,3,0 3 | BUNCH of things about crisis respons… available July 8th… scholarship focuses on improving me… in North America! A s… and frigid temperatures,1,0 4 | FREE ice cream with these local area deals: chance to pitch yourself to hundreds of employers? Msi student Name Here is spending her summer,1,2 5 | AWAY from the Internet of Things attacks… right and the left? See… use DIY language to discuss other projects not traditionally viewed as masculine,3,1 6 | IN City Name!… from @twitteruser has some amazing datasets and tools for collective action. - UMSI a… grateful for… equipping elderly African-American,6,0 7 | ENTREPRENEURSHIP in #City.… a great social media job opportunity for our UMSI alumni looking to work at City Name Public Schools! #goblue,9,5 8 | BRINGING #datascience to community researchers with a team of researchers have been helping people in 'lean' economies learn entrepreneurial,19,0 9 | WHY not pay you?… endure crushing pressures and frigid temperatures but the most difficult part of… faculty and staff across the city,0,0 10 | A bunch of things about crisis respons… – but the implications are much bigger t… for some but a financial burden for others. @umichdpss and,0,0 11 | @THEEMMYS nomination for Best Lead Actor in a library role focused on Digital Services and Projects? As a bonus you get to work at t… by @cab938,82,2 12 | THIS headline has been inescapable this summer. Now the infectious chart-topper from 'Scorpion' gets a vi… Seventh Victim 'Scorpion' gets a,0,0 13 | OF wine with a shoe? Yes but it ain't pretty. Its First Amendment rights. That it claims will for… and non-binary musicians shaping the sound,0,0 14 | HAVE detained six people in history to ride to orbit in private space taxis next year if all to faithful them is that they simply can't afford,47,0 15 | PET Name. She is 1 year old Shiba Inu. When her caregiver is not at home Name likes to have… I tell them about my website and ask if my,2,1 16 | YOU’RE welcome! He was a mix of many breeds. He is a 2 year old Yellow Lab. When he was a mix of breeds but has the bark of a road!!,0,2 17 | Name. He is wild and playful. He likes to chase and play with his stuffed elephant! the Dir. Of Human Resources @twitteruser. He is a,0,0 18 | BORDER Terrier puppy. Name is loving and very protective of the people she loves. Name2 is a 3 year old Maltipoo. Name3 is an 8 year old Corgi.,4,6 19 | REASON they did not rain but they will reign beautifully couldn't asked for a crime 80 years in the Spring Name's Last Love absolutely love,19,0 20 | HOME surrounded by snow in my Garden. But City Name people musn't: such a good book: RT @twitteruser The Literature of Conflicted Lands after a,0,0 21 | -------------------------------------------------------------------------------- /Chapter16. Sorting/sort.py: -------------------------------------------------------------------------------- 1 | L1 = [1, 7, 4, -2, 3] 2 | L2 = ["Cherry", "Apple", "Blueberry"] 3 | 4 | L1.sort() 5 | print(L1) 6 | L2.sort() 7 | print(L2) 8 | 9 | #################################### 10 | 11 | L2 = ["Cherry", "Apple", "Blueberry"] 12 | 13 | L3 = sorted(L2) 14 | print(L3) 15 | print(sorted(L2)) 16 | print(L2) # unchanged 17 | 18 | print("----") 19 | 20 | L2.sort() 21 | print(L2) 22 | print(L2.sort()) #return value is None 23 | -------------------------------------------------------------------------------- /Chapter16. Sorting/sorted_key.py: -------------------------------------------------------------------------------- 1 | L1 = [1, 7, 4, -2, 3] 2 | 3 | def absolute(x): 4 | if x >= 0: 5 | return x 6 | else: 7 | return -x 8 | 9 | L2 = sorted(L1, key=absolute) 10 | print(L2) 11 | 12 | 13 | print(sorted(L1, reverse=True, key=absolute)) 14 | -------------------------------------------------------------------------------- /Chapter17. Nested Data and Nested Iteration/copy_inner.py: -------------------------------------------------------------------------------- 1 | original = [['dogs', 'puppies'], ['cats', "kittens"]] 2 | copied_outer_list = [] 3 | for inner_list in original: 4 | copied_inner_list = [] 5 | for item in inner_list: 6 | copied_inner_list.append(item) 7 | copied_outer_list.append(copied_inner_list) 8 | print(copied_outer_list) 9 | original[0].append(["canines"]) 10 | print(original) 11 | print("-------- Now look at the copied version -----------") 12 | print(copied_outer_list) 13 | -------------------------------------------------------------------------------- /Chapter17. Nested Data and Nested Iteration/course_3_assessment_1.py: -------------------------------------------------------------------------------- 1 | # 1. The variable nested contains a nested list. Assign ‘snake’ to the variable output using indexing. 2 | 3 | nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']] 4 | output = nested[1][2] 5 | print(output) 6 | 7 | # 2. Below, a list of lists is provided. Use in and not in tests to create variables with Boolean values. 8 | # See comments for further instructions. 9 | 10 | lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']] 11 | 12 | #Test to see if 'yellow' is in the third list of lst. Save to variable ``yellow`` 13 | yellow = 'yellow' in lst[2] 14 | 15 | #Test to see if 4 is in the second list of lst. Save to variable ``four`` 16 | four = 4 in lst[1] 17 | 18 | #Test to see if 'orange' is in the first element of lst. Save to variable ``orange`` 19 | orange = 'orange' in lst[0] 20 | 21 | # 3. Below, we’ve provided a list of lists. Use in statements to create variables with Boolean values 22 | # see the ActiveCode window for further directions. 23 | 24 | L = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']] 25 | 26 | # Test if 'hola' is in the list L. Save to variable name test1 27 | test1 = 'hola' in L 28 | # Test if [5, 8, 7] is in the list L. Save to variable name test2 29 | test2 = [5, 8, 7] in L 30 | # Test if 6.6 is in the third element of list L. Save to variable name test3 31 | test3 = 6.6 in L[2] 32 | 33 | # 4. Provided is a nested data structure. Follow the instructions in the comments below. Do not hard code. 34 | 35 | nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], 'window': ['part', 'whole', [], 'sum', ['math', 'calculus', 'algebra', 'geometry', 'statistics',['physics', 'chemistry', 'biology']]]} 36 | 37 | # Check to see if the string data is a key in nested, if it is, assign True to the variable data, otherwise assign False. 38 | if 'data' in nested: 39 | data = True 40 | else: 41 | data = False 42 | # Check to see if the integer 24 is in the value of the key data, if it is then assign to the variable twentyfour the value of True, otherwise False. 43 | if 24 in nested: 44 | twentyfour = True 45 | else: 46 | twentyfour = False 47 | # Check to see that the string 'whole' is not in the value of the key window. If it's not, then assign to the variable whole the value of True, otherwise False. 48 | if 'whole' in nested: 49 | whole = True 50 | else: 51 | whole = False 52 | # Check to see if the string 'physics' is a key in the dictionary nested. If it is, assign to the variable physics, the value of True, otherwise False. 53 | if 'physics' in nested: 54 | physics = True 55 | else: 56 | physics = False 57 | 58 | # 5. The variable nested_d contains a nested dictionary with the gold medal counts 59 | # for the top four countries in the past three Olympics. 60 | # Assign the value of Great Britain’s gold medal count from the London Olympics to the variable london_gold. 61 | # Use indexing. Do not hardcode. 62 | 63 | nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}} 64 | london_gold = nested_d['London']['Great Britain'] 65 | 66 | # 6. Below, we have provided a nested dictionary. 67 | # Index into the dictionary to create variables that we have listed in the ActiveCode window. 68 | 69 | sports = {'swimming': ['butterfly', 'breaststroke', 'backstroke', 'freestyle'], 'diving': ['springboard', 'platform', 'synchronized'], 'track': ['sprint', 'distance', 'jumps', 'throws'], 'gymnastics': {'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']}} 70 | 71 | # Assign the string 'backstroke' to the name v1 72 | v1 = sports['swimming'][2] 73 | # Assign the string 'platform' to the name v2 74 | v2 = sports['diving'][1] 75 | # Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3 76 | v3 = sports['gymnastics']['women'] 77 | # Assign the string 'rings' to the name v4 78 | v4 = sports['gymnastics']['men'][3] 79 | print(v4) 80 | 81 | # 7. Given the dictionary, nested_d, 82 | # save the medal count for the USA from all three Olympics in the dictionary to the list US_count. 83 | 84 | nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}} 85 | US_count = [] 86 | 87 | 88 | US_count.append(nested_d['Beijing']['USA']) 89 | US_count.append(nested_d['London']['USA']) 90 | US_count.append(nested_d['Rio']['USA']) 91 | 92 | # 8. Iterate through the contents of l_of_l and assign the third element of sublist to a new list called third. 93 | 94 | l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']] 95 | 96 | third = [i[2] for i in l_of_l] 97 | 98 | # 9. Given below is a list of lists of athletes. 99 | # Create a list, t, that saves only the athlete’s name if it contains the letter “t”. 100 | # If it does not contain the letter “t”, save the athlete name into list other. 101 | 102 | athletes = [ 103 | ['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], 104 | ['Felix', 'Bolt', 'Gardner', 'Eaton'], 105 | ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton'] 106 | ] 107 | 108 | t = [] 109 | other = [] 110 | 111 | for list in athletes: 112 | for char in list: 113 | if 't' in char: 114 | t.append(char) 115 | else: 116 | other.append(char) -------------------------------------------------------------------------------- /Chapter17. Nested Data and Nested Iteration/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/count.py: -------------------------------------------------------------------------------- 1 | def update_counts(letters, counts_dict): 2 | for c in letters: 3 | counts_dict[c] = 1 4 | if c in counts_dict: 5 | counts_dict[c] = counts_dict[c] + 1 6 | 7 | import test 8 | 9 | counts_dict = {'a': 3, 'b': 2} 10 | update_counts("aaab", counts_dict) 11 | # 3 more occurrences of a, so 6 in all 12 | test.testEqual(counts_dict['a'], 6) 13 | # 1 more occurrence of b, so 3 in all 14 | test.testEqual(counts_dict['b'], 3) 15 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/distance.py: -------------------------------------------------------------------------------- 1 | import test 2 | def distance(x1, y1, x2, y2): 3 | return 0.0 4 | 5 | test.testEqual(distance(1, 2, 1, 2), 0) 6 | 7 | 8 | import test 9 | def distance(x1, y1, x2, y2): 10 | dx = x2 - x1 11 | dy = y2 - y1 12 | dsquared = dx**2 + dy**2 13 | result = dsquared**0.5 14 | return result 15 | 16 | test.testEqual(distance(1,2, 1,2), 0) 17 | test.testEqual(distance(1,2, 4,6), 5) 18 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/intro.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | '''raise x to the second power''' 3 | return x * x 4 | 5 | import test 6 | print('testing square function') 7 | test.testEqual(square(10), 100) 8 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/reverse.py: -------------------------------------------------------------------------------- 1 | import test 2 | 3 | test.testEqual(sorted([1, 7, 4]), [1, 4, 7]) 4 | test.testEqual(sorted([1, 7, 4], reverse=True), [7, 4, 1]) 5 | -------------------------------------------------------------------------------- /Chapter18. Test Cases/testcase.py: -------------------------------------------------------------------------------- 1 | class Point: 2 | """ Point class for representing and manipulating x,y coordinates. """ 3 | 4 | def __init__(self, initX, initY): 5 | 6 | self.x = initX 7 | self.y = initY 8 | 9 | def distanceFromOrigin(self): 10 | return ((self.x ** 2) + (self.y ** 2)) ** 0.5 11 | 12 | def move(self, dx, dy): 13 | self.x = self.x + dx 14 | self.y = self.y + dy 15 | 16 | import test 17 | 18 | #testing instance variables x and y 19 | p = Point(3, 4) 20 | test.testEqual(p.y, 4) 21 | test.testEqual(p.x, 3) 22 | 23 | #testing the distance method 24 | p = Point(3, 4) 25 | test.testEqual(p.distanceFromOrigin(), 5.0) 26 | 27 | #testing the move method 28 | p = Point(3, 4) 29 | p.move(-2, 3) 30 | test.testEqual(p.x, 1) 31 | test.testEqual(p.y, 7) 32 | -------------------------------------------------------------------------------- /Chapter19. Exceptions/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter19. Exceptions/try.py: -------------------------------------------------------------------------------- 1 | try: 2 | items = ['a', 'b'] 3 | third = items[2] 4 | print("This won't print") 5 | except Exception: 6 | print("got an error") 7 | 8 | print("continuing") 9 | 10 | 11 | ###################### 12 | 13 | try: 14 | items = ['a', 'b'] 15 | third = items[2] 16 | print("This won't print") 17 | except IndexError: 18 | print("error 1") 19 | 20 | print("continuing") 21 | 22 | try: 23 | x = 5 24 | y = x/0 25 | print("This won't print, either") 26 | except IndexError: 27 | print("error 2") 28 | 29 | 30 | print("continuing again") 31 | -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.10. Statements and Expressions.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | x = 7 8 | y = 7 9 | print(add(square(y), square(x))) -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.13. Updating Variables.py: -------------------------------------------------------------------------------- 1 | x=2 2 | print(x) 3 | x+=3 4 | print(x) 5 | x-=1 6 | print(x) -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.2.Values and Data types.py: -------------------------------------------------------------------------------- 1 | print(100) #Integer 2 | print("Hello World!") #String 3 | print("Thuss") 4 | print(3.14) #Floats -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.3.Operaors and Operands.py: -------------------------------------------------------------------------------- 1 | print(150 + 200) 2 | print(5-5) 3 | print(2*3) 4 | print(114/3) 5 | print(14//3) 6 | print(15%3) 7 | print(5**2) 8 | print(20+20/2) 9 | print((20+20)/2) 10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.4.Functions calls.py: -------------------------------------------------------------------------------- 1 | import math 2 | print(math.sqrt(5) -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.6. Type conversion functions.py: -------------------------------------------------------------------------------- 1 | print(3.14, int(3.14)) 2 | print(3.9999, int(3.9999)) # This doesn't round to the closest int! 3 | print(3.0, int(3.0)) 4 | print(-3.999, int(-3.999)) # Note that the result is closer to zero 5 | 6 | print("2345", int("2345")) # parse a string to produce an int 7 | print(17, int(17)) # int even works on integers 8 | print(int("23bottles")) 9 | print(str("23bottles")) 10 | print(float("123.45")) 11 | print(type("123.45")) 12 | -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/2.7. Variables.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x*x) 3 | 4 | print(square(4)) -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/hardcoding.py: -------------------------------------------------------------------------------- 1 | x=10 2 | y=20 3 | avg=(x+y)/2 4 | print(avg) -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/input.py: -------------------------------------------------------------------------------- 1 | n= input("Please enter your name:") 2 | print("HEllo", n) 3 | 4 | str_seconds = input("Please enter the number of seconds you wish to convert") 5 | total_secs = int(str_seconds) 6 | 7 | hours = total_secs // 3600 8 | secs_still_remaining = total_secs % 3600 9 | minutes = secs_still_remaining // 60 10 | secs_finally_remaining = secs_still_remaining % 60 11 | 12 | print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining) 13 | -------------------------------------------------------------------------------- /Chapter2. Variables, Statements, and Expressions/rougy.py: -------------------------------------------------------------------------------- 1 | degrees_farenheit = input("Enten the farenheit temp") 2 | degrees_celsius = ((degrees_farenheit) - (32)) 3 | print (degrees_celsius) -------------------------------------------------------------------------------- /Chapter20. Defining your own Classes/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter21. Building Programs/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/1/3.py: -------------------------------------------------------------------------------- 1 | class Cheshire(Cat): # this inherits from Cat, which inherits from Pet 2 | 3 | def smile(self): # this method is specific to instances of Cheshire 4 | print(":D :D :D") 5 | 6 | # Let's try it with instances. 7 | cat1 = Cat("Fluffy") 8 | cat1.feed() # Totally fine, because the cat class inherits from the Pet class! 9 | cat1.hi() # Uses the special Cat hello. 10 | print(cat1) 11 | 12 | print(cat1.chasing_rats()) 13 | 14 | new_cat = Cheshire("Pumpkin") # create a Cheshire cat instance with name "Pumpkin" 15 | new_cat.hi() # same as Cat! 16 | new_cat.chasing_rats() # OK, because Cheshire inherits from Cat 17 | new_cat.smile() # Only for Cheshire instances (and any classes that you make inherit from Cheshire) 18 | 19 | # cat1.smile() # This line would give you an error, because the Cat class does not have this method! 20 | 21 | # None of the subclass methods can be used on the parent class, though. 22 | p1 = Pet("Teddy") 23 | p1.hi() # just the regular Pet hello 24 | #p1.chasing_rats() # This will give you an error -- this method doesn't exist on instances of the Pet class. 25 | #p1.smile() # This will give you an error, too. This method does not exist on instances of the Pet class. 26 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/1/Pet.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | # Here's the original Pet class 4 | class Pet(): 5 | boredom_decrement = 4 6 | hunger_decrement = 6 7 | boredom_threshold = 5 8 | hunger_threshold = 10 9 | sounds = ['Mrrp'] 10 | def __init__(self, name = "Kitty"): 11 | self.name = name 12 | self.hunger = randrange(self.hunger_threshold) 13 | self.boredom = randrange(self.boredom_threshold) 14 | self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class 15 | 16 | def clock_tick(self): 17 | self.boredom += 1 18 | self.hunger += 1 19 | 20 | def mood(self): 21 | if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: 22 | return "happy" 23 | elif self.hunger > self.hunger_threshold: 24 | return "hungry" 25 | else: 26 | return "bored" 27 | 28 | def __str__(self): 29 | state = " I'm " + self.name + ". " 30 | state += " I feel " + self.mood() + ". " 31 | # state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds) 32 | return state 33 | 34 | def hi(self): 35 | print(self.sounds[randrange(len(self.sounds))]) 36 | self.reduce_boredom() 37 | 38 | def teach(self, word): 39 | self.sounds.append(word) 40 | self.reduce_boredom() 41 | 42 | def feed(self): 43 | self.reduce_hunger() 44 | 45 | def reduce_hunger(self): 46 | self.hunger = max(0, self.hunger - self.hunger_decrement) 47 | 48 | def reduce_boredom(self): 49 | self.boredom = max(0, self.boredom - self.boredom_decrement) 50 | 51 | # Here's the new definition of class Cat, a subclass of Pet. 52 | class Cat(Pet): # the class name that the new class inherits from goes in the parentheses, like so. 53 | sounds = ['Meow'] 54 | 55 | def chasing_rats(self): 56 | return "What are you doing, Pinky? Taking over the world?!" 57 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/1/Pet1.py: -------------------------------------------------------------------------------- 1 | p1 = Pet("Fido") 2 | print(p1) # we've seen this stuff before! 3 | 4 | p1.feed() 5 | p1.hi() 6 | print(p1) 7 | 8 | cat1 = Cat("Fluffy") 9 | print(cat1) # this uses the same __str__ method as the Pets do 10 | 11 | cat1.feed() # Totally fine, because the cat class inherits from the Pet class! 12 | cat1.hi() 13 | print(cat1) 14 | 15 | print(cat1.chasing_rats()) 16 | 17 | #print(p1.chasing_rats()) # This line will give us an error. The Pet class doesn't have this method! 18 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/2/1.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | # Here's the original Pet class 4 | class Pet(): 5 | boredom_decrement = 4 6 | hunger_decrement = 6 7 | boredom_threshold = 5 8 | hunger_threshold = 10 9 | sounds = ['Mrrp'] 10 | def __init__(self, name = "Kitty"): 11 | self.name = name 12 | self.hunger = randrange(self.hunger_threshold) 13 | self.boredom = randrange(self.boredom_threshold) 14 | self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class 15 | 16 | def clock_tick(self): 17 | self.boredom += 1 18 | self.hunger += 1 19 | 20 | def mood(self): 21 | if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: 22 | return "happy" 23 | elif self.hunger > self.hunger_threshold: 24 | return "hungry" 25 | else: 26 | return "bored" 27 | 28 | def __str__(self): 29 | state = " I'm " + self.name + ". " 30 | state += " I feel " + self.mood() + ". " 31 | # state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds) 32 | return state 33 | 34 | def hi(self): 35 | print(self.sounds[randrange(len(self.sounds))]) 36 | self.reduce_boredom() 37 | 38 | def teach(self, word): 39 | self.sounds.append(word) 40 | self.reduce_boredom() 41 | 42 | def feed(self): 43 | self.reduce_hunger() 44 | 45 | def reduce_hunger(self): 46 | self.hunger = max(0, self.hunger - self.hunger_decrement) 47 | 48 | def reduce_boredom(self): 49 | self.boredom = max(0, self.boredom - self.boredom_decrement) 50 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/2/2.py: -------------------------------------------------------------------------------- 1 | class Cat(Pet): 2 | sounds = ['Meow'] 3 | 4 | def mood(self): 5 | if self.hunger > self.hunger_threshold: 6 | return "hungry" 7 | if self.boredom <2: 8 | return "grumpy; leave me alone" 9 | elif self.boredom > self.boredom_threshold: 10 | return "bored" 11 | elif randrange(2) == 0: 12 | return "randomly annoyed" 13 | else: 14 | return "happy" 15 | 16 | class Dog(Pet): 17 | sounds = ['Woof', 'Ruff'] 18 | 19 | def mood(self): 20 | if (self.hunger > self.hunger_threshold) and (self.boredom > self.boredom_threshold): 21 | return "bored and hungry" 22 | else: 23 | return "happy" 24 | 25 | c1 = Cat("Fluffy") 26 | d1 = Dog("Astro") 27 | 28 | c1.boredom = 1 29 | print(c1.mood()) 30 | c1.boredom = 3 31 | for i in range(10): 32 | print(c1.mood()) 33 | print(d1.mood()) 34 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/3/1.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | # Here's the original Pet class 4 | class Pet(): 5 | boredom_decrement = 4 6 | hunger_decrement = 6 7 | boredom_threshold = 5 8 | hunger_threshold = 10 9 | sounds = ['Mrrp'] 10 | def __init__(self, name = "Kitty"): 11 | self.name = name 12 | self.hunger = randrange(self.hunger_threshold) 13 | self.boredom = randrange(self.boredom_threshold) 14 | self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class 15 | 16 | def clock_tick(self): 17 | self.boredom += 1 18 | self.hunger += 1 19 | 20 | def mood(self): 21 | if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: 22 | return "happy" 23 | elif self.hunger > self.hunger_threshold: 24 | return "hungry" 25 | else: 26 | return "bored" 27 | 28 | def __str__(self): 29 | state = " I'm " + self.name + ". " 30 | state += " I feel " + self.mood() + ". " 31 | # state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds) 32 | return state 33 | 34 | def hi(self): 35 | print(self.sounds[randrange(len(self.sounds))]) 36 | self.reduce_boredom() 37 | 38 | def teach(self, word): 39 | self.sounds.append(word) 40 | self.reduce_boredom() 41 | 42 | def feed(self): 43 | self.reduce_hunger() 44 | 45 | def reduce_hunger(self): 46 | self.hunger = max(0, self.hunger - self.hunger_decrement) 47 | 48 | def reduce_boredom(self): 49 | self.boredom = max(0, self.boredom - self.boredom_decrement) 50 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/3/2.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | class Dog(Pet): 4 | sounds = ['Woof', 'Ruff'] 5 | 6 | def feed(self): 7 | Pet.feed(self) 8 | print("Arf! Thanks!") 9 | 10 | d1 = Dog("Astro") 11 | 12 | d1.feed() 13 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/3/3.py: -------------------------------------------------------------------------------- 1 | class Bird(Pet): 2 | sounds = ["chirp"] 3 | def __init__(self, name="Kitty", chirp_number=2): 4 | Pet.__init__(self, name) # call the parent class's constructor 5 | # basically, call the SUPER -- the parent version -- of the constructor, with all the parameters that it needs. 6 | self.chirp_number = chirp_number # now, also assign the new instance variable 7 | 8 | def hi(self): 9 | for i in range(self.chirp_number): 10 | print(self.sounds[randrange(len(self.sounds))]) 11 | self.reduce_boredom() 12 | 13 | b1 = Bird('tweety', 5) 14 | b1.teach("Polly wanna cracker") 15 | b1.hi() 16 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/4/Tamagotchi.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setExecutionLimit(60000) 3 | from random import randrange 4 | 5 | class Pet(object): 6 | boredom_decrement = 4 7 | hunger_decrement = 6 8 | boredom_threshold = 5 9 | hunger_threshold = 10 10 | sounds = ['Mrrp'] 11 | def __init__(self, name = "Kitty"): 12 | self.name = name 13 | self.hunger = randrange(self.hunger_threshold) 14 | self.boredom = randrange(self.boredom_threshold) 15 | self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class 16 | 17 | def clock_tick(self): 18 | self.boredom += 1 19 | self.hunger += 1 20 | 21 | def mood(self): 22 | if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: 23 | return "happy" 24 | elif self.hunger > self.hunger_threshold: 25 | return "hungry" 26 | else: 27 | return "bored" 28 | 29 | def __str__(self): 30 | state = " I'm " + self.name + ". " 31 | state += " I feel " + self.mood() + ". " 32 | # state += "Hunger %d Boredom %d Words %s" % (self.hunger, self.boredom, self.sounds) 33 | return state 34 | 35 | def hi(self): 36 | print(self.sounds[randrange(len(self.sounds))]) 37 | self.update_boredom() 38 | 39 | def teach(self, word): 40 | self.sounds.append(word) 41 | self.update_boredom() 42 | 43 | def feed(self): 44 | self.update_hunger() 45 | 46 | def update_hunger(self): 47 | self.hunger = max(0, self.hunger - self.hunger_decrement) 48 | 49 | def update_boredom(self): 50 | self.boredom = max(0, self.boredom - self.boredom_decrement) 51 | 52 | class Cat(Pet): 53 | sounds = ['Meow'] 54 | 55 | def mood(self): 56 | if self.hunger > self.hunger_threshold: 57 | return "hungry" 58 | if self.boredom <2: 59 | return "grumpy; leave me alone" 60 | elif self.boredom > self.boredom_threshold: 61 | return "bored" 62 | elif randrange(2) == 0: 63 | return "randomly annoyed" 64 | else: 65 | return "happy" 66 | 67 | class Dog(Pet): 68 | sounds = ['Woof', 'Ruff'] 69 | 70 | def mood(self): 71 | if (self.hunger > self.hunger_threshold) and (self.boredom > self.boredom_threshold): 72 | return "bored and hungry" 73 | else: 74 | return "happy" 75 | 76 | def feed(self): 77 | Pet.feed(self) 78 | print("Arf! Thanks!") 79 | 80 | class Bird(Pet): 81 | sounds = ["chirp"] 82 | def __init__(self, name="Kitty", chirp_number=2): 83 | Pet.__init__(self, name) # call the parent class's constructor 84 | # basically, call the SUPER -- the parent version -- of the constructor, with all the parameters that it needs. 85 | self.chirp_number = chirp_number # now, also assign the new instance variable 86 | 87 | def hi(self): 88 | for i in range(self.chirp_number): 89 | print(self.sounds[randrange(len(self.sounds))]) 90 | self.update_boredom() 91 | 92 | class Lab(Dog): 93 | def fetch(self): 94 | return "I found the tennis ball!" 95 | 96 | def hi(self): 97 | print(self.fetch()) 98 | print(self.sounds[randrange(len(self.sounds))]) 99 | 100 | class Poodle(Dog): 101 | def dance(self): 102 | return "Dancin' in circles like poodles do." 103 | 104 | def hi(self): 105 | print(self.dance()) 106 | Dog.hi(self) 107 | 108 | def whichone(petlist, name): 109 | for pet in petlist: 110 | if pet.name == name: 111 | return pet 112 | return None # no pet matched 113 | 114 | pet_types = {'dog': Dog, 'lab': Lab, 'poodle': Poodle, 'cat': Cat, 'bird': Bird} 115 | def whichtype(adopt_type="general pet"): 116 | return pet_types.get(adopt_type.lower(), Pet) 117 | 118 | def play(): 119 | animals = [] 120 | 121 | option = "" 122 | base_prompt = """ 123 | Quit 124 | Adopt 125 | Greet 126 | Teach 127 | Feed 128 | 129 | Choice: """ 130 | feedback = "" 131 | while True: 132 | action = input(feedback + "\n" + base_prompt) 133 | feedback = "" 134 | words = action.split() 135 | if len(words) > 0: 136 | command = words[0] 137 | else: 138 | command = None 139 | if command == "Quit": 140 | print("Exiting...") 141 | return 142 | elif command == "Adopt" and len(words) > 1: 143 | if whichone(animals, words[1]): 144 | feedback += "You already have a pet with that name\n" 145 | else: 146 | # figure out which class it should be 147 | if len(words) > 2: 148 | Cl = whichtype(words[2]) 149 | else: 150 | Cl = Pet 151 | # Make an instance of that class and append it 152 | animals.append(Cl(words[1])) 153 | elif command == "Greet" and len(words) > 1: 154 | pet = whichone(animals, words[1]) 155 | if not pet: 156 | feedback += "I didn't recognize that pet name. Please try again.\n" 157 | print() 158 | else: 159 | pet.hi() 160 | elif command == "Teach" and len(words) > 2: 161 | pet = whichone(animals, words[1]) 162 | if not pet: 163 | feedback += "I didn't recognize that pet name. Please try again." 164 | else: 165 | pet.teach(words[2]) 166 | elif command == "Feed" and len(words) > 1: 167 | pet = whichone(animals, words[1]) 168 | if not pet: 169 | feedback += "I didn't recognize that pet name. Please try again." 170 | else: 171 | pet.feed() 172 | else: 173 | feedback+= "I didn't understand that. Please try again." 174 | 175 | for pet in animals: 176 | pet.clock_tick() 177 | feedback += "\n" + pet.__str__() 178 | 179 | play() 180 | -------------------------------------------------------------------------------- /Chapter22. Inheritance/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter23. More on Accumulation: Map, Filter, List Comprehension, and Zip/course_3_assessment_2.py: -------------------------------------------------------------------------------- 1 | #Write code to assign to the variable map_testing all the elements in lst_check while adding the string “Fruit: ” to the beginning of each element using mapping. 2 | 3 | 4 | lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya'] 5 | 6 | map_testing = map(lambda word: "Fruit: " + word,lst_check) 7 | print(map_testing) 8 | 9 | #Below, we have provided a list of strings called countries. Use filter to produce a list called b_countries that only contains the strings from countries that begin with B. 10 | 11 | 12 | countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium'] 13 | 14 | b_countries = filter(lambda c : "B" in c,countries) 15 | 16 | #Below, we have provided a list of tuples that contain the names of Game of Thrones characters. Using list comprehension, create a list of strings called first_names that contains only the first names of everyone in the original list. 17 | 18 | 19 | people = [('Snow', 'Jon'), ('Lannister', 'Cersei'), ('Stark', 'Arya'), ('Stark', 'Robb'), ('Lannister', 'Jamie'), ('Targaryen', 'Daenerys'), ('Stark', 'Sansa'), ('Tyrell', 'Margaery'), ('Stark', 'Eddard'), ('Lannister', 'Tyrion'), ('Baratheon', 'Joffrey'), ('Bolton', 'Ramsey'), ('Baelish', 'Peter')] 20 | 21 | first_names = [name[1] for name in people] 22 | print(list(first_names)) 23 | 24 | #Use list comprehension to create a list called lst2 that doubles each element in the list, lst. 25 | 26 | 27 | lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4] 28 | 29 | lst2 = [word*2 for word in lst] 30 | 31 | #Below, we have provided a list of tuples that contain students’ names and their final grades in PYTHON 101. Using list comprehension, create a new list passed that contains the names of students who passed the class (had a final grade of 70 or greater). 32 | 33 | 34 | students = [('Tommy', 95), ('Linda', 63), ('Carl', 70), ('Bob', 100), ('Raymond', 50), ('Sue', 75)] 35 | 36 | passed = [key[0] for key in students if key[1] >= 70] 37 | print(list(passed)) 38 | 39 | #Write code using zip and filter so that these lists (l1 and l2) are combined into one big list and assigned to the variable opposites if they are both longer than 3 characters each. 40 | 41 | 42 | l1 = ['left', 'up', 'front'] 43 | l2 = ['right', 'down', 'back'] 44 | 45 | l3 = zip(l1, l2) 46 | opposites=list(filter(lambda s:len(s[0])>3 and len(s[1]) >3 ,l3)) 47 | 48 | #Below, we have provided a species list and a population list. Use zip to combine these lists into one list of tuples called pop_info. From this list, create a new list called endangered that contains the names of species whose populations are below 2500. 49 | 50 | 51 | species = ['golden retriever', 'white tailed deer', 'black rhino', 'brown squirrel', 'field mouse', 'orangutan', 'sumatran elephant', 'rainbow trout', 'black bear', 'blue whale', 'water moccasin', 'giant panda', 'green turtle', 'blue jay', 'japanese beetle'] 52 | 53 | population = [10000, 90000, 1000, 2000000, 500000, 500, 1200, 8000, 12000, 2300, 7500, 100, 1800, 9500, 125000] 54 | 55 | pop_info = zip(species,population) 56 | print(pop_info) 57 | 58 | endangered = [x[0] for x in pop_info if x[1]<2500 ] 59 | print(endangered) -------------------------------------------------------------------------------- /Chapter23. More on Accumulation: Map, Filter, List Comprehension, and Zip/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter23. More on Accumulation: Map, Filter, List Comprehension, and Zip/zip.py: -------------------------------------------------------------------------------- 1 | L1 = [3, 4, 5] 2 | L2 = [1, 2, 3] 3 | L3 = [] 4 | 5 | for i in range(len(L1)): 6 | L3.append(L1[i] + L2[i]) 7 | 8 | print(L3) 9 | 10 | ################################# 11 | 12 | L1 = [3, 4, 5] 13 | L2 = [1, 2, 3] 14 | L4 = list(zip(L1, L2)) 15 | print(L4) 16 | 17 | ########################## 18 | 19 | L1 = [3, 4, 5] 20 | L2 = [1, 2, 3] 21 | L3 = [] 22 | L4 = list(zip(L1, L2)) 23 | 24 | for (x1, x2) in L4: 25 | L3.append(x1+x2) 26 | 27 | print(L3) 28 | 29 | ##################################### 30 | 31 | L1 = [3, 4, 5] 32 | L2 = [1, 2, 3] 33 | L3 = [x1 + x2 for (x1, x2) in list(zip(L1, L2))] 34 | print(L3) 35 | 36 | ################################# 37 | 38 | L1 = [3, 4, 5] 39 | L2 = [1, 2, 3] 40 | L3 = map(lambda x: x[0] + x[1], zip(L1, L2)) 41 | print(L3) 42 | 43 | ############################ 44 | 45 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/Apple_com.py: -------------------------------------------------------------------------------- 1 | import requests_with_caching 2 | import json 3 | 4 | parameters = {"term": "Ann Arbor", "entity": "podcast"} 5 | iTunes_response = requests_with_caching.get("https://itunes.apple.com/search", params = parameters,permanent_cache_file="itunes_cache.txt") 6 | 7 | py_data = json.loads(iTunes_response.text) 8 | 9 | 10 | ################################ 11 | 12 | import requests_with_caching 13 | import json 14 | 15 | parameters = {"term": "Ann Arbor", "entity": "podcast"} 16 | iTunes_response = requests_with_caching.get("https://itunes.apple.com/search", params = parameters, permanent_cache_file="itunes_cache.txt") 17 | 18 | py_data = json.loads(iTunes_response.text) 19 | for r in py_data['results']: 20 | print(r['trackName']) 21 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/Fetching_a_page.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | page = requests.get("https://api.datamuse.com/words?rel_rhy=funny") 5 | print(type(page)) 6 | print(page.text[:150]) # print the first 150 characters 7 | print(page.url) # print the url that was fetched 8 | print("------") 9 | x = page.json() # turn page.text into a python object 10 | print(type(x)) 11 | print("---first item in the list---") 12 | print(x[0]) 13 | print("---the whole list, pretty printed---") 14 | print(json.dumps(x, indent=2)) # pretty print the results 15 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/RestAPI_intro.py: -------------------------------------------------------------------------------- 1 | # import statements for necessary Python modules 2 | import requests 3 | 4 | def get_rhymes(word): 5 | baseurl = "https://api.datamuse.com/words" 6 | params_diction = {} # Set up an empty dictionary for query parameters 7 | params_diction["rel_rhy"] = word 8 | params_diction["max"] = "3" # get at most 3 results 9 | resp = requests.get(baseurl, params=params_diction) 10 | # return the top three words 11 | word_ds = resp.json() 12 | return [d['word'] for d in word_ds] 13 | #return resp.json() # Return a python object (a list of dictionaries in this case) 14 | 15 | print(get_rhymes("funny")) 16 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/flicker.py: -------------------------------------------------------------------------------- 1 | # import statements 2 | import requests_with_caching 3 | import json 4 | # import webbrowser 5 | 6 | # apply for a flickr authentication key at http://www.flickr.com/services/apps/create/apply/? 7 | # paste the key (not the secret) as the value of the variable flickr_key 8 | flickr_key = 'yourkeyhere' 9 | 10 | def get_flickr_data(tags_string): 11 | baseurl = "https://api.flickr.com/services/rest/" 12 | params_diction = {} 13 | params_diction["api_key"] = flickr_key # from the above global variable 14 | params_diction["tags"] = tags_string # must be a comma separated string to work correctly 15 | params_diction["tag_mode"] = "all" 16 | params_diction["method"] = "flickr.photos.search" 17 | params_diction["per_page"] = 5 18 | params_diction["media"] = "photos" 19 | params_diction["format"] = "json" 20 | params_diction["nojsoncallback"] = 1 21 | flickr_resp = requests_with_caching.get(baseurl, params = params_diction, permanent_cache_file="flickr_cache.txt") 22 | # Useful for debugging: print the url! Uncomment the below line to do so. 23 | print(flickr_resp.url) # Paste the result into the browser to check it out... 24 | return flickr_resp.json() 25 | 26 | result_river_mts = get_flickr_data("river,mountains") 27 | 28 | # Some code to open up a few photos that are tagged with the mountains and river tags... 29 | 30 | photos = result_river_mts['photos']['photo'] 31 | for photo in photos: 32 | owner = photo['owner'] 33 | photo_id = photo['id'] 34 | url = 'https://www.flickr.com/photos/{}/{}'.format(owner, photo_id) 35 | print(url) 36 | # webbrowser.open(url) 37 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter24. Internet APIs/read&write_file.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | PERMANENT_CACHE_FNAME = "permanent_cache.txt" 5 | TEMP_CACHE_FNAME = "this_page_cache.txt" 6 | 7 | def _write_to_file(cache, fname): 8 | with open(fname, 'w') as outfile: 9 | outfile.write(json.dumps(cache, indent=2)) 10 | 11 | def _read_from_file(fname): 12 | try: 13 | with open(fname, 'r') as infile: 14 | res = infile.read() 15 | return json.loads(res) 16 | except: 17 | return {} 18 | 19 | def add_to_cache(cache_file, cache_key, cache_value): 20 | temp_cache = _read_from_file(cache_file) 21 | temp_cache[cache_key] = cache_value 22 | _write_to_file(temp_cache, cache_file) 23 | 24 | def clear_cache(cache_file=TEMP_CACHE_FNAME): 25 | _write_to_file({}, cache_file) 26 | 27 | def make_cache_key(baseurl, params_d, private_keys=["api_key"]): 28 | """Makes a long string representing the query. 29 | Alphabetize the keys from the params dictionary so we get the same order each time. 30 | Omit keys with private info.""" 31 | alphabetized_keys = sorted(params_d.keys()) 32 | res = [] 33 | for k in alphabetized_keys: 34 | if k not in private_keys: 35 | res.append("{}-{}".format(k, params_d[k])) 36 | return baseurl + "_".join(res) 37 | 38 | def get(baseurl, params={}, private_keys_to_ignore=["api_key"], permanent_cache_file=PERMANENT_CACHE_FNAME, temp_cache_file=TEMP_CACHE_FNAME): 39 | full_url = requests.requestURL(baseurl, params) 40 | cache_key = make_cache_key(baseurl, params, private_keys_to_ignore) 41 | # Load the permanent and page-specific caches from files 42 | permanent_cache = _read_from_file(permanent_cache_file) 43 | temp_cache = _read_from_file(temp_cache_file) 44 | if cache_key in temp_cache: 45 | print("found in temp_cache") 46 | # make a Response object containing text from the change, and the full_url that would have been fetched 47 | return requests.Response(temp_cache[cache_key], full_url) 48 | elif cache_key in permanent_cache: 49 | print("found in permanent_cache") 50 | # make a Response object containing text from the change, and the full_url that would have been fetched 51 | return requests.Response(permanent_cache[cache_key], full_url) 52 | else: 53 | print("new; adding to cache") 54 | # actually request it 55 | resp = requests.get(baseurl, params) 56 | # save it 57 | add_to_cache(temp_cache_file, cache_key, resp.text) 58 | return resp -------------------------------------------------------------------------------- /Chapter24. Internet APIs/requests_with_caching.py: -------------------------------------------------------------------------------- 1 | import requests_with_caching 2 | # it's not found in the permanent cache 3 | res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=happy", permanent_cache_file="datamuse_cache.txt") 4 | print(res.text[:100]) 5 | # this time it will be found in the temporary cache 6 | res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=happy", permanent_cache_file="datamuse_cache.txt") 7 | # This one is in the permanent cache. 8 | res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=funny", permanent_cache_file="datamuse_cache.txt") 9 | -------------------------------------------------------------------------------- /Chapter3. Debugging/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter4. Python Modules/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter4. Python Modules/randommodule.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | prob = random.random() 4 | print(prob) 5 | 6 | diceThrow = random.randrange(1,7) 7 | print(diceThrow) -------------------------------------------------------------------------------- /Chapter4. Python Modules/randon.py: -------------------------------------------------------------------------------- 1 | from random import random, randrange 2 | 3 | prob = random() 4 | print(prob) 5 | 6 | diceThrow = randrange(1,7) 7 | print(diceThrow) -------------------------------------------------------------------------------- /Chapter5. Python Turtle/2stars.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | triangle = turtle.Turtle() 4 | square = turtle.Turtle() 5 | hexagon = turtle.Turtle() 6 | octagon = turtle.Turtle() 7 | line = turtle.Turtle() 8 | star = turtle.Turtle() 9 | d = 50 10 | 11 | for i in range(3): 12 | triangle.forward(d) 13 | triangle.left(120) 14 | for i in range(4): 15 | square.forward(d) 16 | square.left(90) 17 | for i in range(6): 18 | hexagon.forward(d) 19 | hexagon.left(60) 20 | for i in range(8): 21 | octagon.forward(d) 22 | octagon.left(45) 23 | for i in range(5): 24 | star.backward(100) 25 | star.left(145) 26 | 27 | line.forward(d) 28 | line.left(180) 29 | line.backward(100) 30 | line.right(322.5) 31 | line.forward(100) 32 | line.right(145) 33 | line.forward(100) 34 | line.right(145) 35 | line.forward(100) 36 | line.right(145) 37 | line.forward(100) 38 | line.right(145) 39 | 40 | 41 | 42 | 43 | wn.exitonclick() 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Chapter5. Python Turtle/crossarrow.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | wn = turtle.Screen() 4 | wn.bgcolor("lightgreen") 5 | 6 | tess = turtle.Turtle() 7 | tess.color("blue") 8 | tess.pensize(3) 9 | 10 | tess.forward(50) 11 | tess.left(120) 12 | tess.forward(50) 13 | 14 | wn.exitonclick() -------------------------------------------------------------------------------- /Chapter5. Python Turtle/forloop.py: -------------------------------------------------------------------------------- 1 | print("This will execute first") 2 | 3 | for i in range(3): 4 | print("it will print three times") 5 | print("it will also print 3 time") 6 | print("Because of for loop") 7 | 8 | print("Now we r out of for loop... it wont print 3 times") -------------------------------------------------------------------------------- /Chapter5. Python Turtle/loop&turtle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | turtle.Screen() 4 | mujju = turtle.Turtle() 5 | 6 | distance = 50 7 | for i in range(20): 8 | mujju.forward(distance) 9 | mujju.right(90) 10 | distance = distance + 10 -------------------------------------------------------------------------------- /Chapter5. Python Turtle/proj.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | color('red', 'yellow') 3 | begin_fill() 4 | while True: 5 | forward(200) 6 | left(170) 7 | if abs(pos()) < 1: 8 | break 9 | end_fill() 10 | done() -------------------------------------------------------------------------------- /Chapter5. Python Turtle/sq_tr_hex_oct.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | triangle = turtle.Turtle() 4 | square = turtle.Turtle() 5 | hexagon = turtle.Turtle() 6 | octagon = turtle.Turtle() 7 | d = 50 8 | 9 | for i in range(3): 10 | triangle.forward(d) 11 | triangle.left(120) 12 | for i in range(4): 13 | square.forward(d) 14 | square.left(90) 15 | for i in range(6): 16 | hexagon.forward(d) 17 | hexagon.left(60) 18 | for i in range(8): 19 | octagon.forward(d) 20 | octagon.left(45) 21 | wn.exitonclick() -------------------------------------------------------------------------------- /Chapter5. Python Turtle/star.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | star = turtle.Turtle() 4 | d = 50 5 | for i in range(5): 6 | star.forward(d) 7 | star.right(145) -------------------------------------------------------------------------------- /Chapter5. Python Turtle/turtle-shape.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | wn.bgcolour("ligthgreen") 4 | mujju = turtle.Turtle() 5 | mujju.color("red") 6 | mujju.shape("turtle") 7 | 8 | d = 5 9 | mujju.up() 10 | for i in range(30): 11 | mujju.stamp() 12 | mujju.forward(d) 13 | mujju.right(24) 14 | d = d + 2 15 | 16 | wn.exitonclick() 17 | 18 | -------------------------------------------------------------------------------- /Chapter5. Python Turtle/turtle.py: -------------------------------------------------------------------------------- 1 | import turtle # allows us to use the turtles library 2 | wn = turtle.Screen() # creates a graphics window 3 | alex = turtle.Turtle() # create a turtle named alex 4 | alex.forward(150) # tell alex to move forward by 150 units 5 | alex.left(90) # turn by 90 degrees 6 | alex.forward(75) # complete the second side of a rectangle 7 | alex.left(90) # turn by 90 degrees 8 | alex.forward(75) 9 | alex.left(90) # turn by 90 degrees 10 | alex.forward(75) 11 | alex.left(90) # turn by 90 degrees 12 | alex.forward(75) -------------------------------------------------------------------------------- /Chapter5. Python Turtle/turtle.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mujju-palaan/Python3Programming--Coursera/f07ba2081d5eccad31a1b2cee615798166dcd97f/Chapter5. Python Turtle/turtle.pyc -------------------------------------------------------------------------------- /Chapter5. Python Turtle/turtle_forwar_back.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | mujju = turtle.Turtle() 4 | mujju.shape("turtle") 5 | mujju.speed(100) 6 | 7 | d = 100 8 | a = 0 9 | mujju.up() 10 | 11 | 12 | for i in range(12): 13 | 14 | mujju.forward(d) 15 | mujju.stamp() 16 | mujju.backward(d) 17 | mujju.right(a + 30 ) 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter6. Sequences/1.py: -------------------------------------------------------------------------------- 1 | s = '5' 2 | i = 5 3 | 4 | print(s) 5 | print(i) 6 | 7 | print(int(s)) 8 | print(i) 9 | 10 | print(int(s)+10) 11 | print(i+10) -------------------------------------------------------------------------------- /Chapter6. Sequences/count.py: -------------------------------------------------------------------------------- 1 | a = "I had an apple on my desk before" 2 | 3 | print(a.count("e")) 4 | print(a.count("a")) 5 | 6 | z = ['atoms', 4, 'neutron', 6, 'proton', 4, 'electron', 4, 'electron', 'atoms'] 7 | print(z.count("4")) 8 | print(z.count(4)) 9 | print(z.count("a")) 10 | print(z.count("electron")) 11 | -------------------------------------------------------------------------------- /Chapter6. Sequences/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter6. Sequences/index.py: -------------------------------------------------------------------------------- 1 | music = "Pull out your music and dancing can begin" 2 | bio = ["Metatarsal", "Metatarsal", "Fibula", [], "Tibia", "Tibia", 43, "Femur", "Occipital", "Metatarsal"] 3 | 4 | print(music.index("m")) 5 | print(music.index("your")) 6 | 7 | print(bio.index("Metatarsal")) 8 | print(bio.index([])) 9 | print(bio.index(43)) 10 | -------------------------------------------------------------------------------- /Chapter6. Sequences/listslices.py: -------------------------------------------------------------------------------- 1 | singers = "Peter, Paul, and Mary" 2 | print(singers[0:5]) 3 | print(singers[7:11]) 4 | print(singers[17:21]) 5 | 6 | fruit = "banana" 7 | print(fruit[:3]) 8 | print(fruit[3:]) 9 | 10 | a_list = ['a', 'b', 'c', 'd', 'e', 'f'] 11 | print(a_list[1:3]) 12 | print(a_list[:4]) 13 | print(a_list[3:]) 14 | print(a_list[:]) 15 | 16 | julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia") 17 | print(julia[2]) 18 | print(julia[2:6]) 19 | 20 | print(len(julia)) 21 | 22 | julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:] 23 | print(julia) 24 | -------------------------------------------------------------------------------- /Chapter6. Sequences/split.py: -------------------------------------------------------------------------------- 1 | mujju = "Salman is a chaman" 2 | noob = mujju.split('a') 3 | print(noob) -------------------------------------------------------------------------------- /Chapter6. Sequences/str&list&tuples.py: -------------------------------------------------------------------------------- 1 | list = ['one',2,'three'] 2 | tuple = ('one',2,'three') 3 | 4 | print(type(l)) 5 | print(type(t)) 6 | 7 | list = [100] 8 | tuple = (100,) 9 | 10 | print(type(l)) 11 | print(type(t)) -------------------------------------------------------------------------------- /Chapter6. Sequences/str&lists.py: -------------------------------------------------------------------------------- 1 | s = "Hello World" 2 | n = """ 3 | Hey 4 | my 5 | name 6 | is 7 | Mujju 8 | """ 9 | print(n) 10 | print(s) 11 | 12 | s = '5hundred' 13 | mylist= ["one",2,"three"] 14 | print (mylist) -------------------------------------------------------------------------------- /Chapter6. Sequences/str.py: -------------------------------------------------------------------------------- 1 | s= "Python" 2 | mylist = ['one',2,'three'] 3 | 4 | print(s[0]) 5 | print(s[len(s)-1]) #to print the last char in python 6 | 7 | print(mylist[0]) 8 | print(len(s)) 9 | print(len(mylist)) 10 | 11 | numbers = [17, 123, 87, 34, 66, 8398, 44] 12 | print(numbers[2]) 13 | print(numbers[9-8]) 14 | print(numbers[-2]) 15 | 16 | prices = (1.99, 2.00, 5.50, 20.95, 100.98) 17 | print(prices[0]) 18 | print(prices[-1]) 19 | print(prices[3-5]) 20 | -------------------------------------------------------------------------------- /Chapter7. Iteration/RGB.py: -------------------------------------------------------------------------------- 1 | import image 2 | 3 | p = image.Pixel(45, 76, 200) 4 | print(p.getRed()) 5 | 6 | 7 | import image 8 | img = image.Image("luther.jpg") 9 | 10 | print(img.getWidth()) 11 | print(img.getHeight()) 12 | 13 | p = img.getPixel(100, 30) 14 | print(p.getRed(), p.getGreen(), p.getBlue()) 15 | -------------------------------------------------------------------------------- /Chapter7. Iteration/accumulator.py: -------------------------------------------------------------------------------- 1 | nums = [1,2,3,4,5,6,7,8,9,10] 2 | accum = 0 3 | for w in nums: 4 | accum = accum + w 5 | print(accum) 6 | 7 | nums = [1,2,3,4,5,6,7,8,9,10] 8 | accum = 0 9 | for num in nums: 10 | accum = accum + 1 11 | print(accum) 12 | 13 | nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 14 | for w in nums: 15 | accum = 0 16 | accum = accum + w 17 | print(accum) 18 | 19 | print(5 // 3) 20 | n = input("Please enter your age: ") 21 | 22 | print(type(n)) -------------------------------------------------------------------------------- /Chapter7. Iteration/assg.py: -------------------------------------------------------------------------------- 1 | week_temps_f = "75.1,77.7,83.2,82.5,81.0,79.5,85.7" 2 | temp = week_temps_f.split(",") 3 | # for i in temp: 4 | # return i + i 5 | #avg_temp = float(sum(temp))/len(temp) 6 | print(temp) 7 | 8 | original_str = "The quick brown rhino jumped over the extremely lazy fox" 9 | original_list = original_str.split() 10 | print(original_list) 11 | num_words = len(original_list) 12 | num_words_list = [] 13 | for i in original_list: 14 | num_words_list.append((len(i))) 15 | print(num_words_list) 16 | 17 | 18 | lett = "" 19 | 20 | for i in range(7): 21 | i = "b" 22 | lett += i 23 | print(lett) 24 | 25 | import turtle 26 | 27 | wn = turtle.Screen() 28 | lovelace = turtle.Turtle() 29 | 30 | # move the turtle forward a little so that the whole path fits on the screen 31 | lovelace.penup() 32 | lovelace.forward(60) 33 | 34 | # now draw the drunk pirate's path 35 | lovelace.pendown() 36 | current_heading = 0 37 | for angle in [160, -43, 270, -97, -43, 200, -940, 17, -86]: 38 | 39 | # we use .left() so that positive angles are counter-clockwise 40 | # and negative angles are clockwise 41 | current_heading = (current_heading + angle) % 360 42 | lovelace.left(angle) 43 | lovelace.forward(100) 44 | 45 | # the .heading() method gives us the turtle's current heading in degrees 46 | print("The pirate's final heading was", current_heading) 47 | 48 | wn.exitonclick() 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter7. Iteration/forloop_byindex.py: -------------------------------------------------------------------------------- 1 | fruit = ['apple', 'pear', 'apricot', 'cherry', 'peach'] 2 | for n in range(len(fruit)): 3 | print(n, fruit[n]) 4 | -------------------------------------------------------------------------------- /Chapter7. Iteration/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter7. Iteration/loop.py: -------------------------------------------------------------------------------- 1 | # mylist = ["yo","mujju","salman","thuss"] 2 | # for i in mylist: 3 | # print("Hi", i ,"Dawat hai kheenchny aao") 4 | 5 | # mylist = "dgsadafdua" 6 | # for char in mylist: 7 | # print("Hi", char ) 8 | 9 | s = "python rocks" 10 | for ch in s: 11 | print("HELLO") 12 | 13 | import turtle # set up alex 14 | wn = turtle.Screen() 15 | mujju = turtle.Turtle() 16 | 17 | for aColor in ["yellow", "red", "purple", "blue"]: 18 | alex.color(aColor) # repeat four times 19 | mujju.forward(50) 20 | mujju.left(90) 21 | 22 | wn.exitonclick() 23 | -------------------------------------------------------------------------------- /Chapter7. Iteration/reverse_str.py: -------------------------------------------------------------------------------- 1 | user = "Salman thuss hai" 2 | user = user.lower() 3 | print( user[::-1]) 4 | -------------------------------------------------------------------------------- /Chapter8. Conditionals/ass.py: -------------------------------------------------------------------------------- 1 | # rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0. 2 | 3 | # Hard-coded answers will receive no credit. 4 | 5 | 6 | rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85" 7 | num_rainy_months = [] 8 | mylist = rainfall_mi.split(",") 9 | num_rainy_months = 0 10 | print(mylist) 11 | 12 | for num in mylist: 13 | if float(num) > 3.0 : 14 | 15 | num_rainy_months += 1 16 | print(num_rainy_months) 17 | 18 | #################################################### 19 | # The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter, including one-letter words. Store the result in the variable same_letter_count. 20 | 21 | # Hard-coded answers will receive no credit. 22 | 23 | 24 | sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking" 25 | words = sentence.split() 26 | same_letter_count = 0 27 | for word in words: 28 | 29 | if word[0] == word[-1]: 30 | 31 | same_letter_count += 1 32 | 33 | print(same_letter_count) -------------------------------------------------------------------------------- /Chapter8. Conditionals/danger.py: -------------------------------------------------------------------------------- 1 | #Challenge For each word in words, add ‘d’ to the end of the word if the word ends in “e” to make it past tense. Otherwise, add ‘ed’ to make it past tense. Save these past tense words to a list called past_tense. 2 | 3 | 4 | 5 | words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"] 6 | past_tense = [] 7 | 8 | for word in words: 9 | if word[-1] == 'e': 10 | 11 | past_tense.append(word + "d") 12 | else : 13 | 14 | past_tense.append(word + "ed") 15 | 16 | print(past_tense) 17 | 18 | ################################## 19 | # Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable acc_num. 20 | 21 | # HINT 1: Use the accumulation pattern! 22 | 23 | # HINT 2: the in operator checks whether a substring is present in a string. 24 | 25 | # Hard-coded answers will receive no credit. 26 | 27 | items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] 28 | acc_num = 0 29 | for i in items: 30 | 31 | if "w" in i[0:]: 32 | 33 | acc_num += 1 34 | 35 | print(acc_num) 36 | 37 | 38 | ##################################### 39 | # Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable num_a_or_e. 40 | 41 | # Note 1: be sure to not double-count words that contain both an a and an e. 42 | 43 | # HINT 1: Use the in operator. 44 | 45 | # HINT 2: You can either use or or elif. 46 | 47 | # Hard-coded answers will receive no credit. 48 | 49 | sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems." 50 | words = sentence.split() 51 | num_a_or_e = 0 52 | for word in words: 53 | 54 | if "a" in word[0:]: 55 | print("mujju") 56 | num_a_or_e += 1 57 | elif "e" in word[0:]: 58 | print("mujju") 59 | num_a_or_e += 1 60 | 61 | 62 | print(num_a_or_e) 63 | 64 | 65 | ########################## 66 | s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" 67 | vowels = ['a','e','i','o','u'] 68 | num_vowels = [] 69 | words = s.split() 70 | print(words) 71 | num_vowels = 0 72 | 73 | for vowels in words: 74 | print(words.count(vowels)) 75 | num_vowels += 1 76 | 77 | print(num_vowels) 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /Chapter8. Conditionals/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter8. Conditionals/in_notin.py: -------------------------------------------------------------------------------- 1 | print('p' in 'apple') 2 | print('i' in 'apple') 3 | print('ap' in 'apple') 4 | print('pa' in 'apple') 5 | print('x' not in 'apple') 6 | -------------------------------------------------------------------------------- /Chapter8. Conditionals/kirakassignment.py: -------------------------------------------------------------------------------- 1 | percent_rain = [94.3, 45, 100, 78, 16, 5.3, 79, 86] 2 | resps = [] 3 | for i in percent_rain: 4 | if i > 90: 5 | resps.append('Bring an umbrella.') 6 | elif i > 80: 7 | resps.append('Good for the flowers?') 8 | elif i > 50: 9 | resps.append('Watch out for clouds!') 10 | else: 11 | resps.append('Nice day!') 12 | 13 | print(resps) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter8. Conditionals/rough.py: -------------------------------------------------------------------------------- 1 | y = 18 2 | for z in y: 3 | print(z) -------------------------------------------------------------------------------- /Chapter8. Conditionals/turtleexample.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | wn = turtle.Screen() 3 | mujju = turtle.Turtle() 4 | 5 | mujju.pencolor("blue") 6 | mujju.forward(50) 7 | if mujju.pencolor() == "blue": 8 | mujju.right(60) 9 | mujju.forward(100) 10 | else: 11 | mujju.left(60) 12 | mujju.forward(100) 13 | 14 | thuss = turtle.Turtle() 15 | thuss.forward(60) 16 | if thuss.pencolor() == "blue": 17 | thuss.right(60) 18 | thuss.forward(100) 19 | else: 20 | thuss.left(60) 21 | thuss.forward(100) 22 | 23 | ######################################################## 24 | 25 | import turtle 26 | wn = turtle.Screen() 27 | 28 | amy = turtle.Turtle() 29 | amy.pencolor("Pink") 30 | amy.right(170) 31 | 32 | colors = ["Purple", "Yellow", "Orange", "Pink", "Orange", "Yellow", "Purple", "Orange", "Pink", "Pink", "Orange", "Yellow", "Purple", "Orange", "Purple", "Yellow", "Orange", "Pink", "Orange", "Purple", "Purple", "Yellow", "Orange", "Pink", "Orange", "Yellow", "Purple", "Yellow"] 33 | 34 | 35 | for color in colors: 36 | if amy.pencolor() == "Purple": 37 | amy.forward(50) 38 | amy.right(59) 39 | elif amy.pencolor() == "Yellow": 40 | amy.forward(65) 41 | amy.left(98) 42 | elif amy.pencolor() == "Orange": 43 | amy.forward(30) 44 | amy.left(60) 45 | elif amy.pencolor() == "Pink": 46 | amy.forward(50) 47 | amy.right(57) 48 | 49 | amy.pencolor(color) 50 | -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/__pycache__/imp.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mujju-palaan/Python3Programming--Coursera/f07ba2081d5eccad31a1b2cee615798166dcd97f/Chapter9. Transforming Sequences/__pycache__/imp.cpython-37.pyc -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/imp.py: -------------------------------------------------------------------------------- 1 | # ss = " Hello, World " 2 | 3 | # els = ss.count("l") 4 | # print(els) 5 | # print(ss.strip()) 6 | # print("***"+ss.strip()+"***") 7 | 8 | # news = ss.replace("o", "***") 9 | # print(news) 10 | 11 | ####333333333333333333333### 12 | 13 | s = "python rocks" 14 | print(s[1]*s.index("n")) -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/is.py: -------------------------------------------------------------------------------- 1 | a = "banana" 2 | b = "banana" 3 | 4 | print(a is b) -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/mutability.py: -------------------------------------------------------------------------------- 1 | # for list 2 | mylist = ["apple","mangoes","grapes"] 3 | print(mylist) 4 | mylist[0] = "yoo" 5 | mylist[-1] = "is love" 6 | print(mylist) 7 | 8 | #for string 9 | yoo = "Hello, World!" 10 | print(yoo) 11 | yoyo = 'J' + yoo[1:] 12 | print(yoyo) 13 | ############################# 14 | alist = ['a', 'b', 'c', 'd', 'e', 'f'] 15 | alist[1:3] = [] 16 | print(alist) 17 | ############################ 18 | alist = ['a', 'd', 'f'] 19 | alist[1:1] = ['b', 'c'] 20 | print(alist) 21 | alist[4:4] = ['e'] 22 | print(alist) 23 | 24 | -------------------------------------------------------------------------------- /Chapter9. Transforming Sequences/rough.py: -------------------------------------------------------------------------------- 1 | b = ['q', 'u', 'i'] 2 | z = b 3 | b[1] = 'i' 4 | print(b) 5 | z.remove('i') 6 | print(z) 7 | ############################# 8 | v = 2.34567 9 | print('{:.1f} {:.2f} {:.7f}'.format(v, v, v)) 10 | ################### 11 | alist = [4,2,8,6,5] 12 | blist = [ ] 13 | for item in alist: 14 | blist.append(item+5) 15 | print(blist) 16 | ################# 17 | list= [3,0,9,4,1,7] 18 | new_list=[] 19 | for i in range(len(list)): 20 | new_list.append(list[i]+5) 21 | print(new_list) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coursera-Course-Python 2 | -------------------------------------------------------------------------------- /course_1_assessment_10.py: -------------------------------------------------------------------------------- 1 | # 2 | phrase 3 | 4 | #Currently there is a string called str1. Write code to create a list called chars which should contain the characters from str1. Each character in str1 should be its own element in the list chars. 5 | str1 = "I love python" 6 | chars = [] 7 | for char in str1: 8 | print(char) 9 | chars.append(char) 10 | print(chars) 11 | 12 | 13 | -------------------------------------------------------------------------------- /course_1_assessment_11.py: -------------------------------------------------------------------------------- 1 | #For each character in the string saved in ael, append that character to a list that should be saved in a variable app. 2 | ael = "python!" 3 | app = [] 4 | for i in ael: 5 | app.append(i) 6 | 7 | #For each string in wrds, add ‘ed’ to the end of the word (to make the word past tense). Save these past tense words to a list called past_wrds. 8 | wrds = ["end", 'work', "play", "start", "walk", "look", "open", "rain", "learn", "clean"] 9 | past_wrds = [] 10 | for i in wrds: 11 | i = i + "ed" 12 | past_wrds.append(i) 13 | 14 | 15 | # -------------------------------------------------------------------------------- /course_1_assessment_12.py: -------------------------------------------------------------------------------- 1 | #Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 or above and assign that result to the value a_scores. 2 | scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" 3 | a_scores = 0 4 | a = scores.split() 5 | print(a) 6 | 7 | for i in a: 8 | yo = int(i) 9 | 10 | if yo > 89: 11 | a_scores = a_scores + 1 12 | print(a_scores) 13 | 14 | 15 | 16 | #Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro. Only the first letter of each word should be used, each letter in the acronym should be a capital letter, and there should be nothing to separate the letters of the acronym. Words that should not be included in the acronym are stored in the list stopwords. For example, if org was assigned the string “hello to world” then the resulting acronym should be “HW”. 17 | stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', "The"] 18 | org = "The organization for health, safety, and education" 19 | yoo = org.split() 20 | acro = "" 21 | stopwords= [] 22 | for i in yoo: 23 | if i[0] in ["o","h","s","e"]: 24 | 25 | acro = acro + i[0].upper() 26 | print(acro) 27 | 28 | #Write code that uses the string stored in sent and creates an acronym which is assigned to the variable acro. The first two letters of each word should be used, each letter in the acronym should be a capital letter, and each element of the acronym should be separated by a “. ” (dot and space). Words that should not be included in the acronym are stored in the list stopwords. For example, if sent was assigned the string “height and ewok wonder” then the resulting acronym should be “HE. EW. WO”. 29 | stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The'] 30 | sent = "The water earth and air are vital" 31 | yoo = sent.split() 32 | lol = "" 33 | acro = "" 34 | homie = "" 35 | stopwords = [] 36 | for i in yoo: 37 | if i in ["water","earth","air","are"]: 38 | 39 | homie = homie + i[:2].upper() + ". " 40 | 41 | 42 | acro = homie + "VI" 43 | print(acro) 44 | 45 | #A palindrome is a phrase that, if reversed, would read the exact same. Write code that checks if p_phrase is a palindrome by reversing it and then checking if the reversed version is equal to the original. Assign the reversed version of p_phrase to the variable r_phrase so that we can check your work. 46 | p_phrase = "was it a car or a cat I saw" 47 | r_phrase = p_phrase[::-1] 48 | 49 | print(r_phrase) 50 | 51 | #Provided is a list of data about a store’s inventory where each item in the list represents the name of an item, how much is in stock, and how much it costs. Print out each item in the list with the same formatting, using the .format method (not string concatenation). For example, the first print statment should read The store has 12 shoes, each for 29.99 USD. 52 | inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweaters, 10, 30.00", "sweatpants, 25, 15.00", "scarves, 13, 7.75"] 53 | for i in inventory: 54 | yoo = i.split(',') 55 | name = yoo[0] 56 | item = yoo[1] 57 | price = yoo[2] 58 | 59 | print("The store has{} {}, each for{} USD.".format(item, name, price)) 60 | -------------------------------------------------------------------------------- /course_1_assessment_2.py: -------------------------------------------------------------------------------- 1 | #There is a function we are providing in for you in this problem called square. It takes one integer and returns the square of that integer value. Write code to assign a variable called xyz the value 5*5 (five squared). Use the square function, rather than just multiplying with *. 2 | xyz = 25 3 | 4 | squared = square(xyz) 5 | print(squared) 6 | 7 | #Write code to assign the number of characters in the string rv to a variable num_chars. 8 | rv = """Once upon a midnight dreary, while I pondered, weak and weary, 9 | Over many a quaint and curious volume of forgotten lore, 10 | While I nodded, nearly napping, suddenly there came a tapping, 11 | As of some one gently rapping, rapping at my chamber door. 12 | 'Tis some visitor, I muttered, tapping at my chamber door; 13 | Only this and nothing more.""" 14 | 15 | num_chars = 0 16 | for i in rv: 17 | num_chars = num_chars + 1 18 | 19 | 20 | 21 | #(This is not an assessment question) The code below defines functions used by one of the questions above. Do not modify the code, but feel free to take a look. 22 | 23 | def square(num): 24 | return num**2 25 | -------------------------------------------------------------------------------- /course_1_assessment_5.py: -------------------------------------------------------------------------------- 1 | #Write a program that extracts the last three items in the list sports and assigns it to the variable last. Make sure to write your code so that it works no matter how many items are in the list. 2 | sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] 3 | 4 | last = sports[-3:] 5 | # 6 | 7 | #Write code that combines the following variables so that the sentence “You are doing a great job, keep it up!” is assigned to the variable message. Do not edit the values assigned to by, az, io, or qy. 8 | by = "You are" 9 | az = "doing a great " 10 | io = "job" 11 | qy = "keep it up!" 12 | 13 | message = by, az, io, qy 14 | 15 | 16 | # -------------------------------------------------------------------------------- /course_1_assessment_6.py: -------------------------------------------------------------------------------- 1 | #Write one for loop to print out each character of the string my_str on a separate line. 2 | my_str = "MICHIGAN" 3 | for i in my_str: 4 | print(i) 5 | 6 | #Write one for loop to print out each element of the list several_things. Then, write another for loop to print out the TYPE of each element of the list several_things. To complete this problem you should have written two different for loops, each of which iterates over the list several_things, but each of those 2 for loops should have a different result. 7 | several_things = ["hello", 2, 4, 6.0, 7.5, 234352354, "the end", "", 99] 8 | for i in several_things: 9 | print(i) 10 | for i in several_things: 11 | print(type(i)) 12 | 13 | #Write code that uses iteration to print out the length of each element of the list stored in str_list. 14 | str_list = ["hello", "", "goodbye", "wonderful", "I love Python"] 15 | for i in str_list: 16 | print(len(i)) 17 | 18 | #Write code to count the number of characters in original_str using the accumulation pattern and assign the answer to a variable num_chars. Do NOT use the len function to solve the problem (if you use it while you are working on this problem, comment it out afterward!) 19 | mylist = [] 20 | 21 | for i in range(41): 22 | 23 | mylist.append(i) 24 | print(mylist) 25 | print(len(mylist)) 26 | 27 | #addition_str is a string with a list of numbers separated by the + sign. Write code that uses the accumulation pattern to take the sum of all of the numbers and assigns it to sum_val (an integer). (You should use the .split("+") function to split by "+" and int() to cast to an integer). 28 | addition_str = "2+5+10+20" 29 | sum_val = addition_str.split("+") 30 | 31 | print(sum(sum_val)) 32 | 33 | #week_temps_f is a string with a list of fahrenheit temperatures separated by the , sign. Write code that uses the accumulation pattern to compute the average (sum divided by number of items) and assigns it to avg_temp. Do not hard code your answer (i.e., make your code compute both the sum or the number of items in week_temps_f) (You should use the .split(",") function to split by "," and float() to cast to a float). 34 | week_temps_f = "75.1,77.7,83.2,82.5,81.0,79.5,85.7" 35 | temp = week_temps_f.split(",") 36 | print(temp) 37 | total = 0 38 | for ele in range(0, len(temp)): 39 | total = total + temp[ele] 40 | print(total) 41 | avg_temp = float(total)/len(temp) 42 | print(temp) 43 | 44 | #Write code to create a list of numbers from 0 to 67 and assign that list to the variable nums. Do not hard code the list. 45 | nums = range(68) 46 | print(nums) 47 | # 48 | 49 | #Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the answer to a variable num_words_list. (You should use the len function). 50 | original_str = "The quick brown rhino jumped over the extremely lazy fox." 51 | num_words_list = [] 52 | p = original_str.split() 53 | for i in p: 54 | yo = len(i) 55 | num_words_list.append(yo) 56 | print(num_words_list) 57 | 58 | #Create an empty string and assign it to the variable lett. Then using range, write code such that when your code is run, lett has 7 b’s ("bbbbbbb"). 59 | lett = "" 60 | 61 | for i in range(7): 62 | 63 | lett = lett + "b" 64 | 65 | 66 | #Write a program that uses the turtle module and a for loop to draw something. It doesn’t have to be complicated, but draw something different than we have done in the past. (Hint: if you are drawing something complicated, it could get tedious to watch it draw over and over. Try setting .speed(10) for the turtle to draw fast, or .speed(0) for it to draw super fast with no animation.) 67 | import turtle 68 | wn = turtle.Screen() 69 | mujju = turtle.Turtle() 70 | mujju.shape("turtle") 71 | d = 100 72 | a = 30 73 | mujju.speed(0) 74 | 75 | for i in range(12): 76 | 77 | mujju.forward(d) 78 | mujju.stamp() 79 | mujju.backward(d) 80 | 81 | mujju.right(a) 82 | -------------------------------------------------------------------------------- /course_1_assessment_7.py: -------------------------------------------------------------------------------- 1 | #rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0. 2 | #Hard-coded answers will receive no credit.rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85" 3 | num_rainy_months = [] 4 | mylist = rainfall_mi.split(",") 5 | num_rainy_months = 0 6 | print(mylist) 7 | 8 | for num in mylist: 9 | if float(num) > 3.0 : 10 | 11 | num_rainy_months += 1 12 | print(num_rainy_months) 13 | 14 | #The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter, including one-letter words. Store the result in the variable same_letter_count. 15 | 16 | sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking" 17 | words = sentence.split() 18 | print(words) 19 | same_letter_count = 0 20 | for word in words: 21 | 22 | if word[0] == word[-1]: 23 | 24 | same_letter_count += 1 25 | 26 | print(same_letter_count) 27 | 28 | 29 | #Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable acc_num. 30 | 31 | #HINT 1: Use the accumulation pattern! 32 | 33 | #HINT 2: the in operator checks whether a substring is present in a string. 34 | 35 | #Hard-coded answers will receive no credit.# 36 | 37 | items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] 38 | acc_num = 0 39 | for i in items: 40 | 41 | if "w" in i[0:]: 42 | 43 | acc_num += 1 44 | 45 | print(acc_num) 46 | 47 | 48 | #Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable num_a_or_e. 49 | 50 | # Note 1: be sure to not double-count words that contain both an a and an e. 51 | 52 | # HINT 1: Use the in operator. 53 | 54 | # HINT 2: You can either use or or elif. 55 | 56 | # Hard-coded answers will receive no credit. 57 | 58 | 59 | 60 | sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems." 61 | words = sentence.split() 62 | num_a_or_e = 0 63 | for word in words: 64 | 65 | if "a" in word[0:]: 66 | print("mujju") 67 | num_a_or_e += 1 68 | elif "e" in word[0:]: 69 | print("mujju") 70 | num_a_or_e += 1 71 | 72 | 73 | print(num_a_or_e) 74 | 75 | 76 | 77 | #Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem, vowels are only a, e, i, o, and u. Hint: use the in operator with vowels. 78 | s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" 79 | vowels = ['a','e','i','o','u'] 80 | num_vowels = 0 81 | for char in s: 82 | 83 | if char in vowels: 84 | print(char) 85 | num_vowels += 1 86 | 87 | print(num_vowels) -------------------------------------------------------------------------------- /course_1_assessment_9.py: -------------------------------------------------------------------------------- 1 | #Write code to add ‘horseback riding’ to the third position (i.e., right before volleyball) in the list sports. 2 | sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] 3 | sports.insert(2, 'horseback riding') 4 | 5 | #Write code to take ‘London’ out of the list trav_dest. 6 | trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'London', 'Melbourne'] 7 | trav_dest.remove('London') 8 | 9 | #Write code to add ‘Guadalajara’ to the end of the list trav_dest using a list method. 10 | trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne'] 11 | 12 | trav_dest.append('Guadalajara' ) 13 | 14 | #Write code to rearrange the strings in the list winners so that they are in alphabetical order from A to Z. 15 | winners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth'] 16 | 17 | winners.sort() 18 | 19 | #Write code to switch the order of the winners list so that it is now Z to A. Assign this list to the variable z_winners. 20 | winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'] 21 | z_winners = winners 22 | z_winners.reverse() 23 | print(z_winners) 24 | 25 | # -------------------------------------------------------------------------------- /course_2_assessment_1.py: -------------------------------------------------------------------------------- 1 | #The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. Find the total number of characters in the file and save to the variable num. 2 | yoo = open("travel_plans.txt","r") 3 | line = yoo.read() 4 | num = 0 5 | for char in line: 6 | 7 | num = num + 1 8 | print(num) 9 | 10 | #We have provided a file called emotion_words.txt that contains lines of words that describe emotions. Find the total number of words in the file and assign this value to the variable num_words. 11 | yoo = open("emotion_words.txt","r") 12 | line = yoo.read() 13 | homie = line.split() 14 | num_words = 0 15 | print(homie) 16 | for word in homie: 17 | num_words = num_words + 1 18 | print(num_words) 19 | 20 | #Assign to the variable num_lines the number of lines in the file school_prompt.txt. 21 | yoo = open("school_prompt.txt","r") 22 | line = yoo.readlines() 23 | print(line) 24 | num_lines = 0 25 | 26 | for word in line: 27 | num_lines = num_lines + 1 28 | print(num_lines) 29 | 30 | #Assign the first 30 characters of school_prompt.txt as a string to the variable beginning_chars. 31 | yoo = open("school_prompt.txt","r") 32 | line = yoo.readlines() 33 | print(line) 34 | s = 0 35 | beginning_chars ="" 36 | 37 | for mujju in line[:1]: 38 | 39 | beginning_chars = beginning_chars + mujju[:30] 40 | 41 | 42 | print(beginning_chars) 43 | 44 | #Challenge: Using the file school_prompt.txt, assign the third word of every line to a list called three. 45 | yoo = open("school_prompt.txt","r") 46 | lines = yoo.readlines() 47 | 48 | three = [] 49 | 50 | for line in lines: 51 | 52 | w = line.split() 53 | print(w) 54 | three.append(w[2]) 55 | print(three) 56 | 57 | #Challenge: Create a list called emotions that contains the first word of every line in emotion_words.txt. 58 | emotions = [] 59 | yoo = open("emotion_words.txt","r") 60 | lines = yoo.readlines() 61 | for line in lines: 62 | 63 | word = line.split() 64 | print(word[0]) 65 | emotions.append(word[0]) 66 | 67 | #Assign the first 33 characters from the textfile, travel_plans.txt to the variable first_chars. 68 | first_chars = '' 69 | yoo = open("travel_plans.txt","r") 70 | line = yoo.readline() 71 | print(line[:32]) 72 | first_chars = first_chars + line[:33] 73 | print(first_chars) 74 | 75 | #Challenge: Using the file school_prompt.txt, if the character ‘p’ is in a word, then add the word to a list called p_words. 76 | p_words = [] 77 | yoo = open("school_prompt.txt","r") 78 | lines = yoo.readlines() 79 | for line in lines: 80 | word = line.split() 81 | for i in word: 82 | 83 | if 'p' in i: 84 | print(i) 85 | p_words.append(i) 86 | print(p_words) -------------------------------------------------------------------------------- /course_2_assessment_2.py: -------------------------------------------------------------------------------- 1 | #At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as each key’s value. 2 | medal_count = {"United States": 70, "Great Britain": 38, "China": 45 ,"Russia":30, "Germany": 17} 3 | 4 | #Given the dictionary swimmers, add an additional key-value pair to the dictionary with "Phelps" as the key and the integer 23 as the value. Do not rewrite the entire dictionary. 5 | 6 | swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4,"Phelps":23} 7 | 8 | #Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3. Do not rewrite the entire dictionary. 9 | 10 | sports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2,'hockey':3} 11 | 12 | #The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics. But today, Spain won 2 more gold medals. Update golds to reflect this information. 13 | 14 | golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} 15 | golds['Spain'] = 21 16 | 17 | #Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries. Do not hard code this. 18 | 19 | golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} 20 | countries = [] 21 | for i in golds: 22 | countries.append(i) 23 | 24 | #Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point in the 2016 Rio Olympics. Using dictionary mechanics, assign the medal count value for "Belarus" to the variable belarus. Do not hardcode this. 25 | 26 | medal_count = {'United States': 70, 'Great Britain':38, 'China':45, 'Russia':30, 'Germany':17, 'Italy':22, 'France': 22, 'Japan':26, 'Australia':22, 'South Korea':14, 'Hungary':12, 'Netherlands':10, 'Spain':5, 'New Zealand':8, 'Canada':13, 'Kazakhstan':8, 'Colombia':4, 'Switzerland':5, 'Belgium':4, 'Thailand':4, 'Croatia':3, 'Iran':3, 'Jamaica':3, 'South Africa':7, 'Sweden':6, 'Denmark':7, 'North Korea':6, 'Kenya':4, 'Brazil':7, 'Belarus':4, 'Cuba':5, 'Poland':4, 'Romania':4, 'Slovenia':3, 'Argentina':2, 'Bahrain':2, 'Slovakia':2, 'Vietnam':2, 'Czech Republic':6, 'Uzbekistan':5} 27 | 28 | belarus = medal_count['Belarus'] 29 | 30 | 31 | print(belarus) 32 | 33 | #The dictionary total_golds contains the total number of gold medals that countries have won over the course of history. Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds. Do not hard code this! 34 | 35 | total_golds = {"Italy": 114, "Germany": 782, "Pakistan": 10, "Sweden": 627, "USA": 2681, "Zimbabwe": 8, "Greece": 111, "Mongolia": 24, "Brazil": 108, "Croatia": 34, "Algeria": 15, "Switzerland": 323, "Yugoslavia": 87, "China": 526, "Egypt": 26, "Norway": 477, "Spain": 133, "Australia": 480, "Slovakia": 29, "Canada": 22, "New Zealand": 100, "Denmark": 180, "Chile": 13, "Argentina": 70, "Thailand": 24, "Cuba": 209, "Uganda": 7, "England": 806, "Denmark": 180, "Ukraine": 122, "Bahamas": 12} 36 | total_golds['Chile'] 37 | chile_golds = total_golds['Chile'] 38 | print(chile_golds) 39 | 40 | #Provided is a dictionary called US_medals which has the first 70 metals that the United States has won in 2016, and in which category they have won it in. Using dictionary mechanics, assign the value of the key "Fencing" to a variable fencing_value. Remember, do not hard code this. 41 | 42 | US_medals = {"Swimming": 33, "Gymnastics": 6, "Track & Field": 6, "Tennis": 3, "Judo": 2, "Rowing": 2, "Shooting": 3, "Cycling - Road": 1, "Fencing": 4, "Diving": 2, "Archery": 2, "Cycling - Track": 1, "Equestrian": 2, "Golf": 1, "Weightlifting": 1} 43 | US_medals["Fencing"] 44 | fencing_value = US_medals["Fencing"] 45 | print(fencing_value) 46 | -------------------------------------------------------------------------------- /course_2_assessment_3.PY: -------------------------------------------------------------------------------- 1 | #The dictionary Junior shows a schedule for a junior year semester. The key is the course name and the value is the number of credits. Find the total number of credits taken this semester and assign it to the variable credits. Do not hardcode this – use dictionary accumulation! 2 | Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3} 3 | credits = 0 4 | for key in Junior: 5 | 6 | credits = credits + Junior[key] 7 | 8 | #Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value. 9 | str1 = "peter piper picked a peck of pickled peppers" 10 | freq = {} 11 | for i in str1: 12 | if i not in freq: 13 | freq[i] = 0 14 | freq[i] = freq[i] + 1 15 | 16 | #Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1 and the number of times it occurs. 17 | s1 = "hello" 18 | counts = {} 19 | for i in s1: 20 | if i not in counts: 21 | counts[i] = 0 22 | counts[i] = counts[i] + 1 23 | 24 | #Create a dictionary, freq_words, that displays each word in string str1 as the key and its frequency as the value. 25 | str1 = "I wish I wish with all my heart to fly with dragons in a land apart" 26 | word = str1.split() 27 | freq_words = {} 28 | for i in word: 29 | if i not in freq_words: 30 | freq_words[i] = 0 31 | freq_words[i] = freq_words[i] + 1 32 | 33 | #Create a dictionary called wrd_d from the string sent, so that the key is a word and the value is how many times you have seen that word. 34 | sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good" 35 | wrd_d = {} 36 | word = sent.split() 37 | for i in word: 38 | if i not in wrd_d: 39 | wrd_d[i] = 0 40 | wrd_d[i] = wrd_d[i] + 1 41 | 42 | #Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the most frequent letter based on the dictionary. Assign this letter to the variable best_char. 43 | sally = "sally sells sea shells by the sea shore" 44 | characters = {} 45 | for i in sally: 46 | if i not in characters: 47 | characters[i] = 0 48 | characters[i] = characters[i] + 1 49 | print(characters) 50 | ks = characters.keys() 51 | 52 | best_char = list(ks)[0] 53 | 54 | 55 | for k in ks: 56 | print(characters[k]) 57 | if characters[k] > characters[best_char]: 58 | best_char = k 59 | print(best_char) 60 | 61 | #Do the same as above but now find the least frequent letter. Create the dictionary characters that shows each character from string sally and its frequency. Then, find the least frequent letter in the string and assign the letter to the variable worst_char. 62 | sally = "sally sells sea shells by the sea shore and by the road" 63 | characters = {} 64 | for i in sally: 65 | if i not in characters: 66 | characters[i] = 0 67 | characters[i] = characters[i] + 1 68 | print(characters) 69 | ks = characters.keys() 70 | worst_char = list(ks)[0] 71 | for k in ks: 72 | if characters[k] < characters[worst_char]: 73 | worst_char = k 74 | print(worst_char) 75 | 76 | #Create string1 = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures." 77 | yoo = string1.lower() 78 | letter_counts = {} 79 | for i in yoo: 80 | if i not in letter_counts: 81 | letter_counts[i] = 0 82 | letter_counts[i] = letter_counts[i] + 1 83 | print(letter_counts)a dictionary named letter_counts that contains each letter and the number of times it occurs in string1. Challenge: Letters should not be counted separately as upper-case and lower-case. Intead, all of them should be counted as lower-case. 84 | 85 | #Create a dictionary called low_d that keeps track of all the characters in the string p and notes how many times each character was seen. Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as a “t” for example. 86 | p = "Summer is a great time to go outside. You have to be careful of the sun though because of the heat." 87 | yoo = p.lower() 88 | low_d = {} 89 | for i in yoo: 90 | if i not in low_d: 91 | low_d[i] = 0 92 | low_d[i] = low_d[i] + 1 93 | 94 | # -------------------------------------------------------------------------------- /course_2_assessment_4.PY: -------------------------------------------------------------------------------- 1 | #Write a function called int_return that takes an integer as input and returns the same integer. 2 | def int_return(num): 3 | return num 4 | int_return(8) 5 | 6 | #Write a function called add that takes any number as its input and returns that sum with 2 added. 7 | def add(num): 8 | return num + 2 9 | add(2) 10 | 11 | #Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given, and returns that new string. 12 | def change(str): 13 | x = (str +"Nice to meet you!") 14 | return x 15 | 16 | (change("I'm Bob.")) 17 | 18 | #Write a function, accum, that takes a list of integers as input and returns the sum of those integers. 19 | def accum(num): 20 | tot = 0 21 | for i in num: 22 | tot = tot + i 23 | return tot 24 | 25 | accum([1,2,3]) 26 | 27 | #Write a function, length, that takes in a list as the input. If the length of the list is greater than or equal to 5, return “Longer than 5”. If the length is less than 5, return “Less than 5”. 28 | def length(num): 29 | if len(num) >= 5: 30 | return ('Longer than 5') 31 | else: 32 | return ('Less than 5') 33 | length([4, 4, 4, 3, 5, 6, 7, 8, 9]) 34 | 35 | 36 | 37 | #You will need to write two functions for this problem. The first function, divide that takes in any number and returns that same number divided by 2. The second function called sum should take any number, divide it by 2, and add 6. It should return this new number. You should call the divide function within the sum function. Do not worry about decimals. 38 | def divide(num): 39 | x = num/2 40 | return x 41 | divide(2) 42 | def sum(nu): 43 | y = divide(nu) + 6 44 | return y 45 | sum(2) 46 | 47 | # -------------------------------------------------------------------------------- /course_2_assessment_5.PY: -------------------------------------------------------------------------------- 1 | #Create a tuple called olympics with four elements: “Beijing”, “London”, “Rio”, “Tokyo”. 2 | olympics = ("Beijing","London","Rio","Tokyo") 3 | 4 | #The list below, tuples_lst, is a list of tuples. Create a list of the second elements of each tuple and assign this list to the variable country. 5 | 6 | tuples_lst = [('Beijing', 'China', 2008), ('London', 'England', 2012), ('Rio', 'Brazil', 2016, 'Current'), ('Tokyo', 'Japan', 2020, 'Future')] 7 | country = [] 8 | for i in tuples_lst: 9 | print(i[1]) 10 | country.append(i[1]) 11 | print(country)\ 12 | 13 | #With only one line of code, assign the variables city, country, and year to the values of the tuple olymp. 14 | 15 | olymp = ('Rio', 'Brazil', 2016) 16 | (city,country,year) = olymp 17 | print(city) 18 | 19 | #Define a function called info with five parameters: name, gender, age, bday_month, and hometown. The function should then return a tuple with all five parameters in that order. 20 | def info(a,b,c,d,e): 21 | name = a 22 | gender = b 23 | age = c 24 | bday_month = d 25 | hometown = e 26 | return name, gender, age, bday_month,hometown 27 | 28 | yoo = info("Mujju", "Male", '21', '11',"Hyderabad") 29 | print(yoo) 30 | 31 | #Given is the dictionary, gold, which shows the country and the number of gold medals they have earned so far in the 2016 Olympics. Create a list, num_medals, that contains only the number of medals for each country. You must use the .items() method. Note: The .items() method provides a list of tuples. Do not use .keys() method. 32 | 33 | gold = {'USA':31, 'Great Britain':19, 'China':19, 'Germany':13, 'Russia':12, 'Japan':10, 'France':8, 'Italy':8} 34 | num_medals = [] 35 | yoo = gold.items() 36 | print(yoo) 37 | for i in yoo: 38 | num_medals.append(i[1]) 39 | print(num_medals) 40 | 41 | -------------------------------------------------------------------------------- /course_2_assessment_6.py: -------------------------------------------------------------------------------- 1 | #Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5). 2 | def sublist(x): 3 | sub = [] 4 | x = (num for num in x) 5 | num = next(x, 5) 6 | while num != 5: 7 | sub.append(num) 8 | num = next(x, 5) 9 | return sub 10 | 11 | x = [1, 3, 4, 5, 6, 7, 3] 12 | print(sublist(x)) 13 | 14 | #Write a function called check_nums that takes a list as its parameter, and contains a while loop that only stops once the element of the list is the number 7. What is returned is a list of all of the numbers up until it reaches 7. 15 | def check_nums(x): 16 | sub = [] 17 | x = (num for num in x) 18 | num = next(x, 7) 19 | while num != 7: 20 | sub.append(num) 21 | num = next(x, 7) 22 | return sub 23 | 24 | x = [1, 3, 4, 5, 6, 7, 3] 25 | print(check_nums(x)) 26 | 27 | #Write a function, sublist, that takes in a list of strings as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the string “STOP” (it should not contain the string “STOP”). 28 | def sublist(list): 29 | i = 0 30 | while i < len(list): 31 | 32 | if (list[i] == 'STOP'): 33 | return list[0:i] 34 | i+=1 35 | return list[0:i] 36 | print(sublist(['mujju','salman','yo','STOP'])) 37 | 38 | #Write a function called stop_at_z that iterates through a list of strings. Using a while loop, append each string to a new list until the string that appears is “z”. The function should return the new list. 39 | def stop_at_z(list): 40 | i = 0 41 | while i < len(list): 42 | 43 | if (list[i] == 'z'): 44 | return list[0:i] 45 | i+=1 46 | return list[0:i] 47 | print(stop_at_z(['a','b','c','z'])) 48 | 49 | #Below is a for loop that works. Underneath the for loop, rewrite the problem so that it does the same thing, but using a while loop instead of a for loop. Assign the accumulated total in the while loop code to the variable sum2. Once complete, sum2 should equal sum1. 50 | 51 | sum1 = 0 52 | sum2 = 0 53 | i = 0 54 | lst = [65, 78, 21, 33] 55 | 56 | for x in lst: 57 | sum1 = sum1 + x 58 | print(sum1) 59 | while i < len(lst): 60 | 61 | sum2 += lst[i] 62 | i = i + 1 63 | 64 | print(sum2) 65 | 66 | 67 | #Challenge: Write a function called beginning that takes a list as input and contains a while loop that only stops once the element of the list is the string ‘bye’. What is returned is a list that contains up to the first 10 strings, regardless of where the loop stops. (i.e., if it stops on the 32nd element, the first 10 are returned. If “bye” is the 5th element, the first 4 are returned.) If you want to make this even more of a challenge, do this without slicing 68 | lst = [65, 78, 21, 33] 69 | sum2 = 0 70 | i =0 71 | while i < len(lst): 72 | 73 | sum2 += lst[i] 74 | i = i + 1 75 | 76 | print(sum2) -------------------------------------------------------------------------------- /course_2_assessment_7.py: -------------------------------------------------------------------------------- 1 | #Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second. 2 | lol = 6 3 | def mult(x,y = lol): 4 | 5 | return x*y 6 | print(mult(4)) 7 | 8 | #The following function, greeting, does not work. Please fix the code so that it runs without error. This only requires one change in the definition of the function. 9 | 10 | def greeting(name, greeting="Hello ", excl="!"): 11 | return greeting + name + excl 12 | 13 | print(greeting("Bob")) 14 | print(greeting("")) 15 | print(greeting("Bob", excl="!!!")) 16 | 17 | #Below is a function, sum, that does not work. Change the function definition so the code works. The function should still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5. 18 | 19 | def sum(intx, intz=5): 20 | return intz + intx 21 | 22 | #Write a function, test, that takes in three parameters: a required integer, an optional boolean whose default value is True, and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, the function should test to see if the integer is a key in the dictionary. The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”. 23 | def test(x, abool = True, dict1 = {2:3, 4:5, 6:8}): 24 | return abool and dict1.get(x) 25 | 26 | #Write a function called checkingIfIn that takes three parameters. The first is a required parameter, which should be a string. The second is an optional parameter called direction with a default value of True. The third is an optional parameter called d that has a default value of {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}. Write the function checkingIfIn so that when the second parameter is True, it checks to see if the first parameter is a key in the third parameter; if it is, return True, otherwise return False. 27 | #But if the second paramter is False, then the function should check to see if the first parameter is not a key of the third. If it’s not, the function should return True in this case, and if it is, it should return False. 28 | 29 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 30 | if direction == True: 31 | if a in d: 32 | return True 33 | else: 34 | return False 35 | else: 36 | if a not in d: 37 | return True 38 | else: 39 | return False 40 | 41 | #We have provided the function checkingIfIn such that if the first input parameter is in the third, dictionary, input parameter, then the function returns that value, and otherwise, it returns False. Follow the instructions in the active code window for specific variable assignmemts. 42 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 43 | if direction == True: 44 | if a in d: 45 | return d[a] 46 | else: 47 | return False 48 | else: 49 | if a not in d: 50 | return TrueA 51 | else: 52 | return d[a] 53 | 54 | # Call the function so that it returns False and assign that function call to the variable c_false 55 | c_false = checkingIfIn('peas') 56 | # Call the fucntion so that it returns True and assign it to the variable c_true 57 | c_true = checkingIfIn('apples', False, {'carrots': 1, 'peas': 9, 'potatos': 8, 'corn': 32, 'beans': 1}) 58 | # Call the function so that the value of fruit is assigned to the variable fruit_ans 59 | fruit_ans= checkingIfIn('fruit') 60 | # Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check 61 | param_check = checkingIfIn('potatos', False, {'carrots': 1, 'peas': 9, 'potatos': 8, 'corn': 32, 'beans': 1}) 62 | 63 | -------------------------------------------------------------------------------- /course_2_assessment_8.py: -------------------------------------------------------------------------------- 1 | #Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters. 2 | letters = "alwnfiwaksuezlaeiajsdl" 3 | sorted_letters = sorted(letters, reverse = True) 4 | 5 | #Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted. 6 | 7 | animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear'] 8 | animals_sorted = sorted(animals) 9 | 10 | #The dictionary, medals, shows the medal count for six countries during the Rio Olympics. Sort the country names so they appear alphabetically. Save this list to the variable alphabetical. 11 | 12 | medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} 13 | alphabetical = sorted(medals) 14 | 15 | 16 | #Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count to the list, top_three. 17 | top_three = [] 18 | medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} 19 | def g(k,d): 20 | return d[k] 21 | ks = medals.keys() 22 | top_three = sorted(ks,key=lambda x : g(x,medals),reverse = True)[:3] 23 | 24 | #We have provided the dictionary groceries. You should return a list of its keys, but they should be sorted by their values, from highest to lowest. Save the new list as most_needed. 25 | most_needed = [] 26 | groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9} 27 | def g(k,d): 28 | return d[k] 29 | ks = groceries.keys() 30 | most_needed = sorted(ks, key=lambda x:g(x,groceries), reverse = True) 31 | 32 | #Create a function called last_four that takes in an ID number and returns the last four digits. For example, the number 17573005 should return 3005. Then, use this function to sort the list of ids stored in the variable, ids, from lowest to highest. Save this sorted list in the variable, sorted_ids. Hint: Remember that only strings can be indexed, so conversions may be needed. 33 | ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] 34 | 35 | def last_four(x): 36 | 37 | return (str(x)[-4:]) 38 | last_four(ids) 39 | 40 | sorted_ids = sorted(ids, key=last_four ) 41 | print(sorted_ids) 42 | 43 | #$Sort the list ids by the last four digits of each id. Do this using lambda and not using a defined function. Save this sorted list in the variable sorted_id. 44 | 45 | ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] 46 | 47 | sorted_id = sorted(ids, key=lambda x: str(x)[-4:]) 48 | 49 | # 50 | ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance'] 51 | 52 | lambda_sort = sorted(ex_lst, key = lambda x: x[1]) 53 | print(lambda_sort) -------------------------------------------------------------------------------- /course_2_project.py: -------------------------------------------------------------------------------- 1 | # 2 | projectTwitterDataFile = open("project_twitter_data.csv","r") 3 | resultingDataFile = open("resulting_data.csv","w") 4 | 5 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 6 | # lists of words to use 7 | positive_words = [] 8 | with open("positive_words.txt") as pos_f: 9 | for lin in pos_f: 10 | if lin[0] != ';' and lin[0] != '\n': 11 | positive_words.append(lin.strip()) 12 | 13 | def get_pos(strSentences): 14 | strSentences = strip_punctuation(strSentences) 15 | listStrSentences= strSentences.split() 16 | 17 | count=0 18 | for word in listStrSentences: 19 | for positiveWord in positive_words: 20 | if word == positiveWord: 21 | count+=1 22 | return count 23 | 24 | negative_words = [] 25 | with open("negative_words.txt") as pos_f: 26 | for lin in pos_f: 27 | if lin[0] != ';' and lin[0] != '\n': 28 | negative_words.append(lin.strip()) 29 | 30 | 31 | def get_neg(strSentences): 32 | strSentences = strip_punctuation(strSentences) 33 | listStrSentences = strSentences.split() 34 | 35 | count=0 36 | for word in listStrSentences: 37 | for negativeWord in negative_words: 38 | if word == negativeWord: 39 | count+=1 40 | return count 41 | 42 | 43 | def strip_punctuation(strWord): 44 | for charPunct in punctuation_chars: 45 | strWord = strWord.replace(charPunct, "") 46 | return strWord 47 | 48 | 49 | def writeInDataFile(resultingDataFile): 50 | resultingDataFile.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score") 51 | resultingDataFile.write("\n") 52 | 53 | linesPTDF = projectTwitterDataFile.readlines() 54 | headerDontUsed= linesPTDF.pop(0) 55 | for linesTD in linesPTDF: 56 | listTD = linesTD.strip().split(',') 57 | resultingDataFile.write("{}, {}, {}, {}, {}".format(listTD[1], listTD[2], get_pos(listTD[0]), get_neg(listTD[0]), (get_pos(listTD[0])-get_neg(listTD[0])))) 58 | resultingDataFile.write("\n") 59 | 60 | 61 | 62 | writeInDataFile(resultingDataFile) 63 | projectTwitterDataFile.close() 64 | resultingDataFile.close() 65 | 66 | ############################################### 67 | 68 | 69 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 70 | # list of positive words to use 71 | positive_words = [] 72 | with open("positive_words.txt") as pos_f: 73 | for lin in pos_f: 74 | if lin[0] != ';' and lin[0] != '\n': 75 | positive_words.append(lin.strip()) 76 | 77 | def get_pos(strSentences): 78 | strSentences = strip_punctuation(strSentences) 79 | listStrSentences= strSentences.split() 80 | 81 | count=0 82 | for word in listStrSentences: 83 | for positiveWord in positive_words: 84 | if word == positiveWord: 85 | count+=1 86 | return count 87 | 88 | 89 | def strip_punctuation(strWord): 90 | for charPunct in punctuation_chars: 91 | strWord = strWord.replace(charPunct, "") 92 | return strWord 93 | 94 | 95 | ################################## 96 | 97 | 98 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 99 | 100 | negative_words = [] 101 | with open("negative_words.txt") as pos_f: 102 | for lin in pos_f: 103 | if lin[0] != ';' and lin[0] != '\n': 104 | negative_words.append(lin.strip()) 105 | 106 | def get_neg(strSentences): 107 | strSentences = strip_punctuation(strSentences) 108 | listStrSentences = strSentences.split() 109 | 110 | count=0 111 | for word in listStrSentences: 112 | for negativeWord in negative_words: 113 | if word == negativeWord: 114 | count+=1 115 | return count 116 | 117 | 118 | def strip_punctuation(strWord): 119 | for charPunct in punctuation_chars: 120 | strWord = strWord.replace(charPunct, "") 121 | return strWord 122 | 123 | 124 | ################################################################# 125 | 126 | projectTwitterDataFile = open("project_twitter_data.csv","r") 127 | resultingDataFile = open("resulting_data.csv","w") 128 | 129 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 130 | # lists of words to use 131 | positive_words = [] 132 | with open("positive_words.txt") as pos_f: 133 | for lin in pos_f: 134 | if lin[0] != ';' and lin[0] != '\n': 135 | positive_words.append(lin.strip()) 136 | 137 | def get_pos(strSentences): 138 | strSentences = strip_punctuation(strSentences) 139 | listStrSentences= strSentences.split() 140 | 141 | count=0 142 | for word in listStrSentences: 143 | for positiveWord in positive_words: 144 | if word == positiveWord: 145 | count+=1 146 | return count 147 | 148 | negative_words = [] 149 | with open("negative_words.txt") as pos_f: 150 | for lin in pos_f: 151 | if lin[0] != ';' and lin[0] != '\n': 152 | negative_words.append(lin.strip()) 153 | 154 | 155 | def get_neg(strSentences): 156 | strSentences = strip_punctuation(strSentences) 157 | listStrSentences = strSentences.split() 158 | 159 | count=0 160 | for word in listStrSentences: 161 | for negativeWord in negative_words: 162 | if word == negativeWord: 163 | count+=1 164 | return count 165 | 166 | 167 | def strip_punctuation(strWord): 168 | for charPunct in punctuation_chars: 169 | strWord = strWord.replace(charPunct, "") 170 | return strWord 171 | 172 | 173 | def writeInDataFile(resultingDataFile): 174 | resultingDataFile.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score") 175 | resultingDataFile.write("\n") 176 | 177 | linesPTDF = projectTwitterDataFile.readlines() 178 | headerDontUsed= linesPTDF.pop(0) 179 | for linesTD in linesPTDF: 180 | listTD = linesTD.strip().split(',') 181 | resultingDataFile.write("{}, {}, {}, {}, {}".format(listTD[1], listTD[2], get_pos(listTD[0]), get_neg(listTD[0]), (get_pos(listTD[0])-get_neg(listTD[0])))) 182 | resultingDataFile.write("\n") 183 | 184 | 185 | 186 | writeInDataFile(resultingDataFile) 187 | projectTwitterDataFile.close() 188 | resultingDataFile.close() -------------------------------------------------------------------------------- /course_3_assessment_1.py: -------------------------------------------------------------------------------- 1 | # 1. The variable nested contains a nested list. Assign ‘snake’ to the variable output using indexing. 2 | 3 | nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']] 4 | output = nested[1][2] 5 | print(output) 6 | 7 | # 2. Below, a list of lists is provided. Use in and not in tests to create variables with Boolean values. 8 | # See comments for further instructions. 9 | 10 | lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']] 11 | 12 | #Test to see if 'yellow' is in the third list of lst. Save to variable ``yellow`` 13 | yellow = 'yellow' in lst[2] 14 | 15 | #Test to see if 4 is in the second list of lst. Save to variable ``four`` 16 | four = 4 in lst[1] 17 | 18 | #Test to see if 'orange' is in the first element of lst. Save to variable ``orange`` 19 | orange = 'orange' in lst[0] 20 | 21 | # 3. Below, we’ve provided a list of lists. Use in statements to create variables with Boolean values 22 | # see the ActiveCode window for further directions. 23 | 24 | L = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']] 25 | 26 | # Test if 'hola' is in the list L. Save to variable name test1 27 | test1 = 'hola' in L 28 | # Test if [5, 8, 7] is in the list L. Save to variable name test2 29 | test2 = [5, 8, 7] in L 30 | # Test if 6.6 is in the third element of list L. Save to variable name test3 31 | test3 = 6.6 in L[2] 32 | 33 | # 4. Provided is a nested data structure. Follow the instructions in the comments below. Do not hard code. 34 | 35 | nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], 'window': ['part', 'whole', [], 'sum', ['math', 'calculus', 'algebra', 'geometry', 'statistics',['physics', 'chemistry', 'biology']]]} 36 | 37 | # Check to see if the string data is a key in nested, if it is, assign True to the variable data, otherwise assign False. 38 | if 'data' in nested: 39 | data = True 40 | else: 41 | data = False 42 | # Check to see if the integer 24 is in the value of the key data, if it is then assign to the variable twentyfour the value of True, otherwise False. 43 | if 24 in nested: 44 | twentyfour = True 45 | else: 46 | twentyfour = False 47 | # Check to see that the string 'whole' is not in the value of the key window. If it's not, then assign to the variable whole the value of True, otherwise False. 48 | if 'whole' in nested: 49 | whole = True 50 | else: 51 | whole = False 52 | # Check to see if the string 'physics' is a key in the dictionary nested. If it is, assign to the variable physics, the value of True, otherwise False. 53 | if 'physics' in nested: 54 | physics = True 55 | else: 56 | physics = False 57 | 58 | # 5. The variable nested_d contains a nested dictionary with the gold medal counts 59 | # for the top four countries in the past three Olympics. 60 | # Assign the value of Great Britain’s gold medal count from the London Olympics to the variable london_gold. 61 | # Use indexing. Do not hardcode. 62 | 63 | nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}} 64 | london_gold = nested_d['London']['Great Britain'] 65 | 66 | # 6. Below, we have provided a nested dictionary. 67 | # Index into the dictionary to create variables that we have listed in the ActiveCode window. 68 | 69 | sports = {'swimming': ['butterfly', 'breaststroke', 'backstroke', 'freestyle'], 'diving': ['springboard', 'platform', 'synchronized'], 'track': ['sprint', 'distance', 'jumps', 'throws'], 'gymnastics': {'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']}} 70 | 71 | # Assign the string 'backstroke' to the name v1 72 | v1 = sports['swimming'][2] 73 | # Assign the string 'platform' to the name v2 74 | v2 = sports['diving'][1] 75 | # Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3 76 | v3 = sports['gymnastics']['women'] 77 | # Assign the string 'rings' to the name v4 78 | v4 = sports['gymnastics']['men'][3] 79 | print(v4) 80 | 81 | # 7. Given the dictionary, nested_d, 82 | # save the medal count for the USA from all three Olympics in the dictionary to the list US_count. 83 | 84 | nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}} 85 | US_count = [] 86 | 87 | 88 | US_count.append(nested_d['Beijing']['USA']) 89 | US_count.append(nested_d['London']['USA']) 90 | US_count.append(nested_d['Rio']['USA']) 91 | 92 | # 8. Iterate through the contents of l_of_l and assign the third element of sublist to a new list called third. 93 | 94 | l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']] 95 | 96 | third = [i[2] for i in l_of_l] 97 | 98 | # 9. Given below is a list of lists of athletes. 99 | # Create a list, t, that saves only the athlete’s name if it contains the letter “t”. 100 | # If it does not contain the letter “t”, save the athlete name into list other. 101 | 102 | athletes = [ 103 | ['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], 104 | ['Felix', 'Bolt', 'Gardner', 'Eaton'], 105 | ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton'] 106 | ] 107 | 108 | t = [] 109 | other = [] 110 | 111 | for list in athletes: 112 | for char in list: 113 | if 't' in char: 114 | t.append(char) 115 | else: 116 | other.append(char) -------------------------------------------------------------------------------- /course_3_assessment_2.py: -------------------------------------------------------------------------------- 1 | #Write code to assign to the variable map_testing all the elements in lst_check while adding the string “Fruit: ” to the beginning of each element using mapping. 2 | 3 | 4 | lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya'] 5 | 6 | map_testing = map(lambda word: "Fruit: " + word,lst_check) 7 | print(map_testing) 8 | 9 | #Below, we have provided a list of strings called countries. Use filter to produce a list called b_countries that only contains the strings from countries that begin with B. 10 | 11 | 12 | countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium'] 13 | 14 | b_countries = filter(lambda c : "B" in c,countries) 15 | 16 | #Below, we have provided a list of tuples that contain the names of Game of Thrones characters. Using list comprehension, create a list of strings called first_names that contains only the first names of everyone in the original list. 17 | 18 | 19 | people = [('Snow', 'Jon'), ('Lannister', 'Cersei'), ('Stark', 'Arya'), ('Stark', 'Robb'), ('Lannister', 'Jamie'), ('Targaryen', 'Daenerys'), ('Stark', 'Sansa'), ('Tyrell', 'Margaery'), ('Stark', 'Eddard'), ('Lannister', 'Tyrion'), ('Baratheon', 'Joffrey'), ('Bolton', 'Ramsey'), ('Baelish', 'Peter')] 20 | 21 | first_names = [name[1] for name in people] 22 | print(list(first_names)) 23 | 24 | #Use list comprehension to create a list called lst2 that doubles each element in the list, lst. 25 | 26 | 27 | lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4] 28 | 29 | lst2 = [word*2 for word in lst] 30 | 31 | #Below, we have provided a list of tuples that contain students’ names and their final grades in PYTHON 101. Using list comprehension, create a new list passed that contains the names of students who passed the class (had a final grade of 70 or greater). 32 | 33 | 34 | students = [('Tommy', 95), ('Linda', 63), ('Carl', 70), ('Bob', 100), ('Raymond', 50), ('Sue', 75)] 35 | 36 | passed = [key[0] for key in students if key[1] >= 70] 37 | print(list(passed)) 38 | 39 | #Write code using zip and filter so that these lists (l1 and l2) are combined into one big list and assigned to the variable opposites if they are both longer than 3 characters each. 40 | 41 | 42 | l1 = ['left', 'up', 'front'] 43 | l2 = ['right', 'down', 'back'] 44 | 45 | l3 = zip(l1, l2) 46 | opposites=list(filter(lambda s:len(s[0])>3 and len(s[1]) >3 ,l3)) 47 | 48 | #Below, we have provided a species list and a population list. Use zip to combine these lists into one list of tuples called pop_info. From this list, create a new list called endangered that contains the names of species whose populations are below 2500. 49 | 50 | 51 | species = ['golden retriever', 'white tailed deer', 'black rhino', 'brown squirrel', 'field mouse', 'orangutan', 'sumatran elephant', 'rainbow trout', 'black bear', 'blue whale', 'water moccasin', 'giant panda', 'green turtle', 'blue jay', 'japanese beetle'] 52 | 53 | population = [10000, 90000, 1000, 2000000, 500000, 500, 1200, 8000, 12000, 2300, 7500, 100, 1800, 9500, 125000] 54 | 55 | pop_info = zip(species,population) 56 | print(pop_info) 57 | 58 | endangered = [x[0] for x in pop_info if x[1]<2500 ] 59 | print(endangered) -------------------------------------------------------------------------------- /course_3_project.py: -------------------------------------------------------------------------------- 1 | import requests_with_caching 2 | import json 3 | 4 | def get_movies_from_tastedive(title): 5 | url = 'https://tastedive.com/api/similar' 6 | param = {} 7 | param['q']= title 8 | param['type']= 'movies' 9 | param['limit']= 5 10 | 11 | this_page_cache = requests_with_caching.get(url, params=param) 12 | return json.loads(this_page_cache.text) 13 | 14 | get_movies_from_tastedive('Captain Marvel') 15 | get_movies_from_tastedive('Sherlock Holmes') 16 | 17 | #Please copy the completed function from above into this active code window. Next, you will need to write a function that extracts just the list of movie titles from a dictionary returned by get_movies_from_tastedive. Call it extract_movie_titles. 18 | import requests_with_caching 19 | import json 20 | 21 | 22 | def get_movies_from_tastedive(title): 23 | endpoint = 'https://tastedive.com/api/similar' 24 | param = {} 25 | param['q'] = title 26 | param['limit'] = 5 27 | param['type'] = 'movies' 28 | 29 | this_page_cache = requests_with_caching.get(endpoint, params=param) 30 | return json.loads(this_page_cache.text) 31 | 32 | 33 | def extract_movie_titles(dic): 34 | return ([i['Name'] for i in dic['Similar']['Results']]) 35 | 36 | 37 | # some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages 38 | extract_movie_titles(get_movies_from_tastedive("Tony Bennett")) 39 | extract_movie_titles(get_movies_from_tastedive("Black Panther")) 40 | 41 | ####Please copy the completed functions from the two code windows above into this active code window. Next, you’ll write a function, called get_related_titles. It takes a list of movie titles as input. It gets five related movies for each from TasteDive, extracts the titles for all of them, and combines them all into a single list. Don’t include the same movie twice. 42 | import requests_with_caching 43 | import json 44 | 45 | 46 | def get_movies_from_tastedive(title): 47 | endpoint = 'https://tastedive.com/api/similar' 48 | param = {} 49 | param['q'] = title 50 | param['limit'] = 5 51 | param['type'] = 'movies' 52 | 53 | this_page_cache = requests_with_caching.get(endpoint, params=param) 54 | return json.loads(this_page_cache.text) 55 | 56 | 57 | def extract_movie_titles(dic): 58 | return ([i['Name'] for i in dic['Similar']['Results']]) 59 | 60 | 61 | def get_related_titles(movie_list): 62 | li = [] 63 | for movie in movie_list: 64 | li.extend(extract_movie_titles(get_movies_from_tastedive(movie))) 65 | return list(set(li)) 66 | 67 | 68 | get_related_titles(["Black Panther", "Captain Marvel"]) 69 | 70 | ##Your next task will be to fetch data from OMDB. The documentation for the API is at https://www.omdbapi.com/ 71 | 72 | #Define a function called get_movie_data. It takes in one parameter which is a string that should represent the title of a movie you want to search. The function should return a dictionary with information about that movie. 73 | 74 | #Again, use requests_with_caching.get(). For the queries on movies that are already in the cache, you won’t need an api key. You will need to provide the following keys: t and r. As with the TasteDive cache, be sure to only include those two parameters in order to extract existing data from the cache. 75 | 76 | import requests_with_caching 77 | import json 78 | 79 | 80 | def get_movie_data(title): 81 | endpoint = 'http://www.omdbapi.com/' 82 | param = {} 83 | param['t'] = title 84 | param['r'] = 'json' 85 | this_page_cache = requests_with_caching.get(endpoint, params=param) 86 | 87 | return json.loads(this_page_cache.text) 88 | 89 | 90 | get_movie_data("Venom") 91 | get_movie_data("Baby Mama") 92 | 93 | ##Please copy the completed function from above into this active code window. Now write a function called get_movie_rating. It takes an OMDB dictionary result for one movie and extracts the Rotten Tomatoes rating as an integer. For example, if given the OMDB dictionary for “Black Panther”, it would return 97. If there is no Rotten Tomatoes rating, return 0. 94 | import requests_with_caching 95 | import json 96 | 97 | 98 | def get_movie_data(title): 99 | endpoint = 'http://www.omdbapi.com/' 100 | param = {} 101 | param['t'] = title 102 | param['r'] = 'json' 103 | this_page_cache = requests_with_caching.get(endpoint, params=param) 104 | return json.loads(this_page_cache.text) 105 | print(get_movie_data("Black Panther")['Ratings'][1]) 106 | def get_movie_rating(dic): 107 | ranking = dic['Ratings'] 108 | for dic_item in ranking: 109 | if dic_item['Source'] == 'Rotten Tomatoes': 110 | return int(dic_item['Value'][:-1]) 111 | return 0 112 | 113 | 114 | get_movie_rating(get_movie_data("Deadpool 2")) 115 | 116 | ###Now, you’ll put it all together. Don’t forget to copy all of the functions that you have previously defined into this code window. Define a function get_sorted_recommendations. It takes a list of movie titles as an input. It returns a sorted list of related movie titles as output, up to five related movies for each input movie title. The movies should be sorted in descending order by their Rotten Tomatoes rating, as returned by the get_movie_rating function. Break ties in reverse alphabetic order, so that ‘Yahşi Batı’ comes before ‘Eyyvah Eyvah’. 117 | 118 | import requests_with_caching 119 | import json 120 | 121 | def get_movies_from_tastedive(title): 122 | endpoint = 'https://tastedive.com/api/similar' 123 | param = {} 124 | param['q'] = title 125 | param['limit'] = 5 126 | param['type'] = 'movies' 127 | this_page_cache = requests_with_caching.get(endpoint, params=param) 128 | return json.loads(this_page_cache.text) 129 | 130 | def extract_movie_titles(dic): 131 | list = [] 132 | for i in dic['Similar']['Results']: 133 | list.append(i['Name']) 134 | return(list) 135 | 136 | def get_related_titles(titles_list): 137 | list = [] 138 | for i in titles_list: 139 | new_list = extract_movie_titles(get_movies_from_tastedive(i)) 140 | for i in new_list: 141 | if i not in list: 142 | list.append(i) 143 | print(list) 144 | return list 145 | 146 | def get_movie_data(title): 147 | endpoint = 'http://www.omdbapi.com/' 148 | param = {} 149 | param['t'] = title 150 | param['r'] = 'json' 151 | this_page_cache = requests_with_caching.get(endpoint, params=param) 152 | return json.loads(this_page_cache.text) 153 | 154 | # some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages 155 | # get_movie_rating(get_movie_data("Deadpool 2")) 156 | 157 | def get_movie_rating(data): 158 | rating = 0 159 | for i in data['Ratings']: 160 | if i['Source'] == 'Rotten Tomatoes': 161 | rating = int(i['Value'][:-1]) 162 | #print(rating) 163 | return rating 164 | 165 | def get_sorted_recommendations(list): 166 | new_list = get_related_titles(list) 167 | new_dict = {} 168 | for i in new_list: 169 | rating = get_movie_rating(get_movie_data(i)) 170 | new_dict[i] = rating 171 | print(new_dict) 172 | #print(sorted(new_dict, reverse=True)) 173 | return [i[0] for i in sorted(new_dict.items(), key=lambda item: (item[1], item[0]), reverse=True)] 174 | 175 | 176 | 177 | # some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages 178 | # get_sorted_recommendations(["Bridesmaids", "Sherlock Holmes"]) 179 | 180 | -------------------------------------------------------------------------------- /course_4_assessment_1.py: -------------------------------------------------------------------------------- 1 | #Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to two instance variables, color and price. Assign to the variable testOne an instance of Bike whose color is blue and whose price is 89.99. Assign to the variable testTwo an instance of Bike whose color is purple and whose price is 25.0. 2 | 3 | 4 | class Bike: 5 | """ Point class for representing and manipulating x,y coordinates. """ 6 | 7 | def __init__(self, initX, initY): 8 | 9 | self.color = initX 10 | self.price = initY 11 | 12 | testOne = Bike('blue',89.99) 13 | testTwo = Bike('purple',25.0) 14 | 15 | 16 | 17 | #Create a class called AppleBasket whose constructor accepts two inputs: a string representing a color, and a number representing a quantity of apples. The constructor should initialize two instance variables: apple_color and apple_quantity. Write a class method called increase that increases the quantity by 1 each time it is invoked. You should also write a __str__ method for this class that returns a string of the format: "A basket of [quantity goes here] [color goes here] apples." e.g. "A basket of 4 red apples." or "A basket of 50 blue apples." (Writing some test code that creates instances and assigns values to variables may help you solve this problem!) 18 | 19 | 20 | class AppleBasket: 21 | """ Point class for representing and manipulating x,y coordinates. """ 22 | 23 | def __init__(self, initX, initY): 24 | 25 | self.apple_color = initX 26 | self.apple_quantity = initY 27 | 28 | def increase(self): 29 | return self.apple_quantity + 1 30 | 31 | def increase(self): 32 | self.apple_quantity = self.apple_quantity + 1 33 | 34 | def __str__(self): 35 | return "A basket of {} {} apples.".format(self.apple_quantity, self.apple_color) 36 | 37 | testOne = AppleBasket('red',4) 38 | print(testOne) 39 | testOne.increase() 40 | print(testOne) 41 | 42 | 43 | 44 | #Define a class called BankAccount that accepts the name you want associated with your bank account in a string, and an integer that represents the amount of money in the account. The constructor should initialize two instance variables from those inputs: name and amt. Add a string method so that when you print an instance of BankAccount, you see "Your account, [name goes here], has [start_amt goes here] dollars." Create an instance of this class with "Bob" as the name and 100 as the amount. Save this to the variable t1. 45 | 46 | 47 | class BankAccount: 48 | """ Point class for representing and manipulating x,y coordinates. """ 49 | 50 | def __init__(self, initX, initY): 51 | 52 | self.name = initX 53 | self.amt = initY 54 | 55 | def __str__(self): 56 | return "Your account, {}, has {} dollars.".format(self.name, self.amt) 57 | 58 | t1 = BankAccount("Bob",100) 59 | print(t1) -------------------------------------------------------------------------------- /course_4_assessment_2.py: -------------------------------------------------------------------------------- 1 | # The class, Pokemon, is provided below and describes a Pokemon and its leveling and evolving characteristics. An instance of the class is one pokemon that you create. 2 | 3 | # Grass_Pokemon is a subclass that inherits from Pokemon but changes some aspects, for instance, the boost values are different. 4 | 5 | # For the subclass Grass_Pokemon, add another method called action that returns the string "[name of pokemon] knows a lot of different moves!". Create an instance of this class with the name as "Belle". Assign this instance to the variable p1. 6 | 7 | class Pokemon(object): 8 | attack = 12 9 | defense = 10 10 | health = 15 11 | p_type = "Normal" 12 | 13 | def __init__(self, name, level = 5): 14 | self.name = name 15 | self.level = level 16 | 17 | def train(self): 18 | self.update() 19 | self.attack_up() 20 | self.defense_up() 21 | self.health_up() 22 | self.level = self.level + 1 23 | if self.level%self.evolve == 0: 24 | return self.level, "Evolved!" 25 | else: 26 | return self.level 27 | 28 | def attack_up(self): 29 | self.attack = self.attack + self.attack_boost 30 | return self.attack 31 | 32 | def defense_up(self): 33 | self.defense = self.defense + self.defense_boost 34 | return self.defense 35 | 36 | def health_up(self): 37 | self.health = self.health + self.health_boost 38 | return self.health 39 | 40 | def update(self): 41 | self.health_boost = 5 42 | self.attack_boost = 3 43 | self.defense_boost = 2 44 | self.evolve = 10 45 | 46 | def __str__(self): 47 | self.update() 48 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 49 | 50 | class Grass_Pokemon(Pokemon): 51 | attack = 15 52 | defense = 14 53 | health = 12 54 | 55 | def update(self): 56 | self.health_boost = 6 57 | self.attack_boost = 2 58 | self.defense_boost = 3 59 | self.evolve = 12 60 | 61 | def moves(self): 62 | self.p_moves = ["razor leaf", "synthesis", "petal dance"] 63 | 64 | class Grass_Pokemon(Pokemon): 65 | def action(self): 66 | return self.name + " knows a lot of different moves!" 67 | 68 | p1 = Grass_Pokemon('Belle', 5) 69 | 70 | 71 | #Modify the Grass_Pokemon subclass so that the attack strength for Grass_Pokemon instances does not change until they reach level 10. At level 10 and up, their attack strength should increase by the attack_boost amount when they are trained. 72 | 73 | #To test, create an instance of the class with the name as "Bulby". Assign the instance to the variable p2. Create another instance of the Grass_Pokemon class with the name set to "Pika" and assign that instance to the variable p3. Then, use Grass_Pokemon methods to train the p3 Grass_Pokemon instance until it reaches at least level 10. 74 | class Pokemon(object): 75 | attack = 12 76 | defense = 10 77 | health = 15 78 | p_type = "Normal" 79 | 80 | def __init__(self, name, level = 5): 81 | self.name = name 82 | self.level = level 83 | 84 | def train(self): 85 | self.update() 86 | self.attack_up() 87 | self.defense_up() 88 | self.health_up() 89 | self.level = self.level + 1 90 | if self.level%self.evolve == 0: 91 | return self.level, "Evolved!" 92 | else: 93 | return self.level 94 | 95 | def attack_up(self): 96 | self.attack = self.attack + self.attack_boost 97 | return self.attack 98 | 99 | def defense_up(self): 100 | self.defense = self.defense + self.defense_boost 101 | return self.defense 102 | 103 | def health_up(self): 104 | self.health = self.health + self.health_boost 105 | return self.health 106 | 107 | def update(self): 108 | self.health_boost = 5 109 | self.attack_boost = 3 110 | self.defense_boost = 2 111 | self.evolve = 10 112 | 113 | def __str__(self): 114 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 115 | 116 | class Grass_Pokemon(Pokemon): 117 | attack = 15 118 | defense = 14 119 | health = 12 120 | p_type = "Grass" 121 | 122 | def update(self): 123 | self.health_boost = 6 124 | self.attack_boost = 2 125 | self.defense_boost = 3 126 | self.evolve = 12 127 | 128 | def train(self): 129 | self.update() 130 | if self.level >= 10: 131 | self.attack_up() 132 | self.defense_up() 133 | self.health_up() 134 | self.level = self.level + 1 135 | if self.level%self.evolve == 0: 136 | return self.level, "Evolved!" 137 | else: 138 | return self.level 139 | 140 | def moves(self): 141 | self.p_moves = ["razor leaf", "synthesis", "petal dance"] 142 | 143 | 144 | p2 = Grass_Pokemon("Bulby", level = 5) 145 | p3 = Grass_Pokemon("Pika", level = 5) 146 | p3.train() 147 | 148 | 149 | #Along with the Pokemon parent class, we have also provided several subclasses. Write another method in the parent class that will be inherited by the subclasses. Call it opponent. It should return which type of pokemon the current type is weak and strong against, as a tuple. 150 | 151 | # Grass is weak against Fire and strong against Water 152 | # Ghost is weak against Dark and strong against Psychic 153 | # Fire is weak against Water and strong against Grass 154 | # Flying is weak against Electric and strong against Fighting 155 | # For example, if the p_type of the subclass is 'Grass', .opponent() should return the tuple ('Fire', 'Water') 156 | 157 | class Pokemon(): 158 | attack = 12 159 | defense = 10 160 | health = 15 161 | p_type = "Normal" 162 | 163 | def __init__(self, name,level = 5): 164 | self.name = name 165 | self.level = level 166 | self.weak = "Normal" 167 | self.strong = "Normal" 168 | 169 | def train(self): 170 | self.update() 171 | self.attack_up() 172 | self.defense_up() 173 | self.health_up() 174 | self.level = self.level + 1 175 | if self.level%self.evolve == 0: 176 | return self.level, "Evolved!" 177 | else: 178 | return self.level 179 | 180 | def attack_up(self): 181 | self.attack = self.attack + self.attack_boost 182 | return self.attack 183 | 184 | def defense_up(self): 185 | self.defense = self.defense + self.defense_boost 186 | return self.defense 187 | 188 | def health_up(self): 189 | self.health = self.health + self.health_boost 190 | return self.health 191 | 192 | def update(self): 193 | self.health_boost = 5 194 | self.attack_boost = 3 195 | self.defense_boost = 2 196 | self.evolve = 10 197 | 198 | def __str__(self): 199 | self.update() 200 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 201 | 202 | def opponent(self): 203 | return self.weak, self.strong 204 | 205 | class Grass_Pokemon(Pokemon): 206 | attack = 15 207 | defense = 14 208 | health = 12 209 | p_type = "Grass" 210 | 211 | def __init__(self, name,level = 5): 212 | self.name = name 213 | self.level = level 214 | self.weak = "Fire" 215 | self.strong = "Water" 216 | 217 | def update(self): 218 | self.health_boost = 6 219 | self.attack_boost = 2 220 | self.defense_boost = 3 221 | self.evolve = 12 222 | 223 | class Ghost_Pokemon(Pokemon): 224 | p_type = "Ghost" 225 | 226 | def __init__(self, name,level = 5): 227 | self.name = name 228 | self.level = level 229 | self.weak = "Dark" 230 | self.strong = "Psychic" 231 | 232 | def update(self): 233 | self.health_boost = 3 234 | self.attack_boost = 4 235 | self.defense_boost = 3 236 | 237 | class Fire_Pokemon(Pokemon): 238 | p_type = "Fire" 239 | 240 | def __init__(self, name,level = 5): 241 | self.name = name 242 | self.level = level 243 | self.weak = "Water" 244 | self.strong = "Grass" 245 | 246 | class Flying_Pokemon(Pokemon): 247 | p_type = "Flying" 248 | 249 | def __init__(self, name,level = 5): 250 | self.name = name 251 | self.level = level 252 | self.weak = "Electric" 253 | self.strong = "Fighting" -------------------------------------------------------------------------------- /course_4_project.py: -------------------------------------------------------------------------------- 1 | VOWEL_COST = 250 2 | LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 3 | VOWELS = 'AEIOU' 4 | 5 | # Write the WOFPlayer class definition (part A) here 6 | class WOFPlayer(): 7 | def __init__(self, initName): 8 | self.name = initName 9 | self.prizeMoney = 0 10 | self.prizes = [] 11 | def goBankrupt(self): 12 | self.prizeMoney = 0 13 | def addPrize(self, prize): 14 | self.prizes.append(prize) 15 | def addMoney(self,amt): 16 | self.prizeMoney = self.prizeMoney + amt 17 | def __str__(self): 18 | state = self.name + " ($" + str(self.prizeMoney) + ")" 19 | return state 20 | # Write the WOFHumanPlayer class definition (part B) here 21 | class WOFHumanPlayer(WOFPlayer): 22 | def getMove(category, obscuredPhrase, guessed): 23 | str = input(self.name + "has $"+ str(self.prizeMoney)+ "/n" + ", Category:" + category + "/n" + ", Phrases:" + "/n" + obscuredPhrase + "/n" + ", Guessed:" + guessed + "/n" + "Guess a letter, phrase, or type 'exit' or 'pass':") 24 | print(str) 25 | # Write the WOFComputerPlayer class definition (part C) here 26 | class WOFComputerPlayer(WOFPlayer): 27 | SORTED_FREQUENCIES = 'ZQXJKVBPYGFWMUCLDRHSNIOATE' 28 | prizemoney = 0 29 | def __init__(self, name, difficulty): 30 | self.name = name 31 | self.difficulty = difficulty 32 | self.prizeMoney = 0 33 | self.prizes = [] 34 | 35 | def smartCoinFlip(self): 36 | if random.randint(1, 10) > self.difficulty: 37 | return True 38 | else: 39 | return False 40 | 41 | def getPossibleLetters(self, guessed): 42 | list = [] 43 | if self.prizemoney >= 250: 44 | for l in LETTERS: 45 | list.append(l) 46 | else: 47 | for l in LETTERS: 48 | if l not in VOWELS: 49 | list.append(l) 50 | return list 51 | 52 | def getMove(self, category, obscuredPhrase, guessed): 53 | list = self.getPossibleLetters(guessed) 54 | FlipResult = self.smartCoinFlip() 55 | if len(list) == 0: 56 | return 'pass' 57 | else: 58 | if FlipResult==True: 59 | for l in self.SORTED_FREQUENCIES: 60 | if l in list: 61 | return l 62 | elif FlipResult==False: 63 | return random.choice(list) 64 | -------------------------------------------------------------------------------- /formulas.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | return (x * x) 3 | 4 | def add(x,y): 5 | return (x+y) 6 | 7 | def sub(x,y): 8 | return (x-y) 9 | -------------------------------------------------------------------------------- /list.py: -------------------------------------------------------------------------------- 1 | mylist = [] 2 | mylist.append(5) 3 | mylist.append(27) 4 | mylist.append(3) 5 | mylist.append(12) 6 | print(mylist) 7 | 8 | mylist.insert(1, 12) 9 | print(mylist) 10 | print(mylist.count(12)) 11 | 12 | print(mylist.index(3)) 13 | print(mylist.count(5)) 14 | 15 | mylist.reverse() 16 | print(mylist) 17 | 18 | mylist.sort() 19 | print(mylist) 20 | 21 | mylist.remove(5) 22 | print(mylist) 23 | 24 | lastitem = mylist.pop() 25 | print(lastitem) 26 | print(mylist) 27 | -------------------------------------------------------------------------------- /rough.py: -------------------------------------------------------------------------------- 1 | a = ["holiday", "celebrate!"] 2 | quiet = a 3 | quiet.append("company") --------------------------------------------------------------------------------