I am trying to do the "Grocery" problem, and I have many issues.
First, the program exits after the first input.
Second, I have an issue with associating the counted item with the list.
My code is as follows:
x = input("give me the list: ").capitalize()
#gets input from user
while True:
try:
z = [""]
y = 1
if x in z:
y += y
z.append(x)
z.sort()
#if the user input already is in the list, then the count of the item (y) should increase by one,
#and the input is added to the list
else:
y = 1
z.append(x)
z.sort()
#Otherwise the list increase and the count remain of one
except EOFError:
for i in z:
print(y, i)
#I do not know how I can print the associated item counted
break
Following the advice given, I have the following code:
def main():
while True:
try:
x = input("give me the list: ")
except EOFError:
print(groceries_dict).capitalize()
#print the list by using the function below
def updateGroceries(cart,item):
cart = [""]
cart.append(item)
return cart
def DicGroceries(cart):
cart.count()
groceries_dict = {i:cart.count(i) for i in cart}
return groceries_dict
if __name__ == "__main__":
main()
I know that it is still not working. My main issue is making the functions communicate with each other.
I do not understand why python is telling me that "groceries_dict" is not defined.
With this proposal, I know that I am completely disrespecting all the advice in the answer, but trying to setup functions still make me crazy. Naturally I see the point of breaking down a program in small unit, but functions really break my head. Calling them make me crazy.
I did respect however the point that a dictionary was needed, but I wonder why I could not rather use a list.
Anyway, the result is still wrong...but it is "something":
cart = {}
while True:
try:
x = input("give me the list: ").lower()
if x in cart:
cart[x] += 1
else:
cart[x] = 1
except EOFError:
for key in cart.keys():
print(cart[key])
This counting is inspired by the piece of code shared in the answer. But this frustrates me because I do not understand why this happens in this way. I get that we are telling the dictionary to have keys representing a count. But why would it ever happen in that way? What in the dictionary as a python object makes it happen in this way? I mean when I see this dictionary description, I do not see or understand anything that would make the dictionary "behave" that way. Why is it doing this? Why?
Again I understand the principle of:
cart[x] += 1
but why is this happening for the dictionary?
What I also understand is that dictionary is not allowing any duplicates. OK. Good. But I still cannot understand full.