Intro to Business Programming Chapter 8

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Write an expression to print each price in stock_prices.Sample output with inputs: 34.62 76.30 85.05 $34.62 $76.30 $85.05

# NOTE: The following statement converts the input into a list container stock_prices = input().split() for price in stock_prices: print(f'${price}')

x = 10 while x != 3: print(x, end=' ') x = x / 2

IL (Infinite Loop) (infinite loop) because no matter how many times 10 is divided by 2, the result will never equal 3. The programmer perhaps should have used ">= 3".

Assume that my_list is [0, 5, 10, 15]. What value is returned by max(my_list)?

The largest element in the list is 15.

Assume that my_list is [0, 5, 10, 15]. What value is returned by any(my_list)?

The list contains non-zero elements, thus any() returns True.

Assume that my_list is [0, 5, 10, 15]. What value is returned by min(my_list)?

The smallest element in the list is 0.

Iterating over a list and deleting elements from the original list might cause a logic program error.

True

Loop iterates over the odd integers from 211 down to 31 (inclusive). i = 211 while i >= 31: # Loop body statements go here

i -= 2

Loop iterates from -100 to 65. (blank) while i <= 65: # Loop body statements go here i = i + 1

i = -100

Write a while loop that prints from 1 to user_num, increasing by 1 each time. Sample output with input: 4 1 2 3 4

i = 1 user_num = int(input()) # Assume positive n = 1 while n <= user_num: print(n) n += 1

Program Specifications Write a program to play an automated game of Rock, Paper, Scissors. Two players make one of three hand signals at the same time. Hand signals represent a rock, a piece of paper, or a pair of scissors. Each combination results in a win for one of the players. Rock crushes scissors, paper covers rock, and scissors cut paper. A tie occurs if both players make the same signal. Use a random number generator of 0, 1, or 2 to represent the three signals.Note: this program is designed for incremental development. Complete each step and submit for grading before starting the next step. Only a portion of tests pass after each step but confirm progress.Step 0. Read starter template and do not change the provided code. Variables are defined for ROCK, PAPER, and SCISSORS. A seed is read from input to initialize the random number generator. This supports automated testing and creates predictable results that would otherwise be random. Step 1 (2 pts). Read two player names from input (str). Read number of rounds from input. Continue reading number of rounds if value is below one and provide an error message. Output player names and number of rounds. Submit for grading to confirm 2 tests pass.Ex: If input is: 3 Anna Bert -3 -4 4

import random ROCK = 0 PAPER = 1 SCISSORS = 2 # Read random seed to support testing (do not alter) and starting credits seed = int(input()) # Set the seed for random random.seed(int(seed)) # Read the names for both the players player_1 = input() player_2 = input() # Declare and initialize the number of rounds to 0 rounds = 0 # Declare and initialize a count to keep track of the rounds to 0 count = 0 # Declare and initialize counts to keep track of both player's wins to 0 winCount1 = 0 winCount2 = 0 # Keep looping till the number of rounds is less than 1 while True: # Read the number of rounds from the user rounds = int(input()) # Break the loop if the number of rounds is greater than or equal to 1 if rounds >= 1: break # Else display the error message else: print("Rounds must be > 0") # Display both the player's names & rounds print(player_1 + " vs " + player_2 + " for " + str(rounds) + " rounds") # keep looping till the count is less than the number of rounds while count < rounds: # generate two random values between 0 and 2 p1 = random.randint(0, 2) p2 = random.randint(0, 2) # if both the values are same then it is a tie if p1 == p2: print("Tie") # if the first player plays a rock elif p1 == ROCK: # if the second player plays a scissors if p2 == SCISSORS: # then the first player wins with rock since rock breaks scissors print(player_1 + " wins with rock") # increment player 1's count of wins winCount1 = winCount1 + 1 # else the seond player plays a paper else: # so the second player wins with paper since paper covers rock print(player_2 + " wins with paper") # increment player 2's count of wins winCount2 = winCount2 + 1 # increment the count of rounds count = count + 1 # else if the first player plays a paper elif p1 == PAPER: # if the second player plays a rock if p2 == ROCK: # then the first player wins with paper since paper covers rock print(player_1 + " wins with paper") # increment player 1's count of wins winCount1 = winCount1 + 1 # else the seond player plays a scissors else: # so the second player wins with scissors since scissors cuts paper print(player_2 + " wins with scissors") # increment player 2's count of wins winCount2 = winCount2 + 1 # increment the count of rounds count = count + 1 # else if the first player plays a scissors elif p1 == SCISSORS: # if the second player plays a paper if p2 == PAPER: # then the first player wins with scissors since scissors cuts paper print(player_1 + " wins with scissors") # increment player 1's count of wins winCount1 = winCount1 + 1 # else the seond player plays a rock else: # so the second player wins with rock since rock breaks scissors print(player_2 + " wins with rock") # increment player 2's count of wins winCount2 = winCount2 + 1 # increment the count of rounds count = count + 1 # print the count of wins for both the players print(player_1 + " wins " + str(winCount1) + " and " + player_2 + " wins " + str(winCount2))

