简体   繁体   中英

Python Lo Shu Magic

I am trying to test a Lo Shu Magic Square function, but I am running into a few problems. One of the problems is that I am getting an error message that says TypeError: 'int' object is not iterable, but I do not see what I am doing wrong. Secondly is there a better more efficient way to write this code to check if the lo_shu_square variable is a Lo Shu Magic Square? I am a newb to Python but it just seems inefficient.

ROWS = 3
COLUMNS = 3

def magic():
    lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
    for r in range (ROWS):
        for c in range (COLUMNS):
            if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
                if sum(r)== sum(r[c] for r in lo_shu_square):
                    answer_output = str('a Lo Shu Magic Square')
            else:
                answer_output = str('not a Lo Shu Magic Square')

    print("The inputs are", answer_output)

magic()

The error message:

if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
TypeError: 'int' object is not iterable
#print out our list in the shape of a square
for row in Square:
    print(row)


def LoShu(List2d):
      if isinstance(List2d,list) and len(List2d)==3:
        List1d-sum(List2d,[])
        print(List1d)
        if max(Listd) >=10 or min(List1d) <=0:
            print("out of range, check if you list has a value greater than 9 or less than 0")
            return False
        if len(List1d) != len(set(List1d)):
            print("check your list there are duplicate values")
            return False
        if len(List1d) != len(set(List1d)):
            print("check your list there are duplicate values")
            return False
        

Thanks @Arman. It was a simple fix.

COLUMNS = 3

def magic():
    lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
    for r in lo_shu_square:
        for c in range (COLUMNS):
            if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
                if sum(r)== sum(r[c] for r in lo_shu_square):
                    answer_output = str('a Lo Shu Magic Square')
            else:
                answer_output = str('not a Lo Shu Magic Square')

    print("The inputs are", answer_output)

magic()

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