So I am trying to distribute a String over a tuple. For example:
x = ["a", ("b", ("c", "d"))]
Then after I would like to have
x = ["a", ("bc", "bd")]
And then finally:
x = ["abc", "abd"]
However the tuple does not always have to be the second element: For example:
x = [(("c", "d"), "b"), "a"]
Would simplify to:
x = [("cb", "db"), "a"]
And finally:
x = ["cba", "dba"]
I am wondering how I would go about writing a single function to simplify the first expression directly to the last.
What i've tried so far is:
def distribute(x):
if isinstance(x, list) and any([True if isinstance(o, tuple) else False for o in x]):
if isinstance(x[0], tuple):
return (x[0][0] + x[1], x[0][1] + x[1])
else:
return (x[0] + x[1][0], x[0] + x[1][1])
print (distribute(["a", ("b", "c")]))
Final Edit: Editted Oscars code to work for my second example:
def dist(tpl):
if not isinstance(tpl[1], tuple) and not isinstance(tpl[0], tuple):
return tpl
if isinstance(tpl[1], tuple):
ret = dist(tpl[1])
return [tpl[0] + ret[0], tpl[0] + ret[1]]
elif isinstance(tpl[0], tuple):
ret = dist(tpl[0])
return [ret[0] + tpl[1], ret[1] + tpl[1]]
Thanks for the help!
Try this, it's a recursive solution that works for both examples in the question, under the assumption that both elements in a tuple are never going to be tuples at the same time.
def dist(tpl):
if not isinstance(tpl[0], tuple) and not isinstance(tpl[1], tuple):
return tpl
elif isinstance(tpl[0], tuple):
ret = dist(tpl[0])
return [ret[0] + tpl[1], ret[1] + tpl[1]]
else:
ret = dist(tpl[1])
return [tpl[0] + ret[0], tpl[0] + ret[1]]
It works as expected:
dist(["a", ("b", ("c", "d"))])
=> ['abc', 'abd']
dist([(("c", "d"), "b"), "a"])
=> ['cba', 'dba']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With