Change all negative values in my_dict to 0. for key, value in

my_dict.items()

Print each key in the dictionary my_dict. for key in

my_dict.keys()

Print twice the value of every value in my_dict. for v in

my_dict.values()

Iterate over the given list using a variable called my_pet.

my_pet

Write a statement using *= that doubles the value of a variable my_var.

my_var *= 2

Write a statement using += that is equivalent tomy_var = my_var + my_var / 2

my_var += my_var / 2

Write a loop to populate the list user_guesses with a number of guesses. The variable num_guesses is the number of guesses the user will have, which is read first as an integer. Read each guess (an integer) one at a time using int(input()).Sample output with input: 3 9 5 2 user_guesses: [9, 5, 2]

num_guesses = int(input()) user_guesses = [] for i in range(num_guesses): guess = int(input()) user_guesses.append(guess) print(f'user_guesses: {user_guesses}')

Assign num_neg with the number of below-freezing Celsius temperatures in the list. temperatures = [30, 20, 2, -5, -15, -8, -1, 0, 5, 35] num_neg = 0 for temp in temperatures: if temp < 0:

num_neg += 1

Retype or copy, and then run the following code; note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks. while num_printed != num_stars: print('*') Sample output with input: 3 * * *

num_printed = 0 num_stars = int(input()) num_printed = 0 while num_printed != num_stars: print('*') num_printed += 1

Iterate over the list my_prices using a variable called price.

price in my_prices

Write an expression using random.randint() that returns a number between 0 and 5, inclusive.

random.randint(0, 5)

Every integer from 10 to 20

range(10, 21)

Every 2nd integer from 10 to 20

range(10, 21, 2)

Every integer from 5 down to -5

range(5, -6, -1)

Every integer from 0 to 500.

range(501)

Print scores in order from highest to lowest. Note: List is pre-sorted from lowest to highest. scores = [75, 77, 80, 85, 90, 95, 99] for scr in

reversed(scores)

Write a program that compares two strings given as input. Output the number of characters that match in each string position. The output should use the correct verb (match vs matches) according to the character count. Ex: If the input is: crash crush the output is: 4 characters match Ex: If the input is: cat catnip the output is: 3 characters match Ex: If the input is: mall saw the output is: 1 character matches Ex: If the input is: apple orange the output is: 0 characters match

string1 = input() string2 = input() # Find the length of the shorter string min_length = min(len(string1), len(string2)) # Initialize a counter for the number of matching characters matching_chars = 0 # Iterate through the characters in both strings and compare them for i in range(min_length): if string1[i] == string2[i]: matching_chars += 1 # Output the result if matching_chars == 1: print(f"{matching_chars} character matches") else: print(f"{matching_chars} characters match")

A programmer can iterate over a copy of a list to safely make changes to the original list.

True

Compute the average number of kids. # Each list item is the number of kids in a family. num_kids = [1, 1, 2, 2, 1, 4, 3, 1] total = 0 for num in num_kids: total +=

num

For inputs 5 10 7 20 8 0, with what values should max be assigned? A) -1, 20 B) -1, 5, 10, 20 C) -1, 5, 10, 7, 20

B

