【问题标题】:How can you take letters from a string and make them integers?如何从字符串中取出字母并使它们成为整数?
【发布时间】:2016-05-03 17:30:49
【问题描述】:

我被指派创建一个应用程序,该应用程序采用用户的名字和第二名(确保它们不超过 10 个字符)并根据此网格计算他们的“幸运姓名编号”:

Lucky Name Number Grid

例如,约翰·史密斯将是:

= (1 + 6 + 8 + 5) + (1 + 4 + 9 + 2 + 8)

= 20 + 24

然后将每个值中的数字相加:

= (2 + 0) + (2 + 4)

= 2 + 6

= 8

这是我目前的代码:

while True:
    first_name = input("What is your first name? ")
    if len(first_name) < 10:
        print("Hello " + first_name + ", nice name!")
        break
    else:
        print("First name is too long, please enter a shorter name.")

while True:
     second_name = input("What is your second name? ")
     if len(second_name) < 10:
         print ("Wow, " + first_name + " " + second_name + " is a really cool name. Let's see how lucky you are...")
         break
     else:
          print ("Second name is too long, please enter a shorter name.")

但是,我不确定下一步是什么,因为我需要获取名称中的每个字母并将其设为特定值。

我能想到的唯一方法是列出每个字母及其分配的值,如下所示:

A = 1
B = 2
C = 3
D = 4
E = 5
F = 6
G = 7
H = 8
I = 9
J = 1
K = 2
L = 3
M = 4
N = 5
O = 6
P = 7
Q = 8
R = 9
S = 1
T = 2
U = 3
V = 4
W = 5
X = 6
Y = 7
Z = 8

fletter_1 = first_name[0]
fletter_2 = first_name[1]
fletter_3 = first_name[2]
fletter_4 = first_name[3]
fletter_5 = first_name[4]
fletter_6 = first_name[5]
fletter_7 = first_name[6]
fletter_8 = first_name[7]
fletter_9 = first_name[8]
fletter_10 = first_name[9]

print fletter_1 + fletter_2 + fletter_3 + fletter_4 + fletter_5 + fletter_6 + fletter_7 + fletter_8 + fletter_9

但这是一个极其漫长的过程,并不是最好的编码方式。

