The problem set I am trying to solve: CS50P 2022 psets/3/grocery/
My code:
def main():
lst = []
try:
while True:
lst.append(input().upper())
except EOFError:
pass
lst.sort()
grocery = [[lst[0], 1]]
for item in lst[1:]:
if item.upper() != grocery[-1][0]:
grocery.append([item.upper(), 1])
else:
grocery[-1][1] += 1
for item in grocery:
print(f'{item[1]} {item[0]}')
return
main()
The Check50 results:
:) grocery.py exists
:( input of EOF halts program
Cause
expected exit code 0, not 1
Log
running python3 grocery.py...
sending EOF...
checking that program exited with status 0...
:| input of "apple" and "banana" yields "1 APPLE 1 BANANA"
Cause
can't check until a frown turns upside down
:| input of "strawberry" and "strawberry" yields "2 STRAWBERRY"
Cause
can't check until a frown turns upside down
:| input of "mango", "sugar", and "mango" yields "2 MANGO 1 SUGAR"
Cause
can't check until a frown turns upside down
:| input of "tortilla" and "sweet potato" yields "1 SWEET POTATO 1 TORTILLA"
The issue seems to lie here:
:( input of EOF halts program
Cause
expected exit code 0, not 1
I have tried different ways of coding this problem, and although in testing I always get the right output, I always fail this Check50 test.
I am having trouble understanding how to make this work. Please help.
Here:
def main():
lst = []
try:
while True:
lst.append(input().upper())
except EOFError:
pass
If the input consists of just an EOF (no other input), your code simply passes on the EOFError
and lst
will still be the empty list []
. So, the code will fail on [lst[0]
and exit with an error code here:
lst.sort()
grocery = [[lst[0], 1]]
Instead of just passing, you probably want to return or exit in case lst
is still the empty list. Add a simple if to the except
section, like this:
def main():
lst = []
try:
while True:
lst.append(input().upper())
except EOFError:
if lst == []:
exit()
else:
pass