zoukankan      html  css  js  c++  java
  • 【Kata Daily 190910】Who likes it?(谁点了赞?)

    题目:

    Description:

    You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

    Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

    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"

    For 4 or more names, the number in and 2 others simply increases.

    -----------------------------------------------------------------------------------------------

    题目大意就是根据names的个数,返回一段文字,说明谁点了赞。

    解题办法:

    def likes(names):
        if len(names) == 0:
            return "no one likes this"
        elif len(names) == 1:
            return "%s likes this" % names[0]
        elif len(names) == 2:
            return "%s and %s like this" % (names[0], names[1])
        elif len(names) == 3:
            return "%s, %s and %s like this" % (names[0], names[1], names[2])
        else:
            return "%s, %s and %s others like this" % (names[0], names[1], len(names)-2)

    简单粗暴的方式,直接枚举出来所有的结果。

    还有一种比较优秀的方式:

    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)

    解读:通过字典的方式,再配合min函数来确定字典的key值,根据key值来找到对应的返回文字。

    知识点:

    1、使用星号* 可以表示打印出list中的元素

    2、min()函数可以返回最小值

    3、格式化的打印可以使用百分号%,或者.format()来表示。

  • 相关阅读:
    codevs 2021 中庸之道
    bzoj 1227: [SDOI2009]虔诚的墓主人
    cogs 2620. [HEOI2012]朋友圈
    bzoj 3123: [Sdoi2013]森林(45分暴力)
    cogs 1685 魔法森林
    bzoj 1061: [Noi2008]志愿者招募
    poj 1743 Musical Theme
    bzoj 1001: [BeiJing2006]狼抓兔子
    bzoj 4006: [JLOI2015]管道连接
    hdu 5693 D Game
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11498220.html
Copyright © 2011-2022 走看看