Skip to content
Advertisement

Need to add an element to a set and I need the resulting set to be returned

I see that the ‘+’ operation is not supported in sets but supported for lists

[1, 2, 3] + [4]  # Works

{1, 2, 3} + {4}  # Error

If I add an element to set using .add() func it modifies the original set but doesn’t return the result instead returns None type object. I don’t want to modify the original set but I just need the resultant set.

For context I was writing a func to print permutations of a string, but this func does not work if the string has duplicate chars

def my_func1(s, temp, i, n):

    if i == n:
        print(temp)
    
    for x in range(n):
        if s[x] not in temp:
            my_func1(s, temp + s[x], i+1, n)
    
string = 'abcd'
my_func1(string, '', 0, len(string))

In order to make this string work for duplicate chars I thought of using a set containing indexes of element and when I add a char to the final string (temp) I add the index so that now I can treat each duplicate char as unique

def my_func2(s, temp, i, n, hash):

    if i == n:
        print(temp)
        return
    
    for x in range(n):
        if x not in hash:
            my_func2(s, temp + s[x], i+1, n, hash = hash + x) # Throws error as cannot + op not supported in set

string = 'abcd'
my_func2(string, '', 0, len(string), {})

I cannot use hash.add(x) and pass hash as arg because it alters the state of the hash for other function calls in the program’s recursion stack

I wrote code to support duplicate chars with using list to check for duplicates but I want to use set instead (performance reason)

def my_func3(s, temp, i, n, hash): #Works for dup s but uses list as hash

    if i == n:
        print(temp)
        return
    
    for x in range(n):
        if x not in hash:
            my_func2(s, temp + s[x], i+1, n, hash + [x])

string = 'abcd'
my_func2(string, '', 0, len(string), [])

Advertisement

Answer

welcome to Python

In python, type({}) is ‘dict’, however type({x1, x2, …, x_n}) is ‘set’.

I suppose what you want is a set(to remove duplicated values).

Here are two mistakes you made:

  1. You should use ‘set()’ to initialize a set instead of ‘{}’
  2. You should use ‘|’ to insert a value to set instead of ‘+’

Below is code modified:

def my_func2(s, temp, i, n, hash):

    if i == n:
        print(temp)
        return
    
    for x in range(n):
        if x not in hash:
            my_func2(s, temp + s[x], i+1, n, hash = hash | {x}) # modify '+' to '|'

string = 'abcd'

my_func2(string, '', 0, len(string), set()) # init with 'set()' instead of '{}'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement