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

JavaScript

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

JavaScript

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

JavaScript

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)

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement