想電腦科學家一樣思考python(3)

來源:互聯網
上載者:User

標籤:python   除法   strip   lse   ext   style   思考   代碼   pen   

第五章 條件和遞迴

“//”代表向下取整除法

“%”求模操作符

 

判斷互文的代碼:

# -*- coding: utf-8 -*-

def first(word):

    return word[0]

def last(word):

    return word[-1]

def middle(word):

    return word[1:-1]

def huwen(word):

    if len(word)<=1:

        return True

    if first(word)!=last(word):

        return False

    else:

        return huwen(middle(word))

print(huwen(‘a‘))

print(huwen(‘afbhj‘))

print(huwen(‘adhsuia‘))

print(huwen(‘heeh‘))

 

def huwen(word1,word2):

    if len(word1) != len(word2):

        return False

    i=0

    j=len(word2)-1

    while j>0:

        if word1[i]!=word2[j]:

            return False

        i+=1

        j-=1

    return True

print(huwen(‘hkl‘, ‘lkh‘))

 

def is_huwen(word):

    i=0

    j=len(word)-1

    while i<=j:

        if word[i]!=word[j]:

            return False

        i+=1

        j-=1

    return True

print(is_huwen(‘guug‘))

 

 

 

epsilon=0.0000001

 

 

用python寫下面式子代碼

 

# -*- coding:utf-8 -*-

import math

def jiecheng(n):

    if n==0:

        return 1

    else:

        b=jiecheng(n-1)

        c=n*jiecheng(n-1)

        return c

 

def estimatepi():

    d=(2*math.sqrt(2))/9801

    k=0

    total=0

    while True:

        e=(jiecheng(4*k))*(1103+26390*k)

        f=(jiecheng(k))**4

        g=f*(396**(4*k))

        total1=d*e/g

        total+=total1

        if abs(total1)<1e-15:

            break

        k+=1

    return 1/total

print(estimatepi())

 

兩種遍曆字串的方法

 

Find用法

# -*- coding: utf-8 -*-

word=‘banana‘

print(word.find(‘na‘))#2  找第一次遇到字串時的下標

print(word.find(‘na‘,3))#4  表示從哪一個下標開始尋找

print(word.find(‘a‘,0,1))#-1 表示從哪個小標開始尋找到哪個下表結束

 

 

找具有三個重複字母的單詞

# -*- coding:utf-8 -*-

def liayiyang(word):

    count=0

    i=0

    while i<len(word)-1:

        if word[i]==word[i+1]:

            count+=1

            if count==3:

                return True

            i=i+2

        else:

            count=0

            i=i+1           

    return False

def wenjian():

    fin = open(‘C:\\Users\\chenxi\\Desktop\\words.txt‘)

    for line in fin:

        word=line.strip()

        if liayiyang(word):

            print(word) 

wenjian()

 

想電腦科學家一樣思考python(3)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.