Output Set And Its Contents In Python?
I am merely wanting to output the contents of a set (because I have to use this cursed and inflexible type), but every time I go to do it or loop through and print each element, I
Solution 1:
Your powerset
function actually alters its input. In combinations
, you use s.pop()
. That's almost certainly wrong, and would explain why its contents have changed when you try to print it.
The simplest fix is to replace your powerset
function with the recipe from the itertools
documentation:
http://docs.python.org/2/library/itertools.html#recipes
from itertools import chain, combinations
defpowerset(input_set):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(input_set)
return chain.from_iterable(combinations(s, r) for r inrange(len(s)+1))
Solution 2:
Change the top of your combinations definition to the following:
defcombinations(r, tokens):
s = set(r)
# everything else you had
This creates a new set which will not be altered in the combinations function. The reason it was being altered before is because the local variable in combinations was a reference to the same object outside the function. If two names reference the same object, mutating one will affect the other.
In main you want the following:
for (i, item) in enumerate(s):
msg += str(item) + ", "
msg = msg[:-2]
msg += "])"
Post a Comment for "Output Set And Its Contents In Python?"