我需要创建一个算法来读取列表A
和B
的用户输入,并确定列表B
中的元素是否出现在列表A
中(如果出现,程序需要打印“Yes”,否则打印“No”)。你知道吗
我提出了以下代码,可以作为一个起点:
n=int(input('Enter the length of list A '))
A=[]
for i in range (0,n):
InpEl=int(input('Enter the elements '))
A.append(InpEl)
print(A)
n=int(input('Enter the length of list B '))
B=[]
for i in range (0,n):
InpEl2=int(input('Enter the elements '))
B.append(InpEl2)
print(B)
checklist=B
for each in A:
if each in checklist:
print('YES')
else:
print('NO')
不管怎样,我都会说“不”。这里出了什么错?你知道吗
另外,稍后我可能需要修改列表,以便程序可以确定B
的元素是否按照它们在B
中出现的顺序出现在A
,但不一定是连续出现的。你知道吗
For example, let M be the length of B and N be the length of A.
Then the program should return yes if there are indices i0, i1...im+1 such that 0<= i0 < i1...< im-1 < N such that A[i0] = B[0];A[i1] = B[1]...A[im-1] =
B[m-1].
有没有更简单的方法来构建满足这种请求的循环?你知道吗
附言:是否可以让用户输入不仅读取整数,而且读取字符串?我不确定raw_input
在python3.5中是否有用。你知道吗
附言: 对不起,我在这里输入代码时犯了一个小错误,我现在已经改正了。 另一个问题:我得到每个元素的多个“是”和“否”的输出:
Enter the length of list A 3
Enter the elements 1
Enter the elements 2
Enter the elements 3
[1, 2, 3]
Enter the length of list B 3
Enter the elements 5
Enter the elements 4
Enter the elements 3
[5, 4, 3]
NO
NO
YES
如何修改代码,以便在发生任何错误时只打印一次“是”和“否”?你知道吗
你得到的一个武器是all操作符,它只检查iterable中的所有项是否为真:
输出:
为了获得顺序,您需要返回到一个迭代方法,使用循环遍历第一个列表,同时维护一个索引以知道您在第二个列表中的位置。对于第一个列表中的每个值,遍历第二个列表的rest,直到找到项目(临时成功)或到达末尾(失败)。你知道吗
读入数字名并将其转换为整数是一个单独的问题,而且代码较长。你知道吗
这里有一个解决方案。请记住,有很多人以前问过这类问题,最好的做法是在问之前四处搜索。你知道吗
最好将原始输入放在一起,并使用Python将其拆分为列表。这样,用户就不需要事先给出列表的长度。而且,不需要转换成
int
字符串比较也可以。你知道吗contained_in_b
使用列表理解-Python的一个便利特性,它将布尔值element in b
应用于a
中的每个element
。现在您有了一个真/假值列表,您可以通过它enumerate
打印出所需的输出。你知道吗相关问题 更多 >
编程相关推荐