Instructions: Using an array, enhance the program that you have performed in the previous exercise. The program should accept multiple entries and iteratively perform the following operations. Submit the source code and screenshot of output. Using a user-defined function and appropriate conditional and looping statements, create a program that will: (a) ask the item price from the user (b) ask how many items to purchase for a specific item price (c) ask if there are other items to purchase, if yes, repeat the first step, proceed to the next step if otherwise (d) compute and display for the total amount to pay (e) ask for the payment from the user (f) accepts only enough amount of payment, ask another payment if otherwise (g) compute and display change

Answers

Answer 1

Here is the code in Python which accepts multiple entries and iteratively perform the following operations: (a) ask the item price from the user (b) ask how many items to purchase for a specific item price (c) ask if there are other items to purchase, if yes, repeat the first step, proceed to the next step if otherwise (d) compute and display for the total amount to pay (e) ask for the payment from the user (f) accepts only enough amount of payment, ask another payment if otherwise

(g) compute and display change: Code:```def total amount(items):    total = 0    for i in items:        total += i    return totaldef change(amount, paid):    return paid - amountitems = []while True:    item_price = float(input("Enter the item price: "))    item_quantity = int(input("Enter the quantity of the item: "))    items.append(item price * item_quantity)    choice = input("Do you have another item to purchase? (y/n)")  

if choice.lower() == "n":        breaktotal = total amount(items)print("Total Amount: PHP", total)while True:    paid_amount = float(input("Enter the amount paid: PHP "))    if paid_amount >= total:        break    else:        print("Insufficient amount paid, please try again!")change_amount = change(total, paid_amount)print("Change amount: PHP", change_amount)```

To know more about Python  visit:-

https://brainly.com/question/30391554

#SPJ11


Related Questions

What are the best data structures to create the following items? And why?
1. Designing a Card Game with 52 cards.
2. Online shopping cart (Amazon, eBay, Walmart, Cosco, Safeway....)
3. Online waiting list (De Anza College class waiting list, ...)
4. Purchasing online Tickets (Flight tickets, concert tickets, ...) (=> Fixed-size <=)

Answers

For designing a card game with 52 cards, the best data structure is a stack, For an online shopping cart, the best data structure is a list,  For an online waiting list, the best data structure is a queue, For purchasing online tickets with a fixed size, the best data structure is an array.

1.

The stack data structure is used here.

A stack is a data structure that operates on the principle of Last In First Out (LIFO). In a card game, the deck of cards is shuffled, and then each player takes turns drawing a card from the top of the deck. In order to simulate this, we can use a stack where each card is pushed onto the top of the stack and each player pops a card from the top of the stack.

2.

Here list data structure is used.

A list is a dynamic collection of elements that maintains their order and allows for the addition or removal of elements as needed.In an online shopping cart, items are added to the cart and then the user can choose to remove them or proceed to checkout. A list can easily handle these operations.

3.

Here queue data structure is used.

A queue is a data structure that operates based on the principle of First In First Out (FIFO). In an online waiting list, users are added to the list in the order that they joined, and are served in that order as well. A queue is the ideal data structure for this.

4.

Here array data structure is used.

An array is a data structure that stores elements of the same type in a sequence, occupying adjacent memory locations.Since the number of tickets is fixed, an array can be used to store information about each ticket, such as the ticket type, price, and availability.

To learn more about data structure: https://brainly.com/question/29585513

#SPJ11

