- 2^15 = 32768 然后這個(gè)數(shù)的每個(gè)數(shù)字加起來(lái)是 3 + 2 + 7 + 6 + 8 = 26.
那么 2^1000的得數(shù)的所有數(shù)字和加起來(lái)是多少呢?
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)
運(yùn)行結(jié)果: 26
1366
- 如果數(shù)字1到5用英語(yǔ)寫出:one, two, three, four, five偷线,則總共使用3 + 3 + 5 + 4 + 4 = 19個(gè)字母摇零。如果所有1到1001(包含一千零一)的數(shù)字都用英語(yǔ)寫出來(lái)推掸,會(huì)用多少個(gè)字母?
解題思路:
1) 判斷是否是數(shù)字
2) 判斷是否在100以內(nèi)驻仅, 1-20必須用字典定義谅畅, 百以內(nèi)的整數(shù)必須定義字典和其對(duì)應(yīng)的英文,
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'}
一百以內(nèi)的函數(shù)定義:
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
- 判斷是否在100-1000之間噪服,獲取千位上的英文并且調(diào)用還是那個(gè)面定義的百以內(nèi)的函數(shù)
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
以下是完整判斷數(shù)字并調(diào)用不同代碼的函數(shù):
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
程序的主函數(shù)如下毡泻,這里需要去除每個(gè)返回?cái)?shù)字英文之間的空格符號(hào),在累加計(jì)算總長(zhǎng)度粘优。
去除字符串中的空格 -> 1) 使用replace函數(shù): replace(' ', '')仇味; 2)使用join 函數(shù):''.join(str.split(' '))呻顽,3) 使用正則表達(dá)式re.sub實(shí)現(xiàn)字符串替換, re_comp = re.compile(' '), re_comp.sub('',str)
if __name__ == '__main__':
inputt = input("please input a number:").strip() # 去除字符串前后的空格
tol_length = 0
# 判斷是否為數(shù)字,
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')
運(yùn)行結(jié)果: total length: 21948