我试图解决的问题集: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..."
但是当我运行 pythongrocery.py 时,结果似乎与预期结果相符:
tortilla
sweet potato
1 TORTILLA
1 SWEET POTATO
我无法理解我在哪里犯了错误。请帮忙。
我没有找到这段代码的确切问题,但您可以尝试在将字符串添加到字典之前对其进行格式化。 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 中。这样,您就拥有了一个正确的字符串,没有多余的空格、制表符或行尾...不知道它是否有效,请告诉我!
我的错误是字典的排序不正确。我通过从 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]))
...
我认为我们必须按字母顺序打印杂货清单, 所以对于打印项目我用这个:
for key,value in sorted(dict.items()):
print(value,key)
list_str=[]
虽然正确: 尝试: 值=输入() list_str.append(值) 除了 EOF 错误: 打破
new_list=列表(设置(list_str)) 对于 new_list 中的 i: print(f"{list_str.count(i)} {i.upper()}")