每天一習題,提升Python不是問題!!有更簡潔的寫法請評論告知我!
https://www.cnblogs.com/poloyy/category/1676599.html
題目
要求:判斷數組元素是否對稱。例如[1,2,0,2,1],[1,2,3,3,2,1]這樣的都是對稱數組 用Python代碼判斷,是對稱數組打印True,不是打印False,如: x = [1, "a", 0, "2", 0, "a", 1]
解題思路
- 循環取值,循環次數只需要列表長度的一半
- 每次取頭尾對稱下標的值比較
答案
a, b, c = [1, 2, 0, 2, 1], [1, 2, 3, 3, 2, 1], [1, 2, 3, 4, 5] def duicheng(lists): lens = len(lists) flag = True for i in range(0, int(lens / 2)): if lists[i] != lists[lens - 1 - i]: flag = False break print(flag) duicheng(a) duicheng(b) duicheng(c)