1
def number_of_cases(list_data):
    result = []

    for i in list_data:
        for j in list_data:
            result.append(str(i) + str(j))

    return result

print(number_of_cases(['a', 'b', '1', '2']))

Whatever I input as the list_data argument, I want to get a deduplicated list of number of cases. But when the argument is ['a', 'a'], I get ['aa', 'aa', 'aa', 'aa'], not ['aa']. How do I remove duplicated elements in a list while preserving their order using list_data.count() (because this is homework)?

martineau
  • 119,623
  • 25
  • 170
  • 301
Titus Yun
  • 33
  • 5

1 Answers1

1

This seems to work. Note I added a dedup keyword argument with a default value of True only to make testing easy (feel free to remove it).

The tricky part is it needs to go through the elements in result backwards, so the indexes of elements it hasn't looked at yet don't change each time one is deleted.

Another way to think about is, by going backwards through the initial result, if it sees something that occurs more than once, it can assume there's another one occurring earlier in the list and can safely delete the current one.

def number_of_cases(list_data, dedup=True):
    result = []

    for i in list_data:
        for j in list_data:
            result.append(str(i) + str(j))

    if dedup:
        # remove duplicates
        for i in range(len(result)-1, 0, -1):
            if result.count(result[i]) > 1:
                del result[i]

    return result

print(number_of_cases(['a', 'a', 'b'], dedup=False))
print(number_of_cases(['a', 'a', 'b']))  # will dedup by default

Output:

['aa', 'aa', 'ab', 'aa', 'aa', 'ab', 'ba', 'ba', 'bb']
['aa', 'ab', 'ba', 'bb']
martineau
  • 119,623
  • 25
  • 170
  • 301