|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目:
Your goal in this kata is to implement an difference function, which subtracts one list from another
it shoud remove all values from list a,which are present in list b
- array_diff([1,2],[1]) == [2]
复制代码
if a value is present in b ,all of its occurances must be removed from the other:
- array_diff([1,2,2,2,3],[2]) == [1,3]
复制代码
Solution1(正常)
- def array_diff(a, b):
- #your code here
- c = []
- for each in a:
- if each not in b:
- c.append(each)
- return c
复制代码
Solution2(有点问题)
- def array_diff(a, b):
- #your code here
- for each in a:
- if each in b:
- a.remove(each)
- return a
复制代码
Errors: 当a是【1,2,2】,b是【2】时得出的结果是【1,2】,但应该是【1】
搞不懂其中的问题 为什么仅仅remove掉一个2?
def array_diff(a, b):
#your code here
counter=0
for each in a:
if each in b:
a.remove(each)
counter+=1
print(a)
print(counter)
array_diff([1,2,2], [2])
你试试加了counter来指示就明白了,结果是counter=2,即删除了第一个2没动第二个2,为什么
元素少了,迭代对象不会再指到后边的2,第二个2因为第一个2删除位置前移了,尽量不要在循环中
做修改变量的方法,容易出现逻辑问题
|
|