python列表的索引算法_Python-确定列表是否对称的算法
因此,我被困在這個問題上,我被要求在Python中編寫一個函數,以檢查n維數組(是否稱為它們)是否“對稱”,即該行數組的1 ==第1列,第2行==第2列,第3行==第3列,依此類推.目標是要有一個函數,如果它是對稱的,則返回布爾值True,否則返回False.
我設法編寫了一個有效的函數,但它僅適用于大小為完美正方形(例如2 x 2、4 x 4)的列表,并且我的一些測試用例的大小為“不規則”(例如2 x 5、3 x 2).對于那些列表,我最終得到列表索引超出范圍錯誤代碼,這里:
def symmetric(square):
final_result = []
x = 0
y = 0
while x < len(square):
row_list = []
col_list = []
while y < len(square[x]):
print "(x, y): %d, %d" % (x, y)
print "(y, x): %d, %d" % (y, x)
row_list.append(square[x][y])
col_list.append(square[y][x])
y = y + 1
if row_list == col_list:
final_result.append(True)
else:
final_result.append(False)
x = x + 1
for x in final_result:
if x == False:
return False
return True
我在這里失敗的測試用例:
print symmetric([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]])
#Expected result: >>> False
#List index out of range
# This one actually returns the correct result, I'm just including it here
# for reference.
#print symmetric([["cat", "dog", "fish"],
# ["dog", "dog", "fish"],
# ["fish", "fish", "cat"]])
#Expected result: >>> True
#Actual result: >>> True
print symmetric([[1,2,3],
[2,3,1]])
#Expected Result: >>> False
#Actual result: list index out of range
有人可以幫助我修改代碼,使其在這些“形狀不規則”的數組上工作嗎?
總結
以上是生活随笔為你收集整理的python列表的索引算法_Python-确定列表是否对称的算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 酷狗大字版怎么显示歌词
- 下一篇: 中国农业银行股票代码