1. 程式人生 > >python3學習(3)

python3學習(3)

length 個數 sta 取出 nco mat 定義 習題 ()

練習題:
1.?26個字母大小寫成對打印,例如:Aa,Bb....

for i in range(65,91):
    print(chr(i)+chr(i+32)+",",end="")

2、一個list包含10個數字,然後生成新的list,要求,新的list裏面的數都比之前的數多1

list_1 = list(range(10))
result = []
for num in list_1:
  result.append(num + 1)
print(result)

print([num + 1 for num in list_1])

3、倒序取出每個單詞的第一個字母。

s = "I am a good boy "

s_list = s.split()

for i in range(len(s_list)-1,-1,-1):
print(s_list[i][0])

s = "I am a boy!"
s=s.split()
s.reverse()
result = []
for i in s:
    result.append(i[0])
print(result)

4、找出s=”aabbccddxxxxffff”中,出現次數最多的字母

#coding=utf-8

s="aabbccddxxxxffff"

letter_numbers = {}

for c in s:
    letter_numbers[c] = s.count(c)

max_times = max(letter_numbers.values())

for k,v in letter_numbers.items():
    if v == max_times:
        print(k)

5、自定義count函數
只統計單個字符出現次數情況

#coding=utf-8

a = “a1111bceddd”
def count_letters(s,letter):
    times = 0
    if not isinstance(s,str) or not isinstance(letter,str):
        return 0
    else:
        for v in s:
            if v == letter:
                times += 1
    return times

print(count_letters(a,1))

兼容統計多個字符出現次數的情況
算法:
1、首先求出需要查找字符串的長度
2、遍歷源字符串,如果當前索引加上子串長度對應的字符串等於要查找字符串的話次數加1
#encoding=utf-8

def count_letters(s,letter):
    times = 0
    letter_length = len(letter)
    if not isinstance(s,str) or not isinstance(letter,str):
        return 0
    if letter not in s:
        return 0
    else:

        for i in range(len(s)):
            if s[i:i+letter_length] == letter:

#判斷當前索引+字符串長度是否等於要查找的字符串

                        times += 1
return times

s = "abcabdab1"
print(count_letters(s,"ab"))

數學運算符:

math.ceil()向上取整

>> math.ceil(5//2)
2
>> math.ceil(5/2)
3

math.floor()向下取整

>>?import?math
>>?math.floor(1.9/2)
0

>>?math.ceil(1.9/2)
1
>>?math.round(0.5)

>> round(5.1112,2)
5.11

divmod()同時求商和余數

>> divmod(5,2)
(2, 1)

練習題:
自定義divmod

#coding=utf-8

def divmod_2(a,b):
    c = a//b
    d = a%b
    return c,d

print(divmod_2(5,2))

>> 2**3
8

a.zfill(length)
a 的長度如果小於length,左邊補0,總長度是length

>> bin(5)[2:]
‘101‘
>> bin(5)[2:].zfill(8)
‘00000101‘

int()函數攜帶base參數

>> int(bin(3),base=2)#把二進制轉換成10進制
3

>> int("10",base=16)#把16進制轉成10進制
16
>> int("10",16)
16

>> int("10",8)
8
>> int("10",base=8)
8

False取值
0 "" [] () {} None False

python3學習(3)