Question

In: Computer Science

This document describes a computer program you must write in Python and submit to Gradescope. For...

This document describes a computer program you must write in Python and submit to Gradescope. For this project, the program will simulate the operation of a vending machine that sells snacks, accepting coins and dispensing products and change. In an actual vending machine, a program running on an embedded computer accepts input from buttons (e.g. a numeric keypad) and devices such as coin acceptors, and its output consists of signals that control a display, actuate motors to dispense products, etc.. However, for this project you will build a simulation where all of the necessary input signals are replaced by keyboard input from a user, and all output signals and actions are indicated by printing text to the terminal. 2. PREVIEW Here is a sample session of using the kind of vending machine simulator you are going to write. This example is meant to convey the general idea. A longer sample input and output for the program can be found in Section 7. Red boxes indicate keyboard input from the user. CREDIT : $0 .00 > inventory 0 Nutrition nuggets $1 .00 (5 available ) 1 Honey nutrition nuggets $1 .20 (5 available ) 2 Almonds $18 .00 (4 available ) 3 Nutrition nugget minis $0 .70 (10 available ) 4 A carrot $4 .00 (5 available ) 5 Pretzels $1 .25 (8 available ) CREDIT : $0 .00 > 3 MSG : Insufficient credit CREDIT : $0 .00 > quarter CREDIT : $0 .25 > quarter CREDIT : $0 .50 > quarter CREDIT : $0 .75 > 3 VEND : Nutrition nugget minis RETURN : nickel CREDIT : $0 .00 > 3. OPERATIONAL SPECIFICATION This section describes how your program must operate. The program will be given one command line option, which is the name of a text file containing the inventory. The format of this file is described below (Section 3.1). The program will read this file to determine the starting inventory of snacks. It will then begin the simulation, in which it reads user commands and responds accordingly. The required commands are described in Section 3.4. 3.1. Inventory. Before starting the simulation, your program must open, read, and close the text file specified in the first command line argument after the script name. This file will consists of 6 lines, each of which describes one of the six snacks available for purchase. The format of a line is stock,price,name where stock is the number of the snack available at the beginning of the simulation, price is the price of the snack in cents (which will be a multiple of 5), and name is a string not containing the character ”,” that describes the snack. The order of the snacks is important, because when ordering from the machine, a snack is indicated by its 0-based index; thus snack 2 means the third line of the inventory file. Here is a sample inventory you can use for testing: 6,125,Cheesy dibbles 10,115,Oat biscuits 12,75,Sugar rings 5,150,Celery crunchies 6,205,Astringent persimmon 10,95,Almond crescents This inventory file is available for download from https://dumas.io/teaching/2020/fall/mcs260/project2/sample_inventory.txt This inventory indicates, for example, that snack 2 is Sugar rings, of which there are initially 12 available, each of which has a cost of $0.75. 3.2. The simulation. After reading the inventory, your program should enter a loop (the command loop) in which it does the following, repeatedly, in order: • Print CREDIT: followed by the total amount of credit currently deposited in the machine, printed on the same line. The credit is initially $0.00. It should always be printed as a dollar sign, followed by a dollar amount with two digits after the decimal point. • Print a prompt > • Wait for one line of user input • Perform the action associated with the user input, which may involve additional output (see Section 3.4) Note that during the simulation, you need to keep track of the credit (the total amount of money deposited to the machine) and display it on each iteration of the loop. The remaining stock of each snack must also be tracked, as this will change as a result of purchases and restocking. 3.3. Control logic overview. The next section describes the commands your simulation must accept from the user. This section is a high-level description of the underlying principles of operation; for full details see Section 3.4. The simulated vending machine allows the user to insert coins to add credit. If the credit already equals or exceeds the price of the most expensive snack in the inventory, any coin inserted will be immediately returned. The user can select a snack by number (0–5), and if the credit currently in the machine equals or exceeds the price of the snack, then the snack is dispensed. Any change (the difference of the credit and the price) is dispensed as coins. Finally, a maintenance worker can specify that one of the snacks is being restocked, i.e. more of that snack has been loaded into the machine. Restocked snacks are then available for purchase. 3.4. Commands. The simulation must support the following commands: • quarter - simulates deposit of one quarter ($0.25). If the current credit is less than the most expensive item in the inventory (including any items that may be out of stock), the coin is accepted and credit increases by $0.25. Otherwise, the coin is rejected by printing the line RETURN: quarter to indicate that the quarter just deposited is returned. • dime - simulates deposit of one dime ($0.10). The logic is the same as the quarter command, except that if the dime is not accepted, the line to be printed is RETURN: dime • nickel - simulates deposit of one dime ($0.05). The logic is the same as the quarter command, except that if the nickel is not accepted, the line to be printed is RETURN: nickel • inventory - display the current inventory in the format of 0-based index, followed by name, followed by price, and then a parenthetical statement of the number available, in this format: 0 Cheesy dibbles $1.25 (6 available) 1 Oat biscuits $1.15 (10 available) 2 Sugar rings $0.75 (12 avilable) 3 Celery crunchies $1.50 (5 available) 4 Astringent persimmon $2.05 (6 available) 5 Almond crescents $0.95 (10 available) • Any of the digits 0, 1, 2, 3, 4, 5 - this is a request to purchase the snack whose 0-based index in the inventory is the given integer. The action depends on the current credit and stock: – If the current credit is sufficient to purchase that snack, and if the stock of that snack is positive, then the machine dispenses the snack followed by change. Dispensing the snack is simulated by printing VEND: Name of snack where “Name of snack” is replaced by the name specified in the inventory. Then, returning change is simulated by printing lines such as RETURN: quarter RETURN: dime RETURN: nickel so that each line corresponds to one coin that is returned. The process for making change is subject to additional rules, described in Section 3.5. After a successful purchase and dispensing of change, the stock of that item decreases by one, and the credit is set to $0.00. – If the stock of the requested item is zero, the following line is printed: MSG: Out of stock The credit is unchanged, and the loop begins again immediately. (For example, if the credit was also insufficient for that item, no message is printed to that effect.) – If the stock of the requested item is positive, but the current credit is NOT sufficient to purchase that snack, then the following line is printed: MSG: Insufficient credit The credit is unchanged. • restock - add to the inventory of one snack. This command never appears on a line by itself, and is always followed by a space and then two integers separated by spaces. The first integer is the 0-based index of a snack, and the second is the number of additional items loaded. The effect of this command is to immediately increase the inventory of that snack. The current credit is not changed. For example, restock 3 18 means that the inventory of snack 3 should be increased by 18. • return - a request to return all currently-deposited credit. The credit should be returned to the user in the same way that change is returned after a successful purchase (see Section 3.5 for detailed rules). • exit - exit the program. 3.5. Coin return rules. The specifications above include two situations in which coins need to be dispensed to the user: • After a purchase, to give change • In response to the return command, to return the current credit In each case, simulated coins are dispensed by printing lines such as RETURN: quarter RETURN: dime RETURN: nickel each of which corresponds to a single coin. The sequence of coin return lines must begin with quarters, followed by dimes, and lastly nickels. Change must be given using the largest coins possible, so for example it is never permissible to give two or more dimes and one or more nickel, because the same change could be made with the number of quarters increased by one. For the purposes of this assignment, the machine never runs out of coins. The following “greedy” approach will dispense coins meeting these requirements: (1) Dispense quarters until the remaining amount to return is less than $0.25. (2) Dispense dimes until the remaining amount to return is less than $0.10. (3) Dispense nickels until the remaining amount to return is zero. Note that unlike most real-world vending machines, these rules mean that the return command may give back a different set of coins than the user deposited. For example, after depositing five nickels, the return command would return a single quarter. 3.6. Efficiency. Your program must be able to complete 50 commands in less than 30 seconds, not counting the time a user takes to enter the commands. This is an extraordinarily generous time budget, as a typical solution will take at most 0.01 seconds to complete 50 commands. It is almost certain that you will not need to pay attention to the speed of any operation in your program. However, if you perform tens of millions of unnecessary calculations in the command loop, or do something else unusual that makes your program slow to respond to commands, then the autograder will run out of time in testing your program. In this case you will not receive credit.

