############################################################################# # Intro01: Go Cougars!.py ############################################################################# # Description """ In the other window on the screen, replace the (green) string literal '''Put your code here''' with Python code that displays: Go Cougars! Click on the button with the word "run" with a solid triangle next to it. The output should appear in the black terminal screen. After you get it to display the message exactly, press the green submit button. All done! """ # Provided code """ '''Put your code here''' """ # test case # Regex: [gG]o\s+[cC]ougars!? ############################################################################# # Intro02: Quotes.py ############################################################################# # Description """ Write Python code so that the following text is displayed (exactly as shown): Cody the Cougar yelled, "Let's go!" """ # Provided code """ """ # test case # Flexible: Cody the Cougar yelled, "Let's go!" ############################################################################# # Intro03: CSU Fight Song.py ############################################################################# # Description """ Using a single call to the print() function, display the beginning of the CSU fight song (on 4 lines): On! On! Ye Cougars! We will fight for victory! On! On! Ye Cougars! We have the pride for all to see! """ # Provided code """ '''Put your code here''' """ # test case # Flexible: On! On! Ye Cougars! # We will fight for victory! # On! On! Ye Cougars! # We have the pride for all to see! ############################################################################# # Intro04: Assigning a Variable.py ############################################################################# # Description """ Replace the (green) string literal '''Put your code here''' with Python code that creates a variable named letterGrade. Have letterGrade reference the value "A+". Note: Submit your code with the print(letterGrade) statement. """ # Provided code """ '''Put your code here''' print(letterGrade) """ # test case # Flexible: A+ ############################################################################# # Intro05: Number of Classes.py ############################################################################# # Description """ Replace the (green) string literal '''Put your code here''' with Python code that creates a variable named numberOfClasses. Assign the variable numberOfClasses with the number of classes that you are taking this semester. """ # Provided code """ '''Put your code here''' print(numberOfClasses) """ # test case, if any # Regex: \d+ ############################################################################# # Intro06: 1958 (int).py ############################################################################# # Description """ Replace the (green) string literal '''Put your code here''' with Python code that creates a variable named year. Assign 1958 to the variable year so that your code displays the following: """ # Provided code """ '''Put your code here''' print( type( year ) ) """ # test case, if any # flexible: ############################################################################# # Intro07: 1958 (str).py ############################################################################# # Description """ Replace the (green) string literal '''Put your code here''' with Python code that creates a variable named year. Assign 1958 to the variable year so that your code displays the following: """ # Provided code """ '''Put your code here''' print( type( year ) ) """ # test case, if any # flexible: ############################################################################# # Intro08: Pi Approximation.py ############################################################################# # Description """ The fraction 22/7 is sometimes used as a rough approximation for Pi (3.14159...). Write a Python expression that divides 22 by 7 and assigns the result to a variable named piApproximate. """ # Provided code """ '''Put your code here''' print( piApproximate ) """ # test case, if any # flexible: 3.142857142857143 ############################################################################# # Intro09: Friends and Pizza Slices.py ############################################################################# # Description """ Assume that you have 22 slices of pizza and 7 friends that are going to share it (you've already eaten). There's been some arguments among your friends, so you've decided to only give people whole slices. Write a Python expression with the values 22 and 7 that calculates the number of whole slices each person would receive and assigns the result to numberOfWholeSlices. """ # Provided code """ '''Put your code here''' print( numberOfWholeSlices ) """ # test case, if any # Strict: 3 ############################################################################# # Intro10: Pizza for Fido.py ############################################################################# # Description """ Assume that you have 22 slices of pizza and 7 people that are going to share it. There's been some arguments among your friends, so you've decided to only give people whole slices. Your pet dog Fido loves pizza. Write a Python expression with the remainder operator that calculates how many pizza slices will be left over for your dog after serving just whole slices to 7 people. Assign the result of that expression to fidos. """ # Provided code """ '''Put your code here''' print( fidos ) """ # test case, if any # Strict: 1 ############################################################################# # Intro11: Hello.py ############################################################################# # Description """ Python allows you to get information from a user with the built-in function named input(). In repl.it, any input values are already entered, it's just waiting for a Python script to request it. For this problem, write a Python script that prompts the user (in this case, the repl.it system) with exactly the following: Please enter your name: repl.it will then enter a name. Assign that value to username. Example 1: Please enter your name: Pat Hello Pat Example 2: Please enter your name: repl Hello repl """ # Provided code """ '''Put your prompt here''' print( 'Hello', username) """ # test case # Input: repl; Regex: .+Hello repl # Input: Pat; Regex: .+Hello Pat # Input: Chris; Regex: .+Hello Chris ############################################################################# # Intro12: Years as Columbus College.py ############################################################################# # Description """ For this problem, we're going to have python calculate the number of years that CSU was known as Columbus College. First, prompt the user to enter the year that Columbus College was renamed to be Columbus State University and assign that to a variable named csuYear. Then, prompt the user to enter the year that Columbus College was founded and assign that value to ccBirthYear. Note, if after submitting your solution it says: failed Regex - Error Then, click on the green "What's wrong?" button. If the Error details has something like: TypeError: unsupported operand type(s) for -: 'str' and 'str' then that means that the Python interpreter does not know how to subtract one string from another. Hint: It needs those variables to be ints and not strs. Note, if after submitting your solution it says: failed Regex - Output mismatch Then, click on the green "What's wrong?" button. If the difference block has: .+You entered 1996 .+You entered 1958 with the ".+" crossed through, This means that you are missing a prompt. Add one and re-submit. By the way, ".+" is a regular expression. It means it was expecting one or more characters. """ # Provided code """ '''Prompt the user and get the year Columbus College was renamed to CSU''' print('You entered', csuYear) '''Prompt the user and get the year Columbus College was founded from the user''' print('You entered', ccBirthYear) print( 'CSU was known as Columbus College for its first', csuYear - ccBirthYear, 'years') """ # test case, if any def testCase(): # Regex: .+You entered 1996 # .+You entered 1958 # CSU was known as Columbus College for its first 38 years ############################################################################# # Intro13: Lowest to Highest Precedence.py ############################################################################# # Description """ In math and Python, 3 * 4 + 5, (3 * 4) + 5 and ((3 * 4) + 5) are equivalent. The set of parentheses only makes the precedence order explicit. For this problem, add sets of parentheses so that the Python expression is evaluated with the lowest order of precedence first. (See https://runestone.academy/runestone/static/thinkcspy/Appendices/PrecedenceTable.html for a Python operator precedence table.) Hint, for the first expression, the operator with the lowest precedence is subtraction, so the first set of parentheses to add would be around 9 - 2. """ # Provided code """ '''Add parentheses so that the following expression is evaluated from the lowest to the highest precedence order''' result1 = 8 / 2 ** 9 - 2 print( 'result1:', result1 ) result2 = 1 - 2 * 3 + 4 / 5 print( 'result2:', result2 ) result3 = 1 * 2 - 3 / 4 print( 'result3:', result3 ) result4 = 66 // 7 ** 8 % 9 + 10) print( 'result4:', result4 ) """ # test case, if any # Flexible: result1: 16384.0 # result2: -1.4 # result3: -0.25 # result4: 43046721 ############################################################################# # Intro14: Making Change.py ############################################################################# # Description """ Implement a Python program that directs a cashier how to give change. The program has two inputs: the amount due and the amount received from the customer. Display the dollars, quarters, dimes, nickels, and pennies that the customer should receive in return. In order to avoid round-off errors, the user should supply both amounts in pennies. For example, for the amount $5 and 26 cents, the user will enter 526 (instead of 5.26). For this assignment you may need find it helpful to use // (the integer division operator) and % (the remainder operator) . Example 1: Enter the amount due in pennies: 828 Enter the amount received from the customer in pennies: 1000 Give the following change to the customer: 1 dollars, 2 quarters, 2 dimes, 0 nickels and 2 pennies Example 2: Enter the amount due in pennies: 456 Enter the amount received from the customer in pennies: 2000 Give the following change to the customer: 15 dollars, 1 quarters, 1 dimes, 1 nickels and 4 pennies Example 3: Enter the amount due in pennies: 401 Enter the amount received from the customer in pennies: 500 Give the following change to the customer: 0 dollars, 3 quarters, 2 dimes, 0 nickels and 4 pennies """ # Provided code """ # Retrieve inputs # Calculate dollars to return # Calculate quarters to return # Calculate dimes to return # Calculate nickels to return # Calculate pennies to return # Display change due print("Give the following change to the customer:") print( dollars, "dollars,", quarters, "quarters,", dimes, "dimes,", nickels, "nickels and", pennies, "pennies") """ # test case # Input: 828\n1000; Regex: .+Give the following change to the customer: # 1 dollars, 2 quarters, 2 dimes, 0 nickels and 2 pennies # Input: 456\n2000; Regex: .+Give the following change to the customer: # 15 dollars, 1 quarters, 1 dimes, 1 nickels and 4 pennies # Input: 401\n500; Regex: .+Give the following change to the customer: # 0 dollars, 3 quarters, 2 dimes, 0 nickels and 4 pennies # Input: 499\n500; Regex: .+Give the following change to the customer: # 0 dollars, 0 quarters, 0 dimes, 0 nickels and 1 pennies ############################################################################# # Modules01: Dice Simulator.py ############################################################################# # Description """ Write a program in Python that simulates the roll of a 6-sided die and an 8-sided die. Generate a random number for the 6-side die and store it in a variable named die1. Generate a random number for the 8-side die and store it in a variable named die2. Note: Submit your code with the print("You rolled two dice:", die1, "and", die2) statement.""" # Provided code """ """ # test case # Regex: ^You rolled two dice: [1-6] and [1-8]$ ############################################################################# # Modules02: Square Garden.py ############################################################################# # Description """ You have a square garden and want to build a fence around it. Write a program in Python that calculates the total length of fence you will need to surround the garden. Your program should prompt the user to enter the area of the square garden. Store the area in a variable named area. Hint: The side of the square is equal to the square root of the area of the garden. calculates how many meters of fence you will need to surround the garden and stores the perimeter into a variable named total_fence. Hint: You have to calculate the perimeter of the square garden which is four times the length of one side. Note: Submit your code with the print( "You will need", total_fence, "meters" ) statement. Example 1: Please enter the area of the garden: 81 You will need 36.0 meters of fence Example 2: Please enter the area of the garden: 25 You will need 20.0 meters of fence """ # Provided code """ import math # Write your code here # Print the total meters of fence (Do not change the following line!) print( "You will need", total_fence, "meters of fence" ) """ # test case # Input: 25; Regex: .+You will need 20.0 meters of fence # Input: 81; Regex: .+You will need 36.0 meters of fence # Input: 98; Regex: .+You will need 39.395\d+ meters of fence ############################################################################# # Modules03: Random Number.py ############################################################################# # Description """ Write a Python program that generates a random number between 10 and 20 (not including 10 and 20). Store the randomly generated number in a variable named number. Note: Submit your code with the print("The randomly generated number is:", number) statement. Do not change this line. """ # Provided code """ # Write your code here # Display the number (Do not change the following line!) print("The randomly generated number is:", number) """ # test case # Regex: The randomly generated number is: 1\d ############################################################################# # Modules04: Mathematical Constant e.py ############################################################################# # Description """ Write a Python program to display the value of the mathematical constant e supplied by the math module. """ # Provided code """ # Write code here """ # test case # Regex: 2.71828\d+ ############################################################################# # Modules05: Pi.py ############################################################################# # Description """ Write a Python program to display the value of the pi supplied by the math module (see https://docs.python.org/3/library/math.html). """ # Provided code """ # Write your code here """ # test case # Regex: 3.14159\d+ ############################################################################# # Modules06: Pizza Area.py ############################################################################# # Description """ For this assignment, write a Python program that calculates and displays the area of a pizza. Complete the Python program so that it prompts the user to enter the diameter of a pizza calculates the area of the pizza and stores the result in a variable named area. The area of a circle is calculated by π * r^2, where r is the radius (which is half of the diameter). For this assignment, you must use the math module to get the value of π (pi). """ # Provided code """ # Write your code here print("The area of the pizza is:", area) """ # test cases # Input: 16; Regex: .+The area of the pizza is: 201.06\d+ # Input: 14; Regex: .+The area of the pizza is: 153.9\d+ # Input: 12; Regex: .+The area of the pizza is: 113.\d+ ############################################################################# # Functions01CupstoOunces.py ############################################################################# # Description """ Complete the cupsToOunces function so that it takes a number of cups, converts to ounces, and returns the ounces. One cup is eight ounces. The main thing to note here is that you are returning something. There should be no print() calls within your function. If you would like to test your result, execute your code with the "run" button. Example: cupsToOunces(6) will return 48 because 6 cups is 48 ounces """ # Provided code """ def cupsToOunces(): # The following call will only execute when you press the # "run" button above (but not when you submit it). # You need to have cupsToOunces() return a value # (and not display something). print( cupsToOunces( 6 ) ) """ # test case def test_testCtoOz(self): # Failure message: #Your cupsToOunces function must return 8 ounces for every cup self.assertEquals(cupsToOunces(2.5), 20) self.assertEquals(cupsToOunces(1), 8) self.assertEquals(cupsToOunces(3), 24) ############################################################################# # Functions02OuncestoCups.py ############################################################################# # Description """ Complete the ouncesToCups function so that it takes a number of ounces, converts to cups, and returns the cups. One cup is eight ounces. Example: ouncesToCups(48) returns 6 because 48 ounces is 6 cups. """ # Provided code """ def ouncesToCups(): """ # test case def test_testOztoC(self): # Failure message: #Your ouncesToCups functions should 1 cup for every 8 ounces self.assertEquals(ouncesToCups(20), 2.5) self.assertEquals(ouncesToCups(8), 1) self.assertEquals(ouncesToCups(16), 2) ############################################################################# # Functions03ReverseName.py ############################################################################# # Description """ Complete the reverseName() function so that it takes a first name and a last name and returns a string with the entire name reversed. For example, if the first name is Sue and the last name is Walters then the function returns WaltersSue. Note that 'takes' implies that there are parameters, in this case there are two. Example: reverseName("Bob", "Smith") returns 'SmithBob' """ # Provided code """ def reverseName(): """ # test case def test_rvsNme(self): # Failure message: This function should return and first and last name in reverse order. Note that there is no space between the names. self.assertEquals(reverseName("Elaine", "Hollyfield"), "HollyfieldElaine") self.assertEquals(reverseName("Andrew", "Smith"), "SmithAndrew") self.assertEquals(reverseName("Roger", "Jones"), "JonesRoger") ############################################################################# # Functions04CalculateInterest.py ############################################################################# # Description """ Complete the calcInterest function so that it takes in interest rate per period, principal, and number of periods, and returns the amount of simple interest. The interest rate should be expressed as a decimal. Example: For an interest rate of 0.01, a principal of $10,000.00, and 10 periods, the simple interest would be $1,000.00 i.e. calcInterest(0.01, 10000, 10) returns 1000 (0.01 * 10000 * 10) """ # Provided code """ def calcInterest(): """ # test case def test_testCalcIntst(self): # Failure message: The calcInterest function should return the interest rate times the principal times the number of periods. Note that these should be parameters sent to the function. self.assertEquals(calcInterest(0.01, 10000.00, 10), 1000.0) self.assertEquals(calcInterest(0.02, 1000.00, 4), 80.0) self.assertEquals(calcInterest(0.01, 35000, 5), 1750.0) ############################################################################# # Functions05PropertyTax.py ############################################################################# # Description """ A county collects property taxes on the assessment value of property, which is 60% of the property's actual value. The property tax is then $0.56 for each $100 of the assessment value. Complete the propertyTax function so that it takes a property's actual value and returns the property tax using 60% for the assessment value and $0.56 per $100 of assessment value to calculate the tax. Round to 2 decimal places. For example, if a property is valued a $50,000, it's assessment value is $30,000. The tax for property assessed at $30,000 will be $168.00. i.e. propertyTax(50000) returns 168.00 """ # Provided code """ def propertyTax(): """ # test case def test_propertyTax(self): # Failure message: #This function should return a property tax that is $0.56 per $100 of the assessment value of the property. The assessment value is 60% of the actual value of the property. self.assertEquals(propertyTax(50000), 168) self.assertEquals(propertyTax(1000), 3.36) self.assertEquals(propertyTax(24100.55), 80.98) ############################################################################# # Functions06PaintJob.py ############################################################################# # Description """ A painting company has determined that for every 110 square feet of wall space, one gallon of paint and eight hours of labor will be required. Your labor costs depend on how experienced the worker is. Complete the paintJobEstimator function so that takes the number of square feet of wall space to be painted, the cost per hour for labor, and the price of the paint per gallon. Return the total cost of the paint job. Round to two decimal places. Note that you will use the number of square feet to determine how much paint (in gallons) and how much labor (hours) is needed. These can then be multiplied times the cost. Example: paintJobEstimator(200, 15, 25) returns 263.64 """ # Provided code """ def paintJobEstimator(): """ # test case def test_paintJob(self): # Failure message: #This function should return the total cost of the job according to the assignment specifications. self.assertEquals(paintJobEstimator(320, 15, 25.99), 424.70) self.assertEquals(paintJobEstimator(120.5, 19.50, 21), 193.90) self.assertEquals(paintJobEstimator(200, 15, 25), 263.64) ############################################################################# # Functions07StadiumSeating.py ############################################################################# # Description """ There are three seating categories at a stadium. For an upcoming concert, Class A seats cost $75, Class B seats cost $65, and Class C seats cost $50. Complete the eventSeatSales function so that it takes in the number of seats of each class that were sold and returns the amount of income generated from ticket sales. Example: eventSeatSales(100, 50, 150) returns 18250 """ # Provided code """ def eventSeatSales(): """ # test case def test_stadiumSeating(self): # Failure message: #The function should return the total seat sales from all three classes of stadium seats. self.assertEquals(eventSeatSales(10, 12, 40), 3530) self.assertEquals(eventSeatSales(50, 35, 33), 7675) self.assertEquals(eventSeatSales(2, 0, 90), 4650) ############################################################################# # Functions08CaloriesFromFat.py ############################################################################# # Description """ Complete the calFromFat function so that it will take a number of fat grams and return the number of calories from fat using the following calculation: calories from fat = fat grams x 9. Round to 1 decimal place. Example: calFromFat(40.2) returns 361.8 """ # Provided code """ def calFromFat(): """ # test case def test_calFromFat(self): # Failure message: #This function should return the number of calories from fat grams self.assertEquals(calFromFat(50), 450) self.assertEquals(calFromFat(0), 0) self.assertEquals(calFromFat(12.3), 110.7) ############################################################################# # Functions09CaloriesFromCarbs.py ############################################################################# # Description """ Complete the calFromCarbs function so that it that returns the number of calories from grams of carbohydrates according to the following calculation: calories from carbs = carb grams * 4. Round the result to 1 decimal place. Example, calFromCarbs(40.2) returns 160.8 """ # Provided code """ def calFromCarbs(): """ # test case def test_calFromCarbs(self): # Failure message: #This function should return the number of calories from carbs. self.assertEquals(calFromCarbs(50), 200) self.assertEquals(calFromCarbs(0), 0) self.assertEquals(calFromCarbs(68.4), 273.6) ############################################################################# # Functions10DivisionFunction.py ############################################################################# # Description """ Complete the divWithRem function so that it takes two numbers, one number to be divided by the second number. The function should return the number of times the second number goes into the first and the remainder. Example: divWithRem(9, 5) should return 1 and 4. Note that Python allows you to return more than one value. You will need an equal number of variables, one for each value returned. """ # Provided code """ def divWithRem(): """ # test case def test_testdivRem(self): # Failure message: #The function should return how many times the second number goes into the first as well as the remainder. self.assertEquals(divWithRem(9,5),(1,4)) self.assertEquals(divWithRem(10,2),(5,0)) self.assertEquals(divWithRem(20,9),(2,2)) ############################################################################# # Functions11SweetOrderP1.py ############################################################################# # Description """ A candy shop that sells three different types of sweets: saltwater taffy, fudge, and praline. The shop sells the saltwater taffy for $5.99 / lb, the fudge for $9.99 / lb, and the praline for $8.99 / lb. Complete the helper functions for each type of sweet so that each takes the weight of the candy sold and returns the cost for the candy type. Round each to 2 decimal places. Example: costTaffy(5.5) returns 32.95 costFudge(8) returns 79.92 costPraline(2.3) returns 20.68 """ # Provided code """ def costTaffy(): def costFudge(): def costPraline(): """ # test cases def test_taffy(self): # Failure message: #This function should return the weight of the taffy times 5.99 self.assertEquals(costTaffy(5),29.95) self.assertEquals(costTaffy(2.5),14.98) self.assertEquals(costTaffy(0),0) def test_fudge(self): # Failure message: # This function should return the weight of the fudge times 9.99 self.assertEquals(costFudge(5),49.95) self.assertEquals(costFudge(2.5),24.98) self.assertEquals(costFudge(0),0) def test_praline(self): # Failure message: # This function should return the weight of the praline times 8.99 self.assertEquals(costPraline(5),44.95) self.assertEquals(costPraline(2.5),22.48) self.assertEquals(costPraline(0),0) ############################################################################# # Functions12SweetOrderP2.py ############################################################################# # Description """ Complete the main function that uses the helper functions you wrote in part 1. The main function should get the weight of each candy type from the user, call each helper function, add the cost for each candy type, and returns the total sale. Use the following prompts for input: Enter weight of taffy in pounds: Enter weight of fudge in pounds: Enter weight of praline in pounds: For the output use: Your total is: Note: Don't forget you need a call to main() at the end. """ # Provided code """ def costTaffy(): #Copy code from part 1 def costFudge(): #Copy code from part 1 def costPraline(): #Copy code from part 1 def Main(): """ # test case Input: 0 1.1 0.9 Output: Enter weight of taffy in pounds: Enter weight of fudge in pounds: Enter weight of praline in pounds: Your total is: 19.08 Input: 2.1 4 3 Output: Enter weight of taffy in pounds: Enter weight of fudge in pounds: Enter weight of praline in pounds: Your total is: 79.51 Input: 5 3.5 0 Output: Enter weight of taffy in pounds: Enter weight of fudge in pounds: Enter weight of praline in pounds: Your total is: 64.92 ############################################################################# # Functions13HypotenuseP1.py ############################################################################# # Description """ Complete the function hypotenuse() so that it takes the lengths of the two shorter sides of a right triangle and returns the hypotenuse of the triangle, computed using the Pythagorean theorem. Round to 2 decimal places. Note: Review the Pythagorean theorem - https://en.wikipedia.org/wiki/Pythagorean_theorem Example: hypotenuse(10, 14) returns 17.20 """ # Provided code """ def hypotenuse(): """ # test case def test_hypotenuse(self): # Failure message: #Use the Pythagorean theorem to calculate the hypotenuse from the other two sides of a right triangle. self.assertEquals(hypotenuse(5,4),6.40) self.assertEquals(hypotenuse(1.25,3.6),3.81) self.assertEquals(hypotenuse(9.4,6),11.15) ############################################################################# # Functions14HypotenuseP2.py ############################################################################# # Description """ Complete a main function that reads the lengths of the shorter sides of a right triangle from the user, uses your hypotenuse function to compute the length of the hypotenuse, and displays the result. Use the following prompts for user input: Enter side 1: Enter side 2: Use the following for output to the screen: The hypotenuse is: Note: Don't forget you need a call to main() at the end. """ # Provided code """ def hypotenuse(): #Copy code from part 1 def main(): """ # test cases Input: 4 5.14 Output: Enter side 1: Enter side 2: The hypotenuse is: 6.51 Input: 7.1 2.25 Output: Enter side 1: Enter side 2: The hypotenuse is: 7.45 Input: 7 8 Output: Enter side 1: Enter side 2: The hypotenuse is: 10.63 ############################################################################# # Functions15TaxiFareP1.py ############################################################################# # Description """ Complete the taxiFare() function so that it takes a base rate, a rate per mile, and the number of miles and returns the total taxi fare rounded to two decimal places. The total fare is the base rate plus the rate per miles times the number of miles. Example: taxiFare(3.15, 1.20, 30) returns 39.15 """ # Provided code """ def taxiFare(): """ # test case def test_taxi(self): # Failure message: #This function should return the base rate plus the rate per mile times the number of miles self.assertEquals(taxiFare(3.00,1.50,25),40.50) self.assertEquals(taxiFare(4.25,2.25,13.4), 34.40) self.assertEquals(taxiFare(2.75,1.90,100.5), 193.70) ############################################################################# # Functions16TaxiFareP2.py ############################################################################# # Description """ Complete a main function so that it takes input from the user to get a base rate, rate per mile, and number of miles traveled and then uses your taxiFare function to get the total fare. Lastly, it should print the total fare for the user. Use the following prompts for input: Enter base rate: Enter cost per mile: Enter number of miles traveled: Use the following for output: Your fare is: Note: Don't forget you need a call to main() at the end. """ # Provided code """ def taxiFare(): #Copy code from Part 1 def main(): """ # test cases Input: 4.50 2.40 38.75 Output: Enter base rate: Enter cost per mile: Enter number of miles traveled: Your fare is: 97.5 Input: 2.50 2.28 14 Output: Enter base rate: Enter cost per mile: Enter number of miles traveled: Your fare is: 34.42 Input: 3.00 2.40 45.4 Output: Enter base rate: Enter cost per mile: Enter number of miles traveled: Your fare is: 111.96 ############################################################################# # Functions17TurtleMuralP1.py ############################################################################# # Description """ You are interested in painting a mural that you designed with turtle using only a circle, a rectangle, and a triangle. You need to calculate the area that will need to be painted. Complete 3 helper functions (1 for each shape) that take the needed information, calculate, and return the area. Round each to two decimal places. Note: If you need a reminder of the formulas for area check - https://en.wikipedia.org/wiki/Area Note 2: Import math and use the constant pi for a more accurate value of pi Examples: areaTriangle(12, 14.4) returns 86.4 areaRectangle(13.2, 4.5) returns 59.4 areaCircle(52.1) returns 8527.57 """ # Provided code """ def areaTriangle(): def areaRectangle(): def areaCircle(): """ # test cases def test_circle(self): # Failure message: # This function should return the radius squared times pi self.assertEquals(areaCircle(4), 50.27) self.assertEquals(areaCircle(15.4), 745.06) self.assertEquals(areaCircle(8.113), 206.78) def test_rectangle(self): # Failure message: # This function should return length times width self.assertEquals(areaRectangle(4,5), 20) self.assertEquals(areaRectangle(15.4,6), 92.4) self.assertEquals(areaRectangle(2.25,8.113), 18.25) def test_triangle(self): # Failure message: # This function should return the base times the height, divided by 2 self.assertEquals(areaTriangle(4,5), 10) self.assertEquals(areaTriangle(15.4,6), 46.2) self.assertEquals(areaTriangle(2.25,8.113), 9.13) ############################################################################# # Functions18TurtleMuralP2.py ############################################################################# # Description """ Complete a main function to get input from the user about the size of the triangle, rectangle, and circle in the mural. Use the helper functions you wrote in part 1 to calculate the areas of each shape. Add these together in main to get the total area. Lastly, print the total area. Round to 2 decimal places. Use the following prompts for input: Enter the base of the triangle: Enter the height of the triangle: Enter the length of the rectangle: Enter the width of the rectangle: Enter the radius of the circle: Use the following for output: Total area is: Note: Don't forget you need a call to main() at the end. """ # Provided code """ def areaTriangle(): #Copy code from part 1 def areaRectangle(): #Copy code from part 1 def areaCircle(): #Copy code from part 1 def main(): """ # test cases Input: 4 7 5 8 4 Output: Enter the base of the triangle: Enter the height of the triangle: Enter the length of the rectangle: Enter the width of the rectangle: Enter the radius of the circle: Total area is: 104.27 Input: 6.66 3.2 4 6.8 12 Output: Enter the base of the triangle: Enter the height of the triangle: Enter the length of the rectangle: Enter the width of the rectangle: Enter the radius of the circle: Total area is: 490.25 Input: 5.1 2.22 8.8 2.3 8.07 Output: Enter the base of the triangle: Enter the height of the triangle: Enter the length of the rectangle: Enter the width of the rectangle: Enter the radius of the circle: Total area is: 230.5 ############################################################################# # Selection01_ isOdd.py ############################################################################# # Description """ """ # Provided code """ """ # test case import unittest import random def test_random(self): # Failure message: # This test has no failure messages # choose 5 random values between 0..999 for i in range( 5 ): num = random.randrange( 1000 ) self.assertEquals( isOdd( num ), bool(num % 2) ) ############################################################################# # Selection02DivisionsAndRemainders.py ############################################################################# # Description """ Complete the canDivideNoRem function so that it takes a dividend and divisor and returns true if the division operation can be done without a remainder and false if not. Example: canDivideNoRem(44, 4) returns True canDivideNoRem(20, 3) returns False """ # Provided code """ def canDivideNoRem(): """ # test case def test_testName(self): # Failure message: # The function should return true if the first parameter is evenly divisible the second and false otherwise. self.assertEquals(canDivideNoRem(50, 2), True) self.assertEquals(canDivideNoRem(33, 2), False) self.assertEquals(canDivideNoRem(1024, 8), True) self.assertEquals(canDivideNoRem(1025, 8), False) ############################################################################# # Selection03BiggestNumber.py ############################################################################# # Description """ Complete the biggest function so that it takes 4 numbers and returns the biggest one. Assume all values are unique (no duplicate numbers). Examples: biggest(35, 32, 1, 9) returns 35 biggest(4, 9, 45, 3) returns 45 """ # Provided code """ def biggest(): """ # test case def test_first(self): # Failure message: # Not all cases returned the largest number self.assertEquals(biggest(1, 5,33,2), 33) self.assertEquals(biggest(12, 5,33,200), 200) self.assertEquals(biggest(9, 5545,0,-20000), 5545) ############################################################################# # Selection04SmallestNumber.py ############################################################################# # Description """ Complete the smallest function so that it takes 4 numbers and returns the smallest one. Assume all values are unique (no duplicate numbers). Examples: smallest(35, 32, 1, 9) returns 1 smallest(4, 9, 45, 3) returns 3 """ # Provided code """ def smallest(): """ # test case def test_first(self): # Failure message: # Not all cases returned the smallest number self.assertEquals(smallest(1, 5,33,2), 1) self.assertEquals(smallest(12, 5,33,200), 5) self.assertEquals(smallest(9, 5545,0,-20000), -20000) ############################################################################# # Selection05MiddleNumber.py ############################################################################# # Description """ Complete the middleNumber function so that it takes 3 numbers and returns the middle value. Assume all values are unique (no duplicate numbers). Examples: smallest(35, 1, 32) returns 32 smallest(14, 9, 45) returns 14 """ # Provided code """ def middle(): """ # test case def test_first(self): # Failure message: # Not all cases returned the middle number self.assertEquals(middle(1, 5,33), 5) self.assertEquals(middle(12, 5,33), 12) self.assertEquals(middle(9, 0,-20000), 0) ############################################################################# # Selection06LetterGrade.py ############################################################################# # Description """ Complete the letterGrade() function so that it takes a number score and returns a letter grade. Use the following scale: 90 or above: 'A' 80-89: 'B' 70-79: 'C' 60-69: 'A' <60: 'F' Examples: letterGrade(75) returns 'C' letterGrade(98) returns 'A' letterGrade(55) returns 'F' """ # Provided code """ def letterGrade(): """ # test case def test_first(self): # Failure message: # Not all cases returned the correct letter grade. self.assertEquals(letterGrade(89), "B") self.assertEquals(letterGrade(60), "D") self.assertEquals(letterGrade(95), "A") ############################################################################# # Selection07ZipZapZop.py ############################################################################# # Description """ Complete the zipZapZop function so that it takes an integer. The function should print a response following this pattern: Divisible by 3: zip Divisible by 5: zap Divisible by 7: zop Otherwise, just print the number. Note 1: numbers that are divisible by more than one (3, 5, or 7) should contain all applicable terms. Notes 2: Note that you are printing directly from this function, not returning a value to the calling function. Examples: zipZapZop(5) prints zip zipZapZop(15) prints zipzap zipZapZop(2) prints 2 Hint: The number only prints if it is not divisible by ALL of 3, 5, or 7. In order to pass the Repl.it tests, you will need to write a main function that takes a number from the user and calls the zipZapZop function with that number. Use the following prompts for input: Enter a number: Note: Don't forget you need a call to main() at the end. """ # Provided code """ def zipZapZop(): """ # test cases Input: 9 Output: Enter a number: zip Input: 10 Output: Enter a number: zap Input: 77 Output: Enter a number: zop Input: 13 Output: Enter a number: 13 Input: 30 Output: Enter a number: zipzap Input: 21 Output: Enter a number: zipzop Input: 35 Output: Enter a number: zapzop Input: 105 Output: Enter a number: zipzapzop ############################################################################# # Selection08Speeding.py ############################################################################# # Description """ Complete the speeding() function so that it takes a speed and a speed limit and returns the total fine according to the following: If you are caught speeding it is a $50 fine plus $4 for each mph over the speed limit. If the speed is 90 mph or more, add another $150 fine. If there is 25 mph or more difference between the speed and speed limit add another $300 fine. If you are not speeding the function should return: No speed violation Examples: speeding(75, 60) returns 110 speeding(90, 75) returns 260 speeding(50, 25) returns 450 speeding(35, 40) returns 'No speed violation' """ # Provided code """ def speeding(): """ # test case def test_first(self): # Failure message: # Not all cases returned the correct fine self.assertEquals(speeding(40, 50), "No speed violation") self.assertEquals(speeding(70, 65), 70) self.assertEquals(speeding(90, 70), 280) self.assertEquals(speeding(100, 70), 620) ############################################################################# # Loops01: Sum of Natural Numbers.py ############################################################################# # Description """ Natural numbers are whole numbers starting at 1. So, 1, 2, 3, 4, 5, 6, ... Write a Python program that asks for a number from the user and then displays the sum of all of the natural numbers up to and including that number. Use a while loop. If user input is 5. The output is 1+2+3+4+5= 15 Example 1: Please enter a number: 3 The sum of the natural numbers up to and including 3 is 6 Example 2: Please enter a number: 40 The sum of the natural numbers up to and including 40 is 820 """ # Provided code """ def main(): main() """ # test cases # Input: 1200; Regex: .+ 720600$ # Input: 5; Regex: .+ 15$ # Input: 100; Regex: .+ 5050$ ############################################################################# # Loops02: Product of Natural Numbers.py ############################################################################# # Description """ Natural numbers are whole numbers starting at 1. So, 1, 2, 3, 4, 5, 6, ... Complete the productOf() function to take a number an int as a parameter. Use a for loop and an accumulator to calculate the product of all of the natural numbers between 1 and the parameter's value. Return this product. Example 1: productOf( 4 ) returns 24 (because 1*2*3*4 = 24) Example 2: productOf( 100 ) returns 3628800 (because 1*2*3*4*5*6*7*8*9*10 = 3628800) """ # Provided code """ def productOf(): """ # test cases import unittest import random class UnitTests(unittest.TestCase): def test_random(self): # Failure message: # This test has no failure messages def solution( n ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY for i in range( 5 ): n = random.randrange( 25 ) self.assertEquals( productOf(n), solution(n) ) ############################################################################# # Loops03: Number Series.py ############################################################################# # Description """ Write a Python program that requests the following three int values from the user: a starting number a ending number an increment size Display all of the numbers, starting with the first value, up to, but not including the second value, by incrementing by the third value. Display each value on it's own line. Example 1: Please enter a starting number: 10 Please enter an ending number: 22 Please enter an increment size: 3 10 13 16 19 (Notice that 22 is not included in the output) Example 2: Please enter a starting number: 0 Please enter an ending number: 51 Please enter an increment size: 10 10 20 30 40 50 Example 3: Please enter a starting number: 5 Please enter an ending number: 0 Please enter an increment size: -1 5 4 3 2 1 (Notice that the increment size is negative) """ # Provided code """ def main(): main() """ # test case(s) # Input: 110\n122\n3; Regex: .+110 # 113 # 116 # 119$ # Input: 0\n55\n5; Regex: .+0 # 5 # 10 # 15 # 20 # 25 # 30 # 35 # 40 # 45 # 50$ # Input: 10\n-1\n-1; Regex: .+10 # 9 # 8 # 7 # 6 # 5 # 4 # 3 # 2 # 1 # 0$ ############################################################################# # Loops04: Number Series (with commas).py ############################################################################# # Description """ Write a Python program that requests the following three int values from the user: a starting number a ending number an increment size Display all of the numbers, starting with the first value, up to, but not including the second value, by incrementing by the third value. Separate values with commas. If the relationship between the starting and ending values does not make sense given the increment size, then do not display anything. Example 1: Please enter a starting number: 10 Please enter an ending number: 22 Please enter an increment size: 3 10, 13, 16, 19 Example 2: Please enter a starting number: 0 Please enter an ending number: 101 Please enter an increment size: 10 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 Example 3: Please enter a starting number: 10 Please enter an ending number: 0 Please enter an increment size: -1 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Example 4: Please enter a starting number: 10 Please enter an ending number: 100 Please enter an increment size: -1 (Notice that no number series was displayed) Example 5: Please enter a starting number: 1000 Please enter an ending number: 10 Please enter an increment size: 1 (Notice that no number series was displayed) """ # Provided code """ def main(): main() """ # test case(s) # Input: 110\n122\n3; Regex: .+110, 113, 116, 119$ # Input: 0\n505\n5; Regex: .+0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 310, 315, 320, 325, 330, 335, 340, 345, 350, 355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 440, 445, 450, 455, 460, 465, 470, 475, 480, 485, 490, 495, 500$ # Input: 100\n-1\n-1; Regex: .+100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0$ # Input: 0\n100\n-1; Regex: ^\D+$ # Input: 10\n1\n1; Regex: ^\D+$ ############################################################################# # Loops05: Number series \(while\).py ############################################################################# # Description """ Complete the getLastValue() function to take the following three int values: a starting number a ending number an increment size Return the last value in the series that starts with the first value, continues up to, but not including the second value, by incrementing by the third value. If the relationship between the starting and ending values does not make sense given the increment size, then return (the built-in constant) None. Use a while loop. Do not use any for loops. Example 1: getLastValue( 10, 22, 3 ) returns 19 Example 2: getLastValue( 0, 101, 10 ) returns 100 Example 3: getLastValue( 10, 0, -1 ) returns 1 Example 4: getLastValue( 10, 100, -1 ) returns None Example 5: getLastValue( 1000, 10, 1 ) returns None """ # Provided code """ def getLastValue( ): print( getLastValue( 10, 22, 3 ) ) print( getLastValue( 0, 101, 10 ) ) print( getLastValue( 10, 0, -1 ) ) print( getLastValue( 10, 100, -1 ) ) print( getLastValue( 1000, 10, 1 ) ) """ # test cases import inspect import unittest import inspect#EditDelete import random#EditDelete #Click to add an import class UnitTests(unittest.TestCase): def test_HasWhile(self): # Failure message: # You need to use a while loop # Verify that the function uses a while statement (that is not in a comment) # Regex verbose description: starting from a new line (which is valid because their will be a newline after the function header), there's 0 or more characters that are not a # and while starts a word boundary and while is followed by a whitespace then one or more characters until a : regexWhile = r'\n[^#]*\bwhile\s.+:' sourceCode = inspect.getsource( getLastValue ) # import re # # for line in sourceCode: # # print('line:', line) # print( 're.search( regexWhile, sourceCode ):', re.search( regexWhile, sourceCode ) ) # print( 're.search( regexFor, sourceCode ):', re.search( regexFor, sourceCode ) ) self.assertRegex( sourceCode, regexWhile ) def test_NoForLoops(self): # Failure message: # You can not use a for loop regexFor = r'\n[^#]*\bfor\s.+:' sourceCode = inspect.getsource( getLastValue ) self.assertNotRegex( sourceCode, regexFor ) def test_random(self): # Failure message: # This test has no failure messages for i in range( 5 ): start = random.randrange( 100 ) end = random.randrange( 100 ) step = random.randrange( 10 ) - 5 # -5..4 # step cannot be 0 if step == 0: step = 1 # MANUALLY REMOVED FOR PUBLIC REPOSITORY self.assertEqual( getLastValue( start, end, step), last ) def test_NoRange(self): # Failure message: # You can not use range() regexRange = r'\n[^#]*\brange\s*\(.+' sourceCode = inspect.getsource( getLastValue ) self.assertNotRegex( sourceCode, regexRange ) ############################################################################# # Loops06: Compound Interest.py ############################################################################# # Description """ In general, after a payment is due for a credit card, the balance increases daily due to interest. The interest amount is calculated by multiplying the balance by the daily interest rate. The interest is then added to the balance. The daily interest rate is the annual percentage rate (APR) divided by 365. For example, if you have a $1000.00 balance on your credit card and you have a "store credit card" with the average APR of 25.74% (Source: https://wallethub.com/edu/cc/average-credit-card-interest-rate/50841/), then your daily interest rate is about 0.071% (= 25.74/365) and the balance after one day is $1000.71 (= 1000*0.071/100). (Notice that we use the rate form (0.071/100) instead of the percentage form of 0.071% to perform the calculations.) The balance on the next day is about $1001.41 (= $1000.71*0.071/100). This continues until the balance is paid in full. Complete the futureBalance() function to have the following parameters: balance APR (as a percentage, not a rate) number of days Have the function return the balance after the specified number of days by adding in the interest for each day. Example 1: futureBalance( 1000.00, 25.74, 1 ) returns (about) 1000.71 (see description above for details) Example 2: futureBalance( 1000.00, 25.74, 2 ) returns (about) 1001.41 (see description above for details) Example 3: futureBalance( 1000.00, 25.74, 180 ) returns (about) 1135.29 Example 4: futureBalance( 1000.00, 25.74, 365 ) returns (about) 1293.45 (Wow, that's what happens if you owe $1000 and don't pay it off for one year, you now owe $1293.45!) Note, don't worry about rounding to cents for this assignment. """ # Provided code """ def futureBalance( ): print( futureBalance( 1000.00, 25.74, 1 ) ) print( futureBalance( 1000.00, 25.74, 2 ) ) print( futureBalance( 1000.00, 25.74, 180 ) ) print( futureBalance( 1000.00, 25.74, 365 ) ) """ # test case(s) def test_example1(self): balance = 1000 rate = 25.74 days = 1 # compare results up to 2 decimal places self.assertAlmostEqual( futureBalance( balance, rate, days), balance * (1 + rate/365/100), 2 ) def test_example2(self): balance = 1000 rate = 25.74 days = 2 # compare results up to 2 decimal places self.assertAlmostEqual( futureBalance( balance, rate, days), (balance * (1 + rate/365/100)) * (1 + rate/365/100), 2 ) def test_random(self): # MANUALLY REMOVED FOR PUBLIC REPOSITORY for i in range( 3 ): # random balance between 1000..10000 balance = random.randrange( 9000 ) + 1000 rate = random.randrange( 2, 26 ) days = random.randrange( 1, 720 ) # compare results up to 2 decimal places self.assertAlmostEqual( futureBalance( balance, rate, days), futureValue( balance, rate, days), 2 ) ############################################################################# # Loops07: Inches to Feet.py ############################################################################# # Description """ Write a Python program that does the following: Displays a welcome message Prompts a user to enter a number (an integer), and then converts that value from inches to feet. If the user entered a negative number, display an error message telling the user that it was not a "positive " number and prompt the user to enter a number again. Displays the converted value, then " feet" Continue converting the user's valid values until the user enters 0. Your program should then display a goodbye message. Example 1: Welcome to my inches to feet converter! Please enter a number of inches: 32 2.7 feet Please enter a number of inches: 60 5.0 feet Please enter a number of inches: -20 Please enter a positive number! Please enter a number of inches: 40 3.3 feet Please enter a number of inches: 0 Have a nice day! Example 2: Welcome to my inches to feet converter! Please enter a number of inches: -32 Please enter a positive number! Please enter a number of inches: -21 Please enter a positive number! Please enter a number of inches: -10 Please enter a positive number! Please enter a number of inches: 0 Have a nice day! """ # Provided code """ def main(): main() """ # test cases # Input: 32\n60\n-20\n40\n0; Regex: .+ # .+2.\d+ feet # .+5.0\d* feet # .+positive.+ # .+3.3\d* feet # .+ # Input: 65\n236\n-4\n8\n0; Regex: .+ # .+5.4\d+ feet # .+19.\d+ feet # .+positive.+ # .+0.\d+ feet # .+ # Input: 14\n45\n0; Regex: .+ # .+1.1\d+ feet # .+3.\d+ feet # .+ ############################################################################# # Loops08: Odd and Even.py ############################################################################# # Description """ Write a Python program that will ask a user to enter a number. Display the number and whether it is odd or even. After that your program should ask if user wants to continue. If the user enters 'y', then repeat the steps above. If user chooses anything else, display a goodbye message. You can assume that the numbers that the user will enter are integers. Note, feel free to use your isOdd() function from your previous repl.it assignment. Example 1: Please enter a number: 7 7 is an odd number Do you want to continue (y or n): y Please enter a number: 24 24 is an even number Do you want to continue (y or n): n Have a great day! Example 2: Please enter a number: 1 1 is an odd number Do you want to continue (y or n): n Have a great day! """ # Provided code """ def main(): main() """ # test cases # Input: 9\ny\n8\ny\n7\nn; Regex: .+9 is an odd number # .+8 is an even number # .+7 is an odd number # .+ # Input: 7\ny\n24\nn; Regex: .+7 is an odd number # .+24 is an even number # .+ # Input: 7\ny\n24\nn; Regex: .+ # 7 is an odd number # .+ # .+ # 24 is an even number # .+ # .+ ############################################################################# # Loops09: isPrime.py ############################################################################# # Description """ Complete the isPrime() function to take an int and return True if it is a prime number and False if it is not. Note: A prime number is not divisible (meaning, the remainder is 0) for all numbers smaller than itself (down to 2). Examples: isPrime( 2 ) returns True isPrime( 3 ) returns True isPrime( 4 ) returns False isPrime( 101 ) returns True """ # Provided code """ def isPrime( ): """ # test cases import unittest import random#EditDelete class UnitTests(unittest.TestCase): def test_1to100(self): # Failure message: # Tested numbers 1..100 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] for n in range( 1, 100 + 1 ): self.assertEquals( isPrime(n), n in primes ) def test_random(self): # Failure message: # Tests 3 random numbers def solution( n ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY # test for 3 random values for i in range( 3 ): n = random.randrange( 101, 1000 + 1 ) self.assertEquals( isPrime( n ), solution( n ) ) ############################################################################# # Loops10: Prime Numbers.py ############################################################################# # Description """ Write a Python program that prompts the user for a integer and then displays all of the prime numbers between 2 and the user's input (with each number on it's own line). Note: A prime number is not divisible (meaning, the remainder is 0) for all numbers smaller than itself (down to 2). Example 1: Please enter a number: 10 2 3 5 7 Example 2: Please enter a number: 20 2 3 5 7 11 13 17 19 """ # Provided code """ """ # test cases # Input 10; Regex: .+2 # 3 # 5 # 7$ # Input 23; Regex: .+2 # 3 # 5 # 7 # 11 # 13 # 17 # 19 # 23$ # Input 30; Regex: .+2 # 3 # 5 # 7 # 11 # 13 # 17 # 19 # 23 # 29$ ############################################################################# # Loops11: Calculator.py ############################################################################# # Description """ Write a calculator that will give the user the following menu options: 1) Add 2) Subtract 3) Multiply 4) Divide 5) Exit Your program should continue asking until the user chooses 5. If user chooses to exit give a goodbye message. After the user selections options 1 - 4, prompt the user for two numbers. Perform the requested mathematical operation on those two numbers. Round the result to 1 decimal place. Example 1: Let's calculate! 1) Add 2) Subtract 3) Multiply 4) Divide 5) Exit Please select one of options above: 4 Enter the first number: 2.81 Enter the second number: 1.111 Answer is 3.1 1) Add 2) Subtract 3) Multiply 4) Divide 5) Exit Please select one of options above: 5 Have a good day! """ # Provided code """ def main(): main() """ # test cases # Input: 4\n1\n3\n1\n5\n4\n2\n7\n9\n3\n1.25\n1.25\n1\n45\n55\n5; Regex: [\s\S]+Answer: 0.3 # [\s\S]+Answer: 9.0 # [\s\S]+Answer: -2.0 # [\s\S]+Answer: 1.6 # [\s\S]+Answer: 100.0 # .+ # Input: 4\n234\n11\n1\n11\n29\n5; Regex: [\s\S]+Answer: 21.3 # [\s\S]+Answer: 40.0 # .+ # Input: 2\n233\n33\n3\n11\n100\n5; Regex: [\s\S\]+Answer: 200.0 # [\s\S\]+Answer: 1100.0 # .+ ############################################################################# # Strings01: Iterating Over a String.py ############################################################################# # Description """ Ask the user to input a string. Use a for loop to display each letter of a string. Example: Please enter a string: Geeks G e e k s """ # Provided code """ """ # test cases # Input: test; Regex: [\s\S]*t # e # s # t # Input: PythonPractice; Regex: [\s\S]*P # y # t # h # o # n # P # r # a # c # t # i # c # e # Input: ThisIsJustAReallyLongPhraseThatHasNoReasonToBeLong; Regex: [\s\S]*T # h # i # s # I # s # J # u # s # t # A # R # e # a # l # l # y # L # o # n # g # P # h # r # a # s # e # T # h # a # t # H # a # s # N # o # R # e # a # s # o # n # T # o # B # e # L # o # n # g ############################################################################# # Strings02: Reverse the String.py ############################################################################# # Description """ Write a Python script that requests a string from the user and displays the string in reverse order. Example: Please enter a string: hello olleh """ # Provided code """ """ # test cases # Input: Iterator; Regex: [\s\S]*rotaretI # Input: python; Regex: [\s\S]*nohtyp # Input: ThisIsAnAbsurdStatement; Regex: [\s\S]*tnemetatSdrusbAnAsIsihT ############################################################################# # Strings03: Uppercase Letters.py ############################################################################# # Description """ Complete the countUpper() function to return the number of uppercase letters in string. Examples: countUpper( 'Jake went to Publix in Columbus Georgia.') returns 4 countUpper( 'python') returns 0 countUpper( 'CPSC 1301K') returns 5 """ # Provided code """ def countUpper( string ): print( countUpper( 'Jake went to Publix in Columbus Georgia.') ) print( countUpper( 'python') ) print( countUpper( 'CPSC 1301K') ) """ # test case(s) def testCase(): pass ############################################################################# # Strings04: Changing Hills.py ############################################################################# # Description """ Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I HOPE MY CAPS LOCK DOES NOT GET STUCK ON' """ # Provided code """ def swapCaps( string ): """ # test case(s) def test_October(self): # Failure message: # This was Example 1 self.assertEquals(swapCaps("Hope you are all enjoying October"), "hOPE YOU ARE ALL ENJOYING oCTOBER") def test_allLower(self): # Failure message: # This test has no failure messages self.assertEquals(swapCaps("i hope my caps lock does not get stuck on"), "I HOPE MY CAPS LOCK DOES NOT GET STUCK ON") def test_Symbols(self): # Failure message: # If you completed the first two but failed this one you probably did not account for symbols being in the sentence. They should remain unchanged. The test was "H@lloween W!ll Sc@re You @s Much @s This Test C@se!" should result in "h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE!" self.assertEquals(swapCaps("H@lloween W!ll Sc@re You @s Much @s This Test C@se!"), "h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE!") ############################################################################# # Strings05: Password.py ############################################################################# # Description """ Complete the goodPassword() function to return True if password is a good password. Otherwise, have it return False. Criteria for a good password are: At least 8 characters At least 1 uppercase letter At least 1 lowercase letter At least 1 number At least 1 symbol Examples: goodPassword( 'P@ssword1' ) returns True goodPassword( 'password' ) returns False """ # Provided code """ def goodPassword( password ): """ # test cases def test_password(self): # Failure message: # "password" should not be a good password self.assertEquals(goodPassword("password"), False) def test_password1(self): # Failure message: # "P@ssword1" isn't really a good password but we should accept it self.assertEquals(goodPassword("P@ssword1"), True) def test_notEnough(self): # Failure message: # "$1gn3D" is not a long enough password self.assertEquals(goodPassword("$1gn3D"), False) def test_MissingUppercase(self): # Failure message: # Missing an uppercase letter self.assertEquals(goodPassword("p@ssword1"), False) def test_MissingLowercase(self): # Failure message: # Missing a lowercase letter self.assertEquals(goodPassword("P@SSWORD1"), False) def test_MissingNumber(self): # Failure message: # Missing a number self.assertEquals(goodPassword("P@ssword"), False) def test_MissingSymbol(self): # Failure message: # Missing one or more symbols self.assertEquals(goodPassword("Password1"), False) def test_password2(self): # Failure message: # Should've passed all of the criteria self.assertEquals(goodPassword("12345678Aa!"), True) ############################################################################# # Strings06: Scrambled.py ############################################################################# # Description """ Complete the isScrambled() function to return True if stringA can be reordered to make stringB. Otherwise, return False. Ignore spaces and capitalization. Note, you can not use a list for this assignment. Examples: isScrambled( 'Easy', 'Yase' ) returns True isScrambled( 'Easy', 'EasyEasy' ) returns False isScrambled( 'eye', 'eyes' ) returns False isScrambled( 'abcdefghijklmnopqrstuvwxyz', 'zyxwvutsrqponmlkjihgfedcba' ) returns True isScrambled( 'Game Test', 'tamegest' ) returns True Hint: One solution is to remove all spaces and make a lowercase version of each string. Then, compare the lengths to make sure that they're equal. Then, for each character in the first string, replace the first occurrence of it in the second string with an empty string. You can use the str method replace() to do this. Then, test that the second string is now an empty string. """ # Provided code """ def isScrambled( stringA, stringB ): """ # test cases import inspect def test_NoLists(self): # Failure message: # You can not use a list for this assignment regexList = r'\n[^#]*(\[|list)' sourceCode = inspect.getsource( isScrambled ) self.assertNotRegex( sourceCode, regexList ) def test_Easy(self): # Failure message: # Easy and Ysea should work, casing should not matter self.assertEquals(isScrambled("Easy", "Ysea"), True) def test_EasyEasy(self): # Failure message: # Easy and EasyEasy should not work because stringB has too many characters self.assertEquals(isScrambled("Easy", "EasyEasy"), False) def test_alphabet(self): # Failure message: # its too much to type but you should be able to tell the alphabet backwards self.assertEquals(isScrambled("abcdefghijklmnopqrstuvwxyz","zyxwvutsrqponmlkjihgfedcba"), True) def test_spaces_hurt(self): # Failure message: # "Game Test" and "Tamegest" should be the same, spaces don't matter self.assertEquals(isScrambled("Game Test", "Tamegest"), True) def test_oneortwo(self): # Failure message: # eye and eyes should not work because all letters must be used. self.assertEquals(isScrambled("eye", "eyes"), False) def test_ItTruelyFailed(self): # Failure message: # "ItTruelyFailed" does not match "ItTruelyWorked" This covers all my bases self.assertEquals(isScrambled("ItTruelyFailed","ItTruelyWorked"),False) ############################################################################# # Strings07: Manipulating Strings.py ############################################################################# # Description """ Complete the firstMiddleLast() function to return a new string with the first, middle, and last character from string. If string has an even number of characters, grab the middle two characters. It is safe to assume that no string passed in will be less than 3 characters. Examples: firstMiddleLast( 'hello' ) returns 'hlo' firstMiddleLast( 'Grounds' ) returns 'Gus' firstMiddleLast( 'plural' ) returns 'purl' firstMiddleLast( 'password' ) returns 'pswd' """ # Provided code """ def firstMiddleLast( string ): """ # test cases def test_plural(self): # Failure message: # "plural" should return "purl" make sure you are grabbing the middle two characters self.assertEquals(firstMiddleLast("plural"),"purl") def test_password(self): # Failure message: # "password" should return "pswd" self.assertEquals(firstMiddleLast("password"),"pswd") def test_hello(self): # Failure message: # "hello" should return "hlo" self.assertEquals(firstMiddleLast("hello"),"hlo") def test_Gus(self): # Failure message: # "Grounds" should return "Gus" self.assertEquals(firstMiddleLast("Grounds"),"Gus") ############################################################################# # Strings08: Split and Swap.py ############################################################################# # Description """ Complete the splitAndSwap() function to return a str with the first and last halves swapped. For example, if the parameter was "moon", then it would return "onmo" by splitting it down the middle: "mo | on" and then swapping the first and last halves. If the word has an odd number of characters, ignore the middle character. Examples: splitAndSwap( 'moon' ) returns 'onmo' splitAndSwap( 'orange' ) returns 'ngeora' splitAndSwap( 'oranges' ) returns 'gesora' (Notice that the middle letter was ignored and not part of the return value) splitAndSwap( 'hello' ) returns 'lohe' """ # Provided code """ def splitAndSwap( string ): """ # test cases def test_moon(self): # Failure message: # "moon" should result in "onmo" self.assertEquals(splitAndSwap("moon"),"onmo") def test_oranges(self): # Failure message: # "oranges" should return "gesora" self.assertEquals(splitAndSwap("oranges"),"gesora") def test_hello(self): # Failure message: # "hello" should return "lohe" self.assertEquals(splitAndSwap("hello"),"lohe") def test_orange(self): # Failure message: # "orange" should return "ngeora" self.assertEquals(splitAndSwap("orange"),"ngeora") def test_NursesRun(self): # Failure message: # This test has no failure messages self.assertEquals(splitAndSwap("nursesrun"),"srunnurs") ############################################################################# # Strings09: Palidromes.py ############################################################################# # Description """ A palindrome is a word spelled the same forwards and backwards. This can also apply to any phrases that might be the same forwards and backwards (if you ignore the spaces). Complete the isPalindrome() function to return True if the string is a palindrome or False otherwise. For this assignment, ignore capitalization. Examples: isPalindrome( 'Eevee' ) returns True isPalindrome( 'nurses run' ) returns True isPalindrome( 'Hello There' ) returns False """ # Provided code """ def isPalindrome( string ): """ # test cases ############################################################################# # Strings10: Letter Grade.py ############################################################################# # Description """ Write a Python program that: requests a grade between 0 and 100 from the user displays "Your letter grade is" and then the letter grade according to the following scale: 90 or above: 'A' 80-89: 'B' 70-79: 'C' 60-69: 'A' <60: 'F' Use a str method to determine if the user typed something other than an integer value. Additionally, verify that the value is between 0 and 100. If the user did not enter a number or entered an invalid number, repeatedly display "Sorry, this program only accepts values between 0 and 100" prompt the user, until valid input is given. Example 1: Please enter a grade (between 0 and 100): perfect Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): ABCDF Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): 85 Your letter grade is B Example 2: Please enter a grade (between 0 and 100): -4 Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): -99 Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): A+ Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): Ok, just A Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): A Sorry, this program only accepts values between 0 and 100. Please enter a grade (between 0 and 100): 91 Your letter grade is A Feel free to add more functions to this program to help separate the work. For example, you could have a validation function that returns True or False, depending on if the user input is a valid grade. """ # Provided code """ def main(): main() """ # test case # Input 59; Regex: .+Your letter grade is F # Input 61; Regex: .+Your letter grade is D # Input 75; Regex: .+Your letter grade is C # Input perfect\nABCDF\n85; Regex: .+Sorry, this program only accepts values between 0 and 100. # .+Sorry, this program only accepts values between 0 and 100. # .+Your letter grade is B # Input: -4\n-99\nA+\nOk, just A\nA\n91; Regex: .+Sorry, this program only accepts values between 0 and 100. # .+Sorry, this program only accepts values between 0 and 100. # .+Sorry, this program only accepts values between 0 and 100. # .+Sorry, this program only accepts values between 0 and 100. # .+Sorry, this program only accepts values between 0 and 100. # .+Your letter grade is B ############################################################################# # Lists01: Names.py ############################################################################# # Description """ Write a Python program that prompts the user for how many names to store in a list. Then, prompt the user that many times, storing each of the user's entries into a list named names. Display the names list. Example 1: How many names do you want to enter? 3 Please enter a name: Pat Please enter a name: Chris Please enter a name: Ryan ['Pat', 'Chris', 'Ryan'] Example 2: How many names do you want to enter? 7 Please enter a name: Casey Please enter a name: Riley Please enter a name: Jessie Please enter a name: Jackie Please enter a name: Jaime Please enter a name: Kerry Please enter a name: Jody ['Casey', 'Riley', 'Jessie', 'Jackie', 'Jaime', 'Kerry', 'Jody'] """ # Provided code """ def main(): ''' Your solution goes here ''' print( names ) main() """ # test cases: # Input: 7Casey\nRiley\nJessie\nJackie\nJaime\nKerry\nJody; Regex: [\s\S]+\['Casey', 'Riley', 'Jessie', 'Jackie', 'Jaime', 'Kerry', 'Jody'\] # Input: 3\nPat\nChris\nRyan; Regex: [\s\S]+\['Pat', 'Chris', 'Ryan'\] ############################################################################# # Lists02: Powers of 5.py ############################################################################# # Description """ Complete the function powersOf5(). Have the function take a parameter n and return a list of the first n powers of 5. One way to calculate powers of 5 is by starting with 1 and then multiplying the previous number by 5. Examples: powersOf5( 1 ) returns [1] powersOf5( 2 ) returns [1, 5] powersOf5( 3 ) returns [1, 5, 25] powersOf5( 6 ) returns [1, 5, 25, 125, 625, 3125] powersOf5( 10 ) returns [1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125] """ # Provided code """ def powersOf5( ): """ # test cases class UnitTests(unittest.TestCase): def test_1_10(self): # Failure message: # Tested with parameter values 1..10 lst = [1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125] for i in range( 1, 10+1 ): self.assertEquals( powersOf5( i ), lst[ : i ] ) ############################################################################# # Lists03: Odd and Even.py ############################################################################# # Description """ Complete the oddNumbers() functions to take an int (as a parameter). Return a list of all of the odd numbers between 1 and one less than the parameter. Also, complete the evenNumbers() functions to take an int (as a parameter). Return a list of all of the even numbers between 2 and one less than the parameter. Examples: oddNumbers( 9 ) returns [1, 3, 5, 7] evenNumbers( 7 ) returns [2, 4, 6] """ # Provided code """ def oddNumbers( ): def evenNumbers( ): """ # test case(s) class UnitTests(unittest.TestCase): def test_1_10(self): # Failure message: # Tested with values 1..10 def oddNumbersSolution( n ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY def evenNumbersSolution( n ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY for i in range( 1, 10 + 1 ): self.assertEquals( oddNumbers( i ), oddNumbersSolution( i ) ) self.assertEquals( evenNumbers( i ), evenNumbersSolution( i ) ) ############################################################################# # Lists04: Modify a list.py ############################################################################# # Description """ Write the modifyList() function to delete the first element of names and change the last element to Ava. Examples: modifyList( ['Gertrude', 'Sam', 'Ann', 'Joseph'] ) returns ['Sam', 'Ann', 'Ava'] modifyList( ['Ulysses', 'Bob', 'Giuseppe'] ) returns ['Bob', 'Ava'] """ # Provided code """ def modifyList( names ): """ # test case class UnitTests(unittest.TestCase): def test_random(self): # Failure message: # Tested with 3 random lists def modifyListSolution( names ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY # source https://www.ssa.gov/cgi-bin/namesbystate.cgi # georgiaBabyNames2018 = ['William', 'Noah', 'Liam', 'Elijah', 'James', 'Mason', 'Carter', 'Logan', 'John', 'Aiden', 'Ava', 'Olivia', 'Emma', 'Amelia', 'Isabella', 'Charlotte', 'Harper', 'Sophia', 'Elizabeth', 'Abigail'] georgiaBabyNames2018 = ['William', 'Noah', 'Liam', 'Elijah', 'James', 'Mason', 'Carter', 'Logan', 'John', 'Aiden', 'Olivia', 'Emma', 'Amelia', 'Isabella', 'Charlotte', 'Harper', 'Sophia', 'Elizabeth', 'Abigail'] for i in range( 3 ): # create a list of 1..9 values lst = [ ] for j in range( random.randrange( 1, 10 ) ): lst += [ random.choice( georgiaBabyNames2018 ) ] self.assertEquals( modifyList( lst ), modifyListSolution( lst ) ) ############################################################################# # Lists05: Reverse Sort.py ############################################################################# # Description """ Complete reverseSort() so that it returns a copy of lst that is in reverse alphabetical order. Examples: reverseSort( ['Jan', 'Sam', 'Ann', 'Joe', 'Todd'] ) returns ['Todd', 'Sam', 'Joe', 'Jan', 'Ann'] reverseSort( ['I', 'Love, 'Python'] ) returns ['Python', 'Love', 'I'] """ # Provided code """ def reverseSort( lst ): ''' Your solution goes here '' """ # test case class UnitTests(unittest.TestCase): def test_random(self): # Failure message: # Tested with 3 random lists def reverseSortSolution( lst ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY # source https://www.ssa.gov/cgi-bin/namesbystate.cgi georgiaBabyNames2018 = ['William', 'Noah', 'Liam', 'Elijah', 'James', 'Mason', 'Carter', 'Logan', 'John', 'Aiden', 'Ava', 'Olivia', 'Emma', 'Amelia', 'Isabella', 'Charlotte', 'Harper', 'Sophia', 'Elizabeth', 'Abigail'] for i in range( 3 ): # create a list of 1..9 values lst = [ ] for j in range( random.randrange( 1, 10 ) ): lst += [ random.choice( georgiaBabyNames2018 ) ] self.assertEquals( reverseSort( lst ), reverseSortSolution( lst ) ) ############################################################################# # Lists06: Min, Max, Sum and Count.py ############################################################################# # Description """ Complete the minMaxSumCount() function to take a list as a parameter and return a different list with the following elements (in order): the lowest value value the largest value, the total of all of the values the number of elements in the parameter list. Examples: minMaxSumCount( [90, 95, 94, 92, 91, 98, 97, 97, 90] ) returns [90, 98, 844, 9] minMaxSumCount( [95] ) returns [95, 95, 95, 1] """ # Provided code """ def minMaxSumCount( ): """ # test cases class UnitTests(unittest.TestCase): def test_primes(self): # Failure message: # Tested with prime numbers 2..97 def solution( lst ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] self.assertEquals( minMaxSumCount( primes ), solution( primes ) ) def test_random(self): # Failure message: # Tested with 3 random lists def solution( lst ): # MANUALLY REMOVED FOR PUBLIC REPOSITORY for i in range( 3 ): # create a list of 1..9 values lst = [ ] for j in range( random.randrange( 1, 10 ) ): lst += [ random.randrange( 101 ) ] self.assertEquals( minMaxSumCount( lst ), solution( lst ) ) ############################################################################# # Lists07: Party Invitation.py ############################################################################# # Description """ Write a Python program to display an invitation to each of the people in the friends list, using a for loop. Example: Casey, please come to my party on Saturday Riley, please come to my party on Saturday Jessie, please come to my party on Saturday Jackie, please come to my party on Saturday Jaime, please come to my party on Saturday Kerry, please come to my party on Saturday Jody, please come to my party on Saturday """ # Provided code """ def main(): # Display an invitation to each friend in the following list friends = ['Casey', 'Riley', 'Jessie', 'Jackie', 'Jaime', 'Kerry', 'Jody'] main() """ # test case(s) def testCase(): pass ############################################################################# # Lists08: Extra Credit Total.py ############################################################################# # Description """ Complete the extraCreditTotal() function to take a list of grades as a parameter and return the total number points above 100. Examples: extraCreditTotal( [101, 83, 107, 90] ) returns 8 (because 1 + 0 + 7 + 0 is 8) extraCreditTotal( [89, 113, 95] ) returns 13 extraCreditTotal( [89, 73, 96, 97, 99, 100] ) returns 0 """ # Provided code """ def extraCreditTotal( ): """ # test cases class UnitTests(unittest.TestCase): def test_testcase(self): # Failure message: # This test has no failure messages self.assertEquals(extraCreditTotal( [101, 83, 107, 90] ), 8) def test_testName3(self): # Failure message: # This test has no failure messages self.assertEquals(extraCreditTotal( [101, 73, 101, 97, 99, 100,0,101,101] ), 4) def test_testcase3(self): # Failure message: # This test has no failure messages self.assertEquals(extraCreditTotal( [89, 73, 96, 97, 99, 100] ), 0) def test_emptyArg(self): # Failure message: # With no elements in the list, extraCreditTotal() should've returned 0 self.assertEquals(extraCreditTotal( [] ), 0) ############################################################################# # Lists09: Shift Grades.py ############################################################################# # Description """ Write a Python program that asks the user how many points to shift the grades in the list named grades. Display each of the values in grades (each on its own line), shifted by the value from the user. Example 1: Please enter the amount to shift the grades: 1 92 91 86 88 94 77 93 Example 2: Please enter the amount to shift the grades: 5 96 95 90 92 98 81 97 """ # Provided code """ def main(): grades = [91, 90, 85, 87, 93, 76, 92] main() """ # test cases # Input: 1; Regex: [\s\S]+92\n91\n86\n88\n94\n77\n93 # Input: 2; Regex: [\s\S]+93\n92\n87\n89\n95\n78\n94 # Input: 4; Regex: [\s\S]+95\n94\n89\n91\n97\n80\n96 ############################################################################# # Lists10: Longest Word.py ############################################################################# # Description """ Complete the longestWord() function to take a list as a parameter and return the length of the longest word in that list. Examples: longestWord(['Python', 'rocks']) returns 5 longestWord(['Casey', 'Riley', 'Jessie', 'Jackie', 'Jaime', 'Kerry', 'Jody']) returns 6 longestWord(['I', 'a', 'am', 'an', 'as', 'at', 'ax', 'the']) returns 3 """ # Provided code """ def longestWord( ): """ # test case(s) def testCase(): pass ############################################################################# # Lists11: isScrambled.py ############################################################################# # Description """ Complete the isScrambled() function to return True if stringA can be reordered to make stringB. Otherwise, return False. Ignore spaces and capitalization. You must use a list for this assignment. Examples: isScrambled( 'Easy', 'Yase' ) returns True isScrambled( 'Easy', 'EasyEasy' ) returns False isScrambled( 'eye', 'eyes' ) returns False isScrambled( 'abcdefghijklmnopqrstuvwxyz', 'zyxwvutsrqponmlkjihgfedcba' ) returns True isScrambled( 'Game Test', 'tamegest' ) returns True """ # Provided code """ def isScrambled( stringA, stringB ): """ # test cases import inspect def test_UsesLists(self): # Failure message: # You must use a list for this assignment regexList = r'\n[^#]*(\[|list)' sourceCode = inspect.getsource( isScrambled ) self.assertRegex( sourceCode, regexList ) def test_Easy(self): # Failure message: # Easy and Ysea should work, casing should not matter self.assertEquals(isScrambled("Easy", "Ysea"), True) def test_EasyEasy(self): # Failure message: # Easy and EasyEasy should not work because stringB has too many characters self.assertEquals(isScrambled("Easy", "EasyEasy"), False) def test_alphabet(self): # Failure message: # its too much to type but you should be able to tell the alphabet backwards self.assertEquals(isScrambled("abcdefghijklmnopqrstuvwxyz","zyxwvutsrqponmlkjihgfedcba"), True) def test_spaces_hurt(self): # Failure message: # "Game Test" and "Tamegest" should be the same, spaces don't matter self.assertEquals(isScrambled("Game Test", "Tamegest"), True) def test_oneortwo(self): # Failure message: # eye and eyes should not work because all letters must be used. self.assertEquals(isScrambled("eye", "eyes"), False) def test_ItTruelyFailed(self): # Failure message: # "ItTruelyFailed" does not match "ItTruelyWorked" This covers all my bases self.assertEquals(isScrambled("ItTruelyFailed","ItTruelyWorked"),False) ############################################################################# # Files01ReadanEntireTextFile.py ############################################################################# # Description """ Complete the function, file_read(), to read an entire text file and return a string that contains all the file's contents. The parameter should be the file name. Note: To read a file, you need to open the file in read mode and save it as a file object. You can then use the .read() function on the file object. Example: file_read("mytxt.txt") will return You just read the file! """ # Provided code """ def file_read(filename): mytxt.txt You just read the file! mytxt2.txt This is the first line of this file This is the second line of this file """ # test case(s) def testCase(): self.assertEquals(file_read('mytxt.txt'),"You just read the file!") self.assertEquals(file_read("mytxt2.txt"), "This is the first line of this file\nThis is the second line of this file") ############################################################################# # Files02: Read File Contents and Remove End Returns.py ############################################################################# # Description """ Complete the function get_Astring(filename) to read the file contents from filename (note that the test will use the file data.txt and data2.txt provided in the second and third tabs), strip the carriage return at the end of each line and return the contents as a single string. Note that the character for a carriage return is "\n" . There is more than one way to complete this lab. Example: get_Astring("data.txt") will return 12345 """ # Provided code """ def get_Astring(filename): data.txt 1 2 3 4 5 data2.txt ice cream cookies candy cake data3.txt 143 dog 14.2 """ # test case(s) def testCase(): def get_Astring(filename): # MANUALLY REMOVED FOR PUBLIC REPOSITORY ############################################################################# # Files03Readthe3rdLineofAFile.py ############################################################################# # Description """ Complete the Python function read_third_line() so that it takes a filename and returns the third line of the file as a string. Note: There are multiple ways to write the code to accomplish this task. Example: read_third_line("afile.txt") returns LOL, you get the third line """ # Provided code """ def read_third_line(fname): afile.txt This the first line This the second line LOL, you get the third line It is wrong afile2.txt Hey pickle Woah pickle No pickle Yo pickle """ # test case(s) def testCase(): self.assertEquals(read_third_line("afile.txt").rstrip(),"LOL, you get the third line") self.assertEquals(read_third_line("afile2.txt").rstrip(),"No pickle") ############################################################################# # Files04AppendTexttoaFile.py ############################################################################# # Description """ Complete the function append_text() to append the string, "I appended it" to the file, fname. Note that you will need to open the file in the appropriate mode. """ # Provided code """ def append_text(fname): my1stwrite.txt Cat Fish Tiger Cougar """ # test case(s) def testCase(): # MANUALLY REMOVED FOR PUBLIC REPOSITORY ############################################################################# # Files05ReadingandStoring.py ############################################################################# # Description """ Complete the function read_filetolist() so that it takes the name of a file, reads that file and stores its contents into a list, then return the list. Example: read_filetolist("myf.txt") will return: Fall break, Thanksgiving, Christmas is coming """ # Provided code """ def read_filetolist(fname): myf.txt Fall break Thanksgiving Christmas is coming myf2.txt Hello Kitty Chococat Kero Kero Keroppi Pom Pom Purin Tuxedosam Pochacco """ # test case(s) def testCase(): testl= ['Fall break\n', 'Thanksgiving\n', 'Christmas is coming'] test2 = ["Hello Kitty\n", "Chococat\n", "Kero Kero Keroppi\n", "Pom Pom Purin\n", "Tuxedosam\n", "Pochacco"] self.assertEquals(read_filetolist('myf.txt'),testl) self.assertEquals(read_filetolist('myf2.txt'),test2) ############################################################################# # Files06CountingLines.py ############################################################################# # Description """ Complete the Python function count_lines() so that it take a file name, read the file's contents, counts the number of lines in the file and returns the number of lines. Example: count_lines("myf.txt") will return 10 """ # Provided code """ def count_lines(fname): myf.txt 0 1 2 3 4 5 6 7 8 9 myf2.txt 1. The Lord Of The Rings Trilogy, by J.R.R. Tolkien 2. The Hitchhiker's Guide To The Galaxy, by Douglas Adams 3. Ender's Game, by Orson Scott Card 4. The Dune Chronicles, by Frank Herbert 5. A Song Of Ice And Fire Series, by George R. R. Martin 6. 1984, by George Orwell 7. Fahrenheit 451, by Ray Bradbury 8. The Foundation Trilogy, by Isaac Asimov 9. Brave New World, by Aldous Huxley 10. American Gods, by Neil Gaiman 11. The Princess Bride, by William Goldman 12. The Wheel Of Time Series, by Robert Jordan 13. Animal Farm, by George Orwell 14. Neuromancer, by William Gibson 15. Watchmen, by Alan Moore 16. I, Robot, by Isaac Asimov 17. Stranger In A Strange Land, by Robert Heinlein 18. The Kingkiller Chronicles, by Patrick Rothfuss 19. Slaughterhouse-Five, by Kurt Vonnegut 20. Frankenstein, by Mary Shelley 21. Do Androids Dream Of Electric Sheep?, by Philip K. Dick 22. The Handmaid's Tale, by Margaret Atwood 23. The Dark Tower Series, by Stephen King 24. 2001: A Space Odyssey, by Arthur C. Clarke 25. The Stand, by Stephen King 26. Snow Crash, by Neal Stephenson 27. The Martian Chronicles, by Ray Bradbury 28. Cat's Cradle, by Kurt Vonnegut 29. The Sandman Series, by Neil Gaiman 30. A Clockwork Orange, by Anthony Burgess 31. Starship Troopers, by Robert Heinlein 32. Watership Down, by Richard Adams 33. Dragonflight, by Anne McCaffrey 34. The Moon Is A Harsh Mistress, by Robert Heinlein 35. A Canticle For Leibowitz, by Walter M. Miller 36. The Time Machine, by H.G. Wells 37. 20,000 Leagues Under The Sea, by Jules Verne 38. Flowers For Algernon, by Daniel Keys 39. The War Of The Worlds, by H.G. Wells 40. The Chronicles Of Amber, by Roger Zelazny 41. The Belgariad, by David Eddings 42. The Mists Of Avalon, by Marion Zimmer Bradley 43. The Mistborn Series, by Brandon Sanderson 44. Ringworld, by Larry Niven 45. The Left Hand Of Darkness, by Ursula K. LeGuin 46. The Silmarillion, by J.R.R. Tolkien 47. The Once And Future King, by T.H. White 48. Neverwhere, by Neil Gaiman 49. Childhood's End, by Arthur C. Clarke 50. Contact, by Carl Sagan 51. The Hyperion Cantos, by Dan Simmons 52. Stardust, by Neil Gaiman 53. Cryptonomicon, by Neal Stephenson 54. World War Z, by Max Brooks 55. The Last Unicorn, by Peter S. Beagle 56. The Forever War, by Joe Haldeman 57. Small Gods, by Terry Pratchett 58. The Chronicles Of Thomas Covenant, The Unbeliever, by Stephen R. Donaldson 59. The Vorkosigan Saga, by Lois McMaster Bujold 60. Going Postal, by Terry Pratchett 61. The Mote In God's Eye, by Larry Niven & Jerry Pournelle 62. The Sword Of Truth, by Terry Goodkind 63. The Road, by Cormac McCarthy 64. Jonathan Strange & Mr Norrell, by Susanna Clarke 65. I Am Legend, by Richard Matheson 66. The Riftwar Saga, by Raymond E. Feist 67. The Shannara Trilogy, by Terry Brooks 68. The Conan The Barbarian Series, by R.E. Howard 69. The Farseer Trilogy, by Robin Hobb 70. The Time Traveler's Wife, by Audrey Niffenegger 71. The Way Of Kings, by Brandon Sanderson 72. A Journey To The Center Of The Earth, by Jules Verne 73. The Legend Of Drizzt Series, by R.A. Salvatore 74. Old Man's War, by John Scalzi 75. The Diamond Age, by Neil Stephenson 76. Rendezvous With Rama, by Arthur C. Clarke 77. The Kushiel's Legacy Series, by Jacqueline Carey 78. The Dispossessed, by Ursula K. LeGuin 79. Something Wicked This Way Comes, by Ray Bradbury 80. Wicked, by Gregory Maguire 81. The Malazan Book Of The Fallen Series, by Steven Erikson 82. The Eyre Affair, by Jasper Fforde 83. The Culture Series, by Iain M. Banks 84. The Crystal Cave, by Mary Stewart 85. Anathem, by Neal Stephenson 86. The Codex Alera Series, by Jim Butcher 87. The Book Of The New Sun, by Gene Wolfe 88. The Thrawn Trilogy, by Timothy Zahn 89. The Outlander Series, by Diana Gabaldan 90. The Elric Saga, by Michael Moorcock 91. The Illustrated Man, by Ray Bradbury 92. Sunshine, by Robin McKinley 93. A Fire Upon The Deep, by Vernor Vinge 94. The Caves Of Steel, by Isaac Asimov 95. The Mars Trilogy, by Kim Stanley Robinson 96. Lucifer's Hammer, by Larry Niven & Jerry Pournelle 97. Doomsday Book, by Connie Willis 98. Perdido Street Station, by China Mieville 99. The Xanth Series, by Piers Anthony 100. The Space Trilogy, by C.S. Lewis myf3.txt Women's World Cup Winners: United States (1991) Norway (1995) United States (1999) Germany (2003) Germany (2007) Japan (2011) United States (2015) United States (2019) """ # test case(s) def testCase(): num = 10 self.assertEquals(count_lines("myf.txt") ,10) self.assertEquals(count_lines("myf2.txt") ,199) self.assertEquals(count_lines("myf3.txt") ,9) ############################################################################# # Files07WriteaListcontenttoafile.py ############################################################################# # Description """ Complete function write_list () to take a filename and then write a list of colors to the file Note: Make sure you open the file in the appropriate mode. This one is a bit tricky. Note that each element of the list is on it's own line in the file. If you use append mode, you may also need to open the file in write mode to clear the contents of the file and close it again and then reopen in append mode. Example: After adding the list elements, the test file, myf.txt, should look like this: Red Green White Black Pink Yellow """ # Provided code """ def write_list(fname): color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] myf.txt """ # test case(s) def testCase(): # MANUALLY REMOVED FOR PUBLIC REPOSITORY self.assertEquals(content_list,color) ############################################################################# # Files08RandomLine.py ############################################################################# # Description """ Complete the function read_r_line(fname, ln) to take a file name and a line number and return the contents of that line number from the file as a string. Hint: The code from Files03 will be helpful. Example: read_r_line(myf.txt, 5) will return I like peanut """ # Provided code """ def read_r_line(fname,ln): myf.txt I like banana I like apple I like blueberry I like strawberry I like peanut myf2.txt 89 200 56 72 44 28 90 100 32 98 """ # test case(s) def testCase(): self.assertEquals(read_r_line("myf.txt",3) ,'I like blueberry\n') self.assertEquals(read_r_line("myf2.txt",5) ,'44\n') ############################################################################# # Files09SearchinaFile.py ############################################################################# # Description """ Complete the function search_file(fname, wd) to take a file name and a word. If the the word is found in the file contents, the function should return True, otherwise it should return False. Note that the function should return the Boolean True / False NOT strings "True" / "False" . Also make sure you handle differences in capitalization. DoG and dog should both count as True for DOG. Example: search_file("myfs.txt", "file") will return True. """ # Provided code """ def search_file(fname, wd): myfs.txt Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. myfs2.txt A Bag of Tools by R. L. Sharpe Isn'T it strange That princes and kings, And clowns that caper In sawdust rings, And common people Like you and me Are builders for eternity? Each is given a bag of tools, A shapeless mass, A book of rules; And each must make— Ere life is flown— A stumbling block Or a steppingstone. """ # test case(s) def testCase(): self.assertEquals( search_file("myfs.txt","reading"),True) self.assertEquals( search_file("myfs.txt","search"),False) self.assertEquals( search_file("myfs2.txt","Shapeless"),True) self.assertEquals( search_file("myfs2.txt","spider"),False) ############################################################################# # Files10CompareFiles.py ############################################################################# # Description """ Complete the function compare_files(fn1,fn2) so that it takes two file names and if their content is exactly the same return True, otherwise return False. Note: Capitalization, punctuation and spacing must also be the same. Example: compare_files("myf1.txt", "myf3.txt") will return True. """ # Provided code """ def compare_files(fn1,fn2): myf1.txt a b c d myf2.txt A B C D myf3.txt a b c d """ # test case(s) def testCase(): self.assertEquals(compare_files("myf1.txt","myf3.txt"),True) self.assertEquals(compare_files("myf1.txt","myf2.txt"),False) self.assertEquals(compare_files("myf3.txt","myf2.txt"),False) ############################################################################# # Dict01: Login Validation.py ############################################################################# # Description """ Compete the passwordCheck() function that will authenticate a user’s login by accepting that user’s name, their password, and a dictionary of users’ login credentials. The function will return the str 'login successful' if the user’s login information is correct and the str 'login failed' otherwise. Examples: passwordCheck( 'user2', 'P@ssword2', {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword33', 'user4':'P&ssw0rd4'} ) returns 'login successful' passwordCheck( 'user3', 'P#ssword33', {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword33', 'user4':'P&ssw0rd4'} ) returns 'login failed' """ # Provided code """ def passwordCheck(username, password, users): '''Your code goes here''' """ # test cases import unittest import random class UnitTests(unittest.TestCase): def test_wrongUser(self): # Failure message: # This test has no failure messages credentials = {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword3', 'user4':'P&ssw0rd4'} # create random user and password randUser = 'user' + str(random.randrange(10,20)) # unique range wrongUser = 'user' + str(random.randrange(20,30)) # unique range randPassword = 'password' + str(random.randrange(100)) # insert into a dictionary # MANUALLY REMOVED FOR PUBLIC REPOSITORY # add in more dummy users and passwords for i in range(random.randrange(2,5)): credentials[ 'user' + str(random.randrange(10)) ] = 'password' + str(random.randrange(100)) # run the test self.assertEquals(passwordCheck(wrongUser, randPassword, credentials), 'login failed') def test_wrongPassword(self): # Failure message: # This test has no failure messages credentials = {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword3', 'user4':'P&ssw0rd4'} # create random user and password randUser = 'user' + str(random.randrange(100,200)) randPassword = 'password' + str(random.randrange(100)) wrongPassword = 'secret' + str(random.randrange(100)) # insert into a dictionary # MANUALLY REMOVED FOR PUBLIC REPOSITORY # add in more dummy users and passwords for i in range(random.randrange(2,5)): credentials[ 'user' + str(random.randrange(10)) ] = 'password' + str(random.randrange(100)) # run the test self.assertEquals(passwordCheck(randUser, wrongPassword, credentials), 'login failed') def test_notPresent(self): # Failure message: # Test two failed credentials = {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword3', 'user4':'P&ssw0rd4'} # create random user and password randUser = 'user' + str(random.randrange(100,200)) randPassword = 'password' + str(random.randrange(100)) # # insert into a dictionary # MANUALLY REMOVED FOR PUBLIC REPOSITORY # add in more dummy users and passwords for i in range(random.randrange(2,5)): credentials[ 'user' + str(random.randrange(10)) ] = 'password' + str(random.randrange(100)) # run the test self.assertEquals(passwordCheck(randUser, randPassword, credentials), 'login failed') def test_successful(self): # Failure message: # Test one failed!! credentials = {'user1':'password1', 'user2':'P@ssword2', 'user3':'p#ssword3', 'user4':'P&ssw0rd4'} # create random user and password randUser = 'user' + str(random.randrange(100,200)) randPassword = 'password' + str(random.randrange(100)) # insert into a dictionary # MANUALLY REMOVED FOR PUBLIC REPOSITORY # add in more dummy users and passwords for i in range(random.randrange(2,5)): credentials[ 'user' + str(random.randrange(10)) ] = 'password' + str(random.randrange(100)) # run the test self.assertEquals(passwordCheck(randUser, randPassword, credentials), 'login successful') ############################################################################# # Dict02: Character Frequency.py ############################################################################# # Description """ Complete the function charFrequency( ) so that it will accept a list of characters, and use a dictionary to store each character’s frequency. Return the dictionary. Suggested steps: · Create an empty dictionary and initialize the char count values to 0 using the characters of the list of characters as keys. · Traverse the list of characters and update the count for each character. · Return the dictionary Examples: charFrequency( 'aaaabbbbbccdddeehhhh' ) returns {'a': 4, 'b': 5, 'c': 2, 'd': 3, 'e': 2, 'h': 4} charFrequency( 'PythonRocks' ) returns {'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 1, 'R': 1, 'c': 1, 'k': 1, 's': 1} """ # Provided code """ def charFrequency(charList): '''Enter code here''' print( charFrequency('aaaabbbbbccdddeehhhh') ) print( charFrequency('PythonRocks') ) """ # test cases import unittest import random import string class UnitTests(unittest.TestCase): def test_testOne(self): # Failure message: # Test one failed! def charFrequencyTestOne(charList): # MANUALLY REMOVED FOR PUBLIC REPOSITORY self.assertEquals(charFrequency(randStr), charFrequencyTestOne(randStr)) ############################################################################# # Dict03: What is the Most Common Name?.py ############################################################################# # Description """ Complete the function mostCommonCount() so that will accept a list of names as a parameter, and return the count of the most common name in the list. Examples: mostCommonCount( ['marquard', 'zhen', 'csev', 'zhen', 'cwen', 'marquard', 'zhen', 'csev', 'cwen', 'zhen', 'csev', 'marquard', 'zhen'] ) returns 5 mostCommonCount( ['Jacob', 'Michael', 'Joshua', 'Matthew', 'Emily', 'Madison', 'Emma', 'Olivia', 'Hannah'] ) returns 1 """ # Provided code """ def mostCommonCount(namesList): '''Your code goes here''' """ # test cases import unittest import random class UnitTests(unittest.TestCase): def test_allTheSameCount(self): # Failure message: # Test two failed! names = ['Jacob', 'Michael', 'Joshua', 'Matthew', 'Emily', 'Madison', 'Emma', 'Olivia', 'Hannah'] # MANUALLY REMOVED FOR PUBLIC REPOSITORY self.assertEquals(mostCommonCount(namesInput), count) def test_testOne(self): # Failure message: # Test one failed! def mostCommonCountTestOne(namesList): # MANUALLY REMOVED FOR PUBLIC REPOSITORY self.assertEquals(mostCommonCount(randNames), mostCommonCountTestOne(randNames))