Below is the code to compute the bill for the supermarket. Everything is ok but the issue is that I am told that this solution would not work if the input is only apple.
I do believe that the value of apple should be 0 since apples are not in the stock but still I believe there is something that I am not doing correct. Please help.
groceries = ["apple","banana", "orange",]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(food):
total = 0
for item in food:
tot = prices[item] * stock[item]
print item, tot
total += tot
return total
computeBill(groceries)
I am just going to go off on my own with this answer and make suggestions, since it seems the specifications for your computeBill functionality are not well defined.
If the items are not in stock, and your instructor says it is not acceptable to return 0 in this case, then your other options are to raise an exception, or a sentinel value indicating an error state.
def computeBill(food):
total = 0
for item in food:
stock_count = stock[item]
if stock_count == 0:
raise ValueError("item %s is out of stock" % item)
tot = prices[item] * stock_count
print item, tot
total += tot
return total
Or if you don't want to raise an exception, you could return -1 if you feel that is not a valid total anyways:
if stock_count == 0:
return -1
There are some other problems with the function in how it calculates the list vs stock, but you said you didn't care about those right now.
I don't know why this wouldn't work. If your input was ['apple'], this would happen:
computeBill(['apple'])
total = 0
item = 'apple'
tot = price['apple'] * stock['apple']
tot = 2 * 0
print 'apple',0
total += 0
return total
return 0
Unless they expect to be able to pass in a single item without wrapping it in a list, so calling `computeBill('apple'). In that case, you'd have to do a type check at the beginning of your function. That could look like this
if type(food) is not list:
food = [food]
def compute_bill(food):
total=0
for item in food:
if stock[item]>0:
tot=prices[item]
total+=tot
stock[item]-=1
return total
Related
I'm trying to solve Coin change problem with minimum number of coins
using backtracking method.
I've actually done with it, but I want to add some option that print the number of coins by its unit not only total amount.
this is my python codes below.
def minimum_coins(coin_list, change):
min_coins = change
if change in coin_list:
return 1
else:
for coin in coin_list:
if coin < change:
num_coins = 1 + minimum_coins(coin_list, change - coin)
if num_coins < min_coins:
min_coins = num_coins
return min_coins
coin_list = []
unit = input("Enter the Coin Unit\n")
#1 10 15 20
change = int(input("Enter the Total Change\n"))
#73
unit = unit.split()
for i in unit:
coin_list.append(int(i))
min = minimum_coins(coin_list, change)
#print("You need 3 1's, 1 10's, 0 15's, 3 20's") <- I want to implement this option.
print("Total number of coins required is %s." % min) #7
I'm struggling to implement this in my code.
cause back-tracking is complex, I can't get the idea how to check the number of coins by its unit.
Possible way:
def minimum_coins(coin_list, change):
min_coins = change
if change in coin_list:
return 1, [change]
else:
cl = []
for coin in coin_list:
if coin < change:
mt, t = minimum_coins(coin_list, change - coin)
num_coins = 1 + mt
if num_coins < min_coins:
min_coins = num_coins
cl = t + [coin]
return min_coins, cl
change = 73
coin_list = [1, 10, 15, 20]
min, c = minimum_coins(coin_list, change)
#print("You need 3 1's, 1 10's, 0 15's, 3 20's") <- I want to implement this option.
print("Total number of coins required is %s." % min, c) #7
>>>Total number of coins required is 7. [20, 20, 20, 10, 1, 1, 1]
# create dictionary from list of notes
#i am newbie in python
#the code is not mine, i just found it on the net
notes = [ 200, 100, 50, 20, 10, 5, 1]
notesCount = {}
x=122
for note in notes:
if x >= note:
notesCount[note] = x//note
x=x%note
print(notesCount)
values = notesCount.values()
print(values)
total = sum(values)
print(total)
give_back = 122
return_bills = []
bill_stock = [
{ "bill_type":200, "instock":1 },
{ "bill_type":100, "instock":1 },
{ "bill_type":50, "instock":1 },
{ "bill_type":20, "instock":1 },
{ "bill_type":10, "instock":1 },
{ "bill_type":5, "instock":1 },
{ "bill_type":1, "instock":1 },
]
for item in bill_stock:
# return when give back is 0
if give_back == 0: break
# get maximum amount to give back on the highest bill type
qty = give_back // item["bill_type"]
qty = min(qty, item["instock"])
if qty > 0:
give_back -= (item["bill_type"] * qty)
return_bills.append({
"bill_type": item["bill_type"],
"qty": qty
})
# display what to give back
for item in return_bills:
quantity = item["qty"]
bill_type = item["bill_type"]
print(f"{quantity}X ---- {bill_type}")
# output:
# > py .\calc.py
# 1X ---- 100
# 1X ---- 20
# 1X ---- 1
I created a dictionary and want to create a function called count_type that will take that dictionary and return another dictionary that is called count. This function takes in a menu (dictionary) and returns a count (dictionary) that maps each item type to the count of how many items of that type exist in the menu.
The new dictionary starts looking like:
count = {"Entrees": 0, "Salads": 0, "Sides": 0,
"Kid's Meals": 0, "Desserts": 0, "Drinks": 0}
I want the end result to be the same dictionary but the 0's to be changed to the count of how many times there is a key:value with the value 'Entrees' etc in the original dictionary. an example of what I would like the output to look like:
count = {"Entrees": 3, "Salads": 15, "Sides": 3,
"Kid's Meals": 6, "Desserts": 4, "Drinks": 5}
So far I have the code:
def count_type(carte):
count = {"Entrees": 0, "Salads": 0, "Sides": 0,
"Kid's Meals": 0, "Desserts": 0, "Drinks": 0}
menu = read_file("menu1.csv")
ent = 0
salad = 0
side = 0
kid = 0
dessert = 0
drink = 0
for value in menu:
if value == 'Entrees':
ent += 1
elif value =='Salads':
salad += 1
elif value =='Sides':
side +=1
elif value== "Kid's Meals":
kid +=1
elif value =='Desserts':
dessert +=1
else:
drink +=1
This loop only gives me a count for drink of 46 which is all the values. How do I do this?
The read_file function that I have created already is:
def read_file(filename):
file = open("menu1.csv", "r", encoding='utf-8-sig')
file.readline()
menu = {}
for line in file:
line = line.rstrip('\n')
line = line.split(',')
item = line[0]
price = float(line[1])
cal = int(line[2])
typ = str(line[3])
lst= (price, cal, typ)
tup = tuple(lst)
menu[item] = tup
return menu
print(menu) returns a long dictionary:
{'Chic-fil-A Chicken Sandwich': (3.75, 440, 'Entrees'),
'Chic-fil-A Deluxe Sandwich': (4.45, 500, 'Entrees'),
'Spicy Chicken Sandwich': (3.99, 460, 'Entrees'),
'Spicy Deluxe Sandwich': (4.69, 550, 'Entrees'),
'Grilled Chicken Sandwich': (5.15, 320, 'Entrees'),
'Grilled Chicken Club': (6.55, 460, 'Entrees')
Where some are 'Entrees', 'Salads', etc.
I recommend you try: count[value] += 1 in for value in menu loop
Update: you should edit your loop
for k,v in menu.items():
count[v[2]] += 1
Your code doesn't work because you're iterating over the keys of your menu dictionary, which is the names of the items (e.g. 'Spicy Chicken Sandwich'), but you're expecting to have an item type (e.g. "Entrees").
To fix this you need to change your loop. I'd suggest:
for _, _, value in menu.values():
if value == 'Entrees':
...
I'd note that the name value is not very clear what kind of value it is, especially when you're getting a bunch of other data from the dictionary (and throwing them into the _ variable that will be ignored). Unpacking into more clearly named variables, like price, cal, typ again, might make the code clearer.
It might also be a good idea to match 'Drinks' explicitly, rather than letting any invalid types fall in there. You could have your code raise an exception if it gets an unknown type instead:
elif value == 'Drinks':
drinks += 1
else:
raise ValueError("Unknown menu item type: {}".format(typ))
In your for loop
for value in menu:
instead of checking against value, check against the following
for value in menu:
count[menu[value][2]] += 1
and as mentioned above, instead of creating seperate counters for each variables, you can make use of the already created count dictionary by using
count["Entrees"] += 1
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I'm a novice at writing python, and I'm trying to create a dynamic selection of options to the user, ask them what option they want, and then perform a function based upon what they choose.
My "game" is recreating the scene from Die Hard where they have to get 4 gallons into a 5 gallon jug.
The user starts with two bottles that have nothing in them, and water available. Because they are starting out, they should only have two options:
[1] Fill bottle A
[2] Fill bottle B
Select Option:
Assuming the code was right, and chose option 1 and filled bottle A, the next options they have are now:
[1] pour bottle A into bottle B
[2] Fill bottle B
[3] Empty bottle A
Select Option:
Here is my (probably horrible) code thus far:
class Bottles(object):
amount = 0
def __init__(self,name,capacity,amount):
self.name = name
self.capacity = capacity
self.amount = amount
def AddWater(self,increase):
if (self.amount + increase) > self.capacity:
self.amount = self.capacity
print("Overflow! {0}'s at max capacity ({1} gallons)").format(self.name,self.capacity)
else:
self.amount = self.amount + increase
def RemWater(self,decrease):
if (self.amount - decrease) < 0:
self.amount = 0
print("Empty! {0} is now empty!").format(self.name)
else:
self.amount = self.amount - decrease
def ShowOptions():
available_options = []
option_value = 1
print("Bottle A Amount: {0}").format(bottle_a.amount)
print("Bottle B Amount: {0}").format(bottle_b.amount)
print("Your options are as follows:")
if bottle_a.amount != bottle_a.capacity:
print("[{0}] Fill bottle A").format(option_value)
available_options.append(str(option_value))
option_value += 1
if bottle_b.amount != bottle_b.capacity:
print("[{0}] Fill bottle B").format(option_value)
available_options.append(str(option_value))
option_value += 1
if bottle_a.amount != bottle_a.capacity and bottle_b.amount > 0:
print("[{0}] Pour water in Bottle B into Bottle A").format(option_value)
option_value += 1
if bottle_b.amount != bottle_b.capacity and bottle_a.amount != 0:
print("[{0}] Pour water in Bottle A into Bottle B").format(option_value)
option_value += 1
if bottle_a.amount == 4 or bottle_b.amount == 4:
print("{0}] Defuse bomb.").format(option_value)
option_value += 1
bottle_a = Bottles("Bottle A",5,3) # 5 gallon bottle
bottle_b = Bottles("Bottle B",3,0) # 3 gallon bottle
ShowOptions()
What I'm having a hard time grasping is how to both ask for their selection, and then run that function without adding a whole bunch of extra option checking each time.
You could construct a list of pairs where first item is the text to display and second item is a function to execute if option is selected. Then you would have to code the functionality to decide the options only once and executing selected option would be trivial.
Here's an example on how the game could look with above approach:
class Bottle(object):
def __init__(self,name,capacity,amount):
self.name = name
self.capacity = capacity
self.amount = amount
def fill(self):
self.amount = self.capacity
def empty(self):
self.amount = 0
def fill_from(self, bottle):
amount = min(self.capacity - self.amount, bottle.amount)
self.amount += amount
bottle.amount -= amount
# Add all the possible options for given bottle to the list
def add_bottle_options(options, bottle, other):
# Fill
if bottle.amount != bottle.capacity:
options.append(('Fill {}'.format(bottle.name), lambda: bottle.fill()))
# Empty
if bottle.amount:
options.append(('Empty {}'.format(bottle.name), lambda: bottle.empty()))
# Pour to
if bottle.amount != bottle.capacity and other.amount:
text = 'Pour water in {} into {}'.format(other.name, bottle.name)
options.append((text, lambda: bottle.fill_from(other)))
bottle_a = Bottle("Bottle A", 5, 0) # 5 gallon bottle
bottle_b = Bottle("Bottle B", 3, 0) # 3 gallon bottle
ticking = True
def defuse():
global ticking
ticking = False
while ticking:
print('Bottle A Amount: {}, capacity: {}'.format(bottle_a.amount,
bottle_a.capacity))
print('Bottle B Amount: {}, capacity: {}'.format(bottle_b.amount,
bottle_b.capacity))
print("Your options are as follows:")
# List of option text, function to execute tuples
available_options = []
add_bottle_options(available_options, bottle_a, bottle_b)
add_bottle_options(available_options, bottle_b, bottle_a)
if bottle_a.amount == 4 or bottle_b.amount == 4:
available_options.append(('Defuse bomb', defuse))
# Enumerate will return (number, item) tuples where the number starts
# from second parameter. Since items are (name, function)
# tuples themselves enumerate returns (number, (name, function))
# tuples which we need to unpack so that we can use number and name
# for printing. (s, _) does nested unpacking so that name goes to
# variable s and function to _ which is a common name for throwaway data.
for i, (s, _) in enumerate(available_options, 1):
print('[{}] {}'.format(i, s))
try:
# Ask user choice, convert it to int, subtract 1 since displayed
# options use 1-based indexing and execute the selected option
choice = input('Select option: ')
available_options[int(choice) - 1][1]()
except:
print('Invalid option')
print('Congrats, you defused bomb')
So I am given a menu and the food rating, i have to create a data structure, then make a getInfo function, and findCheapest function.
getInfo(item) takes 1 item and prints outs its price and ratings.
findCheapest(item1, item2) takes in 2 items, checks if items are in menu and gives the cheapest. I have written this far here is where i am struggling.
how to make all the input case insensitive for both functions, but still return correctly formatted words. Eg:
getInfo("tEa") should return:
Tea- price: 7. Rating: 4
I get you could do string compare and convert it to lowercase but you can't do that in a set cause then it will print wrong and how do you do it and still compare each value properly.
The second part i am struggling at is for the findCheapest function how make it so that it can take an arbitrary number of values and still print the cheapest without changing the data structure too much.
So i implemented a formatText(item) function that converts to the correct format.
Here is the code:
menu= {"Tea", "Coffee", "Cookie", "Chips"}
price={
"Tea": 7,
"Coffee": 5,
"Cookie": 2,
"Chips": 3
}
rating= {
"Tea": 4,
"Coffee": 4.5,
"Cookie":5,
"Chips": 2
}
def getInfo(item):
if item in menu:
print item + "- price: %s." % price[item] + " Ratings %s" %rating[item]
else:
print "This item was not found: " + item
def findCheapest (item1,item2):
if item1 in menue and item2 in menue:
if (price[item1] < price[item2]):
print item2+ " is the cheapest"
elif (price[item1] > price[item2]):
print item1 +" is the cheapest"
else:
print "An item was not found."
getInfo("tEa")
getInfo("coFfeE")
findCheapest("tEa", "coFfeE")
Use either #Aswin Murugesh solution to make everything uppercase or lowercase
Or
wrt your current setup, you can use capitalize()
Or
construct following string (1st char upper using upper()+rest char lower using lower()) to make the 1st char capital.
getInfo("tEa".capitalize())
getInfo("coFfeE".capitalize())
findCheapest("tEa".capitalize(), "coFfeE".capitalize())
Apply it to the input values or as the 1st step in your method
my_menu= ["Tea", "Coffee", "Cookie", "Chips"]
price={
"Tea": 7,
"Coffee": 5,
"Cookie": 2,
"Chips": 3
}
rating= {
"Tea": 4,
"Coffee": 4.5,
"Cookie":5,
"Chips": 2
}
def isItemInMenue(item="", menu=[]):
for x in menu:
if x.lower() == item.lower():
return x
return ""
def getInfo(item):
item_ = isItemInMenue(item, my_menu)
if item_:
print item_ + " - price: %s." % price[item_], "Ratings %s" % rating[item_]
else:
print "This item was not found: " + item_
def findCheapest (item1, item2):
item1_ = isItemInMenue(item1, my_menu)
item2_ = isItemInMenue(item2, my_menu)
if item1_ and item2_:
if (price[item1_] price[item2_]):
print item1_ + " is the cheapest"
else:
print "An item was not found."
getInfo("tEa")
getInfo("coFfeE")
findCheapest("tEa", "coFfeE")
Irrespective of the user input, use capitalize function. and get the price and rating. Capitalize returns with just the first letter of each word in capital, all others lower
list_of_items = [x.capitalize() for x in raw_input.split()]
find_cheapest(list_of_items)
def find_cheapest(list_of_items):
cheapest_price = 12345
cheapest_item = ""
for item in list_of_items:
# Get the price of the item and check with the least price
item_price = price.get(item,None)
if item_price and item_price < cheapest_price:
cheapest_price = item_price
cheapest_item = item
if cheapest_item:
return cheapest_item + "is the cheapest"
else:
return "No Items were found"
Code looks pretty good so far. One easy fix is to use the upper and lower functions to properly format your items before doing the logic.
def format_item(someItem):
return " ".join(x[0].upper() + x[1:].lower() for x in someItem.split())
print format_item("tEA") #Tea
Then you can just call format item before the rest of your logic. For example.
def findCheapest (item1,item2):
item1 = format_item(item1)
item2 = format_item(item2)
...