1. Which if-else branch will execute if the user types "Goodbye"?Valid answers are branch 0, 1, 2 or none. 2. How many times does the loop iterate in the program?

1. None, The while loop condition checks if the user typed "Goodbye". If so, the loop body will NOT be executed, and instead the "It was nice talking ..." message is printed. 2. Unknown, The loop iterates until the user types 'Goodbye', so the number of iterations can't be predicted.

x = 5 y = 18 while y >= x: print(y, end=' ') y = y - x

18 13 8

Iterate the string '911' using a variable called number.

number in '911'

Count how many odd numbers (cnt_odd) there are. cnt_odd = for i in num: if i % 2 == 1: cnt_odd += 1

0

Assume the user would enter 'n', then 'n', then 'y'. # Get character from user here while user_char != 'n': # Do something # Get character from user here

0 Upon reaching the loop, the expression user_char != 'n' is False (because user_char IS equal to 'n'). So the loop body is never entered.

Assume that my_list is [0, 5, 10, 15]. 1)What value is returned by sum(my_list)?

0+5+10+15 = 30

x = 1 y = 3 z = 5 while not (y < x < z): print(x, end=' ') x = x + 1

1 2 3 The expression not (y < x < z) is True until x has a value of 4. Each iteration, x is printed out with a space and then incremented by 1.

Consider the following program: nums = [10, 20, 30, 40, 50] for pos in range(len(nums)): tmp = nums[pos] / 2 if (tmp % 2) == 0: nums[pos] = tmp 1) What's the final value of nums[1]?

10.0

Use input values of num_a = 15 and num_b = 10 in the above GCD program. Answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is the value of num_a before the first loop iteration?

15 The loop hasn't executed yet, so num_a is just the input value.

Assume user would enter 'a', then 'b', then 'n'. # Get character from user here while user_char != 'n': # Do something # Get character from user here

2 First check: 'a' != 'n' is True. Second: 'b' != 'n' is True. Third: 'n' != 'n' is False (because they are equal), so the loop body is not entered a third time.

Use input values of num_a = 15 and num_b = 10 in the above GCD program. Answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. How many loop iterations will the algorithm execute?

2 The loop does not enter a third iteration because num_a == num_b (5 == 5), so execution proceeds below the while loop. Thus, 5 is output as the GCD.

For each question, indicate how many times the loop body will execute. x = 3 while x >= 1: # Do something x = x - 1

3 First check, x is 3, so x >= 1 is True. Second check, x is 2, still True. Third check, x is 1, still True. Fourth check, x is 0, so x >= 1 is False.

Use input values of num_a = 15 and num_b = 10 in the above GCD program. Answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is num_b after the second and before the third iteration?

5 num_a = num_a - num_b executes, giving num_a = 5. Then num_b = num_b - num_a executes, giving num_b = 5.

Use input values of num_a = 15 and num_b = 10 in the above GCD program. Answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is num_a after the first iteration and before the second?

5 num_a = num_a - num_b executes; num_a = 15 - 10 = 5

What sequence is generated by range(2, 5)? A) 2 3 4 B) 2 3 4 5 C) 0 1 2 3 4

A 2 3 4

Complete the program so the variable max ends up having the maximum value in an input list of positive values (the list ends with 0). So if the input is 22 5 99 3 0, then max should end as 99. max = -1 val = Get next input while val is not 0 If __(A)__ __(B)__ val = Get next input What should statement (B) be? A) max = val B) val = max C) max = max + 1

A If the current value is greater than the max seen so far, then this statement updates max to the current value, which is now the max seen so far. The program is: max = -1 val = Get next input while val is not 0 If val > max max = val val = Get next input

Consider the example above and the given example input sequence 10 1 6 3 0. What would happen if the following list was input: 10 1 6 3 -1? A) Output would be 5 B) Output would be 4 C) Error

A The loop expression checks for > 0, rather than == 0. Thus, any negative value also acts as a sentinel, ending the loop.

Iterate as long as the user-entered string c is not q. A) While B) For

A) While The number of iterations is not known before the loop, so use "while c != 'q':".

Iterate until the values of x and y are equal, where x and y are changed in the loop body. A) While B) For