PYTHON LIST OF DICTIONARIES PROBLEM
I've been having trouble extracting multiple specific key:value pairs from a list of dictionaries in my code. I will write an example code below:
data_set = [{'diet': 'fruit': 'Apple', 'vegetable': 'Carrot', 'meat': 'Steak', 'starch': 'Rice, 'date': '2022-03-26', 'count': '50'}]
Lets say I would like to:
1. extract the key:value pairs for diet, fruit, meat, count
2. add those key:value pairs to a new dictionary
3. print the new dictionary
4. extract and print the value of 'diet' if the value of 'count' is >= 25 from the new dictionary
How would I code for this?

Answers

The Python code has been written in the space that we have below

How to write the python code

data_set = [

   {'diet': 'fruit', 'fruit': 'Apple', 'vegetable': 'Carrot', 'meat': 'Steak', 'starch': 'Rice', 'date': '2022-03-26', 'count': '50'}

]

# Step 1: Extract specific key-value pairs

keys_to_extract = ['diet', 'fruit', 'meat', 'count']

new_dict = {key: data_set[0][key] for key in keys_to_extract}

# Step 2: Print the new dictionary

print("New Dictionary:")

print(new_dict)

# Step 3: Extract and print the value of 'diet' if the value of 'count' is >= 25

if int(new_dict['count']) >= 25:

   print("\nValue of 'diet' when count is >= 25:")

   print(new_dict['diet'])

Read mroe on Python codes here https://brainly.com/question/26497128

#SPJ4

Please change this code's "if" and "ands" statements and make the code as different as possible without the code loosing it's functionality.
// include the library code:
#include
// Initialize library by way of pin interface
// Elego uno pin number
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
int adl_switch = 6; //switch 6
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
Serial.begin(9600);
lcd.begin(16, 2); // thisn is the LCD's number of columns and row:
pinMode(adl_switch, INPUT_PULLUP); //this indicates internal plug rssitor
}
void loop() {
//Switch on
if (digitalRead (adl_switch) == LOW)
{
lcd.setCursor(0, 0);
lcd.print("Adl Switch");
lcd.setCursor(6, 0);
lcd.print("Adl switch ON ");
}
//code for button inputs when off
if (digitalRead (adl_switch) == HIGH)
{
lcd.setCursor(0, 0);
lcd.print("Switch");
lcd.setCursor(6, 0);
lcd.print(" Off");
}
//this is where my pot is connected, analog pin:
int sensorValue = analogRead(A0);
//equation to convert the input from 0-1023 to a voltage value
float voltage = sensorValue * (5.0/1023.0);
lcd.setCursor(0, 1);
lcd.print("V= V");
lcd.setCursor(2, 1);
lcd.print(voltage);
//this section is to print the position of the switch
if (digitalRead (adl_switch) == HIGH){
Serial.print("digital = 0");
}else{
Serial.print("digital = 1");
}
Serial.print(" ");
Serial.print("analog = ");
Serial.println(voltage);
delay(50);
}

Answers

The given code can be modified by modifying the if and else if statements of the given code. The modification of if and else if statement will make the code different but the functionality of the code will remain the same.

The modified code is as follows:Modifying the code by changing "if" and "else if" statements:#include const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;int adl_switch = 6;LiquidCrystal lcd(rs, en, d4, d5, d6, d7);void setup() {Serial.begin(9600);lcd.begin(16, 2);pinMode(adl_switch, INPUT_PULLUP);}void loop() {//Switch onswitch(digitalRead(adl_switch)){case LOW:lcd.setCursor(0, 0);lcd.print("Adl Switch");lcd.setCursor(6, 0);lcd.print("Adl switch ON ");break;case HIGH:lcd.setCursor(0, 0);lcd.print("Switch");lcd.setCursor(6, 0);lcd.print("

Off");break;default:break;}int sensorValue = analogRead(A0);float voltage = sensorValue * (5.0 / 1023.0);lcd.setCursor(0, 1);lcd.print("V= V");lcd.setCursor(2, 1);lcd.print(voltage);if(digitalRead(adl_switch) == HIGH){Serial.print("digital = 0");}else{Serial.print("digital = 1");}Serial.print(" ");Serial.print("analog = ");Serial.println(voltage);delay(50);}The above given modified code is functionally same as the original code but the statements used are different and unique.

To know more about code visit:-

https://brainly.com/question/17204194

#SPJ11

Briefly answer:
b) Explain why genetic algorithm does not guarantee that a global optimal solution will be found.
c) But, why is genetic algorithm useful? In other words, describe in general situations in which a genetic algorithm may be better than nonlinear or integer programming.
d) In general why cant a genetic algorithm cope with a large number of constraint?

Answers

The genetic algorithm does not guarantee finding a global optimal solution due to its reliance on random variations and selection processes, which can result in suboptimal solutions or getting stuck in local optima. However, it remains useful in complex optimization problems, especially when dealing with nonlinearities, combinatorial optimization, and situations where traditional approaches like nonlinear or integer programming may be less effective.

b) Genetic algorithms do not guarantee finding a global optimal solution because they work based on the principles of natural evolution, using random variations and selection processes that may lead to suboptimal solutions or get stuck in local optima.

c) Despite not guaranteeing a global optimal solution, genetic algorithms are useful in various situations. They excel in complex, nonlinear, and combinatorial optimization problems where traditional approaches like nonlinear or integer programming may struggle. Genetic algorithms can handle large solution spaces, diverse constraints, and nonlinearity effectively, making them suitable for problems with multiple objectives or when the search space is not well-defined.

