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

  • 相关阅读:
    listview右边显示 abcd快速选择
    显示密码
    欢迎界面动画
    web get Post测试
    使用MultiDexApplication
    获取当前运行的Activity信息
    MFC得到运行程序路径
    构建之法阅读笔记01
    个人作业1:随机生成四则运算
    软件工程第一步
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11498220.html
Copyright © 2011-2022 走看看