Python技能大考察!這28道常見題型,看看你會嗎?

數據分析那些事
17 min readApr 12, 2023

--

今天給大家分享30道Python練習題,建議大家先獨立思考一下解題思路,再查看答案。

1.已知一個字串為 “hello_world_yoyo”,如何得到一個佇列

[“hello”,”world”,”yoyo”] ?

使用 split 函式,分割字串,並且將資料轉換成列表型別:

test = 'hello_world_yoyo'
print(test.split("_"))
12

結果:

['hello', 'world', 'yoyo']

2. 有個列表 [“hello”, “world”, “yoyo”],如何把列表裡面的字串聯起來,得到字串 “hello_world_yoyo”?

使用 join 函式將資料轉換成字串:

test = ["hello", "world", "yoyo"]
print("_".join(test))

結果:

hello_world_yoyo

如果不依賴 python 提供的 join 方法,還可以透過 for 迴圈,然後將字串拼接,但是在用“+”連線字串時,結果會生成新的物件,使用 join 時結果只是將原列表中的元素拼接起來,所以 join 效率比較高。

for 迴圈拼接如下:

test = ["hello", "world", "yoyo"]
# 定義一個空字串
j = ''
# 透過 for 迴圈打印出列表中的資料
for i in test:
j = j + "_" + i
# 因為透過上面的字串拼接,得到的資料是“_hello_world_yoyo”,前面會多一個下劃線_,所以把這個下劃線去掉
print(j.lstrip("_"))

3. 把字串 s 中的每個空格替換成”%20”,輸入:s = “We are happy.”,輸出:“We%20are%20happy.”。

使用 replace 函式,替換字元換即可:

s = 'We are happy.'
print(s.replace(' ', '%20'))
12

結果:

We%20are%20happy.

4. Python 如何列印 99 乘法表?

for 迴圈列印:

for i in range(1, 10):
for j in range(1, i+1):
print('{}x{}={}\t'.format(j, i, i*j), end='')
print()

while 迴圈實現:

i = 1
while i <= 9:
j = 1
while j <= i:
print("%d*%d=%-2d"%(i,j,i*j),end = ' ') # %d:整数的占位符,'-2'代表靠左对齐,两个占位符
j += 1
print()
i += 1

結果:

1x1=1 
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81

5. 從下標 0 開始索引,找出單詞 “welcome” 在字串“Hello, welcome to my world.” 中出現的位置,找不到返回 -1。


def test():
message = 'Hello, welcome to my world.'
world = 'welcome'
if world in message:
return message.find(world)
else:
return -1

print(test())

結果:

7

6. 統計字串“Hello, welcome to my world.” 中字母 w 出現的次數。

def test():
message = 'Hello, welcome to my world.'
# 計數
num = 0
# for 迴圈 message
for i in message:
# 判斷如果 ‘w’ 字串在 message 中,則 num +1
if 'w' in i:
num += 1
return num

print(test())
# 結果
2

7. 輸入一個字串 str,輸出第 m 個只出現過 n 次的字元,如在字串 gbgkkdehh 中,找出第 2 個只出現 1 次的字元,輸出結果:d


def test(str_test, num, counts):
"""
:param str_test: 字串
:param num: 字串出現的次數
:param count: 字串第幾次出現的次數
:return:
"""
# 定義一個空陣列,存放邏輯處理後的資料
list = []

# for迴圈字串的資料
for i in str_test:
# 使用 count 函式,統計出所有字串出現的次數
count = str_test.count(i, 0, len(str_test))
# 判斷字串出現的次數與設定的counts的次數相同,則將資料存放在list陣列中
if count == num:
list.append(i)

# 返回第n次出現的字串
return list[counts-1]

print(test('gbgkkdehh', 1, 2))
結果:
d

8. 判斷字串 a = “welcome to my world” 是否包含單詞 b = “world”,包含返回 True,不包含返回 False。

def test():
message = 'welcome to my world'
world = 'world'
if world in message:
return True
return False

print(test())

結果:
True

9. 從 0 開始計數,輸出指定字串 A = “hello” 在字串 B = “hi how are you hello world, hello yoyo!”中第一次出現的位置,如果 B 中不包含 A,則輸出 -1。


def test():
message = 'hi how are you hello world, hello yoyo!'
world = 'hello'
return message.find(world)

print(test())

结果:
15

10. 從 0 開始計數,輸出指定字串 A = “hello”在字串 B = “hi how are you hello world, hello yoyo!”中最後出現的位置,如果 B 中不包含 A,則輸出 -1。

def test(string, str):
# 定義 last_position 初始值為 -1
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position

print(test('hi how are you hello world, hello yoyo!', 'hello'))

結果:
28

11. 給定一個數 a,判斷一個數字是否為奇數或偶數。

