Python練習題6(判斷是否迴文聯):編寫一個函式,判斷傳入的字串引數是否為“迴文聯”(迴文聯即用迴文形式寫成的對聯,既可順讀,也可倒讀。例如:上海自來水來自海上)
阿新 • • 發佈:2019-01-10
方法一:將字串分成兩半,將第一個和最後一個字元進行比較,若一樣則返回True.全部為True則為迴文聯
1 def isPalindrome(): 2 context = input("請輸入字串:") 3 len_half = len(context) // 2 #取長度的一半 4 bool_list = [] 5 if len(context) < 2: #當輸入小於2個字元時,返回 6 return "%s 不是迴文聯" % context7 for n in range(len_half): 8 if context[n] == context[-(n+1)]: #第一個字元和最後一個字元比較,第二個和倒數第二個比較... 9 bool_con = True 10 bool_list.append(bool_con) 11 else: 12 bool_con = False 13 bool_list.append(bool_con) 14 if False not in bool_list: #列表中全是True則為迴文聯 15 return "'%s'是迴文聯" % context 16 else: 17 return "'%s'不是迴文聯" % context 18 19 print(isPalindrome())
方法二:將字串分成兩半,直接判斷前一字串和後半字串是否相同,若相同則為迴文聯。--by 孟楠兄
1 def isSymmetry(): 2 while True: 3 inStr = input("請輸入:").strip() 4 cut = len(inStr) // 2 5if inStr[:cut][::-1] == inStr[-cut:]: 6 print('迴文聯') 7 break 8 else: 9 print('非迴文聯') 10 11 isSymmetry()
方法三:直接翻轉,判斷是否相同,若相同則為迴文聯。--by 書明兄
1 def fu(): 2 lc = ''.join(list(reserved(ID))) 3 if lc == ld: 4 print("是迴文聯") 5 else: 6 print('非迴文聯') 7 8 ld = input("請輸入:") 9 fu()