TAGS :Viewed: 5 - Published at: a few seconds ago
[ Python - Can't code iteration or recursion ]
I have this list and a start point as below:
lst = [[0, 1], [0, 4], [3, 4], [5, 1], [5, 2]]
point = 3
I want to write a function that gives me this list in return: [3,4,0,1,5,2]
. It takes start point, finds the pair containing the start point and takes its other half as the new start point.
Given list is an example, length of the list is not specified.
I tried to write a for
function but, since the length of the list is not constant, it doesn't give the correct output
What I tried:
def func(start,lst):
for i in range(len(lst)):
if lst[i][1]==start:
cont==lst[i][0]
lst2=lst.remove(lst[i])
if lst[i][0]==start:
cont==lst[i][1]
lst2=lst.remove(lst[i])
func(cont,lst2)
Answer 1
How about this (without using recursion):
def func(lst, start):
result = []
while True:
found = False
for item in lst:
if start in item:
item.remove(start)
result.append(start)
found = True
if item:
start = item[0]
item.remove(start)
break
if not found:
result.append(start)
break
return result
Usage:
>>> func([[0, 1], [0, 4], [3, 4], [5, 1], [5, 2]], 3)
[3, 4, 0, 1, 5, 2]
Answer 2
You need something like:
def func(start, lst, out=None):
if out is None: # create new output list on first call
out = []
out.append(start) # add the starting value
if len(lst) == 0: # base case
return out
for i in range(len(lst)):
if start in lst[i]: # find the node
item = lst.pop(i) # remove the node
next_ = item[0] if item[1] == start else item[1] # get next 'start'
return func(next_, lst, out) # recurse
I get:
>>> func(3, [[0, 1], [0, 4], [3, 4], [5, 1], [5, 2]])
[3, 4, 0, 1, 5, 2]