python 學習總結4

來源:互聯網
上載者:User

標籤:改進   編寫   value   題目   []   class   學習總結   new   div   

今天在codewears上做了一道題,僅為6kyu層級,但自己收穫良多

題目為:編寫一個函數,sum_dig_pow(a, b),找到range [a, b]之間所有符合特殊規則的的數字,將其放入列表中,並返回。

這種特殊規則,如下所示;

135 = 1^1 + 3^2 + 5^3

89 = 8^1 + 9^2

自己最開始寫的函數為:

import mathdef sum_dig_pow(a, b):     lis=[]    for i in range(a,b+1):        li=[]        new_i=i        #找到數字是幾位元        k=int(math.log10(new_i))        #將數字切分,如將135切分為[1,3,5]        for j in range(k+1):            li.append(int(new_i/(math.pow(10,k-j))))            new_i=new_i%(math.pow(10,k-j))                #求如 1^1 + 3^2 + 5^3所示的和值        ex=1        sum=0        for x in li:            sum+=math.pow(x,ex)            ex+=1                #判斷和值是否與當前數字相等        if sum==i:            lis.append(i)                             return lis     

  之後複習了之前的一些內容,對上述代碼進行改進;

lis=[]def sum_dig_pow(a, b):     for i in range(a,b+1):        #將數字切分字串,如將135切分為[‘1‘,‘3‘,‘5‘]        li=re.findall(‘[0-9]‘,str(i))        sum=0                #求和        for key,value in enumerate(li):            sum+=pow(int(value),int(key)+1)                        #判斷            if sum==i:                lis.append(i)    return lis   

  

python 學習總結4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.