[英]Python Check for exact amount of characters
My current function checks if there is at least a certain amount of characters ie If I have a 3x3 square grid, it will check if there is 3 characters or more but I want to modify the code to check if its EXACTLY 3 characters not more.我当前的函数检查是否至少有一定数量的字符,即如果我有一个 3x3 方形网格,它会检查是否有 3 个或更多字符,但我想修改代码以检查它是否正好是 3 个字符。
def double(char):
rows = len(char)
for row in char:
if (len(set(row)) != rows):
return False
return True
It's different to when i check for a square grid:这与我检查方形网格时不同:
def square(sq):
rows = len(sq)
for row in sq:
if (len(row) != rows):
return False
return True
In my main code;在我的主要代码中; i raise the exception and call the error:我引发异常并调用错误:
if not double(d):
raise ValueError
break
except ValueError:
if not square(d):
print("The format is incorrect; Has to be in a n x n square format")
elif not double(d):
print("The grid does not contain exactly n amount of characters")
The names of your variables are confusing, for example the variable char
represents a square_grid
, the function called double
checks for a 3x3 grid.变量的名称令人困惑,例如变量char
表示一个square_grid
,该函数称为对 3x3 网格进行double
检查。
sg1 = ['ABC','DEF','GHI']
sg2 = ['WXYZ','AEIOUY']
sg3 = ['ABV','CAB','BCA']
sg4 = ['ABC','CAB','BCA']
def verify3x3( square_grid ):
nb_rows = 0
for row in square_grid:
if len(row) != 3:
return False
nb_rows += 1
return (nb_rows == 3)
print verify3x3(sg1)
print verify3x3(sg2)
print verify3x3(sg3)
print verify3x3(sg4)
With python2, this prints使用 python2,这会打印
True
False
True
True
EDIT: If you want to count distinct characters, and verify how many there are:编辑:如果你想计算不同的字符,并验证有多少:
def verify_3distinct_chars( square_grid ):
chars_list = []
for row in square_grid:
for c in row:
if c not in chars_list:
chars_list.append(c)
return len(chars_list) == 3
print verify_3distinct_chars( sg1 )
print verify_3distinct_chars( sg2 )
print verify_3distinct_chars( sg3 )
print verify_3distinct_chars( sg4 )
With python2, this prints使用 python2,这会打印
False
False
False
True
Nb you could write this much shorter, but I detailed the logic steps.注意你可以写得更短,但我详细说明了逻辑步骤。
Hope this helps:希望这可以帮助:
def double(char):
for row in char:
if len(char) != 3 or len(row) != 3:
return False
else:
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.