Home > database >  Python list recursion instead of string
Python list recursion instead of string

Time:11-04

I'm trying to create a recursion that will iterate over a large list with many double values, and it will create a list with the unique values. I was able to do so with a simple for loop, but I'm trying to solve it through recursion.

I've managed to create a string with the unique values, but I cannot seem to understand how to create a list instead.

Of course I can join my string into a list, but I'm trying to create the list within the function.

thread_sold_split is my large list with double values. colors is the list I'm trying to create via recursion.

def distinct_colors(color_list):
    if not color_list:
        return color_list

    if not color_list[1:]:
        return color_list[0]

    dis_color = distinct_colors(color_list[1:])
    if color_list[0] in dis_color:
        return dis_color

    return color_list[0]   ' '   dis_color


print(colors := distinct_colors(thread_sold_split))

Also, I was told I can delete the second 'if' block, since I'm already checking the head of the list (the first value) at the third 'if' block, but when I'm commenting it out it stops working and returns an error.

The original list to get distinct values from

CodePudding user response:

Code

def distinct_colors(color_list, seen = None):
    '''
        Returns unique items of color_list
    '''
    if seen is None:
        seen = set()                          # keeps track of items we have seen
        
    if not color_list:                        # Base case (empty list)
        return color_list 
    
    # Split color list into first element and rest
    first, *rest = color_list
    
    if first in seen:
        return distinct_colors(rest, seen)      # already seen first element
    else:
        seen.add(first)                         # update items we have seen
        return [first]   distinct_colors(rest, seen)   # Add first element to recurse on rest of elements

Test

Test 1

print(distinct_colors(['r', 'r', 'b', 'g', 'g', 'g']))
Out: ['r', 'b', 'g']

Test 2

thread_sold_split = ['white', 'white', 'blue', 'white', 'blue', 'white', 
                     'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 
                     'yellow', 'blue', 'blue', 'purple', 'blue', 'white', 'white', 
                     'red', 'white', 'blue', 'red', 'blue', 'green', 'blue', 'green', 
                     'blue', 'red', 'green']
print(distinct_colors(thread_sold_split))
Out: ['white', 'blue', 'yellow', 'purple', 'red', 'green']
  • Related