JohnPaul
JohnPaul

Reputation: 394

Python SET FUNCTIONS with TUPLES

The code below works, although I need the same functionality but instead of using sets I need to use tuples. Can anyone help?

word = {'h','e','l','l','o'}
letters = {'a','b','c','l','h'}
remainder = word - letters
print (remainder)

Thanks for taking to time to read this.

Upvotes: 0

Views: 69

Answers (1)

Rory Daulton
Rory Daulton

Reputation: 22544

Since tuples do not have a subtraction operator, you can use a generator expression that is quickly converted to a tuple. This code constructs a tuple from the values inside word but leaves out the values that are also in letters. One advantage of this over using sets is that the items are guaranteed to retain their order in word. The main disadvantage is that it is much slower for large tuples/sets, having time complexity O(n**2) rather than that of the sets solution which is O(n) (if both tuples/sets are of size n). One more thing to note is that this code retains any duplicate values that are in word but not in letters while the set solution removes duplicates--this may be a good or a bad thing, depending.

word = ('h','e','l','l','o')
letters = ('a','b','c','l','h')
remainder = tuple(v for v in word if v not in letters)
print(remainder)

Upvotes: 3

Related Questions