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)
...
Related
I have a list which looks like this: [1 H 1.0079, 2 He 4.0026, 3 Li 6.941, 4 Be 9.01218, ...]
I want to ask the user of the program for the corresponding atomic number to the atom. So the program will take a random atomic symbol and ask the user what's the atoms atomic number.
Code so far:
class Atom:
def __init__(self, number, weight, atom):
self.number = nummer
self.atom = atom
self.weight = weight
def __str__(self):
return self.atom + " " + str(self.weight)
def __repr__(self):
return str(self.number) + " " + self.atom + " " + str(self.weight)
def atom_listan():
atom_file = open('atomer2.txt', 'r')
atom_lista = []
number = 1
for line in atom_fil:
data = line
weight = float(data.split()[1])
atom = data.split()[0]
new_atom1 = Atom(number, weight, atom)
atom_lista.append(new_atom1)
atom_lista.sort(key=lambda x: x.vikt)
atom_lista[17], atom_lista[18] = atom_lista[18], atom_lista[17]
atom_lista[26], atom_lista[27] = atom_lista[27], atom_lista[26]
atom_lista[51], atom_lista[52] = atom_lista[52], atom_lista[51]
atom_lista[89], atom_lista[90] = atom_lista[90], atom_lista[89]
atom_lista[91], atom_lista[92] = atom_lista[92], atom_lista[91]
atom_fil.close()
for i in range(len(atom_lista)):
atom_lista[i].number = i + 1
return atom_lista
Code so far where I create a list consisting of the elements information. I have tried using the random.choice module but I don't really know how to get only the atomic symbol from the list with random.choice and also have the corresponding atomic number to the random atom be the correct answer.
You can get the atomic symbol like this if you have the list of elements as you mentioned in the question.
import random
a=["1 H 1.0079", "2 He 4.0026", "3 Li 6.941", "4 Be 9.01218"]
random_choice = random.choice(a)
random_atom = random_choice.split(" ")[1]
print(random_atom)
Try this. Clearly you could put it into a loop. I just used a part of your List.
import random
elements = ['1 H 1.0079', '2 He 4.0026', '3 Li 6.941', '4 Be 9.01218']
choose = random.choice(elements)
splitted = choose.split(' ')
print('The element symbol is : ', splitted[1])
attempt = input('Enter the Atomic Number ')
if (attempt == splitted[0]):
print('Correct')
else:
print('Wrong')
Encoutering "Terminated due to timeout" Error for Hackerrank Hash Table: Ransom Note for 6 out of 21 test cases
Implemented open address hashing. The size of input strings is up to 30,000 strings: Have experimented with changing the hash table size from 60,000 to 300,000 to no success.
CAPACITY = 300000
hashTable = [None] * CAPACITY
def checkMagazine(magazine, note):
# Store Magazine into hashtable
for element in magazine:
# print("STORED " + element)
position = calculateHash(element)
# print(position)
if hashTable[position] == None:
hashTable[position] = element
# print("Stored into " + str(position))
else:
i = 1
# print("collided into " + str((position) % CAPACITY))
while hashTable[(position + i) % CAPACITY] != None:
# print("collided into " + str((position + i) % CAPACITY))
i += 1
hashTable[(position + i) % CAPACITY] = element
# Check if all items in note is in hashtable
included = True
for item in note:
position = calculateHash(item)
if hashTable[position] != item:
i = 1
while hashTable[(position + i ) % CAPACITY] != item:
if hashTable[(position + i ) % CAPACITY] == None:
included = False
print("No")
return
else:
i += 1
hashTable[(position + i ) % CAPACITY] = "DONED"
else:
hashTable[position] = "DONED"
# print("Found " + item)
print("Yes")
def calculateHash(string):
return hash(string) % CAPACITY
Given that hash table is the optimal way to solve this problem (time complexity O(n)), is the reason why the timeout is happening is because of open address hashing? Or is there another reason?
I think the issue relates to your implementation. Have a look at what happens to your code if you pass a large "magazine" input like ["a", "a", "a", .... "a"].
Should have tried something like this:
magazine = 'two times three is not four'
note = 'two times two is four'
if set(magazine.split()) & set(note.split()) == set(note.split()) :
print 'yes'
else :
print 'no'
you may save some time by precalculating set(note.split()), but I doubt it's very large.
if you care about the number of words, you may use Counter:
from collections import Counter
and then check for every word in the note the counter is smaller than the counter for the same word in magazine.
I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.
I have to create a program that asks user to input the number of items to purchase. the program then asks the user to enter the item and price of each, give a total and provide the amount of change.
I am stuck on the part where I need to combine the lists and output the item and cost in currency format
#Checkout program
print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int (raw_input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = float(raw_input ("What is the cost of %s ?" % groceryitem))
costs.append(itemcost)
order = {}
for index in range (min(len(grocerylist), len(costs))):
order[grocerylist[index]] = costs[index]
print ("This is your purchase") + str(order)
# the simple way
for index in range (min(len(grocerylist), len(costs))):
print("Item: %s Cost: $%5.2f " % (grocerylist[index], costs[index]))
or you can use the locale currency() function.. see Currency formatting in Python or https://docs.python.org/2/library/locale.html
In addition to the above approaches, you can also iterate over order.keys(). And to format use the in-built string methods. Here's an example.
>>> order = {1 : 10.23, 2 : 1.0, 3 : 3.99}
>>> for key, val in order.items():
... print "Item " + key + ": ", "$" + "{0:.2f}".format(val)
...
Item 1: $10.23
Item 2: $1.00
Item 3: $3.99
you can directly store it in dictionary:
#Checkout program
print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int(raw_input ())
order = {}
for i in range(number):
groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
itemcost = float(raw_input("What is the cost of %s ?" % groceryitem))
order[groceryitem] = itemcost
print("your Purchase")
for x,y in order.items():
print (str(x), "$"+str(y))
note: order.values() will give you price list
order.keys() will give you item list
Read about dictionary here :Dictionary
demo:
>>> order = {'cake':100.00,'Coke':15.00}
>>> for x,y in order.items():
... print(x,"$"+str(y))
...
cake $100.0
Coke $15.0
better using format:
>>> for x,y in enumerate(order.items()):
... print("Item {}: {:<10} Cost ${:.2f}".format(x+1,y[0],y[1]))
...
Item 1: cake Cost $100.00
Item 2: Coke Cost $15.00
Make it tabular:
print("{:<5}{:<10}{}".format("Num","Item","Cost"))
for x,y in enumerate(order.items()):
print("{:<5}{:<10}${:.2f}".format(x+1,y[0],y[1]))
print("{:>10}{:>6}{:.2f}".format("Total","$",sum(order.values())))
Num Item Cost
1 cake $100.00
2 Coke $15.00
Total $115.00
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