如何编写一个将字符串转换成一位数字的函数?

时间:2018-12-13 15:56:03

标签: python string algorithm function

我想编写一个将字符串转换为一位数字的函数。每个字母都有一个数字值,最后应返回字母总和,但如果大于10,则应取数字总和,直到找到0到10之间。例如,如果结果为99,则应首先取9 + 9 = 18,则应该取1 + 8,最终答案必须为9。

def name_numerology(name):

    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    numbers = '1234567891234567891234567812345678912345678912345678'

    toq = list(zip(letters, numbers))
    sie = []
    for i in name:
        if i in letters:
            sie.append(toq[letters.index(i)])
    ruk = []
    for i, k in sie:
        ruk.append(int(k))
    zu = sum(ruk)
    da = [i for i in str(zu)]
    re = [int(i) for i in da]
    return sum(re)

print(name_numerology('rasmuuuuuuuu'))

输出为:

12

我被困在这里

4 个答案:

答案 0 :(得分:1)

您的逻辑过于复杂。您只能考虑小写字母,因为小写和大写字母的映射是相同的。使用字典而不是O(1)查找列表。然后使用a tutorial作为数字根。

from string import ascii_lowercase

def name_numerology(name):
    letter_num_map = {v: k % 9 + 1 for k, v in enumerate(ascii_lowercase)}
    num = sum(map(letter_num_map.__getitem__, name.casefold()))    
    return (num - 1) % 9 + 1

res = name_numerology('hello')  # 7

通过filter + str.isalpha可以轻松删除非字母:

def name_numerology(name):
    letter_num_map = {v: k % 9 + 1 for k, v in enumerate(ascii_lowercase)}
    modified_string = filter(str.isalpha, name.casefold())
    num = sum(map(letter_num_map.__getitem__, modified_string))
    return (num - 1) % 9 + 1

res = name_numerology('hello ? 234 ')  # 7

答案 1 :(得分:1)

使用您的代码,我添加了一个while循环以返回小于10的数字,并且不求值为“ None”,它将运行while循环直到满足这些条件:

def name_numerology(name):

    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    numbers = '1234567891234567891234567812345678912345678912345678'

    toq = list(zip(letters, numbers))
    sie = []
    for i in name:
        if i in letters:
            sie.append(toq[letters.index(i)])
    ruk = []
    for i, k in sie:
        ruk.append(int(k))
    zu = sum(ruk)
    while zu > 10:

        da = [i for i in str(zu)]
        re = [int(i) for i in da]
        zu = sum(re)
        if zu is not None and zu < 10:
            return zu
    return zu # will handle if number is less than 10 prior to while loop, otherwise "None"

print(name_numerology('rasmuuuuuuuu'))
# 3
print(name_numerology('GHKLLLlllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmm'))
# 4
print(name_numerology('A'))
# 1

答案 2 :(得分:1)

它只是rule of nines。更直接的方法:

import collections
mapping = collections.defaultdict(int,( (k,int(i)) for k,i in zip(letters,numbers) ) )

def encode(string):
    res=sum( (mapping[c] for c in string) ) % 9 
    return res if res else 9


In [14]: encode('rasmuuuuuuuu')
3
In [15]: encode('Hello$')
7

defaultdict将未知角色映射到0。

答案 3 :(得分:0)

easier ways的项目可以满足您的需要,但是根据您的示例,您可以使用:

na.size()-1

Python Demo