cs22a final practice problems
fruit = 'apple'? - What is the output of fruit[:] - What is the output of fruit[ :3]? - What is the output of fruit[ 3:]? - What is the output of fruit[: -1]? - What is the output of fruit[0 : 11]?
-Set fruit to equal apple -Print output of each ratio separately
Write a step-by-step algorithm to calculate the average of 3 numbers: -Assign the values to your variables initially by hard-coding them. -For example you may use 3 integers (9, 7 and 15) for your numbers -You may use any of the three methods for expressing your algorithm -Next, generalize your program using abstraction so it works for any three numbers (not just the hard-coded values 9, 7 and 15).
-Store each number in memory/prompt user -Calculate the sum of the three numbers -Calculate the average and display it
Write a program that gives simple math quizzes. The program should generate and display two random numbers that are to be added. The program should allow the student to enter the answer. If the answer is correct, a message of congratulations should be displayed. If the answer is incorrect, a message showing the correct answer should be displayed. Your program should include two functions for getting the user answer and displaying the results.
Use import statement to use the random module in the function Generate two random numbers Ask user to solve math problem Based on input, print appropriate statement and correct answer
Write a program that converts Celsius temperatures to Fahrenheit temperatures and vice versa. The formula is as follows: F=((9/5 )* C)+32 C = (F - 32) * 5/9 The program should ask the user to choose from a menu that gives them a choice of what conversion they would like. The choices should be numbered, and the user should enter the choice number. Depending on the choice, your program should prompt the user to enter a temperature in Celsius or in Fahrenheit, perform the calculation and then display the temperature converted. Make sure your output is clearly labeled by adding explanation text next the values printed. Also make sure that you program itself is well documented by adding comments throughout your code
-Ask user which conversion they want -Prompt user for input -Calculate conversion and display result
Assigning expressions to variables Write a generalized app that converts temperature from Celsius to Fahrenheit. Use the expression (C * 9/5) +32)) where C is degrees Celsius. Your app should prompt the user for degrees Celsius, compute the conversion to Fahrenheit and display the result with an appropriate message/label for the output.
-Prompt for temperature in Celsius and store in memory -Multiply stored value by 9/5 and add 32 to calculate temperature in Fahrenheit -Display Fahrenheit calculation
Define an average function that takes 4 arguments, calculates the average of the 4 numbers passed to it, and returns the result back to the caller. -Capture the 4 values from the user in main() and pass them to the function average. -Call the average function from main. Print the results returned in the main function. -Call the average function three more times with three more sets of four numbers and return the results back to the caller. -Save the return values in variables in main(). -Pass all four return values saved in main() back to the average function as arguments to calculate the average of the averages and return the result to main() which will print the final result ( average of the averages).
-Prompt user for 4 values -Store values -Calculate average -Store average of the 4 values (w a variable) (x4) -Calculate the average of the averages
Write a program that calculates and displays a person's body mass index (BMI). The BMI is often used to determine whether a person is overweight or underweight for his or her height. A person's BMI is calculated with the following formula: BMI=weight×703/height2 where weight is measured in pounds and height is measured in inches. The program should ask the user to enter his or her weight and height, then display the user's BMI. The program should also display a message indicating whether the person has optimal weight, is underweight, or is overweight. A person's weight is considered to be optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be underweight. If the BMI value is greater than 25, the person is considered to be overweight.
-Prompt user for for height and weight -Calculate the user's BMI -Display the appropriate message
A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her evaluation, she asks members for the number of fat grams and carbohydrate grams that they consumed in a day. Then, she calculates the number of calories that result from the fat, using the following formula: calories from fat = fat grams x 9 Next, she calculates the number of calories that result from the carbohydrates, using the following formula: calories from carbs = carb grams x 4 The nutritionist asks you to write a program that will make these calculations. Your program should use two separate functions to calculate fat and carb calories. Write a 3rd function that is called from main and capture user input.
-Prompt user for number of fat and carbohydrate grams -Store values -Calculate both equations in different functions -Print results
Define a function, access(), that captures two values: user name and password and returns them to the caller. Write a program that calls access() function from main(). The function should return both values to the caller. The caller then prints the two values returned from the function access().
-Prompt user for username and password -Store values -Return values to caller -Print both values
Write a program that asks the user their name and greets the user using the name they entered. Then the program prompt the user for hours they worked and rate per hour to compute gross pay. The format of the output of your program should look like this: Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25
-Prompt user to enter name them store name in memory -Output greeting to user including their name -Prompt for number of hours worked and store in memory -Prompt for pay rate per hour and store in memory -Multiply number of hours by pay rate to calculate gross pay
Many financial experts advise that property owners should insure their homes or buildings for at least 80 percent of the amount it would cost to replace the structure. Write a program that asks the user to enter the replacement cost of a building, then displays the minimum amount of insurance he or she should buy for the property. Use decomposition to break down the problem into functions in order to solve it. Your program should use at lease one function in addition to main()
-Prompt user to enter replacement cost of building -Store value -Calculate 80% of value -Print the result
Write a program to determine whether the average of 3 numeric grades entered as floats by the user is a passing grade: -Prompt the user to enter the three grades and capture the grades in main() -Calculate the average by calling your average() function. (you may reuse your function code from the previous assignment). Average should be returned to the caller. -Check average in main() and let the student know if they have a passing grade by printing the appropriate message
-Prompt user to enter three grades and store info -Define and call average function -Check average in main and print appropriate message
The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the year: 6/10/60 Design a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the month times the day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
-Prompt user to input date -Calculate the month times day -If it equals the year, print a message saying the date is magic -Otherwise print a message saying it's not magic
-Write the statement that slices 6th to second-to-the-last character (inclusive)r in string "Hello World!" - Write the statement that slices 2nd to 5th character (including the 5th character) in string "Hello World!"
-Use a string to set the phrase "Hello world!" -Print slice statement from 6th to second to last character -Print slice statement from 2nd to 5th character
phrase = "Hello world!" What is the value returned by each index position? phrase[0] phrase[1] phrase[15] phrase[-1] phrase[-2]
-Use a string to set the phrase "Hello world" -Print each index position from the string separately
Write a while loop that validates user input. The user should be prompted to enter a positive integer in the range 0 to 100. The while loop should print a error if an invalid value is entered and prompt the user for another value.. The loop should terminated when the user enters a valid value. The first value should be captured outside the while loop (priming read). Trace the program using a state table showing the state changes for all the variables and the output.
-Use while loop for user input -Prompt user to input a value between 0 and 100 -Print appropriate statement based on input -Terminate loop when valid value inputted
Write a program that calls a function to decide whether the average is a passing grade. Grade, running total and the count of grades is captured in main and passed to the function: Use a while loop to ask the user to enter the scores for as many assignments and/or tests they wish without restricting them to a specific number of score. Hint: Use a negative scores sentinel value (or wild card) to mark the end of input. In the while loop, keep a running total and count of the number of scores as they are entered. Call function average, outside the while loop, to calculate the average, passing it the total and count as arguments (in main). Average should not calculate the sentinel value as part of the grades total or count. Check the average, outside the loop in main, and let the student know if they have a passing grade. You can decide what "passing" criteria should be.
-Use while loop to get scores from user -Mark end of input with negative score sentinel values -Define average function -Calculate and store average -Check the average and print the appropriate statement
Write a sentinel-based while loop that calculates the average weight of a doctor's patients. Your program should include a priming read for the first weight. The while loop must keep track of the number of patient weights entered. Average should be displayed when the sentinel is entered. Trace the program using a state table showing the state changes for all the variables and the output.
-Use while loop to get weights from user -Mark end of input with negative score sentinel values -Display average when input is completed
Write a program that calls the following three functions from main(): 1. function called banner() that generates a banner for "CS 22A Python Programming" with your choice of design. (Hint: Use a multi-line print). 2. function called greet() that takes a person's name as a parameters and greets the person by printing a greeting using the person's name that was passed in as parameter. Your program should prompt the user for their name in the main() function and then pass the name to the function greet(). 3. function called cube() that takes two integer values as arguments and cubes both displaying the result. Your program should prompt the user for the two integers in the main() function and pass the values to the function cube(). Function is called with two arguments.
Banner -Define banner function -Print multi line banner with triple quotes -Call banner function Greet -Prompt user for name in main function and store -Define greet function -Return name from main function -Greet user with name -Call greet function after main Cube -Prompt user to input numbers in main and store -Define cube function -Return input from main -Cube numbers and display result -Call cube function after main
Create a nested dictionary that shows for 3 counties in the Bay Area, 3 cities with name and population for each city. Display the nested dictionary using a nested for loop. Look up the population of one of the cities and display the result, Add a 4th city and display the county dictionary.
Create a dictionary for 3 Bay Area counties with 3 cities each and the population of each city Display the list Look up the population of one of the cities Add another city and display the dictionary
Download the words.txt file on Canvas and read its contents using the readline() method of the file object. Search for 10 words that start with X in the file.
Download text file Use readline to red it's contents Search for 10 words starting with x in the file
Write a function, score(), that uses Python Dictionary to compute the scrabble score of an English word and returns the value to main. The word is captured from the user in the main program and passed to the function score() as an argument. Assume your input word contains no spaces or punctuation and can be a mixture of upper and lower cases. Set up your dictionary in score() with upper case letters and use the Python built-in function upper() to convert the word to all upper case before you calculate the score for each letter. Create your dictionary using the tile values table listed below. Tile Values Table: (Point values for each letter that is used in a Scrabble game) 0 Points - Blank tile. 1 Point - A, E, I, L, N, O, R, S, T and U. 2 Points - D and G. 3 Points - B, C, M and P. 4 Points - F, H, V, W and Y. 5 Points - K. 8 Points - J and X. 10 Points - Q and Z. Test your program with UCLA, Yale, UCSF and SJSU. SAMPLE OUTPUT: UCLA is worth 6 point Yale is worth 7 points UCSF is worth 9 points SJSU is worth 11 points
Make the dictionary with all the values Use a for loop to get the score of each letter and add them all together Print the total score of each word entered
Write a program that prompts a user for a phrase in the main() function and passes the string to a function to count how many times each letter appears in the string passed to it form main(). The function must use a dictionary to count the number of times each letter appears in the string and return the dictionary to the main() function where it is printed.
Prompt the user for a phrase in main and pass it to a function Define the function use a for loop and dictionary to count the number of times each letter appears in the string Return the dictionary to main and print it.
Write a Python program that prompts the user for an integer, n, and generates and displays a dictionary that contains keys (from 1 and n) and values in the form n*n.
Prompt the user for an integer Create an empty dictionary Use a for loop to generate the dictionary and print it
Using string multiplication and a while loop draw a pyramid in Python. Prompt the user for a character and use that character to draw a 5 story pyramid that looks like this: = === ===== ======= ========= Trace the program execution using a state table/diagram and submit with your .docx file.
Prompt user for a character and set as a variable Use string multiplication in a while loop to print the right number of characters for each line
Sort the list created in Part1 in main(). Pass the sorted list and the same key(s) entered by the user in Part 1 to the function linear(). Find the first occurrence of the key in the list. If found, display an appropriate message with the key and location of key. Keep track of the number of comparisons it took to find the key. Your program should display the key and the index position where it was found in the list as well as the number of comparisons it took to find the element. Print an appropriate message if the key is not found. NOTE: You may use the sort() method of lists in Python for Part 2. Test your program with at least 4 key values, What conclusions can you draw based on the number of comparisons it takes to find the key in a sorted vs. unsorted list?
Sort list Pass list and keys to linear Find first occurrence of key in list Print appropriate message Display key, index position, and number of comparisons to find the element
Define a function, matrix(), that takes two arguments, row and column sizes, and creates a variable-size two-dimensional matrix filled with $ signs. Display the matrix by rows. The user is prompted in the main() function for the size of row and columns and the values are passed to the function matrix().
Define function that creates two tables Prompt user for input Pass input to main Print table
Write a grade conversion program that takes a numeric grade (type float) input from the user and converts it to a letter grade (A-F), Use multiple/cascading if statements to convert numeric grades to a letter grades.
Prompt user for input Set values for each letter grade Print appropriate statement
Find and display sum of main diagonal elements of a square matrix (main diagonal, shown in blue, runs from the top left corner to the bottom right corner of the matrix).[[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3],[4, 4, 4, 4]]
Set the matrix Use for loops to calculate the sum of diagonal elements Print table and sum
Given the string "Midterm Exam is almost here" 1. Iterate over the string using a for-each loop and print each element of the string on one line. (output:Midterm Exam is almost here) 2. Iterate over the string using a for-each loop and print each element of the string separated by commas on one line. Remove the blank spaces in the string first,(output:MidtermExamisalmosthereM,i,d,t,e,r,m,E,x ,a ,m ,i ,s ,a ,l ,m ,o ,s ,t ,h ,e ,r ,e ,) 3. Iterate over the sequence using a range-based for loop, and for each index access the character from string using operator. Print each index position and the corresponding character in the string .(output: Index: 0 Element: C, Index: 1 Element: I, etc) 4. Iterate over a portion of string, the slice "Exam" using a for loop. Print the slice on one line. (output: Exam)
Use a string to set the phrase "Midterm Exam is almost here" Print each element of the string on one line using an index for each letter the string End each statement with a command to print on the same line Print each element of the string with s comma after it using indexes for each letter End each statement with a command to print on the same line Print the "exam" portion of the string using s splice statement
Create an 8-Ball app in Python using random number generation. The idea behind an 8-Ball is very simple (http://www.ask8ball.net/) or (https://en.wikipedia.org/wiki/Magic_8-Ball) . You ask the eight ball a yes or no question, and it tells you the answer. Except, that the answer it choses is randomly selected from a set of prefabricated responses.Write a program that continuously prompts the user for a yes or no question, and then randomly selects from a set of canned answers. Your program should generate random integer numbers. The program ends when the user hits ENTER. The classic 8-ball responses were: As I see it, yes. Ask again later. Better not tell you now. Cannot predict now... Sample Output:Ask a yes or no question: Is my real name Sally?My sources say no.Ask a yes or no question: 8-ball, are you using random numbers?Without a doubt.
Use import statement to use the random module in the function Add list of responses Ask user for input Generate a random response and print it
Write a program that lets the user play the game of Rock, Paper, Scissors against the computer. The program should work as follows: When the program begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen scissors. (Don't display the computer's choice yet.) The user enters his or her choice of "rock," "paper," or "scissors" at the keyboard. The computer's choice is displayed. A winner is selected according to the following rules: If one player chooses rock and the other player chooses scissors, then rock wins. (Rock smashes scissors.) If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cuts paper.) If one player chooses paper and the other player chooses rock, then paper wins. (Paper wraps rock.) If both players make the same choice, the game must be played again to determine the winner.
Use import statement to use the random module in the function Add list of rock paper scissors Generate random option from list for computer Ask for user input Based on input, print appropriate statement
Write a program using selection and repetition to simulate the user login authentication process. Check the user's password against a pre-set password of your choice, and grant or deny the user access based on the password entered. Give the user 3 tries for incorrect password entry. Test your program with at least 3 datasets.Your program output screenshots should show the behavior of your program for the following scenarios: - if the user enter the correct password on the first try, - if the user enter the incorrect password 3 times - if the user enters the incorrect password on the first try but enter the correct password on the 2nd or 3rd try. You need to submit 3 output screenshots for this problem showing output for each of the 4 scenarios listed above. Trace the program execution using a state table/diagram and submit with your .docx file.
Use while statement to set the number of attempts Prompt user for password If password is correct, use a flag to break the loop and print "access granted" If password is incorrect, print a denied statement and add to the number of attempts
Write a program that uses a function to calculate the sum and product of 3 numbers passed to it from main. Do not use built-in functions -- write your own sum and product function code. The function should return sum and product to the caller where it is unpacked and displayed on different lines with a string description preceding it. (Example: The Product of 3 , 1 and 7 is 21).
Write a function to calculate the sum and product of 3 numbers Pass the numbers from main Return the sum and product to caller and display them
Check the following two matrices for equality (element by element) using nested forloops: Matrix1:[[1, 1, 1, 1],[2, 5, 2, 5],[3, 3, 3, 3],[4, 7, 4, 7]] Matrix2:[[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3],[4, 4, 4, 4]]
set each matrix Check if the matrices match using for loops Print appropriate statement
An amateur golf club has a tournament every weekend. Write a program that▪ Captures each player's name and their best golf score as keyboard input, then saves these as records in a file named golf.txt (Each record should have a field for the player's name and a field for the player's score.)▪ The program then reads the records from the file golf.txt and displays each record showing the player and their scores in a table format. (hint: use \t in your print statement)
Ask for input for player's name and best scores Save each score and name in a text file Open and print the file to display the socres
Write a Python program that calls a function to sum all the numbers in a list and returns the result to the caller. The main program creates a list (with hard-coded or user input) and passes the list as an argument to the function. You may not use the built-on function, sum. The program calls a second function to multiply all the numbers in a list passed to it by main and returns the product back to the caller. List can be created with user input or hard-coded elements. The program calls a third function that takes the list of words (below) passed to it from main and determines which elements are palindromes without changing the original list. ['racecar', 'Python', 'mom', 'java','level', 'DNA','101101' ] If true, the function appends the word to a new list and returns it to the caller. The main program prints the list of palindromes returned from the function. The function should not modify the original list passed to it from the main (no side effect). A palindrome is a word, phrase, number or sequence of words that reads the same backward as forward
Ask user for input and pass as an argument to the sum function Define a function to calculate the sum of a list Print the sum Define a function to multiply all numbers Print the result Define another function that gets user input for a word Take each element and use negative indexing to read it backwards and determine if its a palindrome
Create a song-finder app that searches for a song in a file with all of your song titles. Create a text file called song.txt that captures the song title and artist from the user and stores these records in song.txt. Each record in the file should have a field for the song title and a field for the artist. The app should give the user the choice to search a song by title or artist and then display the result. An appropriate message should be displayed if the song is not found.
Ask user for input of artist and song Save in a text file Ask user to choose between searching by artist or song Display the result of input or s message if not foung
Assuming two variable x and y. Assign a string value to each of the variables x and y. Display the values of x and y. Swap the values of x and y using traditional swapping and display the output after the swap. Swap the values of x and y using tuple assignment and display the values after the swap.
Assign values to variables Display the values Swap the values (using tradition swapping) and display the result Swap the values (using tuple assignment) and display the result
Create a nested list (two dimensional (2D) List) using three integer lists. Define the three integer lists with at lease 4 elements each. Display the new nested list. Calculate the sum of the all elements in the nested list using a nested for loop.
Create a nested list with three integer lists containing 4 elements each Display nested list Use a for loop to calculate the sum of all elements Display sum
Create a list with a minimum of 35 elements using random number generation. Numbers should be in the range of 1 to 5000. The element should be out of order (unsorted). Implement the linear search algorithm as a function, linear(), to find a key entered by the user. Prompt the user, in main(), for a key to search in the list. Pass the list and the key to function linear() from main(). Search should find the first occurrence of the key in the list. If found, display an appropriate message with the key and location of key. Keep track of the number of comparisons it took to find the key. Your program should display the key and the index position where it was found in the list as well as the number of comparisons it took to find the element. Print an appropriate message if the key is not found. Display the list with the search results. NOTE: You may not use any built-in searching functions, methods or operators in Python. Sample Output: Example scenario if key is found: if the key I am looking for is 422, and I find it at index 20, my program should print that I found the key 422 at index 20, and it took me 20 comparisons to find it. Then, I should print the list that it searched for the key in. Example scenario if key is not found: if the key I am looking for is 422 and my program can't find it, I should print that the key was not found, and then print the list that it searched for the key in.
Create a list using random number generation Prompt user for a key Pass list and key to linear function Search in list Display key, index position, and number of comparisons to find the element Display list with search results
Create a song finder app using a dictionary that stores favorite artist and songs. The keys should represent the artist and the values corresponding to each key represent the song(s). The dictionary should have at least one key that is associated with multiple values (multiple songs by the same artist). Print the dictionary. Look up three songs in your app and display the search result (one should be from a key with multiple values). If the song is in the dictionary, the search results should display a message that the song was found, along with the name of the song and the artist. If it is not found, the program should display a message saying the song cannot be found. Your dictionary should have at least 5 entries (meaning at least 5 artists).
Create a song library using a dictionary Ask the user to choose a song If found, print the song and artist name If not, print song not found
Create a new text file from your Python program, called song.txt and write 7 lyricsof your favorite song to it as lines. Be sure to add the newline character (\n) at theend of each line. (Do not use a text editor to create the file. Create the file fromthe Python program using 'w'). Open the file in read mode and read the entire content as one string. Print the content and the length of the content.
Create a text file wit the song lyrics Create a python file where the text file is opened and printed
Create a list of numbers with at least 7 integer elements entered by the the user. Display the list. I. Print the 1st, 3rd and 7th element II. Create and display a slice/sub-list containing elements 5th to end of the list III. Use the for loop to calculate the sum of all the numbers stored in the list asthe loop traverses the list elements. Display the sum. Can not use the built-on sum() function. IV. Rewrite part III using a while loop. V. Extend the list with the names of your 3 favorite fruits, one at a time. VI. Delete the first 7 elements of the list. VII. Use a for loop to print the name of each fruit , the fist initial and length of each fruit. The output for this part should be as follows: Orange is one of my favorite fruits. Its name starts with OIts name has 6 lettersCherry is one of my favorite fruits. Its name starts with CIts name has 6 lettersMango is one of my favorite fruits. Its name starts with MIts name has 5 letters . . .
Create an empty list Ask user for input on the length of the list Print the list Use indexes to print the 1st, 3rd, and 7th element of the list Use a slice to print a portion of the list Use a for loop to calculate the sum Use a while loop to calculate the sum Extend the list to add fruits Delete first 7 elements of list Use a for loop to print the name of each fruit Use indexing to print the first initial and len to print the length
Create a tuple with user input. Capture keyboard input from the user until the Enter key is pressed. Display the tuple. Test your program with at least 5 values entered before Enter is pressed.
Create an empty list Ask user for input to populate list Convert the list to a tuple Display the tuple
Populate the elements of a 3X3 nested list with user input usingnested for loop(s). Prompt the user for floats and populate the matrix with the user input. Print the matrix that holds the user input.Change the value of the first element of each row to double its value. Print the matrix again after modification.
Create an empty nested list with three lists using user input Ask user for input as floats for lists Print the matrix Double the value of the first element of each row Print the matrix again
Create a tuple with the names of the months in the year. Find and display tuple elements that end with a 'y'. Also show the count of elements that end with 'y'. Print the tuple in reverse order. Copy the elements with the Summer months using tuple slicing and store in another tuple. Display the original tuple and the new tuple.
Create the tuple Search for elements ending with y and display them Print the tuple in reverse Create a new tuple with summer months by slicing original tuple Display both tuples
Write a program that calls a function to filter out the elements with values less than 7 and return a sublist. The function takes an integer list passed to it from main(). The list is created in main() by prompting the user for ten integer values. The sublist, is printed in main(). Save your files as FirsrNameLastName Lists Be sure to submit 2 files for this assignment (.py and .docx ). Be sure to include your algorithm for each problem in your Python program and/or .docx files. Document you code for each program by including comments throughout your program. Label your program output with an appropriate message and document your code for each function and main. Submit 2 files for this lab: .py and .docx (with your algorithm, source code, screenshots and conclusions)
Define a function to filter out values and return a sublist Ask for user input in main and pass list to other function Print sublist