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()来表示。

  • 相关阅读:
    数组中的每一个对象执行一次方法:makeObjectsPerformSelector
    $.each() each
    JQ js选择节点操作
    Sublime Text 3 快捷键
    TotoiseSVN的基本使用方法
    Hbuilder快捷键
    获取网页内容区域各种高/宽汇总
    TP操作
    xhr接收php://output的二进制文件,并转换成excel表格
    Go语言的%d,%p,%v等占位符的使用
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11498220.html
Copyright © 2011-2022 走看看