我必须做一个任务,我们需要检查一个符号是否是一个有效的符号(通过任务的规则)
我可能无法解释的任务的背景信息:
作业提供的示例:
def isvalid(symbol, element, length = None):
elbool = False
if symbol[0]!=symbol[0].upper():
return False #first letter in the symbol has to be a capital letter
for i in range(len(symbol)-1):
if element.find(symbol[i+1])>element.find(symbol[i]): #checking if the order is correct
elbool = True
else:
return False
if length is not None:
if len(symbol)!=length:
return False
else:
elbool = True
return elbool
现在是我的代码,但它不工作,例如这个:isvalid('Rcm','Americium'),因为在 c 之前有一个 m,它计算那个。
所以我想我需要从符号中的最后一个字母拆分元素字符串,所以我没有这个问题,但是我该怎么做呢?
对不起,如果这个问题有点混乱。
您需要使用.find(needle, start_pos)
在element
中的某个位置之后查找字符。此外,您不需要弄乱索引并继续从symbol
中查找上一个和当前字符。只需跟踪下一次迭代的当前字符位置即可。
您还应该进行不区分大小写的搜索,因为,使用您的示例,"Americium"
中没有"R"
。我通过将element
转换为小写一次,然后对symbol
中的每个字符执行.find(c.lower(), ...)
最后,您忘了检查symbol
中第一个字符以外的所有字符都是小写的。
element = element.lower() # Lowercase element so that we can find characters correctly
lastfound = 0
for ix, c in enumerate(symbol):
if ix > 0 and c.isupper():
# Not the first character, and is uppercase
return False
thisfound = element.find(c.lower(), lastfound) # Find the location of this character
if thisfound == -1: # character not found in element after location lastfound
return False
lastfound = thisfound # Set lastfound for the next iteration
其他一些小建议:
你可以return False
只要你发现有问题,然后,在函数的末尾,只需return True
,因为你到达终点的唯一方法是什么都没有错。
您可以使用symbol[0].islower()
检查字符是否为小写。无需执行symbol[0] != symbol[0].upper()
。
在检查字符顺序之前,您应该检查长度要求,因为这是更简单的检查。
应用所有这些:
def isvalid(symbol, element, length = None):
if symbol[0].islower():
return False
if length is not None and len(symbol) != length:
return False
element = element.lower() # Lowercase element so that we can find characters correctly
lastfound = 0
for ix, c in enumerate(symbol):
if ix > 0 and c.isupper():
return False
thisfound = element.find(c.lower(), lastfound) # Find the location of this character
if thisfound == -1: # character not found in element after location lastfound
return False
lastfound = thisfound # Set lastfound for the next iteration
return True
使用您的测试:
>> isvalid('Zer', 'Zeddemorium')
True
>> isvalid('Zer', 'Zeddemorium', 2)
False
>> isvalid('di', 'Zeddemorium')
False
>> isvalid('Rcm', 'Americium')
True
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(14条)