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

  • 相关阅读:
    Ubuntu安装qBittorrent
    资深程序猿冒死揭开软件潜规则:无法维护的代码
    Oracle11g Active Data Guard搭建、管理
    Android 扁平化button
    Eclipse Android 代码自己主动提示功能
    Echoprint系列--编译
    一步步玩pcDuino3--mmc下的bootloader
    【Discuz】去除版权信息,标题栏与底部改动
    phoenixframe自己主动化測试平台对div弹出框(如弹出的div登陆框)的处理
    UVa
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11498220.html
Copyright © 2011-2022 走看看