Solutions

Expert Solution

ANSWER :

PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU

vending.py

inventory = []
max_price = 0
with open('vending.txt', 'r') as file:
    my_reader = file.readlines()
    for line in my_reader:
        row = line.strip('\n').strip(' ').split(',')
        stock = int(row[0])
        price = float(row[1])/100
        name = row[2]
        if(price > max_price):
            max_price = price
        inventory.append([stock, price, name])
file.close()


def return_money(credit):
    while(credit >= 0.25):
        print("RETURN: quarter")
        credit = credit - 0.25
    while(credit < 0.25 and credit >= 0.10):
        print("RETURN: nickel")
        credit = credit - 0.10
    while(credit < 0.10 and credit >= 0.05):
        print("RETURN: dime")
        credit = credit - 0.05
    return credit


def add_credit(credit, user_input):
    if user_input == 'quarter':
        credit = credit + 0.25
    elif user_input == 'nickel':
        credit = credit + 0.10
    elif user_input == 'dime':
        credit = credit + 0.05
    return credit


credit = 0
user_input = ''
while(True):
    print('CREDIT: %.2f' % credit)
    user_input = input('>')
    if(user_input == 'exit'):
        break

    elif(user_input == 'inventory'):
        for idx, items in enumerate(inventory):
            print(idx, " ", items[2], " $", items[1],
                  " (%d" % items[0], "available)")

    elif(user_input == 'quarter' or user_input == 'dime' or user_input == 'nickel'):
        if credit > max_price:
            print("RETURN: ", user_input)
        else:
            credit = add_credit(credit, user_input)

    elif(user_input == 'return'):
        credit = return_money(credit)

    elif(user_input.startswith('restock')):
        item = int(user_input.split(' ')[1])
        stock_update = int(user_input.split(' ')[2])
        inventory[item][0] += stock_update

    elif(user_input >= '0' and user_input <= '5'):
        item = int(user_input)
        if inventory[item][1] > credit:
            print("MSG: Insufficient credit")
            continue
        elif inventory[item][0] == 0:
            print("MSG: out of stock")
            continue
        print("VEND: ", inventory[item][2])
        credit = return_money(credit - inventory[item][1])
        inventory[item][0] -= 1

