实现一个函数likes :: [String] -> String,该函数必须接受输入数组,
其中包含喜欢某个项目的人的姓名。它必须返回显示文本,如示例所示:
- likes([]) # must be "no one likes this"
- likes(["Peter"]) # must be "Peter likes this"
- likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this"
- likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this"
- likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this"
def likes(names):
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
}[min(4, n)].format(*names[:3], others=n-2) #这一行不懂
print(likes(["Alex", "Jacob", "Mark", "Max", "Mark", "Max", "Mark", "Max"]))
输出 Alex, Jacob and 6 others like this
我将代码分解了一下,并加上了注释,应该可以让你看懂。