简体   繁体   中英

Main loop with if statement not working properly

Code:

def nChar(nc):
    grid = len(nc)
    chars = set()
    for line in nc:
        line = set(line)
        if len(line) != grid or len(chars) != grid:
            return False
    return True

Whats wrong? when I open a file which looks like

ABC
BCA
CAB

It should be fine as it is anxn square (gridValidation) and there are exactly n different characters (nChar - problem in code).

for gridValidation I am using

except ValueError: print("error")

and that works fine.

For nChar I am using:

if not nChar(latinsq):
    print ("File does not have n different characters.")
    break
else:
    continue

If I enter filename example: ABC it keeps repeating "Enter filename". It has to do with the def nChar or the way I am using it in the main loop.

an example of one file without nxn:

ABC
BCA
CAB
D

example file which does not have n different characters.

ABD
BCA
CAB

^has 4 different characters, but its 3x3.

I hope someone can explain what I am doing wrong so I can learn what I am doing wrong and also fix the problem.

ty.

EDIT: I read through my post and it doesn't make sense.

The problem is that when I execute the code and enter the filename, it keeps saying "Enter Filename".

Your first problem is that you say else: continue with your if not nChar(latinsq): block. If you get to that point, either the square is wrong and you break, or the square is right and you don't. You should change the if block to use continue , and remove the else block all together. Your second problem is that nChar() is not returning the right thing. It is always checking if the number of unique characters in the line is more than the number of lines, but you don't see if the total number of characters is too many. You can check it all like this:

def nChar(nc):
    grid = len(nc)
    chars = set()
    for line in nc:
        line = set(line)
        chars = chars.union(line)
        if len(line) != grid or len(chars) != grid:
            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