( PLEASE VOTE FOR THIS ANSWER )

I THINK IT WILL BE USEFULL TO YOU ......

PLZZZZ COMMENT IF YOU HAVE ANY PROBLEM .........

THANK YOU .......


Related Solutions

Program must be in Python Write a program in Python whose inputs are three integers, and...
Program must be in Python Write a program in Python whose inputs are three integers, and whose output is the smallest of the three values. Input is 7 15 3
For Python: In this assignment you are asked to write a Python program to determine the...
For Python: In this assignment you are asked to write a Python program to determine the Academic Standing of a studentbased on their CGPA. The program should do the following: Prompt the user to enter his name. Prompt the user to enter his major. Prompt the user to enter grades for 3 subjects (A, B, C, D, F). Calculate the CGPA of the student. To calculate CGPA use the formula: CGPA = (quality points * credit hours) / credit hours...
Write a program IN PYTHON of the JUPYTER NOOTBOOK Write a Python program that gets a...
Write a program IN PYTHON of the JUPYTER NOOTBOOK Write a Python program that gets a numeric grade (on a scale of 0-100) from the user and convert it to a letter grade based on the following table. A: 90% - 100% B 80% - 89% C 70% - 79% D 60% - 69% F <60% The program should be written so that if the user entered either a non-numeric input or a numeric input out of the 0-100 range,...
A document that describes policies to control how computer resources are used is an example of:
A document that describes policies to control how computer resources are used is an example of:
You have been instructed to use C++ to develop, test, document, and submit a simple program...
You have been instructed to use C++ to develop, test, document, and submit a simple program with the following specifications. The program maintains a short data base of DVDs for rent with their name, daily rental charge, genre, and a a short description . The program will welcomes the user, user will enter the name of the movie from a displayed list of all movies that are available, the user will enter the number next to the movie's name, number...
Need this program in python. The data must be taken from user as input. Write a...
Need this program in python. The data must be taken from user as input. Write a program that prompts the user to select either Miles-to-Kilometers or Kilometers-to-Miles, then asks the user to enter the distance they wish to convert. The conversion formula is: Miles = Kilometers X 0.6214 Kilometers = Miles / 0.6214 Write two functions that each accept a distance as an argument, one that converts from Miles-to-Kilometers and another that converts from Kilometers-to-Miles The conversion MUST be done...
Using JavaScript You must submit a file, called indentation.js indentation.js: program to indent The following program...
Using JavaScript You must submit a file, called indentation.js indentation.js: program to indent The following program is difficult to follow because of its indentation: print ( "binary"); var n = Math.pow (2, 31) - 1; var bits = 0; while (n> 0) { bits + = n & 1; n >> = 1; } print ("Number of bits at 1:" + bits); for (var i = 1; i <= bits; i ++) { var str = ""; if (i% 3...
The code that creates this program using Python: Your program must include: You will generate a...
The code that creates this program using Python: Your program must include: You will generate a random number between 1 and 100 You will repeatedly ask the user to guess a number between 1 and 100 until they guess the random number. When their guess is too high – let them know When their guess is too low – let them know If they use more than 5 guesses, tell them they lose, you only get 5 guesses. And stop...
Python This week you will write a program in Python that mimics an online shopping cart...
Python This week you will write a program in Python that mimics an online shopping cart . You will use all the programming techniques we have learned thus far this semester, including if statements, loops, lists and functions. It should include all of the following: The basics - Add items to a cart until the user says "done" and then print out a list of items in the cart and a total price. - Ensure the user types in numbers...
Write a program in python to calculate the amount each person must pay toward the bill...
Write a program in python to calculate the amount each person must pay toward the bill and toward the tip, for a group of friends who are eating out together. Since you are all friends, it is okay to split the costs evenly. Your program should take as input: The restaurant bill (without tax or tip) as a floating point number The sales tax rate as a floating point number (for example: an 8% tax rate would be 0.08) The...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT