Q。我们使用列表来记录参加我们聚会的人以及他们到达的顺序。例如,以下列表代表一个有7位客人的聚会,其中Adela第一个出现,Ford最后一个到达:
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:
我发现接下来的一些错误:
- 函数缩进不正确。点击此处查看更多信息
- 相反,
else final_index_of_list%2>0:
应该是elif final_index_of_list%2>0:
。您可以在此处阅读有关python条件语句的信息
因此,正确的功能是:
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