python練手題目 Python練手題目(七)

2021-10-13 02:00:16 字數 1362 閱讀 1746

1. 計算重複字母出現的次數

編寫乙個函式,該函式將返回在輸入字串**現多次(不同的不區分大小寫的)字母字元和數字的計數。可以假定輸入字串僅包含字母(大寫和小寫)和數字。

例如: "abcde" -> 0 # no characters repeats more than once

"aabbcde" -> 2 # 'a' and 'b'

"aabbcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `b`)

"indivisibility" -> 1 # 'i' occurs six times

"indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice

"aa11" -> 2 # 'a' and '1'

"abba" -> 2 # 'a' and 'b' each occur twice

首先可以利用python的collection包下counter的類

這個方法可以統計出每個元素出現的次數,**如下:

def duplicate_count(text):

from collections import counter

result = counter(text)

return result

print(duplicate_count('aa11'))

其次,可以把輸入的字串全部變成小寫(大寫),然後用if判斷語句進行計數統計,**如下:

def duplicate_count(text):

text = text.lower()

counts = 0

for i in set(text):

if text.count(i) >= 2:

counts += 1

return counts

print(duplicate_count('aa11'))

2. 把0挪到隊尾

編寫乙個演算法,該演算法採用陣列並將所有零移動到最後,保留其他元素的順序。 例如: move_zeros([false,1,0,1,2,0,1,3,"a"]) # returns[false,1,1,2,1,3,"a",0,0]

大家可以試試這個題目,很有意思的。

我是這樣考慮的,對元組中的元素進行判斷,然後用乙個迴圈,刪掉乙個0,就在元組末尾補乙個0,就可以達到題目要求,**如下:

def move_zeros(array):

for i in array:

if i ==0 and str(i) != 'false':

array.remove(0)

return array

3.程式設計技巧

Python練手專案0011

敏感詞文字檔案 filtered words.txt,裡面的內容為以下內容,當使用者輸入敏感詞語時,則列印出 freedom,否則列印出 human rights。coding utf 8 created on thu jan 12 13 55 35 2017 author sky def tran...

Python練手程式 02

2 使用 列印直角三角形 3 使用 列印乙個倒三角形,要求倒三角形是等邊三角形。並且行數由使用者輸入 guess num 98 while true print please input a number num input ifnot num.isdigit print 請輸入乙個整數!conti...

Python練手程式 03

1 有四個數字 1 2 3 4,能組成多少個互不相同且無重複數字的三位數?各是多少?total 0 for i in range 1,5 for j in range 1,5 for k in range 1,5 if i j and i k and j k print i,j,k total 1 ...