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
Related
I'm new to python, I have this knapsack problem where there are items and their weight. The user will insert their priority (low-medium-high). And then the GA will then run to find the best backpacking list that maximizes the priority points without exceeding the maximum weight (30kg).
I did most of the genetic operators, except the termination condition (after 20000 generations or when the fitness reaches 1) did not work,and the graph (plot) of the GA's performance is not showing.
The code:
import matplotlib.pyplot as plt
import random
import time
from unittest import result
# Data (search space)
items = {
'Sleeping bag': 10,
'Rope': 3,
'Pocket Knife': 2,
'Torch': 5,
'Water Bottle': 9,
'Glucose': 8,
'First aid supplies': 6,
'Rain jacket': 3,
'Personal Locator Beacon': 2
}
Genome = list[int]
# Number of items
ITEMS_COUNT = len(items)
# # Number of points for the multi point crossover entered by the user. Default is 3
N_POINT = 3
# # Number of individulas in the population filled with some permutation of 0s and 1s entered by the user. Default is 50
POP_SIZE = 20
# # Elitisim for selection. Default is True
ELITISM = True
# # Number of generations entered by the user. Default is 200
GENERATIONS = 200
# # Crossover probability enterd by the user. Default is 0.1
CROSSOVER_PROBABILTY = 0.1
# # Mutate probability entered by the user. Defaulst is 0.05
MUTATION_PROBABITLY = 0.05
# Priorities
itemsPriorities = {'low': 5, 'medium': 10, 'high': 15}
# User input
def user_input():
print('Welcome to Smart Hiker Backpacking!')
print('Input your priority for items based on the priority legend: ')
print('Low \t Medium \t High')
print()
print('Choose your priority for these items below: ')
print('-'*50) # design: ------
for item, _ in items.items(): # Print items
print(item)
print('-'*50) # design: ------
prio_l = []
# Ask user to enter a priority for every item
# Goes through and displays every item in the data (search space)
for item in items:
prio_input = str(input(f"What is your priority for {item}? "))
while prio_input.lower() not in itemsPriorities.keys(): # convert entered data by the user to lower case
# Asks the user again to enter a correct choice (low, medium, high), regardless of the capitalization
prio_input = str(input('Please enter low, medium or high: '))
else:
prio_l.append(itemsPriorities[prio_input.lower()])
return prio_l
priority_list = user_input()
# Print the item name and its entered priority
print('-'*50) # design: ------
for i, j in enumerate(items):
print(j, 'has a priority of: ', priority_list[i])
# Assume the population size is 20
pop_size = 20
# generate initial population
def create_initial_population(amount):
#global pop_size
return [generate_genome() for i in range(0, amount)]
# generate genome
def generate_genome():
return [random.randint(0, 1) for x in range(0, len(items))]
print('-'*50) # design: ------
#print("Population:\n", create_initial_population(POP_SIZE))
# Compute fitness function
def compute_fitness(target):
total_points = 0
total_weight = 0
index = 0
# Sum of priority points and weight
for i in target:
if index >= len(items):
break
if (i == 1):
total_points += priority_list[index]
total_weight += list(items.values())[index]
index += 1
# Cheking to fit
if total_weight > 30:
return 0
else:
return total_points
def get_total_points(pop):
total_points = 0
for target in pop:
total_points += compute_fitness(target)
return total_points
# mutating a point on a solution
def mutate(target):
r = random.randint(0, len(target)-1)
if target[r] == 1:
target[r] = 0
else:
target[r] = 1
# selecting parents by using roulette wheel selection
def roulette_wheel_selection(pop, parent_number):
parents = []
total_points = get_total_points(pop)
current_value = 0
# spining the wheel and select parent based on rate of value and total_points
for spin in range(0, parent_number):
spin_value = random.randint(0, total_points)
for target in pop:
current_value += compute_fitness(target)
if current_value >= spin_value:
# print "SPIN!!! ,%s, TOTAL VALUE / SPIN VALUE : %s/%s, fit: %s" % (str(target),str(total_points), str(spin_value) , fitness(target))
parents.append(target)
pop.remove(target)
total_points = get_total_points(pop)
break
# print("-------------------------------------------------------------------------")
return parents
# n-point crossover by using two solution to generate their child
def crossover(father, mother):
# deciding the lines to split the solution
genes_points = [0]
genes_points += sorted(random.sample(range(2, ITEMS_COUNT), N_POINT))
genes_points += [ITEMS_COUNT]
child = []
# creating a new child by using father and mother data
for count in range(0, N_POINT+1):
start = genes_points[count]
end = genes_points[count+1]
# chosing which part of father or mother
if count % 2 == 0:
child += father[start:end]
else:
child += mother[start:end]
return child
# generating a new generation by mutation and crossover
def creating_new_generation(pop):
# selection with roulette_wheel_selection
new_generation = []
parents = []
if ELITISM:
parents = pop[int(0): int(POP_SIZE/5)]
else:
parents = roulette_wheel_selection(pop, (POP_SIZE/5))
parents_length = len(parents)
new_generation.extend(parents[:])
# mutating selected parents
for p in parents:
if MUTATION_PROBABITLY > random.random():
mutate(p)
children = []
desired_length = POP_SIZE - parents_length
# creating new children by using parents
while len(children) < desired_length:
# crossover cheking
if CROSSOVER_PROBABILTY > random.random():
# selecting two parents randomly
father_and_mother = random.sample(range(0, parents_length-1), 2)
father = parents[father_and_mother[0]]
mother = parents[father_and_mother[1]]
# crossover selected two parents to create a new child
child = crossover(father[:], mother[:])
else:
# or cloning a parent randomly
child = parents[random.randint(0, parents_length-1)][:]
# checking to mutate the new child
if MUTATION_PROBABITLY > random.random():
mutate(child)
children.append(child[:])
new_generation.extend(children[:])
return new_generation
def genome_to_string(genome) -> str:
return "".join(map(str, genome))
def genome_to_items(genome, ITEMS):
result = []
for i, itm in enumerate(ITEMS):
if genome[i] == 1:
result += [itm]
return result
def main():
#start_time = time.time()
population = create_initial_population(POP_SIZE)
max_fit = 0
for generation in range(1, GENERATIONS+1):
plt.plot(generation, max_fit)
plt.ylabel('Fitness')
plt.xlabel('Generations')
plt.show()
#print("Generation %d with %d" % (generation, len(population)))
population = sorted(
population, key=lambda x: compute_fitness(x), reverse=True)
for i in population:
# print "%s, fit: %s" % (str(i), fitness(i))
if compute_fitness(i) > max_fit:
max_fit = compute_fitness(i)
population = creating_new_generation(population)
# for item in items:
# print(item)
#elapsed_time = time.time() - start_time
#print( "Best: %s (%f)" % (genome_to_string(population[0]), compute_fitness(population[0])))
print(
f"The Best items for the customer backpacking:{(genome_to_items(population[0],items.items()))}")
print("Maximum fitness: " + str(max_fit))
#print ("Time : " + str(elapsed_time) + " seconds")
main()
If I change your main loop to this, it seems to work fine:
def main():
population = create_initial_population(POP_SIZE)
fit = []
for generation in range(GENERATIONS):
#print("Generation %d with %d" % (generation+1, len(population)))
population = sorted(
population, key=lambda x: compute_fitness(x), reverse=True)
# First item in population has best fitness.
fit.append( compute_fitness(population[0] ) )
population = creating_new_generation(population)
print(
f"The Best items for the customer backpacking:{(genome_to_items(population[0],items.items()))}")
print("Maximum fitness: " + str(max(fit)))
plt.plot(fit)
plt.ylabel('Fitness')
plt.xlabel('Generations')
plt.show()
This is a python program that does some sort of simulation,, I am looking for any type of optimization while keeping the same p[i] form, I have tried Pypy and I got an around 3x performance gain over python. Any suggestions are welcomed
import random
from time import perf_counter
infected, non_infected = 1, 99999
infectation_chance, infection_days, death_chance = 1/100, 2/1000, 2/100
population, population_list = infected + non_infected, non_infected * [0] + infected * [1]
place = 10
p = {i: [] for i in range(1,place + 1)}
day = 1
simulation_duration = 3
while 0 < simulation_duration:
print(f"Working on day {day}..")
time1 = perf_counter()
for person in population_list:
p[random.randint(1, place)].append(person)
time2 = perf_counter()
i = 0
while i < place:
tl = []
i += 1
for crowd in p[i]:
if crowd == 0:
if (random.random() < infectation_chance * str(p[i]).count("1")) - (infectation_chance/100 * str(p[i]).count("0")):
tl.append(1)
else:
tl.append(0)
if crowd == 1:
tl.append(1)
p[i] = tl
i = 0
population_list = []
while i < place:
i += 1
population_list.append(p[i])
simulation_duration -= 1
day += 1
print(f"Total time: {perf_counter() - time1} \nInfection time: {perf_counter() - time2} \nPlacing time: {time2-time1}")
print(str(population_list).count("1"), str(population_list).count("0"))
Even tho I received lots of help I still need more optimization.Any type of optimization as far as it doesn't change the results are welcomed.Since this is fully compatible with pypy I am using pypy, I can also use python if it means better performance. Current setup:
import random
import functools
from time import perf_counter
with open("results.txt", "w") as results:
results.seek(0)
results.write("")
results.close()
time1 = perf_counter()
#functools.lru_cache(maxsize=128)
def simulation():
infected, non_infected = 1, 99999999
infectation_chance_c, death_chance, recovery_chance, reinfectation_chance, incubation_time = 1.4, 1 - 0.03, 1 - 0.97, 1 - 1 / 150, 2
death_chance, recovery_chance = death_chance / incubation_time, recovery_chance / incubation_time
population_total, population_list = infected + non_infected, non_infected * [0] + infected * [1]
place = 1
day = 0
simulation_duration = 100000000
with open("results.txt", "a") as results:
print("Starting... \nPlease wait for results, this can take lots of time!")
while infected > 0 and simulation_duration > 0:
population = population_list.count(0) + population_list.count(-1) + population_list.count(1)
healthy = population_list.count(0) + population_list.count(-1)
recovered = population_list.count(-1)
infected = population_list.count(1)
died = population_total - len(population_list)
p = {i: [] for i in range(1,place + 1)}
results.write(f"Day {day}: Infected: {infected} Healthy: {healthy} p-Imune: {recovered} Alive: {population} Died: {died} \n")
print(f"Day {day}: Infected: {infected} Healthy: {healthy} p-Imune: {recovered} Alive: {population} Died: {died}")
for person in population_list:
p[random.randint(1, place)].append(person)
i = 0
while i < place:
i += 1
p_infected = p[i].count(1)
try:
infectation_chance = 1 - float(p_infected) / (float(len(p[i])) / infectation_chance_c)
except:
pass
for j, crowd in enumerate(p[i]):
if crowd == -1:
if random.random() > reinfectation_chance:
p[i][j] = 1
elif random.random() > reinfectation_chance:
p[i][j] = 0
elif crowd:
if random.random() > death_chance:
p[i].pop(j)
elif random.random() > recovery_chance:
if random.random() > 0.4:
p[i][j] = -1
else:
p[i][j] = 0
elif not crowd:
if random.random()>infectation_chance:
p[i][j] = 1
i = 0
population_list = []
while i < place:
i += 1
population_list.extend(p[i])
simulation_duration -= 1
day += 1
print(f"Total time: {perf_counter() - time1}")
simulation()
print(f"Simulation finishsed... \nProcessing time: {perf_counter()-time1}")
here is a corrected version in pure python, commented because there were some bugs. your major time loss was counting infected/non-infected inside the for loop, though the result is always the same. it could be optimized again with numpy if you wanna use a bigger population
import random
from time import perf_counter
infected, non_infected = 1, 99999
infectation_chance, infection_days, death_chance = 1/100, 2/1000, 2/100
population, population_list = infected + non_infected, non_infected * [0] + infected * [1]
place = 10
day = 1
simulation_duration = 3
while 0 < simulation_duration:
# p must be reset here or it will grow indefinitely
p = {i: [] for i in range(1,place + 1)}
print(f"Working on day {day}..")
time1 = perf_counter()
for person in population_list:
p[random.randint(1, place)].append(person)
time2 = perf_counter()
i = 0
while i < place:
i += 1
# if you need to, count infected/non-infected here
# not in your for loop where it has always the same value
# and don't cast to str, what's the point?
# pi_infected = p[i].count(1)
# pi_sane = p[i].count(0)
for j, crowd in enumerate(p[i]):
if crowd == 0:
# your formula was broken (a-b is always true)
# i used a generic one
if random.random()>(1-infectation_chance):
# change your list in place:
# no need for temp list, save lots of cycles
p[i][j] = 1
i = 0
population_list = []
while i < place:
i += 1
# it's extend, not append here or your population list
# will have a length of #place
population_list.extend(p[i])
simulation_duration -= 1
day += 1
print(f"Total time: {perf_counter() - time1} \nInfection time: {perf_counter() - time2} \nPlacing time: {time2-time1}")
print(population_list.count(1), population_list.count(0))
numpy version
import random
import numpy as np
from time import perf_counter
infected, non_infected = 1, 99999
infectation_chance, infection_days, death_chance = 1/100, 2/1000, 2/100
place = 10
population = infected + non_infected
group_size = population//place
population_list=np.zeros((population))
population_list[:infected]=1
day = 1
simulation_duration = 3
while 0 < simulation_duration:
print(f"Working on day {day}..")
time1 = perf_counter()
# shuffle is not recursive so we need to flatten population_list
population_list=population_list.flatten()
np.random.shuffle(population_list)
population_list=population_list.reshape((place, group_size))
time2 = perf_counter()
# we need to rebuild the pure python code with no loops
# first we create randoms for all pop
randoms = np.random.rand(population).reshape((place, group_size))
# list of infected by group: a list of all p[i].count(1)
nb_infected = np.count_nonzero(population_list, axis=1).reshape((place,1))
# compute (1-infectation_chance**p[i].count(1)) for all pop
infection_map=np.full((place, group_size), 1-infectation_chance)**nb_infected
# if randoms>infection_map and population_list==0
new_infected = np.bitwise_and(randoms>infection_map, population_list==0)
# then set to 1 in place
population_list[new_infected] = 1
simulation_duration -= 1
day += 1
print(f"Total time: {perf_counter() - time1} \nInfection time: {perf_counter() - time2} \nPlacing time: {time2-time1}")
total_infected=np.count_nonzero(population_list)
print(total_infected, population-total_infected)
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 want to write a function that calculates the change a machine has to give a customer. The function receives the cost of the product, the sum of money the customer gave and a dictionary that has the money the machine has in it.
The function should give the smallest set of coins and bills and take into account the money available.
It should also avoid running out of any one kind of money; for example, if it has 2 of 10€ and 8 of 5€ it should not use the 2 of 10€ in the same change.
This is my dictionary:
d = {0.01: 10,
0.02: 5,
0.05: 2,
0.1: 10,
0.2: 5,
0.5: 2,
1: 5,
2: 5,
5: 2,
10: 4,
20: 5,
50: 1,
100: 0,
200: 0,
500: 0,
}
and this is my code so far:
def change(cost, given, d):
last_change = 0
change = given - cost #calculates how much we own the customer
if change == 0: #if we don't own the customer anything
return change
else:
if change in d and d[change] != 0: #if change is in the dictionary and its value is not 0 we can give it to the customer
return change
else:
euro = int(change)
cent = change - euro #calculates if we have to give any cents
if cent == 0: #if we only have to give bills
for item in d:
if item > last_change and item < change and d[item] != 0: #biggest bill we can give the customer
last_change = item
I don't know what to do next.
from math import *
dict1 = {0.01: 10,
0.02: 5,
0.05: 2,
0.1: 10,
0.2: 5,
0.5: 2,
1: 5,
2: 5,
5: 2,
10: 4,
20: 5,
50: 1,
100: 0,
200: 0,
500: 0,
}
def change(cost, given, dict1):
last_change = 0
change = given - cost
if change == 0:
print change
else:
if change in dict1 and dict1[change] != 0:
print change
else:
if change >= 500 and dict1[change] != 0:
a = floor( change / 500 )
print a, " --500 's"
change = change - ( a * 500 )
if change >= 200 and dict1[change] != 0:
b = floor( change / 200 )
print b, " --200 's"
change = change - ( b * 200 )
if change >= 100 and dict1[change] != 0:
c = floor( change / 100 )
print c, " --100 's"
change = change - ( c * 100 )
if change >= 50 and dict1[change] != 0:
d = floor( change / 50 )
print d, " --50 's"
change = change - ( d * 50 )
if change >= 20 and dict1[change] != 0:
e = floor( change / 20 )
print e, " --20 's"
change = change - ( e * 20 )
if change >= 10 and dict1[change] != 0:
f = floor( change / 10 )
print f, " --10 's"
change = change - ( f * 20 )
if change >= 5 and dict1[change] != 0:
g = floor( change / 5 )
print g, " --5 's"
change = change - ( g * 5 )
if change >= 2 and dict1[change] != 0:
h = floor( change / 2 )
print h, " --2 's"
change = change - ( h * 2 )
if change >= 1 and dict1[change] != 0:
i = floor( change / 1 )
print i, " --1 's"
change = change - ( i * 1 )
if change >= 0.5 and dict1[change] != 0:
j = floor( change / 0.5 )
print j, " --0.5 's"
change = change - ( j * 0.5 )
if change >= 0.2 and dict1[change] != 0:
k = floor( change / 0.2 )
print k, " --0.2 's"
change = change - ( k * 0.2 )
---------------------------
---------------------------
---------------------------
---------------------------
implement similar steps for 0.1,0.05,0.02,0.01
Output will be like this:
1 - 500 's
2 - 200 's
2 - 100 's
1 - 20 's
Here is some pseudo-code - there are some details you have to fill in:
amount = ... the input amount ...
change = {}
for denomination in [500, 200, 100, 50, ...]:
if amount == 0:
break
n = ... number of coins of this denomination to use
change[denomination] = n # store it
amount = amount - n*denomination # subtract from amount
# the dictionary change contains how to make the change
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