0

Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.

So for python I was thinking of using OOP and using an iterator.

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

This is what I was thinking I'm not sure though.

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

     def __iter__(self):
           return self

     def __next__(self):

I'm not sure what do for the next function of this though. I'm also curious to see how to create a function that does the same method as above but in scheme. Thanks in advance for any comments or help.

d'chang
  • 191
  • 2
  • 2
  • 11

4 Answers4

1

Probably the most straight forward way to do this is using Python's set builtin.

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
chucksmash
  • 5,777
  • 1
  • 32
  • 41
1

In scheme, using a union function like that defined for instance in How to write a scheme function that takes two lists and returns four lists , you could write something like this:

(define (unique lists)
  (if (null lists)
      '()
      (union (unique (cdr lists)) (car lists))))
Community
  • 1
  • 1
Renzo
  • 26,848
  • 5
  • 49
  • 61
0

Not necessary but you wanted to make classes.

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()
Vivek Anand
  • 621
  • 1
  • 7
  • 15
0

Here is a solution in Racket:

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

An explanation:

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

The function list->set turns a list into a set.

If we want a list of the elements rather than a set, we can use set->list to convert the set back to a list.

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

A general function can thus be defined as:

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

Let's test it:

> (unique '(1 1 1 2 2 4 8 2))
'(8 4 2 1)
soegaard
  • 30,661
  • 4
  • 57
  • 106