0

I have a Python Task for online course on Udacity although I put the right code for the task it still gives me that is wrong answer. Can any one tell me why?? You are required to complete the function unique_list(l). where "l" is a list of numbers. the function is expected to return the unique numbers in that list.

Example:

input : [1,1,1,2,2,3,3,3,3,4,5,5,6]

output: [1,2,3,4,5,6]

no_list=[22,22,2,1,11,11,3,3,3,4,5,5,5,55,55,66]

def unique_list(l):

    l = list(set(no_list))

    l.sort()

    return l

print(unique_list(no_list))

l = list(set(no_list))
l.sort()
return l

this part is my answer the other is from udacity site

Community
  • 1
  • 1
Israa
  • 11
  • 1
  • Your posted code is not valid Python. You have indentation errors and a `return` outside of a function. – Prune Aug 31 '19 at 00:05
  • Possible duplicate of [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – Lord Elrond Aug 31 '19 at 01:40

4 Answers4

1

Your function should make use of the argument l instead of using the global variable no_list:

def unique_list(l):
    l = list(set(l))
    l.sort()
    return l
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

First, as @blhsing had already noted, you're manipulating the global variable, not the one passed to the function. Still, I think that your code may be suffering from another problem, which is your assumption that all lists that are being passed to your function are sorted, some of them may not be sorted, but when you sort them, you're losing the original order, and I'm guessing that one of the problem requirements is maintaining the order of the elements in the original list, and to do that in Python, you could sort using the index as a key:

def unique_list(l):
    return sorted(set(l), key = l.index)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Using `list(dict.fromkeys(l))` is a better choice in Python version >= 3.6 when the order needs to be maintained. Every `l.index` call is O(n) so `sorted(set(l), key = l.index)` is basically O(n^2logn) which is undesirable for large lists. – GZ0 Aug 31 '19 at 00:59
0

If you are allowed to use package, you can use numpy which can come handy.

Using numpy it can be done as :

import numpy as np
def unique_list(l):
  return np.unique(np.array(l))

If you want to return list, you can simply:

import numpy as np
def unique_list(l):
  return list(np.unique(np.array(l)))
Milan Lamsal
  • 11
  • 2
  • 3
0

Use this code, They want a certain order

no_list = [22,22,2,1,11,11,2,2,3,3,3,4,5,5,5,55,55,66]


def unique_list(l):
    x = []
    for a in l:
        if a not in x:
            x.append(a)
    return x


print(unique_list(no_list))