Python 练习题

  1. 2^15 = 32768 然后这个数的每个数字加起来是 3 + 2 + 7 + 6 + 8 = 26.
    那么 2^1000的得数的所有数字和加起来是多少呢?
a = sum(int(i) for i in str(pow(2, 15)))
print(a)
b = sum(int(i) for i in str(pow(2, 1000)))
print(b)
运行结果: 26
1366
  1. 如果数字1到5用英语写出:one, two, three, four, five,则总共使用3 + 3 + 5 + 4 + 4 = 19个字母。如果所有1到1001(包含一千零一)的数字都用英语写出来,会用多少个字母?
    解题思路:
    1) 判断是否是数字
    2) 判断是否在100以内, 1-20必须用字典定义, 百以内的整数必须定义字典和其对应的英文,
one_to_nine = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine',
               0: 'Zero', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen',
               16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen'}
number_ty = {20: 'Twenty', 30: 'Thirty', 40: 'Fourty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty',
             90: 'Ninety', 100: 'Hundred', 1000: 'Thousand'}

一百以内的函数定义:

def determine_in_hundred(num):
    if (num >= 0) and (num < 20):
        number_word = one_to_nine.get(num)
    elif num < 100:
        ten_dig = num // 10
        word_one = number_ty.get(ten_dig * 10)
        ge_dit = num % 10
        if ge_dit == 0:
            number_word = word_one
        else:
            word_two = one_to_nine.get(ge_dit)
            number_word = word_one + '-' + word_two
    return number_word
  1. 判断是否在100-1000之间,获取千位上的英文并且调用还是那个面定义的百以内的函数
def determine_in_thousand(num):
    if num % 100 == 0:
        number_word = one_to_nine.get(num // 100) + ' hundred'
    else:
        number_word = one_to_nine.get(num // 100) + ' hundred and ' + determine_in_hundred(num % 100)
    return number_word

以下是完整判断数字并调用不同代码的函数:

def tanslate_number_to_word(num):
    if num < 100:
        number_word = determine_in_hundred(num)
    elif num < 1000:
        number_word = determine_in_thousand(num)
    elif num < 10000:
        if num % 1000 == 0:
            number_word = one_to_nine.get(num // 1000) + ' thousand '
        else:
            number_word = one_to_nine.get(num//1000) + ' thousand and ' + determine_in_thousand(num % 1000)
    return number_word

程序的主函数如下,这里需要去除每个返回数字英文之间的空格符号,在累加计算总长度。
去除字符串中的空格 -> 1) 使用replace函数: replace(' ', ''); 2)使用join 函数:''.join(str.split(' ')),3) 使用正则表达式re.sub实现字符串替换, re_comp = re.compile(' '), re_comp.sub('',str)

if __name__ == '__main__':

    inputt = input("please input a number:").strip()  # 去除字符串前后的空格
    tol_length = 0
    # 判断是否为数字,
    if inputt.isnumeric():  # or inputt.isdigit()/ inputt.isdecimal()
        print('you entered ', inputt)
        num = int(inputt)
        for each_num in range(num):
            word = tanslate_number_to_word(each_num)
            print(''.join(word.split(' ')), word.replace(' ', ''), re.compile(' ').sub('', word))
            tol_length += len(word.replace(' ', ''))
        print('total length:', tol_length)  # 24632  21948
    else:
        print('please enter number again')

运行结果: total length: 21948

你可能感兴趣的:(Python 练习题)