A) While The number of iterations is not known before the loop, so use 'while x != y:'.

Complete the program so the variable max ends up having the maximum value in an input list of positive values (the list ends with 0). So if the input is 22 5 99 3 0, then max should end as 99. max = -1 val = Get next input while val is not 0 If __(A)__ __(B)__ val = Get next input What should expression (A) be? A) max > 0 B) max > val C) val > max

B If the current value is greater than the max value seen so far, then the max value needs to be updated.

Consider the example above and the given example input sequence 10 1 6 3 0. How many actual (non-sentinel) values are given in the first input sequence? A) 1 B) 4 C) 5

B The first four values are 10, 1, 6, and 3.

Complete the program such that variable count ends having the number of negative values in an input list of values (the list ends with 0). So if the input is -1 -5 9 3 0, then count should end with 2. count = 0 val = Get next input While val is not 0 if __(A)__ __(B)__ val = Get next input What should expression (A) be? A) val > 0 B) val < 0 C) val is 0

B The program should count negative values. The expression detects a negative value.

Complete the program such that variable count ends having the number of negative values in an input list of values (the list ends with 0). So if the input is -1 -5 9 3 0, then count should end with 2. count = 0 val = Get next input While val is not 0 if __(A)__ __(B)__ val = Get next input What should statement (B) be? A) val = val + 1 B) count = count + 1 C) count = val

B Variable count should be incremented each time a negative input value is seen. The final loop is: count = 0 val = Get next input While val is not 0 If val < 0 count = count + 1 val = Get next input

Consider the example above and the given example input sequence 10 1 6 3 0. For the given input sequence, what is the final value of num_values? A) 0 B) 4 C) 5

B num_values is initialized with 0 and then incremented in each loop iteration: 10: num_values is 1 1: num_values is 2 6: num_values is 3 3: num_values is 4 0: Loop body not entered. Thus, num_values ends with 4, which is the correct number of non-sentinel values.

Use the following code to answer the question below: for (index, value) in enumerate(my_list): print(index, value) 1) If my_list = ['Greek', 'Nordic', 'Mayan'], what is the output of the program? A) Greek Nordic Mayan B) 0 Greek 1 Nordic 2 Mayan C) 1 Greek 2 Nordic 3 Mayan

B) 0 Greek 1 Nordic 2 Mayan

Iterate 1500 times A) While B) For

B) For The number of iterations is known, so use 'for i in range(1500)'.

What is the output of the following code? (Use "IL" for infinite loops.) x = 0 while x > 0: print(x, end=' ') x = x - 1 print('Bye')

Bye x == 0, so the loop never executes.

What sequence is generated by range(7)? A) 0 1 2 3 4 5 6 7 B) 1 2 3 4 5 6 C) 0 1 2 3 4 5 6

C 0 1 2 3 4 5 6

Assume that my_list is [0, 5, 10, 15]. What value is returned by all(my_list)?

False

Write a program that reads a loan amount, payment amount, and interest rate as inputs and outputs the number of payments required until the loan is paid. Interest is added to current balance before a payment is applied. Ex: If current balance is $100.00 and the interest rate is 0.02, the new balance is $102.00 before a payment is applied. All values are floats. Ex: If the input is: 1000.0 50.0 0.03 the output is: 31 payments Ex: If the input is: 50.0 100.0 0.02 the output is: 1 payment

Input: 1000.0 50.0 0.03 50.0 100.0 0.02 loan_amount = float(input()) payment_amount = float(input()) interest_rate = float(input()) balance = loan_amount num_payments = 0 while balance > 0: balance = balance + balance * interest_rate balance = balance - payment_amount num_payments += 1 print(num_payments, "payment" if num_payments == 1 else "payments")

Many user-created passwords are simple and easy to guess. Write a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "!" to the end of the input string. i becomes 1 a becomes @ m becomes M B becomes 8 s becomes $ Ex: If the input is: mypassword the output is: Myp@$$word!

Input: mypassword k = input() result = '' for p in k: if(p== 'i'): result+= "1" elif(p == 'a'): result += "@" elif (p == 'm'): result += "M" elif (p == 'B'): result += "8" elif (p == 's'): result += "$" else: result += p result += "!" print(result)

Does the final value of max depend on the order of inputs? In particular, would max be different for inputs 22 5 99 3 0 versus inputs 99 3 5 22 0?

No 99 is the max, regardless of the order. For the first order, max will be -1, then 22, then 99. For the second order, max will be -1, then 99.

Consider the example above and the given example input sequence 10 1 6 3 0. Suppose the first input was 0. Would values_sum / num_values be 0? Yes No

No num_values would still have its initial value of 0. Dividing by 0 is an error. This program generates an error in this case.

If the input value is 0, does the loop body execute? Yes No

No As long as the input value is not 0 (such as -1, -5, 9, or 3), the loop body will execute. But when the value IS 0, the loop's expression is false and thus the loop body is not executed.

Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to an expression. Iterate until c equals 'z'.

c != 'z'

Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to an expression. Iterate while c equals 'g'.

c == 'g'

Count how many negative numbers (cnt_neg) there are. cnt_neg = 0 for i in num: if i < 0:

cnt_neg += 1

Write a for loop to print each contact in contact_emails.Sample output with inputs: 'Alf' '[email protected]' [email protected] is Mike Filt [email protected] is Sue Reyn [email protected] is Nate Arty [email protected] is Alf

contact_emails = { 'Sue Reyn' : '[email protected]', 'Mike Filt': '[email protected]', 'Nate Arty': '[email protected]' } new_contact = input() new_email = input() contact_emails[new_contact] = new_email for name, email in contact_emails.items(): print(f"{email} is {name}")

Determine the number of elements in the list that are divisible by 10. (Hint: The number x is divisible by 10 if x % 10 is 0.) div_ten = 0 for i in num: if : div_ten += 1

i % 10 == 0

Loop iterates over the odd integers from 1 to 9 (inclusive). i = 1 while i <= 9: # Loop body statements go here

i += 2

Scrabble is a word game in which words are constructed from letter tiles, each letter tile containing a point value. The value of a word is the sum of each tile's points added to any points provided by the word's placement on the game board. Write a program using the given dictionary of letters and point values that takes a word as input and outputs the base total value of the word (before being put onto a board). Ex: If the input is: PYTHON The output is: PYTHON is worth 14 points.

tile_dict = { 'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10 } total = 0 #variable to sum of each tile's point word = input() #string input from user for ch in word: #iterate over each character in word total = total + tile_dict[ch] #add the tile's point to total print(f'{word} is worth', total,'points.') #display the total sum

Write a while loop that repeats while user_num ≥ 1. In each loop iteration, divide user_num by 2, then print user_num. Sample output with input: 20 10.0 5.0 2.5 1.25 0.625 Note: If the submitted code has an infinite loop, the system will stop running the code after a few seconds and report "Program end never reached." The system doesn't print the test case that caused the reported message.

user_num = int(input()) while (user_num >= 1): user_num = user_num/2 print (user_num)

Write an expression that executes the loop body as long as the user enters a non-negative number.Note: If the submitted code has an infinite loop, the system will stop running the code after a few seconds and report "Program end never reached." The system doesn't print the test case that caused the reported message. Sample outputs with inputs: 9 5 2 -1 Body Body Body Done.

user_num = int(input()) while user_num >= 0: print('Body') user_num = int(input()) print('Done.')

Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to an expression. Iterate while x is less than 100.

while x <100

Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to an expression. Iterate while x is greater than or equal to 0.

while x>=0

The loop iterates 10 times. i = 1 while : (blank) # Loop body statements go here i = i + 1

while: i <= 10

Loop iterates over multiples of 5 from 0 to 1000 (inclusive). i = 0 while : (blank) # Loop body statements go here i = i + 5

while: i <= 1000

The loop iterates 2 times. i = 1 while : (blank) # Loop body statements go here i = i + 1

while: i <= 2

The loop iterates 99 times. i = 1 while : (blank) # Loop body statements go here i = i + 1

while: i<= 99


संबंधित स्टडी सेट्स

Module 15: Closed Chest Drainage Systems

View Set

Psyc1101 Introductory Psychology

View Set

Grief, Mourning, and Bereavement

View Set