【问题标题】:Recursively Checking for List Uniqueness in Python在 Python 中递归检查列表的唯一性
【发布时间】:2014-10-23 21:50:00
【问题描述】:

我有一个包含 100 个数字的列表,我正在尝试编写一个函数来确定所有数字是否都是唯一的(它们应该是唯一的)。我的函数是unique(lst),它需要一个列表作为输入,如果我的列表中的所有数字都是唯一的,它应该返回 True。 Oh and False 否则,一个例子:

>>> unique([1, 2, 3])
True

>>> unique([2, 4, 3, 4])
False

到目前为止我写了这个:

def unique(lst):
    if len(lst) == 1:
        return True
    else:
        if lst[0] in lst[1:]:
            return False
        if lst[1] in unique(lst[2:-1]):
            return False
        else:
            return True 

我无法递归检查 lst[0] 之后的数字是否唯一。谁能告诉我如何编辑我的代码以便正确检查?

【问题讨论】:

  • unique() 返回一个布尔值,所以 lst[1] in unique(...) 不起作用。为什么递归时忽略最后一项?
  • “已关闭主题已关闭”?如果你想删除你的问题,有更好的方法来做到这一点。但总的来说,如果问题是高质量且可回答的,则不应该被删除——StackOverflow 的重点是构建和维护一个通用的、可重用的知识库,其他人可以搜索和学习来自。
  • 另请注意,服务条款规定,在 StackOverflow 上发布内容意味着该网站获得了该内容的永久许可。请参阅meta.stackoverflow.com/questions/274757/… 了解有关删除数据的指南的讨论;一般而言,规则是只有在"没有任何持久价值"的情况下才应删除问题。也就是说,这些问题通常是最初不应该在这里提出的问题。 :)
  • 你想要这种递归方法有什么原因吗?更清晰、更高效的方法是只循环列表一次并使用set 来跟踪已经看到的值。

标签: python list recursion unique


【解决方案1】:

这个怎么样?

def unique(lst):
    if len(lst) == 1:
        return True
    else:
        currentElement = lst[0]
        remaining = lst[1:]
        elementIsUnique = currentElement not in remaining
        recursive = unique(remaining)
        return elementIsUnique and recursive

>>> unique([1, 2, 3])
True

>>> unique([2, 4, 3, 4])
False

【讨论】:

  • 我不确定我是否理解您的问题,您希望我将else 的案例分解成几行,然后逐步进行吗?
  • 好的,我把它分成几个步骤,希望更清楚。
  • 是的,elementIsUnique 将是 bool。并且recursive 将不断调用unique 直到它最终达到1 的长度,除非elementIsUnique 曾经变为False,否则它会提前返回。你不能说return elemtIsunique and return recursive,因为你只能在一个函数中return 1次,这样写是无效的语法。
【解决方案2】:

你只需要在列表中递归移动,你不需要返回一个布尔值:

def unique(lst):
    if len(lst) == 1: # if a single element left, list has unique elements
        return True
    elif lst[0] in lst[1:]: # check if current element is in the remainder of the list
            return False
    else:
        return unique(lst[1:]) # move to next element

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多