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

  • 相关阅读:
    【从零开始学Java】第六章 运算符
    【从零开始学Java】第五章 变量和数据类型
    【从零开始学Java】第四章 常量
    【从零开始学Java】第三章 HelloWorld入门程序
    【从零开始学Java】第二章 Java语言开发环境搭建
    【从零开始学Java】第一章 开发前言
    vim配置
    神奇的洛谷运势汇总
    达哥题表
    数论总结
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11498220.html
Copyright © 2011-2022 走看看