【问题标题】:python: converting two numbers to wordspython:将两个数字转换为单词
【发布时间】:2021-05-13 19:02:29
【问题描述】:

我有一个程序,目前需要两个数字并将它们转换为分数的单词, 例如,“frac(2,3) 应该返回“三分之二”,但我需要第二个输入的帮助,将其转换为单词“第三”。现在像 frac (2,3) 这样的东西只会返回“二" 但我需要它返回 "三分之二"

我的程序:

def frac (numer, den):
    top = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
            '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
    bottom = {'2': "half", '3': "third", '4':"Fourth",'5':"Fifth",'6':"sixth",'7':"seventh",'8':"eighth",'9':"ninth",'10':"tenth"}
    return " ".join(map(lambda x: top[x], str(numer)))


【问题讨论】:

标签: python string list


【解决方案1】:

不需要joinmap,只需使用format

return '{} {}'.format(top[str(numer)], bottom[str(den)])

【讨论】:

  • return f'{top[str(numer)]} {bottom[str(den)]}'
  • @PeterWood:真的是numer - 就像分子一样。
【解决方案2】:

你可以使用

def frac(numer, den):
    top = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
           '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
    bottom = {'2': "half", '3': "thirds", '4': "Fourth", '5': "Fifth", '6': "sixth", '7': "seventh", '8': "eighth",
              '9': "ninth", '10': "tenth"}

    return f"{top[str(numer)]} {bottom[str(den)]}"


print(frac(2, 3))

产量

two thirds

【讨论】:

    【解决方案3】:

    这可能是利用此处的值可以直接映射到索引这一事实的替代方法:

    def frac(numer, den):
    
        if numer > 10 or numer <= 1:
            raise ValueError(f'Numerator must have value between 1 and 10 inclusive, got {numer}.')
        elif  den < 2 or den > 9:
            raise ValueError(f'Denominators only supported for values between 2 and 10 inclusive. got {den}.')
    
        numerator_words = ('one','two','three','four','five','six','seven','eight','nine',)
        denominator_words = ('half','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth',)
    
        return ' '.join((numerator[numer-1], denominator[den-2]))
    

    附:您可能想看看标准库中的fractions module

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多