• 【Kata Daily 190912】Alphabetical Addition(字母相加)


    题目:

    Your task is to add up letters to one letter.

    The function will be given a variable amount of arguments, each one being a letter to add.

    Notes:

    • Letters will always be lowercase.
    • Letters can overflow (see second to last example of the description)
    • If no letters are given, the function should return 'z'

    Examples:

    add_letters('a', 'b', 'c') = 'f'
    add_letters('a', 'b') = 'c'
    add_letters('z') = 'z'
    add_letters('z', 'a') = 'a'
    add_letters('y', 'c', 'b') = 'd' # notice the letters overflowing
    add_letters() = 'z'

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

    题目大意:字母a-z代表了1-26,给定一个list,将里面字母对应的数字加起来的值对应到字母中。

    解题思路:

    def add_letters(*letters):
        # your code here
        if letters == '' or letters == 'z':
            return 'z'
        else:
            dic = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16,
            'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
            dic2 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 8:'h', 9:'i', 10:'j', 11:'k', 12:'l', 13:'m', 14:'n', 15:'o', 16:'p',
            17:'q', 18:'r', 19:'s', 20:'t', 21:'u', 22:'v', 23:'w', 24:'x', 25:'y', 26:'z'}
            sum = 0
            for i in letters:
                sum += dic[i]
            res = sum % 26
            if res == 0:
                return 'z'
            else:
                return dic2[res]

    个人的代码总是那么的不堪入目啊 QAQ。基本思路是:做两个字典,分别将字母和数字为key值,然后将数值相加后取余,得到的数字再对应到字母表。

    看一下网友们的答案:

    num = 'abcdefghijklmnopqrstuvwxyz'
    def add_letters(*letters):
        x = 0
        x = sum(num.index(i)+1 for i in letters)
        while x-1 > 25:
            x -= 26
            
        return num[x-1]

    另一种:

    def add_letters(*letters):
        return chr( (sum(ord(c)-96 for c in letters)-1)%26 + 97)

    知识点:

    1、ord(c) 将c转为数字,chr(c)将c转为ASCII表中的字母

    2、def add_letters(*letters):带星号是代表传入元组

  • 相关阅读:
    终端解析 规格严格
    用HQ时,出现了一个Bug 规格严格
    GC这篇文章介绍得很基本 规格严格
    DB2协议研究 规格严格
    JVM monitoring 规格严格
    很有趣的GC内容 规格严格
    在linux内核中修改TCP MSS值 规格严格
    最近为项目写了一个调试模块,由此想到的一些内容 规格严格
    Java中国象棋博弈程序探秘[3]——着法合法性判断
    NetBeans 时事通讯(刊号 # 10 Jun 03, 2008)
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11512872.html
Copyright © 2020-2023  润新知