为什么在字符串长度等于key之后,字符串没有被修改为Python字典中的值之一呢?

gg0vcinb  于 2023-01-14  发布在  Python
关注(0)|答案(3)|浏览(135)

我有一个数字“n”(例如,n=60),我的任务是将该数字转换为字符串empty = 'sixzero',并计算字符串的长度,然后按以下方式进一步修改,***'sixzero'的长度为7,因此字符串的进一步修改为'seven',seven的长度为5,因此,它将进一步修改为'five',然后length将为4,因此它将被修改为'four',此时,它应该停止,因为string的length将为4,string的value也为'four'。我需要返回'four'***,所以最初我实现了empty = 'sixzero',但我无法实现最终结果'four'。

class Solution(object):

    # (60)

   def numbers_of_letters(self,n):

       arr = {0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',
              6:'six',7:'seven',8:'eight',9:'nine'}
       empty = ''
       modi =''

       to_char_array = list(map(int, str(n)))
       for i in range(len(to_char_array)):

            if to_char_array[i] in arr.keys():
                 empty += str(arr.get(to_char_array[i]))
            else:
                 pass
            k=0
            while len(empty) not in arr.values():
                if len(empty) in arr.keys():
                 modi += str(arr.get(k))
                else:
                    pass
       return modi

if __name__ == "__main__":
    n=60
    print(Solution().numbers_of_letters(n))
0wi1tuuw

0wi1tuuw1#

一个简单的递归方法会给你你需要的答案。注意,无论传递给这个函数的值是什么,结果总是是'four'

MAP = [
    'zero',
    'one',
    'two',
    'three',
    'four',
    'five',
    'six',
    'seven',
    'eight',
    'nine'
]

def as_string(n):
    if n == 0:
        return MAP[0]
    s = []
    while n > 0:
        s.append(MAP[n%10])
        n //= 10
    return ''.join(s)

def number_of_letters(n):
    s = as_string(n)
    if (ls := len(s)) == n:
        return s
    return number_of_letters(ls)

print(number_of_letters(60))
    • 输出:**
four
    • 注:**

as_string()函数将有效地反向返回字符串,例如,对于值60,它将返回'zerosix'。但是,这并不重要,因为我们只关心返回值的长度。
as_string()函数中的整数运算性能明显优于任何涉及与str int之间转换的解决方案<-> int

    • 备选案文:**

使用相同的MAP列表:

def as_string(n):
    def _next(n):
        if n == 0:
            yield 0
        while n > 0:
            yield n % 10
            n //= 10
    return ''.join(reversed([MAP[i] for i in _next(n)]))

def number_of_letters(n, rv=None):
    if rv is None:
        rv = list()
    rv.append(s := as_string(n))
    if (ls := len(s)) == n:
        return rv
    return number_of_letters(ls, rv)

print(number_of_letters(60))
    • 输出:**
['sixzero', 'seven', 'five', 'four']
2nbm6dog

2nbm6dog2#

方法略有不同,每一步使用两个帮助函数:

class Solution(object):
    def numbers_of_letters(self,n):
        while True:
            new_n = words_to_number(number_to_words(n))
            if new_n == n:
                break
            else:
                n = new_n
        return number_to_words(new_n)

def words_to_number(words):
    print("".join(words))
    return sum(map(len, words))

def number_to_words(n):
    print(n)
    arr = {0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',
              6:'six',7:'seven',8:'eight',9:'nine'}
    to_char_array = list(map(int, str(n)))
    words = list(map(lambda x: arr[x], to_char_array))
    return words

if __name__ == "__main__":
    n=60
    print(Solution().numbers_of_letters(n))
h5qlskok

h5qlskok3#

因此,当结束条件不为真时,OP形式的答案只是循环:

class Solution:
    
    def numbers_of_letters(self, n):
        arr = ['zero','one','two','three','four','five','six','seven','eight','nine']

        while True:
           number_as_str = str(n)
           text = ''
           for digit in number_as_str:
               text += arr[int(digit)]
           if len(text) == n:
               return text
           n = len(text)

if __name__ == "__main__":
    n=463829
    print(Solution().numbers_of_letters(n))

输出:
four
正如@Fred所指出的,简单的版本是:

class Solution:
    def numbers_of_letters(self, n):
        return 'four'

相关问题