【每日一题20220704】数字字母的数量

:mage:‍ 如果我们把“60”的数字写成英文单词,我们得到“sixzero”;“sixzero”中的字母数是七个。“七”的字母数是五个。“五”中的字母数是四个。“四”中的字母数是四个:我们已经达到了一个稳定的平衡。

注意:对于大于 9 的整数,用一个单词写出每个数字的名称(而不是英文数字的专有名称)。例如,将 12 写为“onetwo”(而不是 12),将 999 写为“nineninenine”(而不是 999)。

对于 0 到 999 之间的任何整数,返回一个数组,显示从该整数到稳定平衡的路径:

例子

numbersOfLetters(60) --> ["sixzero", "seven", "five", "four"]
numbersOfLetters(1) --> ["one", "three", "five", "four"]

题目难度:一般
题目来源:https://www.codewars.com/kata/599febdc3f64cd21d8000117

编写一个实现

def solution(num: int)-> list:
    # your code here

assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]
char_dict = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven",
                 "8": "eight", "9": "nine"}

def translate(input_str):
    numTLchar = ""
    for item in input_str:
        numTLchar += char_dict.get(item)
    return numTLchar

def solution(num: int)-> list:
    # your code here
    res = []
    numTLchar = translate(str(num))
    res.append(numTLchar)
    while len(res[-1]) >= 10:
        numTLchar = translate(str(len(numTLchar)))
        res.append(numTLchar)
    else:
        lenNum = char_dict.get(str(len(numTLchar)))
        res.append(lenNum)
    while len(res[-1]) != len(res[-2]):
        lenNum = char_dict.get(str(len(res[-1])))
        res.append(lenNum)
    print(res)
    return res

assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]
def solution(num: int)-> list:
    # your code here
    t = True
    b = ''
    a = ''
    list_num = []
    dict_num = {'0':'zero','1':"one","2":"two",'3':'three','4':'four',
                '5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
    if len(str(num)) == 1:
        for i in str(num):
            list_num.append(dict_num[i])
    else:
        for i in str(num):
            b = b + dict_num[i]
        list_num.append(b)
    while t:
        if len(list_num[-1]) <= 9:
            list_num.append(dict_num[str(len(list_num[-1]))])
        else:
            for i in str(len(list_num[-1])):
                a = a + dict_num[i]
            list_num.append(a)
        if len(list_num[-1]) == len(list_num[-2]):
            t = False
            break
    print(list_num)
    return list_num

assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]

def num2str(num: int) -> str:
    convert = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
               '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
    __str = ''
    for i in str(num):
        __str += convert[i]
    return __str


def solution(num: int) -> list:
    __str = num2str(num)
    lst = [__str]
    new_num = len(__str)
    while new_num != num:
        __new_str = num2str(new_num)
        lst.append(__new_str)
        num = new_num
        new_num = len(__new_str)
    return lst

这题能用递归写吗?想半天,写的有问题,就改成现在这个了

def solution(num: int)-> list:
    # your code here
    result = []
    num_en = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    def en_str(number: str) -> str:
        result_str = ""
        for i in number:
            result_str += num_en[int(i)]
        return result_str
    str_num = en_str(str(num))
    result.append(str_num)
    while True:
        if (n:=len(str_num)) <= 9:
            if str_num != (m:=num_en[n]):
                result.append(m)
                str_num = m
            else:
                break
        else:
            str_num = en_str(str(n))
            result.append(str_num)
    return result


assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]

递归

2 个赞
def solution(num: int)-> list:
    # your code here
    if num==4:
        return ["four"]
    length_str = ["zero","one","two","three","four","five","six","seven","eight","nine"]
    list_num = []
    str_num = ""
    for i in range(len(str(num))):
        str_num += length_str[eval(str(num)[i])]
    list_num.append(str_num)
    str_num_1 = ""
    for i in range(len(str(len(str_num)))):
        str_num_1 += length_str[eval(str(len(str_num))[i])]
    list_num.append(str_num_1)
    while len(list_num[-1])!=len(list_num[-2]):
        str_num_2 = ""
        for i in range(len(str(len(list_num[-1])))):
            str_num_2 += length_str[eval(str(len(list_num[-1]))[i])]
        list_num.append(str_num_2)
        if len(list_num[-1])==len(list_num[-2]):
            break
    return list_num


assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]
def numbers_of_letters(num: int):
    """num 为0-999的任意整数
    如果我们把“60”的数字写成英文单词,我们得到“sixzero”;“sixzero”中的字母数是七个。“七”的字母数是五个。“五”中的字母数是四个。“四”中的字母数是四个:我们已经达到了一个稳定的平衡。
    注意:对于大于 9 的整数,用一个单词写出每个数字的名称(而不是英文数字的专有名称)。例如,将 12 写为“onetwo”(而不是 12),将 999 写为“nineninenine”(而不是 999)。
    对于 0 到 999 之间的任何整数,返回一个数组,显示从该整数到稳定平衡的路径:
    例子
    numbersOfLetters(60) --> ["sixzero", "seven", "five", "four"]
    numbersOfLetters(1) --> ["one", "three", "five", "four"]
    """
    if isinstance(num, int) and 999 >= num >= 0:
        num_tuple = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")

        def translate(x):
            """获取整数对应的字符串"""
            return "".join([num_tuple[int(i)] for i in str(x)])
        # 添加到数组
        my_list = [translate(num)]
        while True:
            if my_list[-1] == "four":
                return my_list
            else:
                my_list.append(translate(len(my_list[-1])))
    else:
        raise ValueError("请输入0-999的整数")
def solution(num: int)-> list:
    l1=['zero','one','two','three','four','five','six','seven','eight','nine']
    result = []
    while num != 4:
        translate = ""
        for i in str(num):
            translate += l1[int(i)]
        result.append(translate)
        num = len(translate)
    result.append('four')
    return result
def solution(num: int)-> list:
    data = []
    dict_info = {0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}
    result = "".join([dict_info.get(int(i)) for i in str(num)])
    data.append(result)
    while data[-1] != "four":
        result_len = "".join([dict_info.get(int(i)) for i in str(len(data[-1]))])
        data.append(result_len)
    return data

assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]
def solution(num: int)-> list:
    test_dict={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
    res_list=[]
    res_int=num
    while res_int!=4:
        num_item = ''.join(test_dict[int(str(res_int)[i])] for i in range(len(str(res_int))))
        res_list.append(num_item)
        res_int = len(num_item)
    res_list.append('four')
    return res_list

assert solution(1) == ["one", "three", "five", "four"]
assert solution(37) == ["threeseven", "onezero", "seven", "five", "four"]
assert solution(999) == ["nineninenine", "onetwo", "six", "three", "five", "four"]
class PaginationHelper:

    # The constructor takes in an array of items and a integer indicating
    # how many items fit within a single page
    def __init__(self, collection, items_per_page):
        self.collection = collection
        self.items_per_page = items_per_page

    # returns the number of items within the entire collection
    def item_count(self):
        return len(self.collection)

    # returns the number of pages
    # 返回页码数
    def page_count(self):
        # math.ceil()向上取整
        integral_part = self.item_count()//self.items_per_page  #取商
        decimal_part = self.item_count()%self.items_per_page    #取余/模
        if decimal_part > 0:
            return integral_part + 1
        elif decimal_part== 0:
            return integral_part

    # returns the number of items on the current page. page_index is zero based
    # this method should return -1 for page_index values that are out of range
    # 根据页码索引返回当页数据量
    def page_item_count(self, page_index):
        # integral_part = self.item_count() // self.items_per_page
        # decimal_part = self.item_count() % self.items_per_page
        if 0<=page_index < (self.page_count()-1) :
            return self.items_per_page
        elif  page_index == (self.page_count()-1):
            return  self.item_count()%self.items_per_page
        else:
            return  -1

    # determines what page an item is on. Zero based indexes.
    # this method should return -1 for item_index values that are out of range
    # 根据元素索引返回所在页码索引
    def page_index(self, item_index):
        page_index = item_index//self.items_per_page
        print(page_index)
        if 0<=page_index<=(self.page_count()-1) and item_index<=(self.item_count()-1):
            return page_index
        else:
            return  -1