【每日一题0713】让我康康是哪位小可爱点了赞

你可能从凤凰社和其他app上知道“点赞”系统。人们可以“赞”博客文章、图片或其他项目。我们希望创建一个显示在旁边的文本。
任务:实现一个函数,它必须接受人名组成的列表,返回如下例子所示的显示文本:

likes([]) 返回--> "no one likes this"
likes(["凌熙", "北北"]) 返回--> "凌熙 and 北北 like this"
likes(["思寒", "蚊子", "花满楼", "西西"]) 返回--> "思寒, 蚊子 and 2 others like this"
对于4个或更多的名字,只会增加 and 2 others 中数字的数量。

题目难度:简单
题目来源:codewars

def likes(name_list=None):
    pass

assert likes([]) == "no one likes this"
assert likes(["凌熙", "北北"]) == "凌熙 and 北北 like this"
assert likes(["思寒", "蚊子", "花满楼", "西西"]) == "思寒,蚊子 and 2 others like this"

image

题意理解不知道对不对,一个人和三个人的需求是这样吗?

def likes(name_list):
    length=len(name_list)
    if length ==0:
        return 'no one likes this'
    elif length==1:
        return f'{name_list[0]} like this'
    elif length==2:
        return f'{name_list[0]} and {name_list[1]} like this'
    elif length==3:
        return f'{name_list[0]} and {name_list[1]} and {name_list[2]}like this'
    else:
        return f'{name_list[0]},{name_list[1]} and {length-2} others like this'

assert likes([]) == "no one likes this"
assert likes(["凌熙", "北北"]) == "凌熙 and 北北 like this"
assert likes(["思寒", "蚊子", "花满楼", "西西"]) == "思寒,蚊子 and 2 others like this"
def likes(name_list=None):
    length = len(name_list)
    com_str = 'like this'
    if length == 0:
        return "no one likes this"

    elif length == 1:
        return name_list[0] + com_str
    elif length == 2:
        return f'{name_list[0]} and {name_list[1]} ' + com_str
    elif length > 2:
        return f'{name_list[0]},{name_list[1]} and {len(name_list[2:])} others ' + com_str
    else:
        return False
def likes(name_list=None):
    if not name_list:
        return "no one likes this"
    if len(name_list) < 4:
        return " and ".join(name_list) + " like this"
    if len(name_list) >= 4:
        num = len(name_list) - 2
        return ','.join(name_list[:2]) + f' and {num} others like this'

    
assert likes([]) == "no one likes this"
assert likes(["凌熙", "北北"]) == "凌熙 and 北北 like this"
assert likes(["思寒", "蚊子", "花满楼", "西西"]) == "思寒,蚊子 and 2 others like this" 

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

@fwj 嗯,是的。