├── practice-test-1 ├── question19 │ ├── goal.txt │ ├── happy.txt │ ├── educate.txt │ └── question19.py ├── question20 │ ├── input1.csv │ └── question20.py ├── question01.py ├── question12.py ├── question05.py ├── question03.py ├── question04.py ├── question07.py ├── question10.py ├── question06.py ├── question09.py ├── question02.py ├── question11.py ├── question14.py ├── question13.py └── question08.py ├── practice-test-2 ├── question13 │ ├── input1.csv │ └── question13.py ├── question15.py └── question14.py ├── chapter-14-files ├── question3 │ ├── StudentInfo.tsv │ └── question03.py ├── question2 │ ├── file1.txt │ └── question02.py ├── question1 │ ├── input1.txt │ └── question01.py └── question4 │ ├── ParkPhotos.txt │ └── question04.py ├── chapter-11-lists ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── chapter-12-exceptions ├── question2.py ├── question1.py ├── question3.py └── question4.py ├── README.md └── chapter-13-modules ├── question2.py └── question1.py /practice-test-1/question19/goal.txt: -------------------------------------------------------------------------------- 1 | objective 2 | -------------------------------------------------------------------------------- /practice-test-1/question20/input1.csv: -------------------------------------------------------------------------------- 1 | hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy 2 | -------------------------------------------------------------------------------- /practice-test-2/question13/input1.csv: -------------------------------------------------------------------------------- 1 | a, 100, b, 200, c, 300 2 | bananas, 1.85, steak, 19.99, cookies, 4.52 3 | -------------------------------------------------------------------------------- /chapter-14-files/question3/StudentInfo.tsv: -------------------------------------------------------------------------------- 1 | Barrett Edan 70 45 59 2 | Bradshaw Reagan 96 97 88 3 | Charlton Caius 73 94 80 4 | Mayo Tyrese 88 61 36 5 | Stern Brenda 90 86 45 6 | -------------------------------------------------------------------------------- /chapter-14-files/question2/file1.txt: -------------------------------------------------------------------------------- 1 | 20 2 | Gunsmoke 3 | 30 4 | The Simpsons 5 | 10 6 | Will & Grace 7 | 14 8 | Dallas 9 | 20 10 | Law & Order 11 | 12 12 | Murder, She Wrote 13 | -------------------------------------------------------------------------------- /chapter-14-files/question1/input1.txt: -------------------------------------------------------------------------------- 1 | aspiration 2 | classified 3 | federation 4 | graduation 5 | millennium 6 | philosophy 7 | quadratics 8 | transcript 9 | wilderness 10 | zoologists 11 | -------------------------------------------------------------------------------- /practice-test-1/question19/happy.txt: -------------------------------------------------------------------------------- 1 | blessed blest blissful 2 | cheerful contented 3 | delighted 4 | ecstatic elated 5 | glad 6 | joyful joyous jubilant 7 | lively 8 | merry 9 | overjoyed 10 | peaceful pleasant pleased 11 | thrilled 12 | upbeat 13 | -------------------------------------------------------------------------------- /practice-test-1/question19/educate.txt: -------------------------------------------------------------------------------- 1 | brainwash brief 2 | civilize coach cultivate 3 | develop discipline drill 4 | edify enlighten exercise explain 5 | foster 6 | improve indoctrinate inform instruct 7 | mature 8 | nurture 9 | rear 10 | school 11 | train tutor 12 | -------------------------------------------------------------------------------- /chapter-14-files/question4/ParkPhotos.txt: -------------------------------------------------------------------------------- 1 | Acadia2003_photo.jpg 2 | AmericanSamoa1989_photo.jpg 3 | BlackCanyonoftheGunnison1983_photo.jpg 4 | CarlsbadCaverns2010_photo.jpg 5 | CraterLake1996_photo.jpg 6 | GrandCanyon1996_photo.jpg 7 | IndianaDunes1987_photo.jpg 8 | LakeClark2009_photo.jpg 9 | Redwood1980_photo.jpg 10 | VirginIslands2007_photo.jpg 11 | Voyageurs2006_photo.jpg 12 | WrangellStElias1987_photo.jpg 13 | -------------------------------------------------------------------------------- /practice-test-1/question01.py: -------------------------------------------------------------------------------- 1 | #33.1 LAB: Formatted output: No parking sign 2 | 3 | #Write a program that prints a formatted "No parking" sign as shown below. 4 | #Note the first line has two leading spaces. 5 | #For ALL labs, end with newline (unless otherwise stated). 6 | 7 | # NO PARKING 8 | #2:00 - 6:00 a.m. 9 | 10 | #Solution: This one is pretty obvious, just match formatting. 11 | 12 | print(' NO PARKING') 13 | print('2:00 - 6:00 a.m.') -------------------------------------------------------------------------------- /practice-test-1/question12.py: -------------------------------------------------------------------------------- 1 | # 33.12 LAB: Calculate average 2 | 3 | # Complete the calc_average() function that has an integer list parameter and returns the average value of the elements in the list as a float. 4 | 5 | # Ex: If the input list is: 6 | 7 | # 1 2 3 4 5 8 | # then the returned average will be: 9 | 10 | # 3.0 11 | 12 | # Solution: 13 | 14 | def calc_average(nums): 15 | return (sum(nums) / len(nums)) 16 | 17 | if __name__ == '__main__': 18 | nums = [1, 2, 3, 4, 5] 19 | print(calc_average(nums)) # calc_average() should return 3.0 -------------------------------------------------------------------------------- /practice-test-1/question05.py: -------------------------------------------------------------------------------- 1 | # 33.5 LAB: Input and formatted output: Right-facing arrow 2 | # Given input characters for an arrowhead and arrow body, print a right-facing arrow. 3 | 4 | #Ex: If the input is: 5 | 6 | # * 7 | # # 8 | # Then the output is: 9 | 10 | # # 11 | # ******## 12 | # ******### 13 | # ******## 14 | # # 15 | 16 | base_char = input() 17 | head_char = input() 18 | 19 | row1 = ' ' + head_char 20 | row2 = 6 * base_char + 2 * head_char 21 | row3 = 6 * base_char + 3 * head_char 22 | 23 | 24 | print(row1) 25 | print(row2) 26 | print(row3) 27 | print(row2) 28 | print(row1) -------------------------------------------------------------------------------- /chapter-11-lists/question1.py: -------------------------------------------------------------------------------- 1 | # 11.16 LAB: Varied amount of input data 2 | # 3 | # Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max. 4 | # 5 | # Ex: If the input is: 6 | # 7 | # 15 20 0 5 8 | # 9 | # the output is: 10 | # 11 | # 10 20 12 | # 13 | # Note: For output, round the average to the nearest integer. 14 | 15 | # Solution: 16 | 17 | # Get raw input and convert to list of ints 18 | nums = [int(i) for i in input().split()] 19 | 20 | # Output max and average 21 | print(f'{sum(nums)//len(nums)} {max(nums)}') 22 | -------------------------------------------------------------------------------- /chapter-11-lists/question2.py: -------------------------------------------------------------------------------- 1 | # 11.17 LAB: Filter and sort a list 2 | # 3 | # Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest). 4 | # 5 | # Ex: If the input is: 6 | # 7 | # 10 -7 4 39 -6 12 2 8 | # 9 | # the output is: 10 | # 11 | # 2 4 10 12 39 12 | # 13 | # For coding simplicity, follow every output value by a space. Do not end with newline. 14 | 15 | # Solution: 16 | 17 | # Take input and add to num list if non-negative 18 | nums = [int(i) for i in input().split() if int(i) >= 0] 19 | 20 | # Sort and output 21 | nums.sort() 22 | for num in nums: 23 | print(num, end=" ") -------------------------------------------------------------------------------- /practice-test-1/question03.py: -------------------------------------------------------------------------------- 1 | #33.3 LAB: Convert to dollars 2 | #Given four values representing counts of quarters, dimes, nickels and pennies, output the total amount as dollars and cents. 3 | 4 | #Output each floating-point value with two digits after the decimal point, which can be achieved as follows: 5 | #print(f'Amount: ${dollars:.2f}') 6 | 7 | #Ex: If the input is: 8 | 9 | #4 10 | #3 11 | #2 12 | #1 13 | #where 4 is the number of quarters, 3 is the number of dimes, 2 is the number of nickels, and 1 is the number of pennies, the output is: 14 | 15 | #Amount: $1.41 16 | #For simplicity, assume input is non-negative. 17 | 18 | 19 | quarters = int(input()) 20 | dimes = int(input()) 21 | nickels = int(input()) 22 | pennies = int(input()) 23 | 24 | dollars = quarters * 0.25 + dimes * 0.1 + nickels * 0.05 + pennies * 0.01 25 | 26 | print(f'Amount: ${dollars:.2f}') -------------------------------------------------------------------------------- /practice-test-1/question04.py: -------------------------------------------------------------------------------- 1 | #33.4 LAB: Driving costs 2 | 3 | # Driving is expensive. 4 | # Write a program with a car's gas mileage (miles/gallon) 5 | # and the cost of gas (dollars/gallon) as floating-point 6 | # input, and output the gas cost for 20 miles, 75 miles, and 500 miles. 7 | 8 | # Output each floating-point value with two digits after the 9 | # decimal point, which can be achieved as follows: 10 | # print(f'{your_value1:.2f} {your_value2:.2f} {your_value3:.2f}') 11 | 12 | # Ex: If the input is: 13 | 14 | # 20.0 15 | # 3.1599 16 | 17 | # where the gas mileage is 20.0 miles/gallon and the cost of gas is $3.1599/gallon, the output is: 18 | 19 | # 3.16 11.85 79.00 20 | 21 | 22 | mpg = float(input()) 23 | dpg = float(input()) 24 | 25 | miles20 = 20 * dpg / mpg 26 | miles75 = 75 * dpg / mpg 27 | miles500 = 500 * dpg / mpg 28 | 29 | print(f'{miles20:.2f} {miles75:.2f} {miles500:.2f}') -------------------------------------------------------------------------------- /chapter-12-exceptions/question2.py: -------------------------------------------------------------------------------- 1 | # 12.8 LAB: Exception handling to detect input string vs. integer 2 | # 3 | # The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a string rather than an integer. At FIXME in the code, add try and except blocks to catch the ValueError exception and output 0 for the age. 4 | # 5 | # Ex: If the input is: 6 | # 7 | # Lee 18 8 | # Lua 21 9 | # Mary Beth 19 10 | # Stu 33 11 | # -1 12 | # 13 | # then the output is: 14 | # 15 | # Lee 19 16 | # Lua 22 17 | # Mary 0 18 | # Stu 34 19 | 20 | # Solution: 21 | # Split input into 2 parts: name and age 22 | parts = input().split() 23 | name = parts[0] 24 | while name != '-1': 25 | # try/except blocks to catch the exception. 26 | try: 27 | age = int(parts[1]) + 1 28 | except: 29 | age = 0 30 | print(f'{name} {age}') 31 | 32 | # Get next line 33 | parts = input().split() 34 | name = parts[0] -------------------------------------------------------------------------------- /chapter-11-lists/question3.py: -------------------------------------------------------------------------------- 1 | # 11.18 LAB: Elements in a range 2 | # 3 | # Write a program that first gets a list of integers from input. That list is followed by two more integers representing lower and upper bounds of a range. Your program should output all integers from the list that are within that range (inclusive of the bounds). 4 | # 5 | # Ex: If the input is: 6 | # 7 | # 25 51 0 200 33 8 | # 0 50 9 | # 10 | # the output is: 11 | # 12 | # 25 0 33 13 | # 14 | # The bounds are 0-50, so 51 and 200 are out of range and thus not output. 15 | # 16 | # For coding simplicity, follow each output integer by a space, even the last one. Do not end with newline. 17 | 18 | 19 | user_input = input() 20 | user_input2 = input() 21 | 22 | # determine limits based on input 23 | limits = [int (i) for i in user_input2.split()] 24 | 25 | # determine numbers in range based on input 26 | nums = [int (i) for i in user_input.split() if ((int(limits[0]) <= int(i)) and (int(i) <= int(limits[1])))] 27 | 28 | #print output 29 | for num in nums: 30 | print(f'{num}', end=' ') 31 | -------------------------------------------------------------------------------- /practice-test-1/question07.py: -------------------------------------------------------------------------------- 1 | # 33.7 LAB: Smallest number 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 5. Branching. To successfully complete this lab, review the content of Chapter 5, as well as the preceding chapters, and complete the Challenge Activities associated. 4 | 5 | # Write a program whose inputs are three integers, and whose output is the smallest of the three values. 6 | 7 | # Ex: If the input is: 8 | 9 | # 7 10 | # 15 11 | # 3 12 | # the output is: 13 | 14 | # 3 15 | 16 | # Solution: Take all inputs as members of a list, this allows you to utilized the built in min function 17 | # without needing to write your own min function. 18 | 19 | nums = [] 20 | nums.append(int(input())) 21 | nums.append(int(input())) 22 | nums.append(int(input())) 23 | print(min(nums)) 24 | 25 | # If you don't want to use the built in min function (which you really should): 26 | 27 | # You can use if statements: 28 | # min_val = nums[0] 29 | 30 | # if nums[1] < min_val: 31 | # min_val = nums[1] 32 | # elif nums[2] < min_val: 33 | # min_val = nums[2] 34 | # print(min_val) 35 | 36 | 37 | # Or a loop: 38 | 39 | # min_val = nums[0] 40 | # for num in nums: 41 | # if num < min_val: 42 | # min_val = num 43 | # print(min_val) -------------------------------------------------------------------------------- /practice-test-1/question10.py: -------------------------------------------------------------------------------- 1 | # 33.10 LAB: Print string in reverse 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 6. Loops. To successfully complete this lab, review the content of Chapter 6, as well as the preceding chapters, and complete the Challenge Activities associated. 4 | 5 | # Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text. 6 | 7 | # Ex: If the input is: 8 | 9 | # Hello there 10 | # Hey 11 | # done 12 | # then the output is: 13 | 14 | # ereht olleH 15 | # yeH 16 | 17 | # Solution: String Slicing inside a while loop 18 | 19 | # User input 20 | user_input = input() 21 | 22 | # A while loop is used to check for exit keywords (variations of the word "done") 23 | while((user_input != 'done') and (user_input != 'd') and (user_input != 'Done')): 24 | 25 | # In the slice: [::-1] 26 | # The two empty colons slice the default scope (the entire string), 27 | # but the -1 in the slice makes the interval count backwards from the end 28 | print(user_input[::-1]) 29 | 30 | # next input is taken, if one of the exit keywords is entered, 31 | # the while loop will exit. 32 | user_input = input() -------------------------------------------------------------------------------- /chapter-11-lists/question4.py: -------------------------------------------------------------------------------- 1 | # 11.19 LAB: Contact list 2 | # 3 | # A contact list is a place where you can store a specific contact with other associated information such as a phone number, email address, birthday, etc. Write a program that first takes in word pairs that consist of a name and a phone number (both strings), separated by a comma. That list is followed by a name, and your program should output the phone number associated with that name. Assume the search name is always in the list. 4 | # 5 | # Ex: If the input is: 6 | # 7 | # Joe,123-5432 Linda,983-4123 Frank,867-5309 8 | # Frank 9 | # 10 | # the output is: 11 | # 12 | # 867-5309 13 | 14 | # Solution: 15 | 16 | # take inputs 17 | user_input1 = input() 18 | user_input2 = input() 19 | 20 | # varible declaration 21 | phone_directory = {} 22 | search_key = user_input2 23 | 24 | # split the input into tokens 25 | tokens = user_input1.split() 26 | 27 | # create a dictionary of phone numbers 28 | # based on token values 29 | for token in tokens: 30 | # split the token into name and phone number 31 | temp = token.split(',') 32 | # add the name and phone number to the dictionary 33 | phone_directory[temp[0]] = temp[1] 34 | 35 | # print the phone number associated with the name 36 | print(phone_directory[search_key]) -------------------------------------------------------------------------------- /practice-test-1/question06.py: -------------------------------------------------------------------------------- 1 | # 33.6 LAB: Phone number breakdown 2 | 3 | # Given an integer representing a 10-digit phone number, output the area code, prefix, and line number using the format (800) 555-1212. 4 | 5 | # Ex: If the input is: 6 | 7 | # 8005551212 8 | # the output is: 9 | 10 | # (800) 555-1212 11 | # Hint: Use % to get the desired rightmost digits. Ex: The rightmost 2 digits of 572 is gotten by 572 % 100, which is 72. 12 | 13 | # Hint: Use // to shift right by the desired amount. Ex: Shifting 572 right by 2 digits is done by 572 // 100, which yields 5. (Recall integer division discards the fraction). 14 | 15 | # For simplicity, assume any part starts with a non-zero digit. So 0119998888 is not allowed. 16 | 17 | phone_number = int(input()) 18 | 19 | #Solution One: uses modulo and // as per the hints. 20 | # commented out as it is the more convoluted solution 21 | 22 | # area_code = phone_number // 10000000 23 | 24 | # three = (phone_number // 10000) % 1000 25 | 26 | # four = phone_number % 10000 27 | 28 | # print(f'({area_code}) {three}-{four}') 29 | 30 | # Solution Two: String Slicing 31 | # This is the faster option. The int is converted to a string, 32 | # which is then sliced into the requisite components. 33 | 34 | phone_str = str(phone_number) 35 | print(f'({phone_str[0:3]}) {phone_str[3:6]}-{phone_str[6:]}') -------------------------------------------------------------------------------- /practice-test-2/question15.py: -------------------------------------------------------------------------------- 1 | # 34.15 PRACTICE: Import custom module 2 | # Instructions: 3 | # 4 | # Create a Python solution to the following task. Ensure that the solution produces output in exactly the same format shown in the sample(s) below, including capitalization and whitespace. 5 | # Task: 6 | # 7 | # Create a solution that accepts an integer input representing the age of a pig. Import the existing module pigAge and use its pre-built pigAge_converter() function to calculate the human equivalent age of a pig. A year in a pig's life is equivalent to five years in a human's life. Output the human-equivalent age of the pig. 8 | # 9 | # The solution output should be in the format 10 | # 11 | # input_pig_age is converted_pig_age in human years 12 | # 13 | # Sample Input/Output: 14 | # 15 | # If the input is 16 | # 17 | # 8 18 | # 19 | # then the expected output is 20 | # 21 | # 8 is 40 in human years 22 | 23 | # Solution (NOTE: this code will NOT work outside of the zylabs environment) 24 | 25 | 26 | 27 | import pigAge 28 | input_pig_age = int(input()) 29 | 30 | # IMPORTANT: Know how to find this function in a module with the help() function. 31 | converted_pig_age = pigAge.pigAge_converter(input_pig_age) 32 | 33 | print(f'{input_pig_age} is {converted_pig_age} in human years') 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # D335 WGU Python Lab Solutions Examples 2 | 3 | This repository is a collection of solutions to the ungraded practice activities for WGU's D335 Intro to Python course. 4 | 5 | This repository is intended to be used by students who are having difficulty solving labs or want to see another possible solution to a lab. 6 | 7 | 8 | ## Usage 9 | 10 | The recommended usage of this repository is to attempt the lab independently and to use this repository as a guide if you get stuck on something. All provided solutions will pass all unit tests. 11 | 12 | The code provided can either be directly copied and pasted into the Zylabs (make sure you check inputs!) or (if you have Python installed) they can be run via a CLI while in the script's directory such as the following example: 13 | 14 | ```bash 15 | C:\script_file_directory\python question01.py 16 | ``` 17 | 18 | After which you will have to provide inputs to the command prompt. 19 | 20 | [If you don't have python installed, you can download it here.](https://www.python.org/downloads/) 21 | 22 | This can also be used to compare solutions, as there are multiple ways to solve these questions, some involving much less logic than others. If you find a solution that is more efficient and readable, feel free to submit a pull request. 23 | 24 | ## Contributing 25 | 26 | Pull requests are welcome. 27 | 28 | ## License 29 | 30 | [MIT](https://choosealicense.com/licenses/mit/) -------------------------------------------------------------------------------- /practice-test-2/question14.py: -------------------------------------------------------------------------------- 1 | # 34.14 PRACTICE: Math module 2 | # Instructions: 3 | # 4 | # Create a Python solution to the following task. Ensure that the solution produces output in exactly the same format shown in the sample(s) below, including capitalization and whitespace. 5 | # Task: 6 | # 7 | # Create a solution that accepts an integer input. Import the built-in module math and use its factorial() method to calculate the factorial of the integer input. Output the value of the factorial, as well as a Boolean value identifying whether the factorial output is greater than 100. 8 | # 9 | # The solution output should be in the format 10 | # 11 | # factorial_value 12 | # Boolean_value 13 | # 14 | # Sample Input/Output: 15 | # 16 | # If the input is 17 | # 18 | # 10 19 | # 20 | # then the expected output is 21 | # 22 | # 3628800 23 | # True 24 | # 25 | # Alternatively, if the input is 26 | # 27 | # 3 28 | # 29 | # then the expected output is 30 | # 31 | # 6 32 | # False 33 | 34 | # This is pretty straightforward, just import the 35 | # math module and use math.factorial to get your 36 | # computed result, then assign a bool based on 37 | # that value. 38 | import math 39 | user_input = int(input()) 40 | input_fact = math.factorial(user_input) 41 | is_greater100 = True if input_fact > 100 else False 42 | 43 | print(input_fact) 44 | print(is_greater100) -------------------------------------------------------------------------------- /practice-test-1/question09.py: -------------------------------------------------------------------------------- 1 | # 33.9 LAB: Output range with increment of 5 2 | 3 | # Write a program whose input is two integers. Output the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer. End with a newline. 4 | 5 | # Ex: If the input is: 6 | 7 | # -15 8 | # 10 9 | 10 | # the output is: 11 | 12 | # -15 -10 -5 0 5 10 13 | # Ex: If the second integer is less than the first as in: 14 | 15 | # 20 16 | # 5 17 | # the output is: 18 | 19 | # Second integer can't be less than the first. 20 | #For coding simplicity, output a space after every integer, including the last. 21 | 22 | # Solution: 23 | # Essentially this question is to make sure you can 24 | # iterate through a loop giving a range and an interval 25 | 26 | # A for loop is used to do this 27 | 28 | user_floor = int(input()) 29 | user_ceil = int(input()) 30 | out_str = '' 31 | 32 | # An if statement first checks to make sure range makes sense. 33 | if user_ceil >= user_floor: 34 | 35 | # A for loop is initialized 36 | # in the range starting at the floor value 37 | # and ending at the ceiling value 38 | # by increments of 5: 39 | for i in range(user_floor, user_ceil+1, 5): 40 | 41 | # The code inside the for loop 42 | # Appends each interval integer to a string 43 | # for later output: 44 | out_str += f'{i} ' 45 | else: 46 | # required error output if the floor is greater than the ceiling: 47 | out_str = "Second integer can't be less than the first." 48 | 49 | # Results output 50 | print (out_str) -------------------------------------------------------------------------------- /chapter-11-lists/question5.py: -------------------------------------------------------------------------------- 1 | # 11.20 LAB: Check if list is sorted 2 | # 3 | # Write the in_order() function, which has a list of integers as a parameter, and returns True if the integers are sorted (in order from low to high) or False otherwise. The program outputs "In order" if the list is sorted, or "Not in order" if the list is not sorted. 4 | # 5 | # Ex: If the list passed to the in_order() function is [5, 6, 7, 8, 3], then the function returns False and the program outputs: 6 | # 7 | # Not in order 8 | # 9 | # Ex: If the list passed to the in_order() function is [5, 6, 7, 8, 10], then the function returns True and the program outputs: 10 | # 11 | # In order 12 | # 13 | # Note: Use a for loop. DO NOT use sorted() or sort(). 14 | 15 | # Solution: 16 | 17 | def in_order(nums): 18 | # bool set to true for default case 19 | # to account for one item list 20 | # which is always sorted 21 | is_ordered = True 22 | 23 | # Check if list is sorted 24 | for i in range(len(nums) - 1): 25 | if nums[i] > nums[i+1]: 26 | is_ordered = False 27 | 28 | # Return result 29 | return is_ordered 30 | 31 | 32 | if __name__ == '__main__': 33 | # Test out-of-order example 34 | nums1 = [5, 6, 7, 8, 3] 35 | if in_order(nums1): 36 | print('In order') 37 | else: 38 | print('Not in order') 39 | 40 | # Test in-order example 41 | nums2 = [5, 6, 7, 8, 10] 42 | if in_order(nums2): 43 | print('In order') 44 | else: 45 | print('Not in order') -------------------------------------------------------------------------------- /practice-test-1/question02.py: -------------------------------------------------------------------------------- 1 | #33.2 LAB: Input: Mad Lib 2 | #Mad Libs are activities that have a person provide various words, which are then used to complete a short story in unexpected \(and hopefully funny) ways. 3 | #Complete a program that reads four values from input and stores the values in variables first_name, generic_location, whole_number, and plural_noun. 4 | #The program then uses the input values to output a short story. The first input statement is provided in the code as an example. 5 | 6 | # Notes: To test your program in the Develop mode, pre-enter four values (in separate lines) in the input box and click the Run program button. 7 | # The auto-grader in the Submit mode will test your program with different sets input of values. 8 | 9 | # Ex: If the input values are: 10 | 11 | #Eric 12 | #Chipotle 13 | #12 14 | #cars 15 | 16 | #then the program uses the input values and outputs a story: 17 | 18 | #Eric went to Chipotle to buy 12 different types of cars 19 | 20 | #Ex: If the input values are: 21 | 22 | #Brenda 23 | #Philadelphia 24 | #6 25 | #bells 26 | 27 | #then the program uses the input values and outputs a story: 28 | 29 | #Brenda went to Philadelphia to buy 6 different types of bells 30 | 31 | 32 | # Read a value from a user and store the value in first_name 33 | first_name = input() 34 | generic_location = input() 35 | whole_number = input() 36 | plural_noun = input() 37 | 38 | 39 | # Output a short story using the four input values. Do not modify the code below. 40 | print(first_name, 'went to', generic_location, 'to buy', whole_number, 'different types of', plural_noun) -------------------------------------------------------------------------------- /practice-test-1/question11.py: -------------------------------------------------------------------------------- 1 | #33.11 LAB: Fibonacci sequence 2 | 3 | #The Fibonacci sequence begins with 0 and then 1 follows. 4 | #All subsequent values are the sum of the previous two, ex: 0, 1, 1, 2, 3, 5, 8, 13. 5 | #Complete the fibonacci() function, which has an index n as parameter and returns the nth value in the sequence. 6 | #Any negative index values should return -1. 7 | 8 | #Ex: If the input is: 7 9 | #the output is: 'fibonacci(7) is 13' 10 | 11 | 12 | #Solution: 13 | 14 | def fibonacci(n): 15 | first = 0 16 | second = 1 17 | temp = 0 18 | 19 | # returns -1 if input is below 0: 20 | if n < 0: 21 | return -1 22 | 23 | # immediate returns if the index is one 24 | # of the two predefined start values: 25 | if n == 0: 26 | return 0 27 | elif n == 1: 28 | return 1 29 | 30 | # Values are starting at n = 2 31 | # doing the for loop once per 32 | # iteration above index 0 and 1 33 | # (which are the predefined values) 34 | for i in range(n-1): 35 | # temp value to store the first value: 36 | temp = first 37 | 38 | # the first value is updated to be the original second value: 39 | first = second 40 | 41 | # the second value is then updated with the original first value 42 | # added to the original second value: 43 | second = temp + second 44 | 45 | # Once the loop is complete the top most 46 | # value computed in the sequence (second) is returned: 47 | return second 48 | 49 | if __name__ == '__main__': 50 | start_num = int(input()) 51 | print(f'fibonacci({start_num}) is {fibonacci(start_num)}') -------------------------------------------------------------------------------- /chapter-13-modules/question2.py: -------------------------------------------------------------------------------- 1 | # 13.9 LAB: Quadratic formula 2 | # 3 | # Implement the quadratic_formula() function. The function takes 3 arguments, a, b, and c, and computes the two results of the quadratic formula: 4 | # 5 | # The quadratic_formula() function returns the tuple (x1, x2). Ex: When a = 1, b = -5, and c = 6, quadratic_formula() returns (3, 2). 6 | # 7 | # Code provided in main.py reads a single input line containing values for a, b, and c, separated by spaces. Each input is converted to a float and passed to the quadratic_formula() function. 8 | # 9 | # Ex: If the input is: 10 | # 11 | # 2 -3 -77 12 | # 13 | # the output is: 14 | # 15 | # Solutions to 2x^2 + -3x + -77 = 0 16 | # x1 = 7 17 | # x2 = -5.50 18 | # 19 | # 20 | 21 | # Solution: 22 | 23 | # Import math module 24 | import math 25 | 26 | def quadratic_formula(a, b, c): 27 | # Computes the quadratic formula results in variables x1 and x2 28 | x1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) 29 | x2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) 30 | return (x1, x2) 31 | 32 | 33 | def print_number(number, prefix_str): 34 | if float(int(number)) == number: 35 | print(f'{prefix_str}{number:.0f}') 36 | else: 37 | print(f'{prefix_str}{number:.2f}') 38 | 39 | 40 | if __name__ == "__main__": 41 | input_line = input() 42 | split_line = input_line.split(" ") 43 | a = float(split_line[0]) 44 | b = float(split_line[1]) 45 | c = float(split_line[2]) 46 | solution = quadratic_formula(a, b, c) 47 | print(f'Solutions to {a:.0f}x^2 + {b:.0f}x + {c:.0f} = 0') 48 | print_number(solution[0], 'x1 = ') 49 | print_number(solution[1], 'x2 = ') -------------------------------------------------------------------------------- /chapter-12-exceptions/question1.py: -------------------------------------------------------------------------------- 1 | # 12.7 LAB: Fat-burning heart rate 2 | # 3 | # Write a program that calculates an adult's fat-burning heart rate, which is 70% of the difference between 220 and the person's age respectively. Complete fat_burning_heart_rate() to calculate the fat burning heart rate. 4 | # 5 | # The adult's age must be between the ages of 18 and 75 inclusive. If the age entered is not in this range, raise a ValueError exception in get_age() with the message "Invalid age." Handle the exception in __main__ and print the ValueError message along with "Could not calculate heart rate info." 6 | # 7 | # Ex: If the input is: 8 | # 9 | # 35 10 | # 11 | # the output is: 12 | # 13 | # Fat burning heart rate for a 35 year-old: 129.5 bpm 14 | # 15 | # If the input is: 16 | # 17 | # 17 18 | # 19 | # the output is: 20 | # 21 | # Invalid age. 22 | # Could not calculate heart rate info. 23 | 24 | # Solution: 25 | 26 | def get_age(): 27 | age = int(input()) 28 | # Raise exception for invalid ages 29 | if (age < 18 or 75 < age): 30 | raise ValueError('Invalid age.') 31 | return age 32 | 33 | # Complete fat_burning_heart_rate() function 34 | def fat_burning_heart_rate(age): 35 | heart_rate = 0.7 * (220-age) 36 | return heart_rate 37 | 38 | if __name__ == "__main__": 39 | # get_age() and fat_burning_heart_rate() now handle the exception 40 | try: 41 | age = get_age() 42 | target_heart_rate = fat_burning_heart_rate(age) 43 | print(f'Fat burning heart rate for a {age} year-old: {target_heart_rate:.1f} bpm') 44 | except ValueError as excpt: 45 | print(f'{excpt}') 46 | print('Could not calculate heart rate info.') -------------------------------------------------------------------------------- /practice-test-1/question20/question20.py: -------------------------------------------------------------------------------- 1 | # 33.20 LAB: Word frequencies (lists) 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 14. Files. To successfully complete this lab, review the content of Chapter 14, as well as the preceding chapters, and complete the Challenge Activities associated. 4 | # 5 | # Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method. The file contains a list of words separated by commas. Your program should output the words and their frequencies (the number of times each word appears in the file) without any duplicates. 6 | # 7 | # Ex: If the input is: 8 | # 9 | # input1.csv 10 | # and the contents of input1.csv are: 11 | # 12 | # hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy 13 | # the output is: 14 | # 15 | # hello 1 16 | # cat 2 17 | # man 2 18 | # hey 2 19 | # dog 2 20 | # boy 2 21 | # Hello 1 22 | # woman 1 23 | # Cat 1 24 | # Note: There is a newline at the end of the output, and input1.csv is available to download. 25 | 26 | import csv 27 | 28 | file_name = input() 29 | out_str = '' 30 | word_dict = {} 31 | 32 | with open(file_name, 'r') as file_in: 33 | intake = csv.reader(file_in, delimiter=",") 34 | for row in intake: 35 | for field in row: 36 | # for each field in each row 37 | # if it isn't in the dictionary 38 | # add it, otherwise increment the key 39 | # by one. 40 | if field not in word_dict: 41 | word_dict[field] = 1 42 | else: 43 | word_dict[field] += 1 44 | 45 | # for every word in the dictionary print the word and the count value, using the word as the key. 46 | for word in word_dict: 47 | print(f'{word} {word_dict[word]}') -------------------------------------------------------------------------------- /chapter-14-files/question1/question01.py: -------------------------------------------------------------------------------- 1 | # 14.8 LAB: Words in a range (lists) 2 | # Write a program that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. Your program should output all strings from the list that are within that range (inclusive of the bounds). 3 | # 4 | # Ex: If the input is: 5 | # 6 | # input1.txt 7 | # ammoniated 8 | # millennium 9 | # and the contents of input1.txt are: 10 | # 11 | # aspiration 12 | # classified 13 | # federation 14 | # graduation 15 | # millennium 16 | # philosophy 17 | # quadratics 18 | # transcript 19 | # wilderness 20 | # zoologists 21 | # the output is: 22 | # 23 | # aspiration 24 | # classified 25 | # federation 26 | # graduation 27 | # millennium 28 | # Notes: 29 | # 30 | # There is a newline at the end of the output. 31 | # All input files are hosted in the zyLab and file names can be directly referred to. input1.txt is available to download so that the contents of the file can be seen. 32 | # In the tests, the first word input always comes alphabetically before the second word input. 33 | 34 | 35 | file_name = input() 36 | start_term = input() 37 | final_term = input() 38 | 39 | with open(file_name, 'r') as myfile: 40 | lines = myfile.readlines() 41 | for line in lines: 42 | # whitespace is first stripped for comparison 43 | # (otherwise you could this behavior: 'millenium\n' <= 'millenium' 44 | # as user inputs do not have \n on the end) and the file does. 45 | line = line.strip() 46 | 47 | # Simple range checks are used to see if the word should be output 48 | if ((start_term <= line) and (line <= final_term)): 49 | print(line, end='\n') -------------------------------------------------------------------------------- /chapter-13-modules/question1.py: -------------------------------------------------------------------------------- 1 | # 13.8 LAB: Guess the random number 2 | # 3 | # Given the code that reads a list of integers, complete the number_guess() function, which should choose a random number between 1 and 100 by calling random.randint() and then output if the guessed number is too low, too high, or correct. 4 | # 5 | # Import the random module to use the random.seed() and random.randint() functions. 6 | # 7 | # random.seed(seed_value) seeds the random number generator using the given seed_value. 8 | # random.randint(a, b) returns a random number between a and b (inclusive). 9 | # 10 | # For testing purposes, use the seed value 900, which will cause the computer to choose the same random number every time the program runs. 11 | # 12 | # Ex: If the input is: 13 | # 14 | # 32 45 48 80 15 | # 16 | # the output is: 17 | # 18 | # 32 is too low. Random number was 80. 19 | # 45 is too high. Random number was 30. 20 | # 48 is correct! 21 | # 80 is too low. Random number was 97. 22 | 23 | # Solution: 24 | 25 | # This is pretty straightforward, import random 26 | # and call it's randint() function 27 | 28 | import random 29 | 30 | def number_guess(num): 31 | # TODO: Get a random number between 1-100 32 | rand_num = random.randint(1, 100) 33 | # TODO: Compare parameter num to the random number 34 | if num > rand_num: 35 | print(f'{num} is too high. Random number was {rand_num}.') 36 | elif num < rand_num: 37 | print(f'{num} is too low. Random number was {rand_num}.') 38 | else: 39 | print(f'{num} is correct!') 40 | 41 | 42 | if __name__ == "__main__": 43 | # Use the seed 900 to get the same pseudo random numbers every time 44 | random.seed(900) 45 | 46 | user_input = input() 47 | tokens = user_input.split() 48 | for token in tokens: 49 | # Convert the string tokens into integers 50 | num = int(token) 51 | number_guess(num) 52 | 53 | -------------------------------------------------------------------------------- /chapter-12-exceptions/question3.py: -------------------------------------------------------------------------------- 1 | # 12.9 LAB: Exceptions with lists 2 | # 3 | # Given a list of 10 names, complete the program that outputs the name specified by the list index entered by the user. Use a try block to output the name and an except block to catch any IndexError. Output the message from the exception object if an IndexError is caught. Output the first element in the list if the invalid index is negative or the last element if the invalid index is positive. 4 | # 5 | # Note: Python allows using a negative index to access a list, as long as the magnitude of the index is smaller than the size of the list. 6 | # 7 | # Ex: If the input of the program is: 8 | # 9 | # 5 10 | # 11 | # the program outputs: 12 | # 13 | # Name: Jane 14 | # 15 | # Ex: If the input of the program is: 16 | # 17 | # 12 18 | # 19 | # the program outputs: 20 | # 21 | # Exception! list index out of range 22 | # The closest name is: Johnny 23 | # 24 | # Ex: If the input of the program is: 25 | # 26 | # -2 27 | # 28 | # the program outputs: 29 | # 30 | # Name: Tyrese 31 | # 32 | # Ex: If the input of the program is: 33 | # 34 | # -15 35 | # 36 | # the program outputs: 37 | # 38 | # Exception! list index out of range 39 | # The closest name is: Ryley 40 | 41 | names = ['Ryley', 'Edan', 'Reagan', 'Henry', 'Caius', 'Jane', 'Guto', 'Sonya', 'Tyrese', 'Johnny'] 42 | index = int(input()) 43 | 44 | try: 45 | if index < -1 * len(names) or index >= len(names): 46 | # the index error's argument prints inside the except block 47 | raise IndexError('Exception! list index out of range') 48 | print(f'Name: {names[index]}') 49 | except IndexError as excpt: 50 | # selects the closest name to requested index for output 51 | if index < 0: 52 | out_str = names[0] 53 | else: 54 | out_str = names[len(names)-1] 55 | # outputs the exception message and the closest name 56 | print(excpt) 57 | print(f'The closest name is: {out_str}') 58 | 59 | -------------------------------------------------------------------------------- /practice-test-1/question14.py: -------------------------------------------------------------------------------- 1 | # 33.14 LAB: Palindrome 2 | # 3 | # A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome. 4 | # 5 | # Ex: If the input is: 6 | # 7 | # bob 8 | # the output is: 9 | # 10 | # bob is a palindrome 11 | # Ex: If the input is: 12 | # 13 | # bobby 14 | # the output is: 15 | # 16 | # bobby is not a palindrome 17 | # Hint: Start by removing spaces. Then check if a string is equivalent to it's reverse. 18 | 19 | user_str = input() 20 | palindrome = True 21 | out_str = '' 22 | test_str = '' 23 | 24 | # this for loop removes whitespace and assigns it to a string to be tested 25 | for i in user_str: 26 | if i != ' ' and i != '\n' and i != '\t': 27 | test_str += i 28 | 29 | # this tests the string going to the halfway point 30 | # (not including a central value if the number of characters is odd). 31 | # This is done because in a palindrome you compare the opposite sides 32 | # against each other. So when you have checked halfway up the string, you've 33 | # also checked halfway down the string. 34 | # (If the number of characters is odd, the central value is always considered a mirror 35 | # of itself, so there is never a reason to compare it to anything.) 36 | for i in range(len(test_str)//2): 37 | 38 | # Index -1 is the rightmost char while Index 0 is the leftmost char. 39 | # They are both the starting points as the loop moves one letter 40 | # inward each itteration. If there is a mismatch, the boolean is 41 | # set false and the for loop is exited. 42 | if test_str[0+i] != test_str[-1-i]: 43 | palindrome = False 44 | break 45 | 46 | # This can also be done without a for loop, but is less computationally efficient: 47 | # 48 | # if test_str != test_str[::-1]: 49 | # palindrome = False 50 | 51 | 52 | if palindrome: 53 | out_str += f'{user_str} is a palindrome' 54 | else: 55 | out_str += f'{user_str} is not a palindrome' 56 | 57 | print(out_str) -------------------------------------------------------------------------------- /practice-test-2/question13/question13.py: -------------------------------------------------------------------------------- 1 | # 34.13 PRACTICE: Manipulate CSV files 2 | # Instructions: 3 | # 4 | # Create a Python solution to the following task. Ensure that the solution produces output in exactly the same format shown in the sample(s) below, including capitalization and whitespace. 5 | # Task: 6 | # 7 | # Create a solution that accepts an input identifying the name of a CSV file, for example, "input1.csv". Each file contains two rows of comma-separated values. Import the built-in module csv and use its open() function and reader() method to create a dictionary of key:value pairs for each row of comma-separated values in the specified file. Output the file contents as two dictionaries. 8 | # 9 | # The solution output should be in the format 10 | # 11 | # {'key': 'value', 'key': 'value', 'key': 'value'} 12 | # {'key': 'value', 'key': 'value', 'key': 'value'} 13 | # 14 | # Sample Input/Output: 15 | # 16 | # If the input is 17 | # 18 | # input1.csv 19 | # 20 | # then the expected output is 21 | # 22 | # {'a': '100', 'b': '200', 'c': '300'} 23 | # {'bananas': '1.85', 'steak': '19.99', 'cookies': '4.52'} 24 | # 25 | # Alternatively, if the input is 26 | # 27 | # input2.csv 28 | # 29 | # then the expected output is 30 | # 31 | # {'d': '400', 'e': '500', 'f': '600'} 32 | # {'celery': '2.81', 'milk': '4.34', 'bread': '5.63'} 33 | 34 | import csv 35 | file_name = input() 36 | dictionary1 = {} 37 | dictionary2 = {} 38 | 39 | # File IO, delimiter isn't needed in this case, but I've used it anyways 40 | # because it's important to remember how it works in case you are working 41 | # with a different seperator. 42 | with open(file_name, 'r') as file_in: 43 | intake = csv.reader(file_in, delimiter = ',') 44 | 45 | # Processing the intake file and stripping whitespace 46 | for i, row in enumerate(intake): 47 | if i == 0: 48 | for item in range(0, len(row), 2): 49 | dictionary1[row[item].strip()] = row[item+1].strip() 50 | else: 51 | for item in range(0, len(row), 2): 52 | dictionary2[row[item].strip()] = row[item+1].strip() 53 | 54 | print(dictionary1) 55 | print(dictionary2) 56 | -------------------------------------------------------------------------------- /chapter-14-files/question4/question04.py: -------------------------------------------------------------------------------- 1 | # 14.11 LAB: File name change 2 | # 3 | # A photographer is organizing a photo collection about the national parks in the US and would like to annotate the information about each of the photos into a separate set of files. Write a program that reads the name of a text file containing a list of photo file names. The program then reads the photo file names from the text file, replaces the "_photo.jpg" portion of the file names with "_info.txt", and outputs the modified file names. 4 | # 5 | # Assume the unchanged portion of the photo file names contains only letters and numbers, and the text file stores one photo file name per line. If the text file is empty, the program produces no output. 6 | # 7 | # Ex: If the input of the program is: 8 | # 9 | # ParkPhotos.txt 10 | # 11 | # and the contents of ParkPhotos.txt are: 12 | # 13 | # Acadia2003_photo.jpg 14 | # AmericanSamoa1989_photo.jpg 15 | # BlackCanyonoftheGunnison1983_photo.jpg 16 | # CarlsbadCaverns2010_photo.jpg 17 | # CraterLake1996_photo.jpg 18 | # GrandCanyon1996_photo.jpg 19 | # IndianaDunes1987_photo.jpg 20 | # LakeClark2009_photo.jpg 21 | # Redwood1980_photo.jpg 22 | # VirginIslands2007_photo.jpg 23 | # Voyageurs2006_photo.jpg 24 | # WrangellStElias1987_photo.jpg 25 | # 26 | # the output of the program is: 27 | # 28 | # Acadia2003_info.txt 29 | # AmericanSamoa1989_info.txt 30 | # BlackCanyonoftheGunnison1983_info.txt 31 | # CarlsbadCaverns2010_info.txt 32 | # CraterLake1996_info.txt 33 | # GrandCanyon1996_info.txt 34 | # IndianaDunes1987_info.txt 35 | # LakeClark2009_info.txt 36 | # Redwood1980_info.txt 37 | # VirginIslands2007_info.txt 38 | # Voyageurs2006_info.txt 39 | # WrangellStElias1987_info.txt 40 | 41 | # Solution: 42 | 43 | # Varible Declaration Block 44 | user_input = input() 45 | lines = [] 46 | outfile = '' 47 | 48 | # File IO block 49 | with open(user_input, 'r') as file_in: 50 | lines = file_in.readlines() 51 | 52 | # Replacing the string for each line to change names according to requirements. 53 | for i in range(len(lines)): 54 | outfile += lines[i].replace('_photo.jpg', '_info.txt') 55 | 56 | # Output only if there are lines, failure to put the print statement in an if 57 | # statement makes unit test fail, as eve 58 | if len(lines) != 0: 59 | print(outfile, end="") -------------------------------------------------------------------------------- /practice-test-1/question19/question19.py: -------------------------------------------------------------------------------- 1 | # 33.19 LAB: Thesaurus 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 14. Files. To successfully complete this lab, review the content of Chapter 14, as well as the preceding chapters, and complete the Challenge Activities associated. 4 | # 5 | # Given a set of text files containing synonyms for different words, complete the main program to output the synonyms for a specific word. Each text file contains synonyms for the word specified in the file’s name, and each row within the file lists the word’s synonyms that begin with the same letter, separated by a space. The program reads a word and a letter from the user and opens the text file associated with the input word. The program then stores the contents of the text file into a dictionary predefined in the program. Finally the program searches the dictionary and outputs all the synonyms that begin with the input letter, one synonym per line, or a message if no synonyms that begin with the input letter are found. 6 | # 7 | # Hints: Use the first letter of a synonym as the key when storing the synonym into the dictionary. Assume all letters are in lowercase. 8 | # 9 | # Ex: If the input of the program is: 10 | # 11 | # educate 12 | # c 13 | # the program opens the file educate.txt, which contains: 14 | # 15 | # brainwash brief 16 | # civilize coach cultivate 17 | # develop discipline drill 18 | # edify enlighten exercise explain 19 | # foster 20 | # improve indoctrinate inform instruct 21 | # mature 22 | # nurture 23 | # rear 24 | # school 25 | # train tutor 26 | # then the program outputs: 27 | # 28 | # civilize 29 | # coach 30 | # cultivate 31 | # Ex: If the input of the program is: 32 | # 33 | # educate 34 | # a 35 | # then the program outputs: 36 | # 37 | # No synonyms for educate begin with a. 38 | 39 | synonyms = {} 40 | word_ref = input().strip() 41 | char_ref = input().strip() 42 | 43 | with open(word_ref + '.txt', 'r') as file_in: 44 | lines = file_in.readlines() 45 | for line in lines: 46 | wordlist = [] 47 | for word in line.split(): 48 | wordlist.append(word) 49 | synonyms[word[0]] = wordlist 50 | 51 | 52 | if char_ref not in synonyms: 53 | print(f'No synonyms for {word_ref} begin with {char_ref}.') 54 | else: 55 | out_str = '' 56 | for word in synonyms[char_ref]: 57 | out_str += f'{word}\n' 58 | print(f'{out_str}', end='') -------------------------------------------------------------------------------- /practice-test-1/question13.py: -------------------------------------------------------------------------------- 1 | # 33.13 LAB: Warm up: Text analyzer & modifier 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 10. Strings. To successfully complete this lab, review the content of Chapter 10, as well as the preceding chapters, and complete the Challenge Activities associated. 4 | # 5 | # (1) Prompt the user to enter a string of their choosing. Output the string. (1 pt) 6 | # 7 | # Ex: 8 | # 9 | # Enter a sentence or phrase: 10 | # The only thing we have to fear is fear itself. 11 | # 12 | # You entered: The only thing we have to fear is fear itself. 13 | # (2) Complete the get_num_of_characters() function, which returns the number of characters in the user's string. We encourage you to use a for loop in this function. (2 pts) 14 | # 15 | # (3) Extend the program by calling the get_num_of_characters() function and then output the returned result. (1 pt) 16 | # 17 | # (4) Extend the program further by implementing the output_without_whitespace() function. output_without_whitespace() outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is '\t'. Call the output_without_whitespace() function in main(). (2 pts) 18 | # 19 | # Ex: 20 | # 21 | # Enter a sentence or phrase: 22 | # The only thing we have to fear is fear itself. 23 | # 24 | # You entered: The only thing we have to fear is fear itself. 25 | # 26 | # Number of characters: 46 27 | # String with no whitespace: Theonlythingwehavetofearisfearitself. 28 | 29 | def get_num_of_characters(input_str): 30 | # note the count INCLUDES whitespace characters 31 | # they ask you to use a for loop, however you could simply 32 | # output len(input_str) 33 | count = 0 34 | for i in range(len(input_str)): 35 | count += 1 36 | return count 37 | 38 | def output_without_whitespace(input_str): 39 | #output string starts empty 40 | out_str = '' 41 | 42 | # for each char in the string 43 | for i in input_str: 44 | # if the character in the in string isn't a whitespace char 45 | # concatenate it to the end of the out string. 46 | if i != ' ' and i != '\n' and i != '\n' and i != '\t': 47 | out_str += i 48 | # after the for loop return the completed out string 49 | return out_str 50 | 51 | 52 | if __name__ == '__main__': 53 | user_input = input('Enter a sentence or phrase:\n') 54 | print() 55 | print(f'You entered: {user_input}') 56 | print() 57 | print(f'Number of characters: {get_num_of_characters(user_input)}') 58 | print (f'String with no whitespace: {output_without_whitespace(user_input)}') -------------------------------------------------------------------------------- /practice-test-1/question08.py: -------------------------------------------------------------------------------- 1 | # 33.8 LAB: Exact change 2 | # Instructor note: 3 | # The skills required for this lab are covered in Chapter 5. Branching. 4 | # To successfully complete this lab, review the content of Chapter 5, 5 | # as well as the preceding chapters, and complete the Challenge Activities associated. 6 | 7 | # Write a program with total change amount as an integer input, 8 | # and output the change using the fewest coins, one coin type per line. 9 | # The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. 10 | # Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. 11 | 12 | # Ex: If the input is: 13 | 14 | # 0 15 | # (or less than 0), the output is: 16 | 17 | # No change 18 | # Ex: If the input is: 19 | 20 | # 45 21 | # the output is: 22 | 23 | # 1 Quarter 24 | # 2 Dimes 25 | 26 | #Variable Declaration 27 | 28 | dollars = 0 29 | quarter = 0 30 | dimes = 0 31 | nickles = 0 32 | cents = 0 33 | 34 | #User Input 35 | cents = int(input()) 36 | 37 | #The first if statement fulfills requirement: 38 | 39 | # Ex: If the input is: 40 | 41 | # 0 42 | # (or less than 0), the output is: 43 | 44 | # No change 45 | 46 | 47 | # 48 | if cents <= 0: 49 | print("No change") 50 | else: 51 | 52 | # Assignment of values for each currency size 53 | # starting from greatest to least: 54 | 55 | dollars = cents // 100 56 | 57 | # which is the even amount of dollars 58 | # in the total cent amount. 59 | 60 | 61 | # The total cents is then updated the modulo of the 62 | # currency size: 63 | 64 | cents = cents % 100 65 | 66 | # The process is then logically repeated for all 67 | # currency divisions: 68 | 69 | quarters = cents // 25 70 | cents = cents % 25 71 | 72 | dimes = cents // 10 73 | cents = cents % 10 74 | 75 | nickels = cents // 5 76 | cents = cents % 5 77 | 78 | # Total change amounts are now correctly calculated 79 | # The following if statements output the data in the 80 | # required format: 81 | 82 | if dollars > 0: 83 | if dollars == 1: 84 | print(f'{dollars} Dollar') 85 | else: 86 | print(f'{dollars} Dollars') 87 | if quarters > 0: 88 | if quarters == 1: 89 | print(f'{quarters} Quarter') 90 | else: 91 | print(f'{quarters} Quarters') 92 | if dimes != 0: 93 | if dimes > 1: 94 | print(f'{dimes} Dime') 95 | else: 96 | print(f'{dimes} Dimes') 97 | if nickels > 0: 98 | if nickels == 1: 99 | print(f'{nickels} Nickel') 100 | else: 101 | print(f'{nickles} Nickels') 102 | if cents > 0: 103 | if cents == 1: 104 | print(f'{cents} Penny') 105 | else: 106 | print(f'{cents} Pennies') -------------------------------------------------------------------------------- /chapter-14-files/question2/question02.py: -------------------------------------------------------------------------------- 1 | # 14.9 LAB: Sorting TV Shows (dictionaries and lists) 2 | # Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. 3 | # The input file contains an unsorted list of number of seasons followed by the corresponding TV show. 4 | # Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, 5 | # and a list of TV shows are the values (since multiple shows could have the same number of seasons). 6 | # 7 | # Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt. 8 | # Separate multiple TV shows associated with the same key with a semicolon (;), ordering by appearance in the input file. 9 | # Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt. 10 | # 11 | # Ex: If the input is: 12 | # 13 | # file1.txt 14 | # and the contents of file1.txt are: 15 | # 16 | # 20 17 | # Gunsmoke 18 | # 30 19 | # The Simpsons 20 | # 10 21 | # Will & Grace 22 | # 14 23 | # Dallas 24 | # 20 25 | # Law & Order 26 | # 12 27 | # Murder, She Wrote 28 | # the file output_keys.txt should contain: 29 | # 30 | # 10: Will & Grace 31 | # 12: Murder, She Wrote 32 | # 14: Dallas 33 | # 20: Gunsmoke; Law & Order 34 | # 30: The Simpsons 35 | # and the file output_titles.txt should contain: 36 | # 37 | # Dallas 38 | # Gunsmoke 39 | # Law & Order 40 | # Murder, She Wrote 41 | # The Simpsons 42 | # Will & Grace 43 | # Note: There is a newline at the end of each output file, and file1.txt is available to download. 44 | 45 | # Solution: 46 | 47 | # Varible Declaration Block 48 | input_file = input() 49 | my_dict = {} 50 | out_keys = 'output_keys.txt' 51 | out_titles = 'output_titles.txt' 52 | titles = [] 53 | 54 | # with open block takes in lines from the file 55 | with open(input_file, 'r') as file_in: 56 | lines = file_in.readlines() 57 | 58 | # For every other line read, (interval of 2) 59 | # Add the Key and the value inside a list to the dictionary if the key isn't already in the dictionary. 60 | # If the key is in the dictionary updates the key by appending the value to the existing value's list. 61 | for i in range(0, len(lines), 2): 62 | # words from the line are stripped to prevent unwanted whitespace such as leading spaces or newlines (\n's) 63 | # from being entered into the dictionary. 64 | my_key = int(lines[i].strip()) 65 | my_value = lines[i+1].strip() 66 | if my_key in my_dict: 67 | my_dict[my_key].append(my_value) 68 | else: 69 | my_dict[my_key] = [my_value] 70 | 71 | titles.append(my_value) 72 | 73 | # Sorts the dictionary based on key (seasons run) 74 | my_dict = sorted(my_dict.items()) 75 | 76 | out_str = '' 77 | 78 | 79 | # This assembles a string to export output_keys.txt 80 | for i in range(len(my_dict)): 81 | out_str += str(my_dict[i][0]) 82 | for j in range(len(my_dict[i][1])): 83 | sep_str = ': ' 84 | if j > 0: 85 | sep_str = '; ' 86 | out_str += sep_str + my_dict[i][1][j] 87 | out_str += '\n' 88 | 89 | # Exports string into the output_keys.txt 90 | with open(out_keys, 'w') as file_out: 91 | file_out.write(out_str) 92 | # print(out_str) # test outputs, no effect on grading, but I would disable 93 | # this on the real test. 94 | 95 | # Builds string for output into out_titles.txt 96 | out_str = '' 97 | titles.sort() 98 | for title in titles: 99 | out_str += title + '\n' 100 | # print(out_str) # test outputs, no effect on grading, but I would disable 101 | # this on the real test. 102 | 103 | # Exports string into out_titles.txt 104 | with open(out_titles, 'w') as file_out: 105 | file_out.write(out_str) -------------------------------------------------------------------------------- /chapter-12-exceptions/question4.py: -------------------------------------------------------------------------------- 1 | # 12.10 LAB: Student info not found - custom exception types 2 | # 3 | # Given a main program that searches for the ID or the name of a student from a dictionary, complete the find_ID() and the find_name() functions that return the corresponding information of a student. Then, insert a try/except statement in main() to catch any exceptions thrown by find_ID() or find_name(), and output the exception message. Each entry of the dictionary contains the name (key) and the ID (value) of a student. 4 | # 5 | # Function find_ID() takes two parameters, a student's name and a dictionary. Function find_ID() returns the ID associated with the student's name if the name is in the dictionary. Otherwise, the function throws a custom exception type, StudentInfoError, with the message "Student ID not found for studentName", where studentName is the name of the student. 6 | # 7 | # Function find_name() takes two parameters, a student's ID and a dictionary. Function find_name() returns the name associated with the student's ID if the ID is in the dictionary. Otherwise, the function throws a custom exception type, StudentInfoError, with the message "Student name not found for studentID", where studentID is the ID of the student. 8 | # 9 | # The main program takes two inputs from a user: a user choice of finding the ID or the name of a student (int), and the ID or the name of a student (string). If the user choice is 0, find_ID() is invoked with the student's name as one of the arguments. If the user choice is 1, find_name() is invoked with the student's ID as one of the arguments. The main program finally outputs the result of the search or a message if an exception is caught. 10 | # 11 | # Note: StudentInfoError is defined in the program as a custom exception type. StudentInfoError has an attribute to store an exception message. 12 | # 13 | # Ex: If the input of the program is: 14 | # 15 | # 0 16 | # Reagan 17 | # 18 | # and the contents of dictionary are: 19 | # 20 | # 'Reagan' : 'rebradshaw835', 21 | # 'Ryley' : 'rbarber894', 22 | # 'Peyton' : 'pstott885', 23 | # 'Tyrese' : 'tmayo945', 24 | # 'Caius' : 'ccharlton329' 25 | # 26 | # the output of the program is: 27 | # 28 | # rebradshaw835 29 | # 30 | # Ex: If the input of the program is: 31 | # 32 | # 0 33 | # Mcauley 34 | # 35 | # the program outputs an exception message: 36 | # 37 | # Student ID not found for Mcauley 38 | # 39 | # Ex: If the input of the program is: 40 | # 41 | # 1 42 | # rebradshaw835 43 | # 44 | # the output of the program is: 45 | # 46 | # Reagan 47 | # 48 | # Ex: If the input of the program is: 49 | # 50 | # 1 51 | # mpreston272 52 | # 53 | # the program outputs an exception message: 54 | # 55 | # Student name not found for mpreston272 56 | 57 | # Define custom exception 58 | class StudentInfoError(Exception): 59 | def __init__(self, message): 60 | self.message = message # Initialize the exception message 61 | 62 | 63 | def find_ID(name, info): 64 | if not(name in info): 65 | raise StudentInfoError(f'Student ID not found for {name}') 66 | return info[name] 67 | 68 | 69 | def find_name(ID, info): 70 | # Type your code here. 71 | for i in info: 72 | if info[i] == ID: 73 | return i 74 | raise StudentInfoError(f'Student name not found for {ID}') 75 | 76 | 77 | if __name__ == '__main__': 78 | # Dictionary of student names and IDs 79 | student_info = { 80 | 'Reagan' : 'rebradshaw835', 81 | 'Ryley' : 'rbarber894', 82 | 'Peyton' : 'pstott885', 83 | 'Tyrese' : 'tmayo945', 84 | 'Caius' : 'ccharlton329' 85 | } 86 | 87 | userChoice = input() # Read search option from user. 0: find_ID(), 1: find_name() 88 | 89 | # try/except statement catches the exception. 90 | try: 91 | if userChoice == "0": 92 | name = input() 93 | result = find_ID(name, student_info) 94 | else: 95 | ID = input() 96 | result = find_name(ID, student_info) 97 | print(result) 98 | 99 | # exception handler outputs the exception message. 100 | except StudentInfoError as excpt: 101 | print(excpt) 102 | 103 | -------------------------------------------------------------------------------- /chapter-14-files/question3/question03.py: -------------------------------------------------------------------------------- 1 | # 14.10 LAB: Course Grade 2 | # 3 | # Write a program that reads the student information from a tab separated values (tsv) file. The program then creates a text file that records the course grades of the students. Each row of the tsv file contains the Last Name, First Name, Midterm1 score, Midterm2 score, and the Final score of a student. A sample of the student information is provided in StudentInfo.tsv. Assume the number of students is at least 1 and at most 20. Assume also the last names and first names do not contain whitespaces. 4 | # 5 | # The program performs the following tasks: 6 | # 7 | # Read the file name of the tsv file from the user. 8 | # Open the tsv file and read the student information. 9 | # Compute the average exam score of each student. 10 | # Assign a letter grade to each student based on the average exam score in the following scale: 11 | # A: 90 =< x 12 | # B: 80 =< x < 90 13 | # C: 70 =< x < 80 14 | # D: 60 =< x < 70 15 | # F: x < 60 16 | # Compute the average of each exam. 17 | # Output the last names, first names, exam scores, and letter grades of the students into a text file named report.txt. Output one student per row and separate the values with a tab character. 18 | # Output the average of each exam, with two digits after the decimal point, at the end of report.txt. Hint: Use the format specification to set the precision of the output. 19 | # 20 | # Ex: If the input of the program is: 21 | # 22 | # StudentInfo.tsv 23 | # 24 | # and the contents of StudentInfo.tsv are: 25 | # 26 | # Barrett Edan 70 45 59 27 | # Bradshaw Reagan 96 97 88 28 | # Charlton Caius 73 94 80 29 | # Mayo Tyrese 88 61 36 30 | # Stern Brenda 90 86 45 31 | # 32 | # the file report.txt should contain: 33 | # 34 | # Barrett Edan 70 45 59 F 35 | # Bradshaw Reagan 96 97 88 A 36 | # Charlton Caius 73 94 80 B 37 | # Mayo Tyrese 88 61 36 D 38 | # Stern Brenda 90 86 45 C 39 | # 40 | # Averages: midterm1 83.40, midterm2 76.60, final 61.60 41 | 42 | 43 | # Solution: 44 | 45 | # The CSV module will be used to read the tsv file. 46 | import csv 47 | 48 | # Function to read a file and return a list containing the contents 49 | def read_file(user_input): 50 | # declare output varible 51 | grades_out = [] 52 | with open(user_input, 'r') as file_in: 53 | 54 | # *The delimiter attribute is something you should remember 55 | grades_in = csv.reader(file_in, delimiter = '\t') 56 | 57 | # Converting the object to a list. Returning grades_in would 58 | # return a raw csv class object, which is much more awkward 59 | # to manipulate than a list. 60 | for row in grades_in: 61 | grades_out.append(row) 62 | 63 | return(grades_out) 64 | 65 | # Varible declarations and input function calls 66 | grades = read_file(input()) 67 | exam_totals = [0,0,0] 68 | exam_averages = [0.0,0.0,0.0] 69 | fileout = '' 70 | 71 | # A lot of what is coming up is hard to decipher at first, but 72 | # each record (i) is made of 5 parts, 0-4 whos index we'll call j. 73 | # 74 | # Like this: 75 | # i 76 | # | 77 | # V 78 | # j-> [0] [1] [2] [3] [4] 79 | # [0] Barrett Edan 70 45 59 80 | # [1] Bradshaw Reagan 96 97 88 81 | # [2] Charlton Caius 73 94 80 82 | # [3] Mayo Tyrese 88 61 36 83 | # [4] Stern Brenda 90 86 45 84 | # 85 | # To find the final grade for each student we take the sum of 86 | # the values at j indexes 2, 3 and 4 and divide by 3. 87 | # Then a branching statement determines the letter grade. 88 | for i in range(len(grades)): 89 | grade = (int(grades[i][2])+int(grades[i][3])+int(grades[i][4])) / 3 90 | letter_grade = '' 91 | if grade >= 90: 92 | letter_grade = 'A' 93 | elif grade >= 80: 94 | letter_grade = 'B' 95 | elif grade >= 70: 96 | letter_grade = 'C' 97 | elif grade >= 60: 98 | letter_grade = 'D' 99 | else: 100 | letter_grade = 'F' 101 | grades[i].append(letter_grade) 102 | 103 | # Running sums taken here for class exam averages later 104 | exam_totals[0] += int(grades[i][2]) 105 | exam_totals[1] += int(grades[i][3]) 106 | exam_totals[2] += int(grades[i][4]) 107 | 108 | # For loop that calculates the class exam averages 109 | for i in range(3): 110 | exam_averages[i] = exam_totals[i] / len(grades) 111 | 112 | # Each line is added according to required format. 113 | # fileout is initialy a blank string (declared above). 114 | for i in range(len(grades)): 115 | fileout += f'{grades[i][0]}\t{grades[i][1]}\t{grades[i][2]}\t{grades[i][3]}\t{grades[i][4]}\t{grades[i][5]}\n' 116 | 117 | # Closing line according to format, notice the leading newline 118 | # that is used to double space the lines as per output requirements. 119 | fileout += f'\nAverages: midterm1 {exam_averages[0]:.2f}, midterm2 {exam_averages[1]:.2f}, final {exam_averages[2]:.2f}\n' 120 | 121 | # Output to file 122 | with open('report.txt', 'w') as file_out: 123 | file_out.write(fileout) --------------------------------------------------------------------------------