1
\$\begingroup\$

Given an array of ints as input:

  • non_unique([1, 2, 3, 1, 3]) returns [1, 3, 1, 3]
  • non_unique([1, 2, 3, 4, 5]) returns []
  • non_unique([5, 5, 5, 5, 5]) returns [5,5,5,5,5]
  • non_unique([10, 9, 10, 10, 9, 8]) returns [10, 9, 10, 10, 9]

The code itself:

def checkio(originalList: list) -> list:

    checked_list = []
    result_list = []

    for i, number in enumerate(originalList):
        if number in checked_list:
            result_list.append(number)
        else:
            if (len(originalList) - 1) - i > 0:
                if number in originalList[i+1:]:
                    result_list.append(number)
        checked_list.append(number)

    return result_list

How can be the code improved?

\$\endgroup\$
4
\$\begingroup\$

One thing to keep in mind is your variable checked_list, which serves almost no purpose in the function, as you could do without the else block.

The simplest thing I can think of would be just to shorten the function down to one list comprehension, instead of appending to two lists.

Revised code:

def checkio(original_list: list) -> list:
    return [x for x in original_list if original_list.count(x) > 1]

When running this function, these are the outputs:

checkio([1, 2, 3, 1, 3])  # Returns [1, 3, 1, 3]
checkio([1, 2, 3, 4, 5])  # Returns []
checkio([5, 5, 5, 5, 5])  # Returns [5,5,5,5,5]
checkio([10, 9, 10, 10, 9, 8])  # Returns [10, 9, 10, 10, 9]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.