├── Python Functions, Files, and Dictionaries ├── week-5 │ ├── Peer graded project.md │ ├── Sorting.py │ └── Sentimental classifier.py ├── week-3 │ ├── Tuples.py │ └── Functions.py ├── week-1 │ └── Assement files and dict.py ├── week-4 │ ├── More about iteration.py │ └── Advance functions.py └── week-2 │ ├── Dictionary mechanics.py │ └── Dictionary Accumulation.py ├── Python Project: pillow, tesseract, and opencv ├── Week-1 │ └── Final project.md └── Week-3 │ └── Final project.md ├── README.md ├── LICENSE ├── Python Classes and Inheritance ├── week-1 │ └── Python Classes and Inheritance.py └── week-2 │ └── Week two (2).py ├── Python basic ├── week-4 │ ├── Accumulating Lists and Strings.md │ ├── Lists and Strings.md │ ├── Sequence Mutation.md │ └── Way of the Programmer Week Four.md ├── week-1 │ ├── Programming in Python.py │ └── Turtle Graphics.md ├── week-2 │ ├── Lists and Strings.py │ └── Week two.py └── week-3 │ └── Week three.py ├── Data Collection and Processing with Python ├── week-2 │ └── Advanced Accumulation.py ├── week-1 │ └── Nested Data and Iteration.py └── week-3 │ └── OMDB and TasteDive Mashup.py └── CODE_OF_CONDUCT.md /Python Functions, Files, and Dictionaries/week-5/Peer graded project.md: -------------------------------------------------------------------------------- 1 | ![](https://coursera-assessments.s3.amazonaws.com/assessments/1592112135400/b1a20ec6-8521-4039-cc07-bd65ab3f4307/Capture.PNG) 2 | -------------------------------------------------------------------------------- /Python Project: pillow, tesseract, and opencv/Week-1/Final project.md: -------------------------------------------------------------------------------- 1 | [Final project pdf](https://coursera-assessments.s3.amazonaws.com/assessments/1600604635354/8be3203c-d916-4c40-f8d3-e8bc3700b0e6/pillow%20assignment.pdf) 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # py3_programming 2 | Python 3 Specialization - University of Michigan - Coursera 3 | This repository contains the exercises, assignments and experiments I did as part of completing the Python 3 Programming Specialization on Coursera. ( https://www.coursera.org/specializations/python-3-programming ) 4 | The parent folders represent the first 4 out of 5 courses: 5 | * Python Basics 6 | * Python Functions, Files, and Dictionaries 7 | * Data Collection and Processing with Python 8 | * Python Classes and Inheritance 9 | 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Bhavesh Yadav 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python Classes and Inheritance/week-1/Python Classes and Inheritance.py: -------------------------------------------------------------------------------- 1 | #Q-1. 2 | 3 | class Bike: 4 | 5 | def __init__(self, color, price): 6 | self.color = color 7 | self.price = price 8 | 9 | testOne = Bike("blue", 89.99) 10 | testTwo = Bike("purple", 25.0) 11 | 12 | #Q-2. 13 | 14 | class AppleBasket: 15 | 16 | def __init__(self, apple_color, apple_quantity): 17 | self.apple_color = apple_color 18 | self.apple_quantity = apple_quantity 19 | 20 | def increase(self): 21 | return self.apple_quantity + 1 22 | 23 | def increase(self): 24 | self.apple_quantity = self.apple_quantity + 1 25 | 26 | def __str__(self): 27 | return "A basket of {} {} apples.".format(self.apple_quantity, self.apple_color) 28 | 29 | testone = AppleBasket('red', 8) 30 | print(testone) 31 | testone.increase() 32 | print(testone) 33 | 34 | #Q-3. 35 | 36 | class BankAccount: 37 | 38 | def __init__(self, name, amt): 39 | self.name = name 40 | self.amt = amt 41 | 42 | def __str__(self): 43 | return "Your account, {}, has {} dollars.".format(self.name, self.amt) 44 | 45 | t1 = BankAccount("Bob", 100) 46 | print(t1) 47 | -------------------------------------------------------------------------------- /Python basic/week-4/Accumulating Lists and Strings.md: -------------------------------------------------------------------------------- 1 | #### Q-1. Which of these is the accumulator variable? 2 | ``` 3 | byzo = 'hello world!' 4 | c = 0 5 | for x in byzo: 6 | z = x + "!" 7 | print(z) 8 | c = c + 1 9 | ``` 10 | #### Answer: D. c 11 | 12 | #### Q-2. Which of these is the sequence? 13 | ``` 14 | cawdra = ['candy', 'daisy', 'pear', 'peach', 'gem', 'crown'] 15 | t = 0 16 | for elem in cawdra: 17 | t = t + len(elem) 18 | ``` 19 | #### Answer: A. cawdra 20 | 21 | #### Q-3. Which of these is the iterator (loop) variable? 22 | ``` 23 | lst = [5, 10, 3, 8, 94, 2, 4, 9] 24 | num = 0 25 | for item in lst: 26 | num += item 27 | ``` 28 | #### Answer: A. item 29 | 30 | #### Q-4. What is the iterator (loop) variable in the following? 31 | ``` 32 | rest = ["sleep", 'dormir', 'dormire', "slaap", 'sen', 'yuxu', 'yanam'] 33 | let = '' 34 | for phrase in rest: 35 | let += phrase[0] 36 | ``` 37 | #### Answer: phrase 38 | 39 | #### Q-5. 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. 40 | ``` 41 | str1 = "I love python" 42 | # HINT: what's the accumulator? That should go here. 43 | chars = [] 44 | for i in str1: 45 | a =i 46 | chars.append(a) 47 | print(chars) 48 | ``` 49 | -------------------------------------------------------------------------------- /Python basic/week-1/Programming in Python.py: -------------------------------------------------------------------------------- 1 | '''Q-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). 2 | Use the square function, rather than just multiplying with ''' 3 | 4 | xyz = square(5) 5 | print(xyz) 6 | 7 | '''Q-2: Write code to assign the number of characters in the string rv to a variable num_chars''' 8 | 9 | rv = """Once upon a midnight dreary, while I pondered, weak and weary, 10 | Over many a quaint and curious volume of forgotten lore, 11 | While I nodded, nearly napping, suddenly there came a tapping, 12 | As of some one gently rapping, rapping at my chamber door. 13 | 'Tis some visitor, I muttered, tapping at my chamber door; 14 | Only this and nothing more.""" 15 | 16 | # Write your code here! 17 | num_chars=len(rv) 18 | print(num_chars) 19 | 20 | 21 | '''Q-3: data-19-1: The code below initializes two variables, z and y. We want to assign the total number of characters in z and in y to the variable a. 22 | Which of the following solutions, if any, would be considered hard coding?''' 23 | 24 | z = "hello world" 25 | y = "welcome!" 26 | 27 | #a = len("hello worldwelcome!") 28 | #a = 11 + 8 29 | #a = len("hello world") + len("welcome!") 30 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-3/Tuples.py: -------------------------------------------------------------------------------- 1 | ''' Q-1. Create a tuple called olympics with four elements: “Beijing”, “London”, “Rio”, “Tokyo”.''' 2 | 3 | olympics = ("Beijing", "London", "Rio", "Tokyo") 4 | print(olympics) 5 | 6 | ''' Q-2. The list below, tuples_lst, is a list of tuples. Create a list of the second elements of each tuple and assign this 7 | list to the variable country.''' 8 | 9 | tuples_lst = [('Beijing', 'China', 2008), ('London', 'England', 2012), ('Rio', 'Brazil', 2016, 'Current'), ('Tokyo', 'Japan', 2020, 'Future')] 10 | country = [lis[1] for lis in tuples_lst] 11 | print(country) 12 | 13 | ''' Q-3. 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 | 18 | ''' Q-4. Define a function called info with five parameters: name, gender, age, bday_month, and hometown. The function should then return a 19 | tuple with all five parameters in that order.''' 20 | 21 | def info(name, gender, age, bday_month, hometown): 22 | z = (name, gender, age, bday_month, hometown) 23 | return z 24 | 25 | print(info("shantanu", "male", "18", "1982", "locknow")) 26 | 27 | ''' Q-5. Given is the dictionary, gold, which shows the country and the number of gold medals they have earned so far in the 2016 Olympics. 28 | Create a list, num_medals, that contains only the number of medals for each country. You must use the .items() method. Note: The .items() 29 | method provides a list of tuples. Do not use .keys() method.''' 30 | 31 | gold = {'USA':31, 'Great Britain':19, 'China':19, 'Germany':13, 'Russia':12, 'Japan':10, 'France':8, 'Italy':8} 32 | 33 | num_medals=[] 34 | for i in gold.items(): 35 | num_medals.append(i[1]) 36 | -------------------------------------------------------------------------------- /Python basic/week-4/Lists and Strings.md: -------------------------------------------------------------------------------- 1 | #### Q-1. Which method would you use to figure out the position of an item in a list? 2 | ``` 3 | A. .pop() 4 | B. .insert() 5 | C. .count() 6 | D. .index() 7 | ``` 8 | #### Answer: D 9 | 10 | #### Q-2. Which method is best to use when adding an item to the end of a list? 11 | ``` 12 | A. .insert() 13 | B. .pop() 14 | C. .append() 15 | D. .remove() 16 | ``` 17 | #### Answer: C 18 | 19 | #### Q-3. Write code to add ‘horseback riding’ to the third position (i.e., right before volleyball) in the list sports 20 | ``` 21 | sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] 22 | a = sports.insert(2, 'horseback riding') 23 | print(a) 24 | ``` 25 | 26 | #### Q-4. Write code to take ‘London’ out of the list trav_dest. 27 | ``` 28 | trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'London', 'Melbourne'] 29 | a = trav_dest.remove('London') 30 | print(a) 31 | ``` 32 | 33 | #### Q-5. Write code to add ‘Guadalajara’ to the end of the list trav_dest using a list method. 34 | ``` 35 | trav_dest = ['Beirut', 'Milan', 'Pittsburgh', 'Buenos Aires', 'Nairobi', 'Kathmandu', 'Osaka', 'Melbourne'] 36 | a = trav_dest.append('Guadalajara') 37 | print(a) 38 | ``` 39 | 40 | #### Q-6. Write code to rearrange the strings in the list winners so that they are in alphabetical order from A to Z. 41 | ``` 42 | winners = ['Kazuo Ishiguro', 'Rainer Weiss', 'Youyou Tu', 'Malala Yousafzai', 'Alice Munro', 'Alvin E. Roth'] 43 | a = winners.sort() 44 | print(a) 45 | ``` 46 | 47 | #### Q-7. 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. 48 | ``` 49 | winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'] 50 | 51 | z_winners = winners[::-1] 52 | print(z_winners) 53 | ``` 54 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-3/Functions.py: -------------------------------------------------------------------------------- 1 | ''' Q-1. Write a function called int_return that takes an integer as input and returns the same integer.''' 2 | 3 | def int_return(i): 4 | return i 5 | z=int(input()) 6 | int_return(z) 7 | 8 | 9 | ''' Q-2. Write a function called add that takes any number as its input and returns that sum with 2 added.''' 10 | 11 | def add(x): 12 | sum = x+2 13 | return sum 14 | a=int(input()) 15 | add(a) 16 | 17 | 18 | ''' Q-3. 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.''' 19 | 20 | def change(v): 21 | return v+'Nice to meet you!' 22 | 23 | v=input("Enter the string: ") 24 | change(v) 25 | 26 | 27 | ''' Q-4. Write a function, accum, that takes a list of integers as input and returns the sum of those integers.''' 28 | 29 | def accum(lst): 30 | j=0 31 | for i in lst: 32 | j=j+i 33 | return j 34 | lst=[1,2,3,4,5,6,7,8,9] 35 | accum(lst) 36 | 37 | 38 | ''' Q-5. Write a function, length, that takes in a list as the input. 39 | If the length of the list is greater than or equal to 5, return “Longer than 5”. 40 | If the length is less than 5, return “Less than 5”.''' 41 | 42 | 43 | def length(lst): 44 | if len(lst)>=5: 45 | return 'Longer than 5' 46 | else: 47 | return 'Less than 5' 48 | 49 | lst=list(input()) 50 | length(lst) 51 | 52 | 53 | '''Q-6 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. 54 | 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. 55 | Do not worry about decimals.''' 56 | 57 | def divide(n): 58 | return n/2 59 | def sum(n): 60 | return n/2+6 61 | 62 | sum(divide(10)) 63 | -------------------------------------------------------------------------------- /Python basic/week-2/Lists and Strings.py: -------------------------------------------------------------------------------- 1 | '''Q-1: What will the output be for the following code? 2 | let = "z" 3 | let_two = "p" 4 | c = let_two + let 5 | m = c*5 6 | print(m)''' 7 | #Answer : 8 | # pzpzpzpzpz 9 | 10 | 11 | '''Q-2: Write a program that extracts the last three items in the list sports and assigns it to the variable last. 12 | Make sure to write your code so that it works no matter how many items are in the list.''' 13 | 14 | sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey'] 15 | last=sports[-3:] 16 | print(last) 17 | 18 | 19 | '''Q-3: 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. 20 | Do not edit the values assigned to by, az, io, or qy.''' 21 | 22 | by = "You are" 23 | az = "doing a great " 24 | io = "job" 25 | qy = "keep it up!" 26 | message=by+" "+az+io+","+" "+qy 27 | print(message) 28 | 29 | 30 | '''Q-4: What will the output be for the following code? 31 | ls = ['run', 'world', 'travel', 'lights', 'moon', 'baseball', 'sea'] 32 | new = ls[2:4] 33 | print(new)''' 34 | 35 | #Answer : 36 | # ['travel', 'lights'] 37 | 38 | 39 | '''Q-5: What is the type of m? 40 | l = ['w', '7', 0, 9] 41 | m = l[1:2]''' 42 | 43 | #Answer : 44 | # list 45 | 46 | 47 | '''Q-6: What is the type of m? 48 | l = ['w', '7', 0, 9] 49 | m = l[1]''' 50 | 51 | #Answer : 52 | # string 53 | 54 | 55 | '''Q-7: What is the type of x? 56 | b = "My, what a lovely day" 57 | x = b.split(',')''' 58 | 59 | #Answer : 60 | # list 61 | 62 | 63 | '''Q-8: What is the type of a? 64 | b = "My, what a lovely day" 65 | x = b.split(',') 66 | z = "".join(x) 67 | y = z.split() 68 | a = "".join(y)''' 69 | 70 | #Answer : 71 | # string 72 | 73 | 74 | -------------------------------------------------------------------------------- /Python basic/week-4/Sequence Mutation.md: -------------------------------------------------------------------------------- 1 | ### Could aliasing cause potential confusion in this problem? 2 | ``` 3 | b = ['q', 'u', 'i'] 4 | z = b 5 | b[1] = 'i' 6 | z.remove('i') 7 | print(z) 8 | ``` 9 | #### Answer : Yes 10 | 11 | ### Could aliasing cause potential confusion in this problem? 12 | ``` 13 | sent = "Holidays can be a fun time when you have good company!" 14 | phrase = sent 15 | phrase = phrase + " Holidays can also be fun on your own!" 16 | ``` 17 | #### Answer : No 18 | 19 | ### Which of these is a correct reference diagram following the execution of the following code? 20 | ``` 21 | lst = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'] 22 | lst.remove('pluto') 23 | first_three = lst[:3] 24 | ``` 25 | #### 1. 26 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a1_1.png) 27 | #### 2. 28 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a1_2.png) 29 | #### Answer : 1 30 | 31 | ### Which of these is a correct reference diagram following the execution of the following code? 32 | ``` 33 | x = ["dogs", "cats", "birds", "reptiles"] 34 | y = x 35 | x += ['fish', 'horses'] 36 | y = y + ['sheep'] 37 | ``` 38 | #### 1. 39 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a3_1.png) 40 | #### 2. 41 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a3_2.png) 42 | #### 3. 43 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a3_3.png) 44 | #### 4. 45 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a3_4.png) 46 | #### Answer : 4 47 | 48 | ### Which of these is a correct reference diagram following the execution of the following code? 49 | ``` 50 | sent = "The mall has excellent sales right now." 51 | wrds = sent.split() 52 | wrds[1] = 'store' 53 | new_sent = " ".join(wrds) 54 | ``` 55 | #### 1. 56 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a2_1.png) 57 | #### 2. 58 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a2_2.png) 59 | #### 3. 60 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a2_3.png) 61 | #### 4. 62 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a2_4.png) 63 | 64 | #### Answer : 1 65 | -------------------------------------------------------------------------------- /Python basic/week-1/Turtle Graphics.md: -------------------------------------------------------------------------------- 1 | #### What are correct ways to tell a turtle named Tex to move forward 20 pixels? Select as many as apply 2 | ``` 3 | A. Tex.forward(20) 4 | B. forward() + 20 5 | C. forward(20) 6 | D. forward(20).Tex 7 | E. Tex.forward(10 + 10) 8 | ``` 9 | ##### Answer : A, E 10 | 11 | #### Which is the correct way to make a new instance of the Turtle class? 12 | ``` 13 | A. turtle(Turtle) 14 | B. turtle.Turtle() 15 | C. Turtle.turtle() 16 | D. Turtle(turtle) 17 | ``` 18 | ##### Answer : B 19 | 20 | #### What does each instance of the Turtle class represent? 21 | ``` 22 | A. The turtle class. 23 | B. The same turtle that is used in each drawing your programs make. 24 | C. A unique 'turtle' that you can use to draw. 25 | ``` 26 | ##### Answer : C 27 | 28 | #### True or False, attributes/instance variables are just like other variables in Python. 29 | ``` 30 | A. True 31 | B. False 32 | ``` 33 | ##### Answer : A 34 | 35 | #### Select all of the following things that methods can do: 36 | ``` 37 | A. Change the value of an attribute. 38 | B. Return values. 39 | C. Create new attributes of an instance and set their values. 40 | D. Delete object instances. 41 | E. None of the above. 42 | ``` 43 | ##### Answer : A, B, and C 44 | 45 | #### For an instance of a class that is assigned to the variable student, what is the proper way to refer to the title attribute/instance variable? 46 | ``` 47 | A. student.title() 48 | B. title.student() 49 | C. title.student 50 | D. student(title) 51 | E. student.title 52 | ``` 53 | ##### Answer : E 54 | 55 | #### What is the name of jane’s attribute (not method) that is referred to in the following code? 56 | ``` 57 | import turtle 58 | 59 | jane = turtle.Turtle() 60 | jane.forward(20) 61 | print(jane.x) 62 | ``` 63 | ##### Answer : 64 | 65 | | x | 66 | |-----------------| 67 | 68 | 69 | #### What are the names of the instances in the following code? Please put one instance per blank space and enter them in the order that the computer would read them. 70 | ``` 71 | import turtle 72 | wn = turtle.Screen() 73 | 74 | jazz = turtle.Turtle() 75 | jazz.forward(50) 76 | jazz.right(90) 77 | pop = turtle.Turtle() 78 | pop.left(180) 79 | pop.forward(76) 80 | ``` 81 | ##### Answer : 82 | 83 | | wn | jazz | pop | 84 | |-----------------|:-------------|:---------------:| 85 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-1/Assement files and dict.py: -------------------------------------------------------------------------------- 1 | ''' Q-1. The textfile, travel_plans.txt, contains the summer travel plans for someone with some commentary. 2 | Find the total number of characters in the file and save to the variable num.''' 3 | 4 | with open("travel_plans.txt","r") as file: 5 | file_char=file.read() 6 | num = len(file_char) 7 | print(num) 8 | file.close() 9 | 10 | ''' Q-2. We have provided a file called emotion_words.txt that contains lines of words that describe emotions. 11 | Find the total number of words in the file and assign this value to the variable num_words.''' 12 | 13 | num_words=0 14 | with open("emotion_words.txt","r") as file: 15 | for words in file: 16 | num_words+=len(words.split()) 17 | file.close() 18 | 19 | ''' Q-3. Assign to the variable num_lines the number of lines in the file school_prompt.txt.''' 20 | 21 | file=open("school_prompt.txt","r") 22 | char_y=file.readlines() 23 | num_lines=len(char_y) 24 | print(num_lines) 25 | file.close() 26 | 27 | ''' Q-4. Assign the first 30 characters of school_prompt.txt as a string to the variable beginning_chars''' 28 | 29 | file=open("school_prompt.txt","r") 30 | char_y=file.read() 31 | beginning_chars=str(char_y[:30]) 32 | print(beginning_chars) 33 | file.close() 34 | 35 | ''' Q-5. Challenge: Using the file school_prompt.txt, assign the third word of every line to a list called three.''' 36 | 37 | three = [] 38 | 39 | with open('school_prompt.txt', 'r') as f: 40 | three = [line.split()[2] for line in f] 41 | print(three) 42 | 43 | ''' Q-6 Challenge: Create a list called emotions that contains the first word of every line in emotion_words.txt.''' 44 | emotions = [] 45 | 46 | with open('emotion_words.txt', 'r') as f: 47 | emotions = [line.split()[0] for line in f] 48 | print(emotions) 49 | 50 | '''Q-7 Assign the first 33 characters from the textfile, travel_plans.txt to the variable first_chars.''' 51 | 52 | f = open('travel_plans.txt', 'r') 53 | first_chars = f.read(33) 54 | print(first_chars) 55 | 56 | '''Q-8 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.''' 57 | 58 | fileref = open('school_prompt.txt', 'r') 59 | words = fileref.read().split() 60 | p_words = [word for word in words if 'p' in word] 61 | 62 | 63 | -------------------------------------------------------------------------------- /Data Collection and Processing with Python/week-2/Advanced Accumulation.py: -------------------------------------------------------------------------------- 1 | #Q-1. 2 | lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya'] 3 | map_testing=map(lambda st:'Fruit: '+st ,lst_check) 4 | print(map_testing) 5 | 6 | 7 | #Q-2. 8 | 9 | countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium'] 10 | b_countries=filter(lambda strn:strn[0]=='B',countries) 11 | 12 | 13 | #Q-3. 14 | 15 | 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')] 16 | first_names=[name[1] for name in people] 17 | print(first_names) 18 | 19 | 20 | #Q-4. 21 | 22 | lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4] 23 | lst2 =[element*2 for element in lst] 24 | print(lst2) 25 | 26 | 27 | #Q-5 28 | 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}} 29 | london_gold=nested_d['London']['Great Britain'] 30 | 31 | #Q-6 32 | students = [('Tommy', 95), ('Linda', 63), ('Carl', 70), ('Bob', 100), ('Raymond', 50), ('Sue', 75)] 33 | passed=[num[0] for num in students if num[1]>=70] 34 | print(passed) 35 | 36 | 37 | 38 | #Q-7 39 | l1 = ['left', 'up', 'front'] 40 | l2 = ['right', 'down', 'back'] 41 | l3 = zip(l1, l2) 42 | print(l3) 43 | opposites = list(filter(lambda s: len(s[0])>3 and len(s[1])>3, l3)) 44 | print(opposites) 45 | 46 | 47 | #Q-8 48 | 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'] 49 | 50 | population = [10000, 90000, 1000, 2000000, 500000, 500, 1200, 8000, 12000, 2300, 7500, 100, 1800, 9500, 125000] 51 | pop_info = list(zip(species,population)) 52 | print(pop_info) 53 | endangered = [name[0] for name in pop_info if name[1]<2500] 54 | print(endangered) 55 | -------------------------------------------------------------------------------- /Python basic/week-3/Week three.py: -------------------------------------------------------------------------------- 1 | ''' Q-1. rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month 2 | (in inches) with every month separated by a comma. Write code to compute the number of months that have more than 3 3 | inches of rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items 4 | with values > 3.0. 5 | Hard-coded answers will receive no credit.''' 6 | 7 | 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" 8 | rainfall_mi = rainfall_mi.split(",") 9 | lst_rainfall = list(rainfall_mi) 10 | lst_rainfall= [float(n) for n in lst_rainfall] 11 | num_rainy_months = 0 12 | for i in lst_rainfall: 13 | if i>3.0: 14 | num_rainy_months+=1 15 | 16 | 17 | print(num_rainy_months) 18 | 19 | ''' Q-2. The variable sentence stores a string. Write code to determine how many words in sentence start and end with 20 | the same letter, including one-letter words. Store the result in the variable same_letter_count. 21 | Hard-coded answers will receive no credit.''' 22 | 23 | sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking" 24 | lst = sentence.split(" ") 25 | same_letter_count = 0 26 | for i in lst: 27 | if i[0] == i[-1]: 28 | same_letter_count+=1 29 | 30 | 31 | print(same_letter_count) 32 | 33 | ''' Q-3. 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. 34 | HINT 1: Use the accumulation pattern! 35 | HINT 2: the in operator checks whether a substring is present in a string. 36 | Hard-coded answers will receive no credit.''' 37 | 38 | items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] 39 | acc_num = 0 40 | for i in items: 41 | if 'w' in i: 42 | acc_num+=1 43 | 44 | print(acc_num) 45 | 46 | ''' Q-4. 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. 47 | Note 1: be sure to not double-count words that contain both an a and an e. 48 | HINT 1: Use the in operator. 49 | HINT 2: You can either use or or elif. 50 | Hard-coded answers will receive no credit.''' 51 | 52 | sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems." 53 | words = sentence.split(" ") 54 | num_a_or_e = 0 55 | for i in words: 56 | if (('a' in i) or ('e' in i)) : 57 | num_a_or_e+=1 58 | 59 | print(num_a_or_e) 60 | 61 | ''' Q-5. 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, 62 | vowels are only a, e, i, o, and u. Hint: use the in operator with vowels.''' 63 | 64 | s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun" 65 | vowels = ['a','e','i','o','u'] 66 | s = list(s) 67 | num_vowels = 0 68 | for i in s: 69 | for j in i: 70 | if j in vowels: 71 | num_vowels+=1 72 | 73 | print(num_vowels) 74 | -------------------------------------------------------------------------------- /Python Project: pillow, tesseract, and opencv/Week-3/Final project.md: -------------------------------------------------------------------------------- 1 | ``` 2 | import zipfile 3 | 4 | from PIL import Image 5 | import pytesseract 6 | import cv2 as cv 7 | import numpy as np 8 | 9 | # loading the face detection classifier 10 | face_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml') 11 | 12 | # the rest is up to you! 13 | images = {} # dictionary of lists indexed with filenames 14 | # [0] : PIL Image File 15 | # [1] : Text in image 16 | 17 | name_list = [] # list of filenames 18 | 19 | def unzip_images(zip_name): 20 | ''' 21 | iterates over images in a zipfile and extracts and modifies global dictionary for all 22 | also creates a namelist containing all names of all images in the zipfile 23 | ''' 24 | zf = zipfile.ZipFile(zip_name) 25 | for each in zf.infolist(): 26 | images[each.filename] = [Image.open(zf.open(each.filename))] 27 | name_list.append(each.filename) 28 | # print(each.filename) 29 | 30 | if __name__ == '__main__': 31 | # working with a global data structure using HINTS 1 and 2 32 | 33 | # unzip_images('readonly/small_img.zip') 34 | unzip_images('readonly/images.zip') 35 | 36 | for name in name_list: 37 | # display(images[name][0]) 38 | # print(name) 39 | img = images[name][0] 40 | 41 | images[name].append(pytesseract.image_to_string(img).replace('-\n','')) 42 | # using string data to omit line separators "-\n" in the data 43 | # modifying global data structure to append text present in each image 44 | 45 | # print(images[name][1]) 46 | 47 | if 'Mark' in images[name][1]: 48 | # using HINT 3 49 | print('Results found in file',name) 50 | 51 | try: 52 | faces = (face_cascade.detectMultiScale(np.array(img),1.35,4)).tolist() 53 | # storing the bounding boxes of all faces detected in each image of iteration 54 | 55 | images[name].append(faces) 56 | # modifying global data structure to append faces present in each image 57 | 58 | faces_in_each = [] 59 | 60 | for x,y,w,h in images[name][2]: 61 | faces_in_each.append(img.crop((x,y,x+w,y+h))) 62 | # modifying local data structure in each iteration to sotre PIL Image of each face 63 | # display((img.crop((x,y,x+w,y+h))).resize((110,110))) 64 | 65 | contact_sheet = Image.new(img.mode, (550,110*int(np.ceil(len(faces_in_each)/5)))) 66 | # contact sheet modification to display each iteration's result 67 | x = 0 68 | y = 0 69 | 70 | for face in faces_in_each: 71 | face.thumbnail((110,110)) 72 | # using HINT 4 73 | contact_sheet.paste(face, (x, y)) 74 | 75 | if x+110 == contact_sheet.width: 76 | x=0 77 | y=y+110 78 | else: 79 | x=x+110 80 | 81 | display(contact_sheet) 82 | except: 83 | print('But there were no faces in that file!') 84 | 85 | ``` 86 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-4/More about iteration.py: -------------------------------------------------------------------------------- 1 | ''' Q-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 2 | 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 3 | not contain the number 5).''' 4 | 5 | def sublist(x): 6 | sub = [] 7 | x = (num for num in x) 8 | num = next(x, 5) 9 | while num != 5: 10 | sub.append(num) 11 | num = next(x, 5) 12 | print(sub) 13 | return sub 14 | x = [1, 2,3,4,5,1,2,3] 15 | sublist(x) 16 | 17 | ''' Q-2. Write a function called check_nums that takes a list as its parameter, and contains a while loop that only stops once the element 18 | of the list is the number 7. What is returned is a list of all of the numbers up until it reaches ''' 19 | 20 | def check_nums(x): 21 | sub = [] 22 | x = (num for num in x) 23 | num = next(x, 7) 24 | while num != 7: 25 | sub.append(num) 26 | num = next(x, 7) 27 | 28 | 29 | return sub 30 | 31 | ''' Q-3. 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 32 | 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 33 | contain the string “STOP”).''' 34 | 35 | def sublist(list): 36 | i = 0 37 | while i < len(list): 38 | if list[i] == "STOP": 39 | return list[0:i] 40 | i+=1 41 | return list[0:i] 42 | 43 | print(sublist(["mujju", "randi", "shona", "dhona", "STOP"])) 44 | 45 | ''' Q-4. 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 46 | the string that appears is “z”. The function should return the new list.''' 47 | 48 | def stop_at_z(list): 49 | i = 0 50 | while i < len(list): 51 | if list[i] == 'z': 52 | return list[0:i] 53 | i+=1 54 | return list[0:i] 55 | print(stop_at_z(['a', 'bhav', 'mc', 'z', 'as'])) 56 | 57 | ''' Q-5.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 58 | of a for loop. Assign the accumulated total in the while loop code to the variable sum2. Once complete, sum2 should equal sum1.''' 59 | 60 | sum1 = 0 61 | 62 | lst = [65, 78, 21, 33] 63 | 64 | for x in lst: 65 | sum1 = sum1 + x 66 | 67 | sum2 = 0 68 | x = 0 69 | while x < len(lst): 70 | sum2 = sum2 + lst[x] 71 | x = x + 1 72 | print(sum2) 73 | 74 | ''' Q-6. 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 75 | 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 76 | 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, 77 | do this without slicing''' 78 | 79 | def beginning(x): 80 | n = 0 81 | lst = [] 82 | while 'bye' not in x[n] and n < 10: 83 | lst.append(x[n]) 84 | n = n + 1 85 | return lst 86 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-5/Sorting.py: -------------------------------------------------------------------------------- 1 | '''Q-1. Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.''' 2 | 3 | letters = "alwnfiwaksuezlaeiajsdl" 4 | sorted_letters = sorted(letters, reverse = True) 5 | print(sorted_letters) 6 | 7 | ''' Q-2. Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted.''' 8 | 9 | animals = ['elephant', 'cat', 'moose', 'antelope', 'elk', 'rabbit', 'zebra', 'yak', 'salamander', 'deer', 'otter', 10 | 'minx', 'giraffe', 'goat', 'cow', 'tiger', 'bear'] 11 | animals_sorted = sorted(animals) 12 | print(animals_sorted) 13 | 14 | ''' Q-3. The dictionary, medals, shows the medal count for six countries during the Rio Olympics. Sort the country names 15 | so they appear alphabetically. Save this list to the variable alphabetical.''' 16 | 17 | medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} 18 | alphabetical = sorted(medals) 19 | print(alphabetical) 20 | 21 | ''' Q-4. 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.''' 22 | 23 | medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70} 24 | def g(k,d): 25 | return d[k] 26 | top_three = sorted(medals, reverse = True, key = lambda x:g(x, medals))[:3] 27 | print(top_three) 28 | 29 | ''' Q-5. 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. 30 | Save the new list as most_needed.''' 31 | 32 | most_needed = [] 33 | groceries = {'apples': 5, 'pasta': 3, 'carrots': 12, 'orange juice': 2, 'bananas': 8, 'popcorn': 1, 'salsa': 3, 'cereal': 4, 'coffee': 5, 'granola bars': 15, 34 | 'onions': 7, 'rice': 1, 'peanut butter': 2, 'spinach': 9} 35 | def g(k,d): 36 | return d[k] 37 | most_needed = sorted(groceries, reverse = True, key = lambda x: g(x, groceries)) 38 | 39 | ''' Q-6. 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. 40 | Save the new list as most_needed.Create a function called last_four that takes in an ID number and returns the last four digits. For example, the number 17573005 41 | 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, 42 | sorted_ids. Hint: Remember that only strings can be indexed, so conversions may be needed.''' 43 | 44 | def last_four(x): 45 | return str(x)[-4:] 46 | 47 | 48 | ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] 49 | sorted_ids = sorted(ids, key = last_four) 50 | print(sorted_ids) 51 | 52 | ''' Q-7. 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.''' 53 | 54 | ids = [17573005, 17572342, 17579000, 17570002, 17572345, 17579329] 55 | sorted_id = sorted(ids, key = lambda x: str(x)[-4:]) 56 | print(sorted_id) 57 | 58 | ''' Q-8. Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to the variable lambda_sort.''' 59 | 60 | ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance'] 61 | lambda_sort = sorted(ex_lst, key = lambda x: x[1]) 62 | -------------------------------------------------------------------------------- /Python basic/week-4/Way of the Programmer Week Four.md: -------------------------------------------------------------------------------- 1 | #### Q-1. Which of these is a correct reference diagram following the execution of the following code? 2 | ``` 3 | lst = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto'] 4 | lst.remove('pluto') 5 | first_three = lst[:3] 6 | ``` 7 | 1. 8 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a1_1.png) 9 | 2. 10 | ![](https://fopp.umsi.education/books/published/fopp/_images//week3a1_2.png) 11 | #### Answer: 1 12 | 13 | #### Q-2. What will be the value of a after the following code has executed? 14 | ``` 15 | a = ["holiday", "celebrate!"] 16 | quiet = a 17 | quiet.append("company") 18 | ``` 19 | #### Answer: ["holiday", "celebrate!", "company"] 20 | 21 | #### Q-3. Could aliasing cause potential confusion in this problem? 22 | ``` 23 | b = ['q', 'u', 'i'] 24 | z = b 25 | b[1] = 'i' 26 | z.remove('i') 27 | print(z) 28 | ``` 29 | #### Answer: yes 30 | 31 | #### Q-4. Given that we want to accumulate the total sum of a list of numbers, which of the following accumulator patterns would be appropriate? 32 | #### Answer: 33 | ``` 34 | nums = [4, 5, 2, 93, 3, 5] 35 | s = 0 36 | for n in nums: 37 | s = s + n 38 | ``` 39 | 40 | #### Q-5. Given that we want to accumulate the total number of strings in the list, which of the following accumulator patterns would be appropriate? 41 | #### Answer: 42 | ``` 43 | lst = ['plan', 'answer', 5, 9.29, 'order, items', [4]] 44 | s = 0 45 | for item in lst: 46 | if type(item) == type("string"): 47 | s = s + 1 48 | ``` 49 | 50 | #### Q-6. Which of these are good names for an accumulator variable? Select as many as apply. 51 | ``` 52 | A. sum 53 | B. x 54 | C. total 55 | D. accum 56 | E. none of the above 57 | ``` 58 | #### Answer: C, D 59 | 60 | #### Q-7. Which of these are good names for an iterator (loop) variable? Select as many as apply. 61 | ``` 62 | A. item 63 | B. y 64 | C. elem 65 | D. char 66 | E. none of the above 67 | ``` 68 | #### Answer: A, C, D 69 | 70 | #### Q-8. Which of these are good names for a sequence variable? Select as many as apply. 71 | ``` 72 | A. num_lst 73 | B. p 74 | C. sentence 75 | D. names 76 | E. none of the above 77 | ``` 78 | #### Answer: A, C, D 79 | 80 | #### Q-9. Given the following scenario, what are good names for the accumulator variable, iterator variable, and sequence variable? You are writing code that uses a list of sentences and accumulates the total number of sentences that have the word ‘happy’ in them. 81 | ``` 82 | A. accumulator variable: x | iterator variable: s | sequence variable: lst 83 | B. accumulator variable: total | iterator variable: s | sequence variable: lst 84 | C. accumulator variable: x | iterator variable: sentences | sequence variable: sentence_lst 85 | D. accumulator variable: total | iterator variable: sentence |sequence variable: sentence_lst 86 | E. none of the above 87 | ``` 88 | #### Answer: D 89 | 90 | #### Q-10. For each character in the string saved in ael, append that character to a list that should be saved in a variable app. 91 | ``` 92 | ael = "python!" 93 | app = [] 94 | for i in ael: 95 | a = app.append(i) 96 | print(a) 97 | ``` 98 | 99 | #### Q-11. 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. 100 | ``` 101 | wrds = ["end", 'work', "play", "start", "walk", "look", "open", "rain", "learn", "clean"] 102 | past_wrds = [] 103 | for i in wrds: 104 | a = i + "ed" 105 | b = past_wrds.append(a) 106 | print(b) 107 | ``` 108 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at yadavyash0904@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-4/Advance functions.py: -------------------------------------------------------------------------------- 1 | '''Q-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. 2 | The function should return the first parameter multiplied by the second.''' 3 | 4 | def mult(a, b=6): 5 | return a * b 6 | a=5 7 | mult(a) 8 | 9 | 10 | ''' Q-2.The following function, greeting, does not work. Please fix the code so that it runs without error. 11 | This only requires one change in the definition of the function.''' 12 | 13 | def greeting(name, greeting="Hello ", excl="!"): 14 | return greeting + name + excl 15 | 16 | print(greeting("Bob")) 17 | print(greeting("")) 18 | print(greeting("Bob", excl="!!!")) 19 | 20 | 21 | ''' Q-3. Below is a function, sum, that does not work. Change the function definition so the code works. 22 | The function should still have a required parameter, intx, and an optional parameter, intz with a defualt value of 5.''' 23 | 24 | 25 | def sum(intx, intz=5): 26 | return intz + intx 27 | 28 | 29 | ''' Q-4. 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. 30 | If the boolean parameter is False, return the boolean value “False”.''' 31 | 32 | def test(x, abool = True, dict1 = {2:3, 4:5, 6:8}): 33 | return abool and dict1.get(x, False) 34 | x=int(input()) 35 | test(x) 36 | 37 | 38 | ''' Q-5. Write a function called checkingIfIn that takes three parameters. The first is a required parameter, which should be a string. 39 | 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. 40 | 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. 41 | If it’s not, the function should return True in this case, and if it is, it should return False.''' 42 | 43 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 44 | if direction == True: 45 | if a in d: 46 | return True 47 | else: 48 | return False 49 | else: 50 | if a not in d: 51 | return True 52 | else: 53 | return False 54 | 55 | '''Q-6 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. 56 | Follow the instructions in the active code window for specific variable assignmemts.''' 57 | 58 | def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): 59 | if direction == True: 60 | if a in d: 61 | return d[a] 62 | else: 63 | return False 64 | else: 65 | if a not in d: 66 | return True 67 | else: 68 | return d[a] 69 | 70 | # Call the function so that it returns False and assign that function call to the variable c_false 71 | c_false = checkingIfIn('peas') 72 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-5/Sentimental classifier.py: -------------------------------------------------------------------------------- 1 | #Q-1. 2 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 3 | def strip_punctuation(string): 4 | 5 | for char in string: 6 | if char in punctuation_chars: 7 | string=string.replace(char,"") 8 | 9 | return string 10 | 11 | 12 | #Q-2. 13 | 14 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 15 | # list of positive words to use 16 | positive_words = [] 17 | with open("positive_words.txt") as pos_f: 18 | for lin in pos_f: 19 | if lin[0] != ';' and lin[0] != '\n': 20 | positive_words.append(lin.strip()) 21 | 22 | def strip_punctuation(string): 23 | 24 | for char in string: 25 | if char in punctuation_chars: 26 | string=string.replace(char,"") 27 | 28 | return string 29 | #----------------------Answer from Above---------------------------- 30 | def get_pos(x): 31 | c=0 32 | words=x.split() 33 | for word in words: 34 | word= strip_punctuation(word) 35 | if word in positive_words: 36 | c=c+1 37 | return c 38 | 39 | #Q-3. 40 | 41 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 42 | 43 | negative_words = [] 44 | with open("negative_words.txt") as pos_f: 45 | for lin in pos_f: 46 | if lin[0] != ';' and lin[0] != '\n': 47 | negative_words.append(lin.strip()) 48 | 49 | def strip_punctuation(string): 50 | 51 | for char in string: 52 | if char in punctuation_chars: 53 | string=string.replace(char,"") 54 | 55 | return string 56 | #----------------------Answer from Part 1---------------------------- 57 | 58 | def get_neg(sentence): 59 | 60 | count=0 61 | 62 | for string in sentence.split(" "): 63 | if strip_punctuation(string) in negative_words: 64 | count+=1 65 | 66 | return count 67 | 68 | 69 | 70 | #Q-4. 71 | 72 | punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] 73 | # lists of words to use 74 | positive_words = [] 75 | with open("positive_words.txt") as pos_f: 76 | for lin in pos_f: 77 | if lin[0] != ';' and lin[0] != '\n': 78 | positive_words.append(lin.strip()) 79 | 80 | 81 | negative_words = [] 82 | with open("negative_words.txt") as pos_f: 83 | for lin in pos_f: 84 | if lin[0] != ';' and lin[0] != '\n': 85 | negative_words.append(lin.strip()) 86 | def get_pos(x): 87 | c=0 88 | words=x.split() 89 | for word in words: 90 | word= strip_punctuation(word) 91 | if word in positive_words: 92 | c=c+1 93 | return c 94 | 95 | def get_neg(x): 96 | c=0 97 | words=x.split() 98 | for word in words: 99 | word= strip_punctuation(word) 100 | if word in negative_words: 101 | c=c+1 102 | return c 103 | 104 | def strip_punctuation(s): 105 | for x in s: 106 | if x in punctuation_chars: 107 | s = s.replace(x, "") 108 | return s 109 | 110 | outfile = open("resulting_data.csv","w") 111 | outfile.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score") 112 | outfile.write('\n') 113 | 114 | 115 | fileconnection = open("project_twitter_data.csv", 'r') 116 | 117 | lines = fileconnection.readlines() 118 | print(lines) 119 | header = lines[0] 120 | field_names = header.strip().split(',') 121 | print(field_names) 122 | for row in lines[1:]: 123 | 124 | vals = row.strip().split(',') 125 | row_string = '{},{},{},{},{}'.format(vals[1],vals[2],get_pos(vals[0]),get_neg(vals[0]),get_pos(vals[0])-get_neg(vals[0])) 126 | outfile.write(row_string) 127 | outfile.write('\n') 128 | 129 | 130 | outfile.close() 131 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-2/Dictionary mechanics.py: -------------------------------------------------------------------------------- 1 | ''' Q-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. 2 | 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.''' 3 | 4 | medal_count={'United States':70,'Great Britain':38,'China':45,'Russia':30,'Germany':17 } 5 | 6 | ''' Q-2. 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. 7 | Do not rewrite the entire dictionary.''' 8 | 9 | swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4} 10 | swimmers['Phelps']=23 11 | 12 | 13 | ''' Q-3. Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3. 14 | Do not rewrite the entire dictionary.''' 15 | 16 | sports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2} 17 | sports_periods['hockey']=3 18 | 19 | 20 | ''' Q-4. The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics. 21 | But today, Spain won 2 more gold medals. Update golds to reflect this information''' 22 | 23 | golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} 24 | golds["Spain"]=golds["Spain"]+2 25 | 26 | 27 | ''' Q-5. Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries. 28 | Do not hard code this.''' 29 | 30 | 31 | golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} 32 | countries=golds.keys() 33 | 34 | '''Q-6 Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point in the 2016 Rio Olympics. 35 | Using dictionary mechanics, assign the medal count value for "Belarus" to the variable belarus. Do not hardcode this.''' 36 | 37 | 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} 38 | 39 | belarus = medal_count.get("Belarus") 40 | print(belarus) 41 | 42 | '''Q-7 The dictionary total_golds contains the total number of gold medals that countries have won over the course of history. 43 | Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds.''' 44 | 45 | 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} 46 | chile_golds = total_golds.get("Chile") 47 | print(chile_golds) 48 | 49 | '''Q-8 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. 50 | Using dictionary mechanics, assign the value of the key "Fencing" to a variable fencing_value.''' 51 | 52 | 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} 53 | fencing_value = US_medals.get("Fencing") 54 | print(fencing_value) 55 | -------------------------------------------------------------------------------- /Data Collection and Processing with Python/week-1/Nested Data and Iteration.py: -------------------------------------------------------------------------------- 1 | #Q-1. 2 | nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']] 3 | output=nested[1][2] 4 | print(output) 5 | 6 | 7 | #Q-2. 8 | 9 | lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']] 10 | 11 | #Test to see if 'yellow' is in the third list of lst. Save to variable ``yellow`` 12 | yellow = 'yellow' in lst[2] 13 | 14 | #Test to see if 4 is in the second list of lst. Save to variable ``four`` 15 | four = 4 in lst[1] 16 | 17 | #Test to see if 'orange' is in the first element of lst. Save to variable ``orange`` 18 | orange = 'orange' in lst[0] 19 | 20 | 21 | #Q-3. 22 | 23 | L = [[5, 8, 7], ['hello', 'hi', 'hola'], [6.6, 1.54, 3.99], ['small', 'large']] 24 | 25 | # Test if 'hola' is in the list L. Save to variable name test1 26 | test1 = 'hola' in L 27 | # Test if [5, 8, 7] is in the list L. Save to variable name test2 28 | test2 = [5, 8, 7] in L 29 | # Test if 6.6 is in the third element of list L. Save to variable name test3 30 | test3 = 6.6 in L[2] 31 | 32 | 33 | #Q-4. 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 | 59 | #Q-5 60 | 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}} 61 | london_gold=nested_d['London']['Great Britain'] 62 | 63 | #Q-6 64 | 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']}} 65 | 66 | # Assign the string 'backstroke' to the name v1 67 | v1 = sports['swimming'][2] 68 | # Assign the string 'platform' to the name v2 69 | v2 = sports['diving'][1] 70 | # Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3 71 | v3 = sports['gymnastics']['women'] 72 | # Assign the string 'rings' to the name v4 73 | v4 = sports['gymnastics']['men'][3] 74 | print(v4) 75 | 76 | 77 | #Q-7 78 | 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}} 79 | US_count = [] 80 | 81 | 82 | US_count.append(nested_d['Beijing']['USA']) 83 | US_count.append(nested_d['London']['USA']) 84 | US_count.append(nested_d['Rio']['USA']) 85 | 86 | 87 | #Q-8 88 | l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']] 89 | #l_of_l = [['purple', 'mauve', 'blue'], ['red', 'maroon', 'blood orange', 'crimson'], ['sea green', 'cornflower', 'lavender', 'indigo'], ['yellow', 'amarillo', 'mac n cheese', 'golden rod']] 90 | 91 | third = [i[2] for i in l_of_l] 92 | 93 | 94 | #Q-9 95 | athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']] 96 | 97 | 98 | t = [] 99 | other = [] 100 | 101 | for list in athletes: 102 | for char in list: 103 | if 't' in char: 104 | t.append(char) 105 | else: 106 | other.append(char) 107 | -------------------------------------------------------------------------------- /Python basic/week-2/Week two.py: -------------------------------------------------------------------------------- 1 | ''' Q-1: Write one for loop to print out each character of the string my_str on a separate line.''' 2 | 3 | my_str = "MICHIGAN" 4 | lst = list(my_str) 5 | count = 0 6 | for i in lst: 7 | print(i) 8 | count = count +1 9 | 10 | ''' Q-2: Write one for loop to print out each element of the list several_things. Then, write another 11 | for loop to print out the TYPE of each element of the list several_things. To complete this problem you 12 | should have written two different for loops, each of which iterates over the list several_things, but 13 | each of those 2 for loops should have a different result.''' 14 | 15 | several_things = ["hello", 2, 4, 6.0, 7.5, 234352354, "the end", "", 99] 16 | lst = list(several_things) 17 | count = 0 18 | for i in lst: 19 | print(i) 20 | count = count + 1 21 | 22 | for j in lst: 23 | print(type(j)) 24 | count = count + 1 25 | 26 | ''' Q-3: Write code that uses iteration to print out the length of each element of the list stored in str_list.''' 27 | 28 | str_list = ["hello", "", "goodbye", "wonderful", "I love Python"] 29 | 30 | count = 0 31 | for i in str_list: 32 | print(len(i)) 33 | count = count + 1 34 | 35 | ''' Q-4: Write code to count the number of characters in original_str using the accumulation pattern and assign the 36 | answer to a variable num_chars. Do NOT use the len function to solve the problem (if you use it while you are working 37 | on this problem, comment it out afterward!) ''' 38 | 39 | original_str = "The quick brown rhino jumped over the extremely lazy fox." 40 | count = 0 41 | for _ in original_str: 42 | count = count + 1 43 | 44 | num_chars = count 45 | print(num_chars) 46 | 47 | ''' Q-5: addition_str is a string with a list of numbers separated by the + sign. Write code that uses the accumulation 48 | pattern to take the sum of all of the numbers and assigns it to sum_val (an integer). (You should use the .split("+") 49 | function to split by "+" and int() to cast to an integer).''' 50 | 51 | addition_str = "2+5+10+20" 52 | add_str = addition_str.split("+") 53 | add_str = [int(n) for n in add_str] 54 | accum = 0 55 | for i in add_str: 56 | accum = accum + i 57 | 58 | sum_val = accum 59 | print(sum_val) 60 | 61 | ''' Q-6: week_temps_f is a string with a list of fahrenheit temperatures separated by the , sign. Write code that uses 62 | the accumulation pattern to compute the average (sum divided by number of items) and assigns it to avg_temp. Do not hard 63 | 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 64 | .split(",") function to split by "," and float() to cast to a float).''' 65 | 66 | week_temps_f = "75.1,77.7,83.2,82.5,81.0,79.5,85.7" 67 | temp_f = week_temps_f.split(",") 68 | temp_f = [float(n) for n in temp_f] 69 | avg = 0 70 | sum = 0 71 | for num in temp_f: 72 | sum=sum+num 73 | avg_temp = sum/len(temp_f) 74 | print(avg_temp) 75 | 76 | ''' Q-7: 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.''' 77 | 78 | nums = list(range(68)) 79 | print(nums) 80 | 81 | ''' Q-8: Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign the 82 | answer to a variable num_words_list. (You should use the len function).''' 83 | 84 | original_str = "The quick brown rhino jumped over the extremely lazy fox" 85 | b = original_str.split(" ") 86 | num_words_list=[] 87 | for i in b: 88 | a = len(i) 89 | num_words_list.append(a) 90 | 91 | print(num_words_list) 92 | 93 | ''' Q-9: Create an empty string and assign it to the variable lett. Then using range, write code such that when your code is run, 94 | lett has 7 b’s ("bbbbbbb").''' 95 | 96 | lett ="" 97 | for _ in range(7): 98 | lett+='b' 99 | print(lett) 100 | 101 | '''Q-10: Write a program that uses the turtle module and a for loop to draw something. It doesn’t have to be complicated, but draw 102 | something different than we have done in the past. (Hint: if you are drawing something complicated, it could get tedious to watch 103 | 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.)''' 104 | 105 | import turtle 106 | import math 107 | alex = turtle.Turtle() 108 | turtle.Screen() 109 | 110 | for i in [0,1,2,3]: 111 | alex.forward(100) 112 | alex.right(90) 113 | alex.left(90) 114 | dist = math.sqrt((100*100)//2) 115 | alex.right(45) 116 | alex.forward(dist) 117 | alex.right(90) 118 | alex.forward(dist) 119 | alex.left(45) 120 | alex.forward(100) 121 | alex.left(90) 122 | alex.forward(33.5) 123 | alex.right(90) 124 | alex.forward(33.5) 125 | alex.left(90) 126 | alex.forward(33.5) 127 | alex.left(90) 128 | alex.forward(33.5) 129 | -------------------------------------------------------------------------------- /Python Functions, Files, and Dictionaries/week-2/Dictionary Accumulation.py: -------------------------------------------------------------------------------- 1 | ''' Q-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. 2 | Find the total number of credits taken this semester and assign it to the variable credits. 3 | Do not hardcode this – use dictionary accumulation!''' 4 | 5 | Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3} 6 | credits=0 7 | for c in Junior: 8 | credits=credits+Junior[c] 9 | print(credits) 10 | 11 | ''' Q-2. Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value.''' 12 | 13 | str1 = "peter piper picked a peck of pickled peppers" 14 | freq = {} 15 | for i in str1: 16 | if i in freq: 17 | freq[i] += 1 18 | else: 19 | freq[i] = 1 20 | 21 | 22 | ''' Q-3. Provided is a string saved to the variable name s1. 23 | Create a dictionary named counts that contains each letter in s1 and the number of times it occurs.''' 24 | 25 | s1 = "hello" 26 | counts={} 27 | for i in s1: 28 | if i in counts: 29 | counts[i]+=1 30 | else: 31 | counts[i]=1 32 | print(counts) 33 | 34 | 35 | ''' Q-4. Create a dictionary, freq_words, that contains each word in string str1 as the key and its frequency as the value.''' 36 | 37 | str1 = "I wish I wish with all my heart to fly with dragons in a land apart" 38 | str1=str1.split() 39 | freq_words = {} 40 | for i in str1: 41 | if i in freq_words: 42 | freq_words[i] += 1 43 | else: 44 | freq_words[i] = 1 45 | 46 | 47 | ''' Q-5. 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.''' 48 | 49 | sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good" 50 | sent=sent.split() 51 | wrd_d = {} 52 | for i in sent: 53 | if i in wrd_d: 54 | wrd_d[i] += 1 55 | else: 56 | wrd_d[i] = 1 57 | print(wrd_d) 58 | 59 | '''Q-6 Create the dictionary characters that shows each character from the string sally and its frequency. 60 | Then, find the most frequent letter based on the dictionary.Assign this letter to the variable best_char.''' 61 | 62 | 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} 63 | 64 | belarus = medal_count.get("Belarus") 65 | print(belarus) 66 | 67 | '''Q-7 The dictionary total_golds contains the total number of gold medals that countries have won over the course of history. 68 | Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds.''' 69 | 70 | sally = "sally sells sea shells by the sea shore" 71 | characters = {} 72 | for i in sally: 73 | characters[i]=characters.get(i,0)+1 74 | 75 | sorted(characters.items(), key=lambda x: x[1]) 76 | best_char = sorted(characters.items(), key=lambda x: x[1])[-1][0] 77 | 78 | '''Q-8 Find the least frequent letter. 79 | 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.''' 80 | 81 | sally = "sally sells sea shells by the sea shore and by the road" 82 | 83 | characters = {} 84 | for i in sally: 85 | characters[i]=characters.get(i,0)+1 86 | 87 | sorted(characters.items(), key=lambda x: x[1]) 88 | worst_char = sorted(characters.items(), key=lambda x: x[1])[-13][0] 89 | 90 | 91 | ''' Q-9 Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1. 92 | Challenge: Letters should not be counted separately as upper-case and lower-case. Intead, all of them should be counted as lower-case.''' 93 | 94 | 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." 95 | letter_counts={} 96 | for i in string1.lower(): 97 | if i not in letter_counts: 98 | letter_counts[i]=0 99 | letter_counts[i]=letter_counts[i]+1 100 | 101 | 102 | ''' Q-10 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. 103 | Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as a “t” for example.''' 104 | 105 | p = "Summer is a great time to go outside. You have to be careful of the sun though because of the heat." 106 | low_d={} 107 | for i in p.lower(): 108 | if i not in low_d: 109 | low_d[i]=0 110 | low_d[i]=low_d[i]+1 111 | -------------------------------------------------------------------------------- /Data Collection and Processing with Python/week-3/OMDB and TasteDive Mashup.py: -------------------------------------------------------------------------------- 1 | #Q-1 2 | 3 | import requests_with_caching 4 | import json 5 | 6 | 7 | def get_movies_from_tastedive(title): 8 | endpoint = 'https://tastedive.com/api/similar' 9 | param = {} 10 | param['q'] = title 11 | param['limit'] = 5 12 | param['type'] = 'movies' 13 | 14 | this_page_cache = requests_with_caching.get(endpoint, params=param) 15 | return json.loads(this_page_cache.text) 16 | 17 | 18 | ''' some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages''' 19 | get_movies_from_tastedive("Bridesmaids") 20 | get_movies_from_tastedive("Black Panther") 21 | 22 | 23 | #Q-2 24 | import requests_with_caching 25 | import json 26 | 27 | 28 | def get_movies_from_tastedive(title): 29 | endpoint = 'https://tastedive.com/api/similar' 30 | param = {} 31 | param['q'] = title 32 | param['limit'] = 5 33 | param['type'] = 'movies' 34 | 35 | this_page_cache = requests_with_caching.get(endpoint, params=param) 36 | return json.loads(this_page_cache.text) 37 | 38 | 39 | def extract_movie_titles(dic): 40 | return ([i['Name'] for i in dic['Similar']['Results']]) 41 | 42 | 43 | '''some invocations that we use in the automated tests; uncomment these if you are getting errors and want better error messages''' 44 | extract_movie_titles(get_movies_from_tastedive("Tony Bennett")) 45 | extract_movie_titles(get_movies_from_tastedive("Black Panther")) 46 | 47 | #Q-3 48 | 49 | import requests_with_caching 50 | import json 51 | 52 | 53 | def get_movies_from_tastedive(title): 54 | endpoint = 'https://tastedive.com/api/similar' 55 | param = {} 56 | param['q'] = title 57 | param['limit'] = 5 58 | param['type'] = 'movies' 59 | 60 | this_page_cache = requests_with_caching.get(endpoint, params=param) 61 | return json.loads(this_page_cache.text) 62 | 63 | 64 | def extract_movie_titles(dic): 65 | return ([i['Name'] for i in dic['Similar']['Results']]) 66 | 67 | 68 | def get_related_titles(movie_list): 69 | li = [] 70 | for movie in movie_list: 71 | li.extend(extract_movie_titles(get_movies_from_tastedive(movie))) 72 | return list(set(li)) 73 | 74 | 75 | get_related_titles(["Black Panther", "Captain Marvel"]) 76 | 77 | 78 | #Q-4 79 | 80 | import requests_with_caching 81 | import json 82 | 83 | 84 | def get_movie_data(title): 85 | endpoint = 'http://www.omdbapi.com/' 86 | param = {} 87 | param['t'] = title 88 | param['r'] = 'json' 89 | this_page_cache = requests_with_caching.get(endpoint, params=param) 90 | 91 | return json.loads(this_page_cache.text) 92 | 93 | 94 | get_movie_data("Venom") 95 | get_movie_data("Baby Mama") 96 | 97 | 98 | #Q-5 99 | 100 | import requests_with_caching 101 | import json 102 | 103 | 104 | def get_movie_data(title): 105 | endpoint = 'http://www.omdbapi.com/' 106 | param = {} 107 | param['t'] = title 108 | param['r'] = 'json' 109 | this_page_cache = requests_with_caching.get(endpoint, params=param) 110 | return json.loads(this_page_cache.text) 111 | print(get_movie_data("Black Panther")['Ratings'][1]) 112 | def get_movie_rating(dic): 113 | raking = dic['Ratings'] 114 | for dic_item in raking: 115 | if dic_item['Source'] == 'Rotten Tomatoes': 116 | return int(dic_item['Value'][:-1]) 117 | return 0 118 | 119 | 120 | get_movie_rating(get_movie_data("Deadpool 2")) 121 | 122 | 123 | #Q-6 124 | 125 | import requests_with_caching 126 | import json 127 | 128 | 129 | def get_movies_from_tastedive(title): 130 | endpoint = 'https://tastedive.com/api/similar' 131 | param = {} 132 | param['q'] = title 133 | param['limit'] = 5 134 | param['type'] = 'movies' 135 | 136 | this_page_cache = requests_with_caching.get(endpoint, params=param) 137 | return json.loads(this_page_cache.text) 138 | 139 | 140 | def extract_movie_titles(dic): 141 | return ([i['Name'] for i in dic['Similar']['Results']]) 142 | 143 | 144 | def get_related_titles(movie_list): 145 | li = [] 146 | for movie in movie_list: 147 | li.extend(extract_movie_titles(get_movies_from_tastedive(movie))) 148 | return list(set(li)) 149 | 150 | 151 | def get_movie_data(title): 152 | endpoint = 'http://www.omdbapi.com/' 153 | param = {} 154 | param['t'] = title 155 | param['r'] = 'json' 156 | this_page_cache = requests_with_caching.get(endpoint, params=param) 157 | return json.loads(this_page_cache.text) 158 | 159 | 160 | def get_movie_rating(dic): 161 | raking = dic['Ratings'] 162 | for dic_item in raking: 163 | if dic_item['Source'] == 'Rotten Tomatoes': 164 | return int(dic_item['Value'][:-1]) 165 | return 0 166 | 167 | 168 | def get_sorted_recommendations(movie_list): 169 | t_r = {} 170 | for title in get_related_titles(movie_list): 171 | t_r[title] = get_movie_rating(get_movie_data(title)) 172 | 173 | return [i[0] for i in sorted(t_r.items(), key=lambda item: (item[1], item[0]), reverse=True)] 174 | 175 | # return sorted(t_r.items(),key=lambda item:(item[1],item[0]),reverse=True) 176 | 177 | 178 | get_sorted_recommendations(["Bridesmaids", "Sherlock Holmes"]) 179 | -------------------------------------------------------------------------------- /Python Classes and Inheritance/week-2/Week two (2).py: -------------------------------------------------------------------------------- 1 | #Q-1. 2 | 3 | class Pokemon(object): 4 | attack = 12 5 | defense = 10 6 | health = 15 7 | p_type = "Normal" 8 | 9 | def __init__(self, name, level = 5): 10 | self.name = name 11 | self.level = level 12 | 13 | def train(self): 14 | self.update() 15 | self.attack_up() 16 | self.defense_up() 17 | self.health_up() 18 | self.level = self.level + 1 19 | if self.level%self.evolve == 0: 20 | return self.level, "Evolved!" 21 | else: 22 | return self.level 23 | 24 | def attack_up(self): 25 | self.attack = self.attack + self.attack_boost 26 | return self.attack 27 | 28 | def defense_up(self): 29 | self.defense = self.defense + self.defense_boost 30 | return self.defense 31 | 32 | def health_up(self): 33 | self.health = self.health + self.health_boost 34 | return self.health 35 | 36 | def update(self): 37 | self.health_boost = 5 38 | self.attack_boost = 3 39 | self.defense_boost = 2 40 | self.evolve = 10 41 | 42 | def __str__(self): 43 | self.update() 44 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 45 | 46 | class Grass_Pokemon(Pokemon): 47 | attack = 15 48 | defense = 14 49 | health = 12 50 | 51 | def update(self): 52 | self.health_boost = 6 53 | self.attack_boost = 2 54 | self.defense_boost = 3 55 | self.evolve = 12 56 | 57 | def moves(self): 58 | self.p_moves = ["razor leaf", "synthesis", "petal dance"] 59 | 60 | def action(self): 61 | return "{} knows a lot of different moves!".format(self.name) 62 | 63 | p1 = Grass_Pokemon("Belle") 64 | 65 | #Q-2. 66 | 67 | class Pokemon(object): 68 | attack = 12 69 | defense = 10 70 | health = 15 71 | p_type = "Normal" 72 | 73 | def __init__(self, name, level = 5): 74 | self.name = name 75 | self.level = level 76 | 77 | def train(self): 78 | self.update() 79 | self.attack_up() 80 | self.defense_up() 81 | self.health_up() 82 | self.level = self.level + 1 83 | if self.level%self.evolve == 0: 84 | return self.level, "Evolved!" 85 | else: 86 | return self.level 87 | 88 | def attack_up(self): 89 | self.attack = self.attack + self.attack_boost 90 | return self.attack 91 | 92 | def defense_up(self): 93 | self.defense = self.defense + self.defense_boost 94 | return self.defense 95 | 96 | def health_up(self): 97 | self.health = self.health + self.health_boost 98 | return self.health 99 | 100 | def update(self): 101 | self.health_boost = 5 102 | self.attack_boost = 3 103 | self.defense_boost = 2 104 | self.evolve = 10 105 | 106 | def __str__(self): 107 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 108 | 109 | class Grass_Pokemon(Pokemon): 110 | attack = 15 111 | defense = 14 112 | health = 12 113 | p_type = "Grass" 114 | 115 | def update(self): 116 | self.health_boost = 6 117 | self.attack_boost = 2 118 | self.defense_boost = 3 119 | self.evolve = 12 120 | 121 | def train(self): 122 | self.update() 123 | if self.level >= 10: 124 | self.attack_up() 125 | self.defense_up() 126 | self.health_up() 127 | self.level = self.level + 1 128 | if self.level%self.evolve == 0: 129 | return self.level, "Evolved!" 130 | else: 131 | return self.level 132 | 133 | def moves(self): 134 | self.p_moves = ["razor leaf", "synthesis", "petal dance"] 135 | 136 | 137 | p2 = Grass_Pokemon("Bulby", level = 5) 138 | p3 = Grass_Pokemon("Pika", level = 5) 139 | p3.train() 140 | 141 | #Q-3. 142 | 143 | class Pokemon(): 144 | attack = 12 145 | defense = 10 146 | health = 15 147 | p_type = "Normal" 148 | 149 | def __init__(self, name,level = 5): 150 | self.name = name 151 | self.level = level 152 | self.weak = "Normal" 153 | self.strong = "Normal" 154 | 155 | def train(self): 156 | self.update() 157 | self.attack_up() 158 | self.defense_up() 159 | self.health_up() 160 | self.level = self.level + 1 161 | if self.level%self.evolve == 0: 162 | return self.level, "Evolved!" 163 | else: 164 | return self.level 165 | 166 | def attack_up(self): 167 | self.attack = self.attack + self.attack_boost 168 | return self.attack 169 | 170 | def defense_up(self): 171 | self.defense = self.defense + self.defense_boost 172 | return self.defense 173 | 174 | def health_up(self): 175 | self.health = self.health + self.health_boost 176 | return self.health 177 | 178 | def update(self): 179 | self.health_boost = 5 180 | self.attack_boost = 3 181 | self.defense_boost = 2 182 | self.evolve = 10 183 | 184 | def __str__(self): 185 | self.update() 186 | return "Pokemon name: {}, Type: {}, Level: {}".format(self.name, self.p_type, self.level) 187 | 188 | def opponent(self): 189 | return self.weak, self.strong 190 | 191 | class Grass_Pokemon(Pokemon): 192 | attack = 15 193 | defense = 14 194 | health = 12 195 | p_type = "Grass" 196 | 197 | def __init__(self, name,level = 5): 198 | self.name = name 199 | self.level = level 200 | self.weak = "Fire" 201 | self.strong = "Water" 202 | 203 | def update(self): 204 | self.health_boost = 6 205 | self.attack_boost = 2 206 | self.defense_boost = 3 207 | self.evolve = 12 208 | 209 | class Ghost_Pokemon(Pokemon): 210 | p_type = "Ghost" 211 | 212 | def __init__(self, name,level = 5): 213 | self.name = name 214 | self.level = level 215 | self.weak = "Dark" 216 | self.strong = "Psychic" 217 | 218 | def update(self): 219 | self.health_boost = 3 220 | self.attack_boost = 4 221 | self.defense_boost = 3 222 | 223 | class Fire_Pokemon(Pokemon): 224 | p_type = "Fire" 225 | 226 | def __init__(self, name,level = 5): 227 | self.name = name 228 | self.level = level 229 | self.weak = "Water" 230 | self.strong = "Grass" 231 | 232 | class Flying_Pokemon(Pokemon): 233 | p_type = "Flying" 234 | 235 | def __init__(self, name,level = 5): 236 | self.name = name 237 | self.level = level 238 | self.weak = "Electric" 239 | self.strong = "Fighting" 240 | --------------------------------------------------------------------------------