Reputation: 141
I'm with a python problem, I'm new on this and wanting to know what I'm missing.
The thing I want to do is to print a nested tuple, but from inside to outside.
As an example: ('C', ('B', ('A', ())))
should be printed as null, A, B, C
All tuples maximum size is 2.
I was thinking on using a recursive function in order to do that; I have this code, but I don't know what's wrong.
def tuplePrint(t):
if len(t) > 1:
return(tuplePrint(t[1])
else:
return t[0]
x = ('E', ('B', ('A', ())))
print(tuplePrint(x))
I'm not asking for the answer for the problem (that would be great), but if only you could tell me what's wrong with the code I'd be grateful.
Anyone? any ideas?
Thanks!
Upvotes: 0
Views: 108
Reputation: 453
return
statement on line 3 should not have a (
before the contents of the return
.len(t) <= 1
), should return the string "null"
or a single-element list ["null"]
.return tuplePrint(t[1])
) has to also incorporate the current element, so you probably want either tuplePrint(t[1]) + [t[0]]
or tuplePrint(t[1]) + " " + t[0]
."null A B E"
or a list like [null, A, B, E]
, you want to print it comma-separated by joining the list: ", ".join(tuplePrint(x))
(in the string case, you should call split()
on the string returned by tuplePrint(x)
.Resulting in:
def tuplePrint(t):
if len(t) > 1:
return tuplePrint(t[1]) + [t[0]]
else:
return ["null"]
x = ('E', ('B', ('A', ())))
print(", ".join(tuplePrint(x)))
# null, A, B, E
Upvotes: 1
Reputation: 7797
def tuple_print(t):
x, xs = t
v = 'null'
if len(xs):
v = tuple_print(xs)
return ', '.join((v, x))
Upvotes: 1
Reputation: 179
this may work for you
def tuplePrint(t):
if not t:
answer.insert(0, "null")
for each in t:
if isinstance(each, tuple):
tuplePrint(each)
else:
answer.insert(0, each)
x = ('E', ('B', ('A', ())))
answer = []
tuplePrint(x)
print(answer)
Upvotes: 0