def shortenPlus(s):
# Yer Code 'Ere Mate!
# Aye Aye cap'
new = ''
prior = ''
for x in s:
if not (x in 'aeiou' and prior.isalpha()):
new += x
prior = x
return new
print(shortenPlus("I've information vegetable, animal and mineral"))
这是我从this线程中找到的代码。我很难理解for循环的“if not”部分是如何工作的,以及为什么我们有新的和先前的语句
我知道我们从字符串中获取一个变量,如果这个变量不在“aeiou”中,并且之前的容器没有字母表中的任何内容,那么您可以将这个变量添加到新的。但是如果previor是I,x是v,它不满足previor的标准,但是它仍然将它添加到new中
到目前为止,我就是这样理解的。请让我知道我的误解
让我们扩展一下
if not(x in 'aeiou' and prior.isalpha()): ...
到
为了清楚起见。现在,
inner
将为真当且仅当两个条件都为真时:x
是元音如果这些中的或不是真的,那么
inner
将是假的。因此,最初的测试:not(x in 'aeiou' and prior.isalpha())
否定这一点,如果这两个条件都满足,则将为False。如果其中一个(或两个!)未满足,则它将为True,并且将计算If语句。因此,如果满足以下条件,将对if语句进行评估:
x
是不是的值你有点逻辑上的误解。代码指定
NOT (A AND B)
;这相当于NOT A OR NOT B
。换言之:那么,继续假设,如果
prior
是I
,而x
是v
,那么:x in 'aeiou'
为假prior.isalpha()
是真的因此:
x in 'aeiou' and prior.isalpha()
为假因此:
not(x in 'aeiou' and prior.isalpha())
是真的李>new
和prior
是变量,而不是语句。代码使用new
构建一个新字符串,使用prior
存储for循环上一次迭代中的字符你对逻辑的理解不太正确。如果两个{}和{}的计算结果都为false,则执行{}行,这(perDe Morgan's theorem)相当于说,如果或者{}或者{}(或者两者兼而有之),则执行{}行
因此,代码将向字符串添加一个字符,只要它不是元音,或前一个字符不是字母,或两者都不是
相关问题 更多 >
编程相关推荐