while True:
try:
# 判斷輸入是否為整數
num = int(input('輸入一個整數:'))
# 不是純數字需要重新輸入
except ValueError:
print("輸入的不是整數!")
continue
if num % 2 == 0:
print('偶數')
else:
print('奇數')
break

結果:
輸入一個整數:100
偶數

12. 輸入一個姓名,判斷是否姓王。

def test():
user_input = input("請輸入您的姓名:")

if user_input[0] == '王':
return "使用者姓王"

return "使用者不姓王"

print(test())

結果:
請輸入您的姓名:王總
使用者姓王

13. 如何判斷一個字串是不是純數字組成?

利用 Python 提供的型別轉行,將使用者輸入的資料轉換成浮點數型別,如果轉換拋異常,則判斷數字不是純數字組成。

def test(num):
try:
return float(num)
except ValueError:
return "請輸入數字"

print(test('133w3'))

14. 將字串 a = “This is string example….wow!” 全部轉成大寫,字串 b = “Welcome To My World” 全部轉成小寫。


a = 'This is string example….wow!'
b = 'Welcome To My World'

print(a.upper())
print(b.lower())

15. 將字串 a = “ welcome to my world ”首尾空格去掉。

Python 提供了strip() 方法,可以去除首尾空格,rstrip() 去掉尾部空格,lstrip() 去掉首部空格,replace(“ “, “”) 去掉全部空格。


a = ' welcome to my world '
print(a.strip())

還可以透過遞迴的方式實現:

def trim(s):
flag = 0
if s[:1]==' ':
s = s[1:]
flag = 1
if s[-1:] == ' ':
s = s[:-1]
flag = 1
if flag==1:
return trim(s)
else:
return s
print(trim(' Hello world! '))

透過 while 迴圈實現:

def trim(s):
while(True):
flag = 0
if s[:1]==' ':
s = s[1:]
flag = 1
if s[-1:] == ' ':
s = s[:-1]
flag = 1
if flag==0:
break
return s
print(trim(' Hello world! '))

16. 將字串 s = “ajldjlajfdljfddd”,去重並從小到大排序輸出”adfjl”。

def test():
s = 'ajldjlajfdljfddd'
# 定義一個數組存放資料
str_list = []
# for迴圈s字串中的資料,然後將資料加入陣列中
for i in s:
# 判斷如果陣列中已經存在這個字串,則將字串移除,加入新的字串
if i in str_list:
str_list.remove(i)

str_list.append(i)
# 使用 sorted 方法,對字母進行排序
a = sorted(str_list)
# sorted方法返回的是一個列表,這邊將列表資料轉換成字串
return "".join(a)

print(test())

結果:
adfjl

17. 打印出如下圖案(菱形):


def test():
n = 8
for i in range(-int(n/2), int(n/2) + 1):
print(" "*abs(i), "*"*abs(n-abs(i)*2))

print(test())

結果:
**
****
******
********
******
****
**

18. 給一個不多於 5 位的正整數(如 a = 12346),求它是幾位數和逆序打印出各位數字。

class Test:

# 計算數字的位數
def test_num(self, num):
try:
# 定義一個 length 的變數,來計算數字的長度
length = 0
while num != 0:
# 判斷當 num 不為 0 的時候,則每次都除以10取整
length += 1
num = int(num) // 10
if length > 5:
return "請輸入正確的數字"
return length
except ValueError:
return "請輸入正確的數字"

# 逆序打印出個位數
def test_sorted(self, num):
if self.test_num(num) != "請輸入正確的數字":
# 逆序打印出數字
sorted_num = num[::-1]
# 返回逆序的個位數
return sorted_num[-1]

print(Test().test_sorted('12346'))

結果:
1

19. 如果一個 3 位數等於其各位數字的立方和,則稱這個數為水仙花數。例如:153 = 13 + 53 + 33,因此 153 就是一個水仙花數。那麼如何求 1000 以內的水仙花數(3 位數)。

def test():
for num in range(100, 1000):
i = num // 100
j = num // 10 % 10
k = num % 10
if i ** 3 + j ** 3 + k ** 3 == num:
print(str(num) + "是水仙花數")
test()
20. 求 1+2+3…+100 相加的和。
i = 1
for j in range(101):
i = j + i

print(i)

結果:
5051

20. 計算 1–2+3–4+5-…-100 的值。

def test(sum_to):
# 定義一個初始值
sum_all = 0
# 迴圈想要計算的資料
for i in range(1, sum_to + 1):
sum_all += i * (-1) ** (1 + i)
return sum_all

if __name__ == '__main__':
result = test(sum_to=100)
print(result)

-50

21. 現有計算公式 13 + 23 + 33 + 43 + …….+ n3,如何實現:當輸入 n = 5 時,輸出 225(對應的公式 : 13 + 23 + 33 + 43 + 53 = 225)。

