How to accept a list as input?

Asked

Viewed 2,087 times

0

This is an exercise of a USP course. I will post the statement and the code to make the doubt clear.

Write the remove_repeated function that takes as a parameter a list of integer numbers, checks whether such a list has repeated elements and removes them. The function should return a list corresponding to the first list, without repeating elements. The returned list should be sorted.

My code:

def remove_repetidos(x):
    c = 0

    x.sort()

    while c < len(x)-1:
        if x[c] == x[c+1]:
            del x[c]
        else:
            c = c+1
    return x


x = input("Digite sua lista:")

lista = remove_repetidos(x)

print (lista)

I know the code isn’t optimized. But the question is, how to adapt the function so that it receives several lists as input?

For example, the user wants to run the code and enter any list and return a list with the repeated numbers removed?

Abs,

1 answer

2

When you take data via input( ) Python presumes to be a string. To turn into "list," actually array, circumvent the function input( ) with eval( ), already placed the brackets, and type the values separated by comma:

x = eval('[' + input("Digite sua lista: ") + ']')

Example:

>>> Digite sua lista: 4, 4, 8, 6, 7, 9, 9
>>> [4, 6, 7, 8, 9]

At the same time you will be on the margin of all possible errors if the user enters an improper value such as a string in one of the indexes, for example [3, 4, 'a', 3], on account of the function sort( ).

  • is it possible to make this read stop without the numbers being separated by commas? for example 12345

Browser other questions tagged

You are not signed in. Login or sign up in order to post.