[英]Python: if item in list evaluates False even though the item exists
I was trying to solve this Question in HackerRank. 我试图在HackerRank中解决此问题 。
#t=int(input().strip())
t=1
for i in range(0,t):
#u=input()
#pw=str(input()).split(' ')
#s=input().strip()
u=6
pw=['because', 'can','do', 'must', 'we', 'what']
s="wedowhatwemustbecausewecan"
pw_in_s=[]
for p in pw:
if p in s:
pw_in_s.append(p)
print(pw_in_s)
start=0
length=1
res=""
while start+length<=len(s):
tmp=s[start:start+length]
print (tmp)
if tmp in pw_in_s:
res+=" "+tmp
start=length
length=1
else:
length=length+1
print(res)
The code is not complete to solve the question. 代码不完整,无法解决问题。 But I'm stuck in halfway. 但是我陷入了困境。
Problem 问题
Even though the list pw_in_s
contains an item 'do'
, the if tmp in pw_in_s
is not getting satisfied when tmp
is 'do'
. 即使列表pw_in_s
包含项'do'
,当tmp
为'do'
时if tmp in pw_in_s
的if tmp in pw_in_s
也不会令人满意。 Also the program runs into an infinite loop, because length
value is not getting incremented. 另外,由于length
值没有增加,程序也会进入无限循环。
Where is the problem? 问题出在哪儿?
Even though the list pw_in_s contains an item 'do' the if tmp in pw_in_s is not getting satisfied when tmp is 'do'. 即使列表pw_in_s包含项“ do”,但当tmp为“ do”时,如果pw_in_s中的tmp不满意。
I can't reproduce that problem. 我无法重现该问题。
Also the program is in an infinite loop. 而且程序处于无限循环中。
That happens in the code path for if tmp in pw_in_s:
which doesn't necessarily make progress toward the termination condition on each iteration. 对于if tmp in pw_in_s:
这发生在代码路径中,这不一定会使每次迭代的终止条件都取得进展。 Setting start=length
and length=1
doesn't get you closer to making start+length
bigger than len(s)
. 设置start=length
和length=1
并不能使start+length
大于len(s)
。
For debugging, change print (tmp)
to print(start, length, len(s), tmp, pw_in_s, (tmp in pw_in_s))
. 要进行调试, print(start, length, len(s), tmp, pw_in_s, (tmp in pw_in_s))
print (tmp)
更改为print(start, length, len(s), tmp, pw_in_s, (tmp in pw_in_s))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.