d) However, genetic algorithms may face challenges when dealing with a large number of constraints. As the number of constraints increases, it becomes more difficult to find feasible solutions that satisfy all the constraints simultaneously. The search space expands, making it harder for the algorithm to explore and converge towards valid solutions efficiently.

This can lead to longer computation times and lower success rates in finding feasible solutions for highly constrained problems. Therefore, alternative optimization methods or techniques that specifically address constraint handling may be more suitable in such cases.

To learn more about Genetic algorithms, visit:

https://brainly.com/question/28566003

#SPJ11

Must at least read or write to a file • Must utilize at least a list or dictionary • Must incorporate user input • Must utilize functions to make code organized and efficient • Must utilize at least ifs or loops

Answers

An example of a Python program that incorporates the mentioned requirements to take login information (username and password) from the user -

def read_credentials():

   credentials = {}

   with open('login_info.txt', 'r') as file:

       for line in file:

           username, password = line.strip().split(',')

           credentials[username] = password

   return credentials

def write_credentials(username, password):

   with open('login_info.txt', 'a') as file:

       file.write(f'{username},{password}\n')

def login():

   credentials = read_credentials()

   username = input("Enter your username: ")

   password = input("Enter your password: ")

   

   if username in credentials and credentials[username] == password:

       print("Login successful!")

   else:

       print("Invalid credentials.")

def register():

   username = input("Enter a username: ")

   password = input("Enter a password: ")

   

   write_credentials(username, password)

   print("Registration successful!")

# Main program

while True:

   choice = input("Choose an option (login/register/exit): ")

   

   if choice == "login":

       login()

   elif choice == "register":

       register()

   elif choice == "exit":

       break

   else:

       print("Invalid choice. Please try again.")

How does this work?

- The login information is stored in a file called "login_info.txt" in the format `username,password`.

- The `read_credentials()` function reads the credentials from the file and returns them as a dictionary.

- The `write_credentials()` function appends new credentials to the file.

- The `login()` function asks the user for their username and password and checks if they match the stored credentials.

- The `register()` function asks the user to enter a new username and password and saves them to the file.

- The main program uses a while loop to repeatedly prompt the user for options (login, register, or exit) and calls the respective functions based on the choice.

Learn more about User Input at:

https://brainly.com/question/30195673

#SPJ4

Full Question:

Although part of your question is missing, you might be referring to this full question:

In Python Create A Program That Takes Login Information (Username And Password) Please Make Sure All In The Picture Below Is Utilized

in python create a program that takes login information (username and password) please make sure all in the picture below is utilized

Must at least read or write to a file • Must utilize at least a list or dictionary • Must incorporate user input • Must utilize functions to make code organized and efficient • Must utilize at least ifs or loops

To obtain a JTable field's name, the correct statement to use is: A AbstractTableModel getColumnName(Columnindex + 1) 8. ResultSet getColumnName(Columnindex + 1) C JTable getColumnName(Columnindex + 1) D. ResultSetMetaData.columnName(Columnindex +1) E JTable columnName(Columnindex + 1) 10. To notify a JTable that the table has changed, one of the following statements achie A tableDataChanged(?) B. itemStateChanged(?) C. data TableChanged(?) D valueChanged(7) E fire TableStructureChanged() 11. To create a static thread-pool & a pool manager, a programmer would write: A ThreadPool.create(10) B. Executors.newFixed ThreadPool(10) C. ExecutorService.newCachedThreadPool() D. Thread newCachedThreadPool() E. ExecutorService.createCached ThreadPool() 12. How to programmatically enable thread "B" to suspend its execution and wait for thread " assuming that "B" has executed "A"? A. B.notify B.B.wait() C.B.join() DA join() E. Condition await() 13. To release the monitor-lock of an object "A", the following statement should be invoked by t A Condition signall) Condition await) C. Aawait) D. A unlock() E. A notify 14. In order to obtain the result of a task-processing by a thread, a programmer would need to en A Executors 8. Callable C Runnable D. Thread E ExcutorService 15. If a thread attempts to access a "synchronized" method and access to the method can not be the is A Runnable B. Waiting C. Timed Waiting D. Blocked E Suspended 16. Which statement of the following list would schedule the task "long Factorial(int x)" by thread A. A start) B new Thread(A) C. A.call() D. ExecutorService execute(A) E ExecutorService submit(A) 17. How to obtain a remote web client's logical address?: A HttpServletRequest getClientAddress 8. HttpServletRequest getRemoteHost) C.HttpServietRequest getRemoteAddr) D. HitpServletResponse.getClientAddress( E. HttpServletResponse.getRemoteAddr) 2

