鱼C论坛

 找回密码
 立即注册
查看: 2264|回复: 2

[已解决]codewars 基础题

[复制链接]
发表于 2018-3-3 12:24:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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
  1. array_diff([1,2],[1]) == [2]
复制代码

if a value is present in b ,all of its occurances must be removed from the other:
  1. array_diff([1,2,2,2,3],[2]) == [1,3]
复制代码


Solution1(正常)
  1. def array_diff(a, b):
  2.     #your code here
  3.     c  = []
  4.     for each in a:
  5.         if each not in b:
  6.             c.append(each)
  7.     return c
复制代码

Solution2(有点问题)
  1. def array_diff(a, b):
  2.     #your code here
  3.     for each in a:
  4.         if each  in b:
  5.             a.remove(each)
  6.     return a
复制代码

Errors: 当a是【1,2,2】,b是【2】时得出的结果是【1,2】,但应该是【1】
搞不懂其中的问题 为什么仅仅remove掉一个2?
最佳答案
2018-3-3 12:35:53
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删除位置前移了,尽量不要在循环中
做修改变量的方法,容易出现逻辑问题
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-3-3 12:35:53 | 显示全部楼层    本楼为最佳答案   
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删除位置前移了,尽量不要在循环中
做修改变量的方法,容易出现逻辑问题
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-3-3 12:39:34 | 显示全部楼层
塔利班 发表于 2018-3-3 12:35
def array_diff(a, b):
    #your code here
    counter=0

谢谢大佬 明白了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-26 11:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表