由于我不确定该怎么做,请有人指导我如何以最好的方式完成下一步。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    如果您还没有听说过ASCII table,那么它几乎是关于如何用二进制表示字符的约定。根据 ASCII 表,python 中的函数ord(c) 为您提供给定字符的值。 我注意到您的幸运姓名编号网格每 9 个字母给出相同的值,在数学中可以表示为 % 9。因此:

    # ASCII value of A
    >>> ord('A') 
    65
    # Except that we wanted 1 for A
    >>> ord('A') - 64
    1
    # And we also want 1 for J and S
    >>> (ord('J') - 64) % 9
    1
    >>> (ord('S') - 64) % 9
    1
    >>> (ord('Z') - 64) % 9
    8
    

    您可以使用最后一个公式:(ord(c) - 64) % 9

    编辑: 正如 Loïc G. 所指出的,我的公式有一个小错误,因为模函数不时返回 0,而您的表格 Grid 的索引从 1 开始。这里是最终版本:

    ord(c.lower()) - ord('a')) % 9) + 1
    

    ord('a') 返回97(避免硬编码值),c.lower() 使函数对大小写字符起作用。与第一种算法的最大区别在于,+ 1 在末尾,根据您的网格要求将所有索引移动 1。

    【讨论】:

    • 使用ord() 是一个很好的解决方案,而且非常高效,+1。
    • @Leb 请注意,字典查找比使用 ord 进行后续模运算要快得多。
    • @poke 可能是真的,但是在你这边有 1 个硬编码值 (64) 对 52 个(26 个字母 + 26 个值),我相信我的回答会更灵活一些.
    • 取决于您对灵活的定义。对于个别更改,甚至是对字母的额外支持,这比为翻译找出额外的算术规则要容易得多。例如,让我们添加一些其他语言的字符:äöü,或破折号-
    • 正如我在对我的回答的评论中所说,(ord('R') - 64) % 9 返回 0,而不是 8。
    【解决方案2】:

    您应该将网格存储为字典:

    luckyNameGrid = {
        'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9,
        'j': 1, 'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6, 'p': 7, 'q': 8, 'r': 9,
        's': 1, 't': 2, 'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7, 'z': 8
    }
    

    然后,您可以使用该网格将翻译转换为数字(将名称转换为小写后),最后,将这些数字相加得到结果:

    def getLuckyNameNumber (name):
        return sum(map(lambda x: luckyNameGrid[x], name.lower()))
    

    这样使用:

    >>> getLuckyNameNumber('John')
    20
    >>> getLuckyNameNumber('Smith')
    24
    

    要进行最终转换,您基本上要计算每个幸运名称数字的digit sum。有多种方法可以做到这一点。一种是将数字转换为字符串,为每个字符拆分,将字符转换回数字,然后将它们相加:

    def getDigitSum (num):
        return sum(map(int, str(num)))
    

    另一种解决方案是将数字连续除以 10 并将余数相加。这样做的好处是您不需要进行类型转换:

    def getDigitSum (num):
        sum = 0
        while num > 0:
            num, remainder = divmod(num, 10)
            sum += remainder
        return sum
    

    例如:

    >>> getDigitSum(getLuckyNameNumber('John'))
    2
    >>> getDigitSum(getLuckyNameNumber('Smith'))
    6
    

    【讨论】:

      【解决方案3】:

      创建一个从字母到值的字典,称之为 D。

      然后例如 D['A'] = 1

      然后这样做

      def reduce_value(n):
          return sum(int(i) for i in str(n))
      
      string = "HEYDUDE"
      value = sum(D[letter] for letter in string)
      while len(str(value)) > 1:
          value = reduce_value(value)
      print "final value", value
      

      【讨论】:

        【解决方案4】:
        # example char dictionary with corresponding integer values - use the Numerical Value Chart 
        # to get the real values for the whole alphabet. You may need to deal with upper/lower
        # case characters
        charDict = { 'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} 
        
        # example names - use your own code here
        firstName = 'AAB'
        lastName = 'DCDD'
        
        # split the strings into a list of chars
        firstNameChars = list(firstName)
        lastNameChars = list(lastName)
        
        # sum up values
        firstNameSum = 0
        lastNameSum = 0
        for chr in firstNameChars:
            firstNameSum += charDict[chr]
        for chr in lastNameChars:
            lastNameSum += charDict[chr]
        
        # cast sums to strings. In your example, this would be '2024'
        combinedNames = str(firstNameSum) + str(lastNameSum)
        
        # split the string into a list of chars
        combinedNameDigits = list(combinedNames)
        
        # sum them up
        finalSum = 0
        for dgt in combinedNames:
            finalSum += int(dgt)
        
        # print the lucky number
        print finalSum
        

        【讨论】:

        • 欢迎来到 SO 并感谢您发布答案。请考虑在您的代码中添加文本以改进您的答案。
        【解决方案5】:

        您的问题与Convert alphabet letters to number in Python有关

        这里是一些计算幸运数字的代码:

        for char in raw_input('Write Text: ').lower():
            print (ord(c.lower()) - ord('a')) % 9 + 1)
        

        或者通过使用列表推导:

        print [(ord(c.lower()) - ord('a')) % 9 + 1 for c in raw_input('Write Text: ')]
        

        然后,要计算分数,您可以使用列表中的sum() buit-in 方法:

        print sum([(ord(c.lower()) - ord('a')) % 9 + 1 for c in raw_input('Write Text: ')])
        

        【讨论】:

        • 你不需要value &gt; 9来使用% 9,逻辑上是:7 % 9 = 7所以检查没有意义
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多