def test(n):
sum = 0
for i in range(1, n+1):
sum += i*10+i
return sum
print(test(5))
結果:
225

22.已知a的值為“hello”,b的值為“world”,如何交換a和b的值,得到a的值為“world”,b的值為“hello”?

a = 'hello'
b = 'world'

c = a
a = b
b = c
print(a, b)

23. 如何判斷一個數組是對稱陣列?

例如 [1,2,0,2,1],[1,2,3,3,2,1],這樣的陣列都是對稱陣列。用 Python 判斷,是對稱陣列列印 True,不是列印 False。

def test():
x = [1, 'a', 0, '2', 0, 'a', 1]
# 透過下標的形式,將字串逆序進行比對
if x == x[::-1]:
return True
return False

print(test())

結果:
True

24. 如果有一個列表 a = [1,3,5,7,11],那麼如何讓它反轉成 [11,7,5,3,1],並且取到奇數位值的數字 [1,5,11]?

def test():
a = [1, 3, 5, 7, 11]
# 逆序列印陣列中的資料
print(a[::-1])
# 定義一個計數的變數
count = 0
for i in a:
# 判斷每迴圈列表中的一個數據,則計數器中會 +1
count += 1
# 如果計數器為奇數,則打印出來
if count % 2 != 0:
print(i)

test()

結果:
[11, 7, 5, 3, 1]
1
5
11

25. 對列表 a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] 中的數字從小到大排序。

a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
print(sorted(a))

結果:
[1, 1, 6, 6, 7, 8, 8, 8, 8, 9, 11]
27. 找出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大值和最小值。
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
print(max(L1))
print(min(L1))

結果:
88
1

上面是透過 Python 自帶的函式實現,如下,可以自己寫一個計算程式:

class Test(object):

def __init__(self):
# 測試的列表資料
self.L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]

# 從列表中取第一個值,對於資料大小比對
self.num = self.L1[0]

def test_small_num(self, count):
"""
:param count: count為 1,則表示計算最大值,為 2 時,表示最小值
:return:
"""
# for 迴圈查詢列表中的資料
for i in self.L1:
if count == 1:
# 迴圈判斷當陣列中的資料比初始值小,則將初始值替換
if i > self.num:
self.num = i

elif count == 2:
if i < self.num:
self.num = i

elif count != 1 or count != 2:
return "請輸入正確的資料"

return self.num

print(Test().test_small_num(1))
print(Test().test_small_num(2))
結果:
88
1

26. 找出列表 a = [“hello”, “world”, “yoyo”, “congratulations”] 中單詞最長的一個。

def test():
a = ["hello", "world", "yoyo", "congratulations"]

# 統計陣列中第一個值的長度
length = len(a[0])

for i in a:
# 迴圈陣列中的資料,當陣列中的資料比初始值length中的值長,則替換掉length的預設值
if len(i) > length:
length = i
return length

print(test())

結果:
congratulations

27. 取出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大的三個值。

def test():
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
return sorted(L1)[:3]

print(test())

結果:
[1, 2, 2]

28. 把列表 a = [1, -6, 2, -5, 9, 4, 20, -3] 中的數字絕對值。

deftest():
a = [1, -6, 2, -5, 9, 4, 20, -3]
# 定義一個數組,存放處理後的絕對值資料
lists = []
for i in a:
# 使用 abs() 方法處理絕對值
lists.append(abs(i))
return lists

print(test())

結果:
[1, 6, 2, 5, 9, 4, 20, 3]

文章來源:可以叫我才哥
原文連結:https://mp.weixin.qq.com/s/TgMFEnu0msrYaXyY7m_KOw

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

我是「數據分析那些事」。常年分享數據分析乾貨,不定期分享好用的職場技能工具。各位也可以關注我的Facebook,按讚我的臉書並私訊「10」,送你十週入門數據分析電子書唷!期待你與我互動起來~

文章推薦

餅圖變形記,肝了3000字,收藏就是學會!

MySQL必須掌握4種語言!

太實用了!4種方法教你輕鬆製作互動式儀表板!

跟資料打交道的人都得會的這8種資料模型,滿足工作中95%的需求

妙呀!一行Python程式碼

回顧十週入門數據分析系列文:

關注數據君的臉書:

我是「數據分析那些事」。常年分享數據分析乾貨,不定期分享好用的職場技能工具。按贊我的臉書,會有豐富資料包贈送唷!

--

--

數據分析那些事
數據分析那些事

Written by 數據分析那些事

這是一個專注於數據分析職場的內容部落格,聚焦一批數據分析愛好者,在這裡,我會分享數據分析相關知識點推送、(工具/書籍)等推薦、職場心得、熱點資訊剖析以及資源大盤點,希望同樣熱愛數據的我們一同進步! 臉書會有更多互動喔:https://www.facebook.com/shujvfenxi/

No responses yet