17.4k views
1 vote
Implement the function unique that takes as a parameter a two-dimensional list and returns a one-dimensional list containing all the unique entries in the list. The entries in the list returned do not need to be ordered in any particular way. For example, in the list [[1, 0, 1], [0, 1, 0]] there are only two unique values (0 and 1) so the function would return the list [0, 1] (or the list [1, 0] -- both are valid). The list passed as a parameter should not be altered by the function

User Sarfaraz
by
6.1k points

1 Answer

3 votes

Answer:

#Method definition for the function unique()

#The method takes in one argument which is a two dimensional list

def unique (twoDList) :

#Create an empty one dimensional list

oneDList = [];

#Convert the two dimensional list to a one dimensional list by

#looping through the two dimensional list and putting each element in

# the one dimensional list using the python in-built append() function

for i in range(len(twoDList)) :

for j in range(len(twoDList[i])) :

oneDList.append(twoDList[i][j])

#Convert the one dimensional list to a set to make the list unique

#by using the python in-built set() function

mySet = set(oneDList)

#Convert the unique list back to a list

uniqueList = list(mySet)

#Return the unique list

return uniqueList

#End of method declaration

#Call the method with an arbitrary two dimensional list, and print the result

print(unique([[3,5,3],[4,6,3],[1,7,8]]))

print(unique([[1, 0, 1], [0, 1, 0]]))

Output

=================================================================

[1, 3, 4, 5, 6, 7, 8]

[0,1]

================================================================

Step-by-step explanation:

The above code has been written in Python. It contains comments explaining each line of the code. Please go through the comment. The actual code has been written in bold-face to differentiate it from comments. Note that in Python, indentation really matters. Therefore, the code must be written with the appropriate indentations like those shown in the code above.

For clarity, the code is re-written as follows without comments.

def unique (twoDList) :

oneDList = [];

for i in range(len(twoDList)) :

for j in range(len(twoDList[i])) :

oneDList.append(twoDList[i][j])

mySet = set(oneDList)

uniqueList = list(mySet)

return uniqueList

print(unique([[3,5,3],[4,6,3],[1,7,8]]))

print(unique([[1, 0, 1], [0, 1, 0]]))

User Peter Henell
by
5.1k points