如何解决Kaggle练习:列出问题编号 5.使用“打印”的语法错误
问:问。我们正在使用列表来记录参加我们聚会的人和他们到达的顺序。例如,以下列表代表一个有7位客人的聚会,其中Adela出现在第一位,而福特是最后一位到来:party_attendees = ['Adela','Fleda','Owen','May','Mona','Gilbert','Ford'] 如果某个客人至少在聚会的一半客人之后到达,则被视为“时尚迟到”。但是,他们一定不能成为最后一位客人(这太过分了)。在上面的示例中,Mona和Gilbert是仅有的时尚迟到者。
完成下面的功能,该功能将同时列出聚会参与者和一个人,并告诉我们该人是否时尚迟到。
我的回答:
def fashionably_late(arrivals,name):
"""Given an ordered list of arrivals to the party and a name,return whether the guest with that
name was fashionably late.(This is a hint by the website.)
"""
name_index=arrivals.index(name) #This line of code is working fine.
final_index_of_list=arrivals.index((len(arrivals)-1)
print(final_index_of_list)
if final_index_of_list%2==0:
return False if name_index<=(final_index_of_list/2) or name_index==final_index_of_list else True
else final_index_of_list%2>0:
return False if name_index<=(final_index_of_list/2+1) or name_index==final_index_of_list else True
Error Message:
File "<ipython-input-16-d4bcd37e23f2>",line 7
print(final_index_of_list)
^
SyntaxError: invalid syntax
解决方法
您在第6行伪造了括号。
相反:
final_index_of_list=arrivals.index((len(arrivals)-1)
应为:
final_index_of_list=arrivals.index((len(arrivals)-1))
UPD:
接下来我发现一些错误:
- 函数缩进不正确。查看更多here
- 相反,
else final_index_of_list%2>0:
应该是elif final_index_of_list%2>0:
。您可以阅读有关python条件语句here 的信息。
因此,正确的功能是:
def fashionably_late(arrivals,name):
"""Given an ordered list of arrivals to the party and a name,return whether the guest with that
name was fashionably late.(This is a hint by the website.)
"""
name_index=arrivals.index(name) #This line of code is working fine.
final_index_of_list=arrivals.index((len(arrivals)-1))
print(final_index_of_list)
if final_index_of_list%2==0:
return False if name_index<=(final_index_of_list/2) or name_index==final_index_of_list else True
elif final_index_of_list%2>0:
return False if name_index<=(final_index_of_list/2+1) or name_index==final_index_of_list else True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。