I am trying to connect values in tuples in a list without using a dictionary. Specifically, I have this list:
adjList = [('0', '3'), ('1', '0'), ('3', '2'), ('4', '2'), ('5', '4'), ('7', '9'),
('8', '7'), ('9', '6'), ('2', '1'), ('2', '6'), ('6', '5'), ('6', '8')]
and I would like to create a list with the values from a random tuple:
newList = ['1', '0']
then append the second value of a tuple from adjList if the first value of that tuple is the same as the last value of newList, thus:
newList = ['1', '0', '3']
Then delete ('1', '0') and ('0', '3') from adjList.
THEN I want to repeat this action until the last value in newList NO LONGER corresponds to the first value of a tuple from adjList. I am having a lot of trouble figuring out a logical combination of while or for loops that can do this, and any help would be appreciated.
My code so far:
adjList = [('0', '3'), ('1', '0'), ('3', '2'), ('4', '2'), ('5', '4'), ('7', '9'),
('8', '7'), ('9', '6'), ('2', '1'), ('2', '6'), ('6', '5'), ('6', '8')]
firstNode = random.choice(adjList)
newList = []
newList.append(firstNode[0])
newList.append(firstNode[1])
adjList.remove(firstNode)
## I need to repeat the following block of code:
for ax,bx in adjList:
if newList[-1] == ax:
adjList.remove((ax,bx))
newList.append(bx)
break
Everything works the way it should, but of course I am only getting 3 values in newList at the end. I can't quite work out how to repeat that final block of code until I run out of tuples in adjList.
Thanks in advance for any help.
You could just run the outer while loop while there are items still on the adjList. The inner loop could pick the first suitable item from adjList and append the result to newList. In case the inner loop can't find suitable item the outer loop should be terminated.
Here's a sample of the above:
import random
adjList = [('0', '3'), ('1', '0'), ('3', '2'), ('4', '2'), ('5', '4'), ('7', '9'),
('8', '7'), ('9', '6'), ('2', '1'), ('2', '6'), ('6', '5'), ('6', '8')]
newList = list(adjList.pop(random.randint(0, len(adjList) - 1)))
while adjList:
for i, (src, dest) in enumerate(adjList):
if src == newList[-1]:
del adjList[i]
newList.append(dest)
break
else:
break
print('Result: {}'.format(newList))
print('Remaining: {}'.format(adjList))
Output:
Result: ['4', '2', '1', '0', '3', '2', '6', '5', '4']
Remaining: [('7', '9'), ('8', '7'), ('9', '6'), ('6', '8')]
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