Answers

To obtain a JTable field's name, the correct statement to use is: C. JTable getColumnName(Columnindex + 1)To notify a JTable that the table has changed, one of the following statements achieves:

A. To create a static thread-pool & a pool manager, a programmer would write: B. Executors.newFixedThreadPool(10)How to programmatically enable thread "B" to suspend its execution and wait for thread "A" assuming that "B" has executed "A"?B. B.wait()To release the monitor-lock of an object "A", the following statement should be invoked by the thread that acquired it: D. A unlock()In order to obtain the result of a task-processing by a thread, a programmer would need to employ:

B. CallableIf a thread attempts to access a "synchronized" method and access to the method cannot be obtained, the thread is: D. BlockedThe statement that would schedule the task "long Factorial(int x)" by thread is: D. ExecutorService execute(A)To obtain a remote web client's logical address, HttpServletRequest getRemoteAddr() should be used. Answer: C. HttpServletRequest getRemoteAddr)

To know more about monitor-lock visit:

https://brainly.com/question/32420716

#SPJ11

Other Questions
Practice Problem 18 Let (G,.) be a group of order n, that is | G|=n. Suppose that a, be G are given. Find how many solutions the following equations have on n) in G (your answer may depend on A) ax b = a.x.b b. Y B) x a = (x is the variable) (x, Y are the variables) What did Jacob Riis's book do?OA. Supported anti-immigration lawsOB. Told about life in the slumsOC. Got police to visit the slumsOD. Helped poor people get better jobsSUBMIT howdo i solveIf \( t \) is the distance from \( (1,0) \) to \( (-0.9454,0,3258) \) along the circumference of the unit circle, find csc \( t \), sec \( t \), and cot \( t \). Write a Java program to calculate the revenue from a sale based on the unit price and quantity of a product input by the user. The discount rate is 10% for the quantity purchased between and including 100 and 120 units, and 15% for the quantity purchased greater than 120 units. If the quantity purchased is less than 100 units, the discount rate is 0%.You will provide a method called calculateRevenue that takes in two arguments, the unit price and quantity of a product. (Use correct data types). The calculateRevenue method will calculate the revenue from the sale and the discount that was given.The inputs will be handled in the main method which will call the method calculateRevenue and pass it the revenue and quantity.See the example output as shown below:Enter unit price: 25Enter quantity: 110The revenue from sale: $2475.00The discount rate you received is 10%. A mass, m_1 =m1=6.83-kg mass is placed on a frictionless ramp which is inclined at 51.5^\circ above the horizontal. It is connected to a second mass, m_2m2, by a strong rope which is run over a pulley at the apex of the ramp so that the second mass is suspended in the air next to the ramp, as shown in the figure. Calculate the mass, m_2m2 necessary so that the mass, m_1m1accelerates up the incline at 2.64 m/s^2m/s2. Suppose that in the absence of transportation costs Home specializes in coffee and coal while Foreign specializes in cars and corn. Cigars are produced in both countries and are thus a nontraded good. From the data in the accompanying table it can be deduced that Home's relative wage (w/w*) is . (Enter your response as an integer.) If both coal and cars become nontraded goods after transportation costs are included in the analysis, it must be the case that those costs, as a percentage of production costs, are at least A. 150 percent. B. 50 percent. C. 100 percent. D. 200 percent. \begin{tabular}{lc} \hline & Relative Home Productivity Advantage (a Li/a Li) \\ \hline Coffee & 9 \\ Coal & 6 \\ Cigars & 3 \\ Cars & 1.5 \\ Corn & 1 \\ \hline \end{tabular} Give the instruction that will do the following. 9 10. Put the constant value "12" into the register r0. 10. After incrementing r2 by eight, get the value from memory pointed to by the address contained in r2 and put it into r0. At a given time/in an LC circuit, the energy in the capacitor is 25.0% of the energy in the inductor. For this condition to occur, what fraction of a period must clapse following the time the capacitor is fully charged (at t = 0)? 4.0.217 6.0.152 e. 0.167 d. 0.176 how would you reduce the cost of benefits to theemployer without reducing coverage for employees An investment producing cash flows in the amount of $1,445 per month is undertaken for a period of 28 months. The investor pays $28,200 for the investment and the contract stipulates that investment returns must be reported on a basis equivalent with annual compounding. Required: a. Given that the investment is sold after 28 months, what would be the equivalent annual compound rate of interest reported to the investor? b. What would be the annual rate compounded monthly for this investment? Note: For all requirements, do not round intermediate calculations and round your answers to 2 decimal places. Write a C++ program that calls a function to print out hello world ten times using a for loop Here are summary statistics for randomly selected weights of newborn girls: n=291, x=28.6hg,s=7.8 hg. The confidence level is 99%. Select the correct choice below and, if necessary, fill in the answer box to complete your choice. A. t /2= (Round to two decimal places as needed.) B. z /2= (Round to two decimal places as needed.) C. Neither the normal distribution nor the distribution applies. cosx= 31, x in quadrant III. Find the value of sin 2x,cos 2x,tan 2x Assume a String variable named linel has been declared. Write a statement that declares a Scanner object associated with a file named "poem". Then, write another statement that uses the Scanner object to read the first line from the file and stores it in line1. (Do not use a try statement here. Simply write the two lines of code.) Given the language L = {w {0, 1}* | w contains at least three 1s}, (a) show a context-free grammar that generate L. (b) construct a push-down automta using the top-down approach. Solution:: Which of the following should a govt do in order to increase economic growth? Take steps to increase the amount of household spending and reduce the amount of household savings. Take steps to reduce the amount of foreign investment in the country. Take steps to raise import tariffs on foreign goods. Take steps to pass patent laws so that inventors' rights are protected. what is Bombardier inc Market Analysis ?Submarkets.SIZE AND GROWTHImportant submarkets? What are the size and growth characteristics of a market and submarkets? What submarkets are declining or will soon decline? How fast? What are the driving forces behind sales trends?PROFITABILITYFor each major submarket consider the following: Is this a business area in which the average firm will make money? How intense is the competition among existing firms? Evaluate the threats from potential entrants and substitute products. What is the bargaining power of suppliers and customers? How attractive/profitable are the market and its submarkets both now and in the future?COST STRUCTUREWhat are the major cost and value-added components for various types of competitors?DISTRIBUTION SYSTEMSWhat are the alternative channels of distribution? How are they changing?MARKET TRENDSWhat are the trends in the market?KEY SUCCESS FACTORSWhat are the key success factors, assets, and competencies needed to compete successfully? Assume you have written a program that calculates and displays the values of (x,y) coordinate pairs at each time interval for a projectile. As the output from your program, you want to display the values for time, x, and y beneath the following headings Time x-coordinate y-coordinate (in seconds) Thorizontal displacement) (vertical displacement) You decide to avoid "cluttering up the main function by defining a separate user-defined function to handle only the column heading display shown above. This other function will then be called by main. This other function will not return anything. Which of the following would be an appropriate heading for this function? a int printHeadings (int x, inty) Ob vold peintheadings string printHeadings) a.char print Headings (char x, chary e. None of the above need help The Fashion Shoe Company operates a chain of women's shoe shops that carry many styles of shoes that are all sold at the same price. Sales personnel in the shops are paid a sales commission on each pair of shoes sold plus a small base salary. The following data pertains to Shop 48 and is typical of the company's many outlet: Par Pairof Shoen $40.00 Selling price Variable expenaos Invoice cost Salen commission Total variable expenses $14.00 6.00 $20.00 Fixed expenses: Advertising Rent Salaries Total fixed expenses Annual $49.000 41,000 195.000 $285,000 Required: 6.Refer to the original data. The company is considering eliminating sales commissions entirely in its shops and increasing fixed salaries by $37.400 annually.If this change is made,what will be Shop 48's new break-even point in unit sales and dollar sales? NoteDo not round Inlermediate calculatlons. New break-even point in unit sales New-break-even point in dollar sales pairs According to a study done by Nick Wilson of Otago University Wellington, the probability a randomly selected individual will not cover his or her mouth when sneezing is 0.267. Suppose you sit on a bench in a mall and observe people's habits as they sneeze. Complete parts (a) through (c) COD (a) What is the probability that among 12 randomly observed individuals, exactly 5 do not cover their mouth when sneezing? Using the binomial distribution, the probability is (Round to four decimal places as needed) (b) What is the probability that among 12 randomly observed individuals, fewer than 3 do not cover their mouth when sneezing? Micro Tea Using the binomial distribution, the probability is (Round to four decimal places as needed) (c) Would you be surprised it, after observing 12 individuals, fewer than half covered their mouth when sneezing? Why? it be surprising because using the binomial distribution, the probability is which is (Round to four decimal places as needed) 0.05