Scheme 和 Python 的唯一函数迭代器

Unique Function Iterator for Scheme and Python

您好,我目前正在尝试复习我课程中的一些 material,但我很难想出一个我们将调用 'unique' 的函数,它只生成一个列表一组列表中的唯一数字。

所以对于 python,我正在考虑使用 OOP 和迭代器。

 >>> You have a list (1, 3, 3, 3, 5)
 Return the list (1, 3, 5)

这就是我的想法,但我不确定。

Class Unique:
     def __init__(self, s):
           self.s = iter(s)

     def __iter__(self):
           return self

     def __next__(self):

虽然我不确定它的下一个功能是什么。我也很想知道如何创建一个与上面的方法相同但在 scheme 中的函数。在此先感谢您的任何评论或帮助。

可能最直接的方法是使用 Python 的 set 内置函数。

def unique(*args):
    result = set()  # A set guarantees the uniqueness of elements
    result = result.union(*args)  # Include elements from all args
    result = list(result)  # Convert the set object to a list
    return result

没有必要,但你想类。

class Unique:
    def __init__(self):
        self._list = self.user_input()

    def user_input(self):
        _list = raw_input()
        _list = _list.split(' ')
        [int(i) for i in _list]
        return _list

    def get_unique(self):
        self._set = set(self._list)
        return list(self._set)

obj = Unique()
print obj.get_unique()

在方案中,使用 union 函数,例如在 How to write a scheme function that takes two lists and returns four lists 中定义的函数,您可以这样写:

(define (unique lists)
  (if (null lists)
      '()
      (union (unique (cdr lists)) (car lists))))

这里是 Racket 中的一个解决方案:

(define (unique xs) (set->list (list->set xs)))

一个解释:

> (list->set '(1 2 2 4 7))
(set 1 2 4 7)

函数 list->set 将列表转换为集合。

如果我们想要一个元素列表而不是一个集合,我们可以使用 set->list 将集合转换回列表。

> (set->list (list->set '(1 2 2 4 7)))
'(7 4 2 1)

一般函数可以定义为:

 > (define (unique xs) (set->list (list->set xs)))

我们来测试一下:

> (unique '(1 1 1 2 2 4 8 2))
'(8 4 2 1)