python CS50P参数设置3:为什么我的代码没有通过杂货店问题的check50?

nle07wnf  于 2023-01-19  发布在  Python
关注(0)|答案(3)|浏览(123)

我试图解决的问题集:CS50P 2022 psets/3/grocery/
我写的代码:

# Syntax of dict = {'key': value}
mydict = {}

# Infinite loop with break
while True:
    try:
        item = input().upper()
        # Search if item matches a key inside the dict
        if item in mydict:
            mydict[item] = mydict[item] + 1
        else:
            mydict[item] = 1
    except EOFError:
        for i in mydict:
            print(mydict[i], i)
        break

检查50结果:

Results for cs50/problems/2022/python/grocery generated by check50 v3.3.7
:) grocery.py exists
:) input of EOF halts program
:) input of "apple" and "banana" yields "1 APPLE 1 BANANA"
:) input of "strawberry" and "strawberry" yields "2 STRAWBERRY"
:) input of "mango", "sugar", and "mango" yields "2 MANGO 1 SUGAR"
:( input of "tortilla" and "sweet potato" yields "1 SWEET POTATO 1 TORTILLA"
    expected "1 SWEET POTATO...", not "\n\n1 TORTILLA..."

如上图所示,check50失败:

:( input of "tortilla" and "sweet potato" yields "1 SWEET POTATO 1 TORTILLA"
    expected "1 SWEET POTATO...", not "\n\n1 TORTILLA..."

但是当我运行python www.example.com时grocery.py,结果似乎与预期的结果相匹配:

tortilla
sweet potato
1 TORTILLA
1 SWEET POTATO

我很难理解我犯了什么错误。请帮助我。

8xiog9wr

8xiog9wr1#

我没有发现这段代码的确切问题,但是你可以尝试在将字符串添加到字典之前格式化它。Python的split方法在这方面非常强大。也许CS50尝试了一些奇怪的组合来模拟一个糟糕的用户。我会这样做:

s=input()
t=s.split()
ret=""
n=len(t)
for k in range(n-1):
    ret+=f"{t[k].upper()} ".format(t[k].upper())
ret+=t[-1].upper()

然后把ret放进你的dic。这样,你就有了一个合适的字符串,没有多余的空格,制表符或行尾...不知道它是否有效,让我知道!

pkwftd7m

pkwftd7m2#

我的错误是dict没有正确排序。我通过从 collections 类导入OrderedDict方法解决了这个问题。下面是我在except语句中添加的代码:

from collections import OrderedDict

...

while True:
    try:
        ...
    except EOFError:
        # https://docs.python.org/3/library/collections.html#collections.OrderedDict 
        mydict = OrderedDict(sorted(mydict.items(), key=lambda t: t[0]))
        ...
t1qtbnec

t1qtbnec3#

我认为我们必须按字母顺序打印杂货清单,所以打印项目我使用这个:

for key,value in sorted(dict.items()):
                print(value,key)

相关问题