Python入門100道習題(7)——找對稱數
阿新 • • 發佈:2019-01-10
問題描述
【問題描述】已知10個四位數輸出所有對稱數及個數 n,例如1221、2332都是對稱數
【輸入形式】10個整數,以空格分隔開
【輸出形式】輸入的整數中的所有對稱數,對稱數個數
【樣例輸入】1221 2243 2332 1435 1236 5623 4321 4356 6754 3234
【樣例輸出】1221 2332 2
【樣例說明】為測試程式健壯性,輸入數中可能包括3位數、5位數等
不考慮3位數、5位數的情形
#n是對稱的四位數嗎
def is_duicheng(n):
n_str = str(n)
return n_str[0] == n_str[3 ] and n_str[1] == n_str[2]
# if n_str[0] == n_str[3] and n_str[1] == n_str[2]:
# return True
# else:
# return False
#讀入10個整數
line = input().split()
nums = []
for s in line:
nums.append(int(s))
#print("nums=", nums)
duicheng_list = []
for n in nums:
if is_duicheng(n):
duicheng_list.append(n)
for d in duicheng_list:
print(d, end=' ')
print(len(duicheng_list))
對上述程式碼,說明如下:
1. 第2到8行定義了判別一個整數是否是對稱數的函式is_duicheng。函式是一組語句的集合。第19行呼叫了is_duicheng函式,傳入要被判別的整數n。呼叫函式,就會執行函式包含的語句。第19行的n是實際引數,而第2行的n是形式引數,兩者的名字可以不同。
2. 我們把4位數轉換為字串,然後比對第1,4位是否相同,第2,3位是否相同,都相同的話,就是對稱的。
3. 第10到14行,輸入10個整數。第15行,是列印這10個整數,幫助我們判斷輸入動作對了沒有。
4. 第17行,duicheng_list變數用來儲存對稱的四位數。第18到20行求出所有對稱的四位數。
5. 第22,23行,輸出所有。這樣,輸出d的值後,在其尾部接一個空格,且不換行。第24行,輸出對稱數的個數,也就是duicheng_list的長度。它會接在前面的輸出內容尾部。
考慮3位數、5位數的情形
在上一節的程式碼基礎上,增加下面所列的第4,5行,就實現了考慮3位數,5位數的情形。
#n是對稱的四位數嗎
def is_duicheng(n):
n_str = str(n)
if len(n_str) != 4:
return False
return n_str[0] == n_str[3] and n_str[1] == n_str[2]
# if n_str[0] == n_str[3] and n_str[1] == n_str[2]:
# return True
# else:
# return False
#讀入10個整數
line = input().split()
nums = []
for s in line:
nums.append(int(s))
#print("nums=", nums)
duicheng_list = []
for n in nums:
if is_duicheng(n):
duicheng_list.append(n)
for d in duicheng_list:
print(d, end=' ')
print(len(duicheng_list))
小結
- 判斷對稱數的做法是,把4位數轉換為字串,然後比對第1,4位是否相同,第2,3位是否相同,都相同的話,就是對稱的。
- 用函式來定義判斷對稱數的邏輯,是好做法。