简体   繁体   English

if语句无法正常工作的主循环

[英]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). 它应该没问题,因为它是焦平方(gridValidation)并且恰好有n个不同的字符(nChar - 代码中的问题)。

for gridValidation I am using 我正在使用gridValidation

except ValueError: print("error")

and that works fine. 这很好。

For nChar I am using: 对于我正在使用的nChar:

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". 如果我输入文件名示例:ABC它会不断重复“输入文件名”。 It has to do with the def nChar or the way I am using it in the main loop. 它与def nChar或我在主循环中使用它的方式有关。

an example of one file without nxn: 没有nxn的一个文件的示例:

ABC
BCA
CAB
D

example file which does not have n different characters. 示例文件没有n个不同的字符。

ABD
BCA
CAB

^has 4 different characters, but its 3x3. ^有4个不同的字符,但它的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. 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. 你的第一个问题是你说的else: continue你的if not nChar(latinsq):阻止。 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. 您应该更改if块以使用continue ,并一起删除else块。 Your second problem is that nChar() is not returning the right thing. 你的第二个问题是nChar()没有返回正确的东西。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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