简体   繁体   中英

Code to check for symmetry fails some test cases

I am running into trouble trying to get this piece of code to run for all cases:

def symmetric(p):
    """ returns true if list is symmetric"""
    if p==[]:return True
    n=len(p)
    m=len(p[0])
    if m !=n:
        return False
    i=0
    j=0
    t=False
    while i < n:
        while j < n:
            if not p[i][j]==p[j][i]:
                return False
            j=j+1
        i=i+1
    return True

When I run this, it passes for some cases. I can't seem to see what I am doing wrong.

I'd expect [['algebra', 'combinatorics', 'graphs'], ['combinatorics', 'topology', 'sets'], ['graphs', 'topology', 'sets']] to return False but it doesn't.

The break statement only ends the inner while loop.

Since you already found an asymmetry, just use return:

i, j = 0
while i < n:
    while j < n:
        if not p[i][j] == p[j][i]:
            return False
        j += 1
    i += 1
return True

However, you are not comparing each row with each column at the same index here; because you never reset j back to 0, after the first while j < n loop you'll have j == n and you skip all the remaining loops.

Set j = 0 inside the first while :

i = 0
while i < n:
    j = 0
    while j < n:
        if not p[i][j] == p[j][i]:
            return False
        j += 1
    i += 1
return True

Better still, use for loops over range() :

for i in range(n):
    for j in range(n):
        if not p[i][j] == p[j][i]:
            return False
return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM