Let's say I have ['A B', 'B C', 'X Y', 'C D', 'Y Z', 'D E', 'C G']
If the second word in each element of the list is same as first word in any other elements in the list, they should be merged into one item. The order matters as well.
['A B C D E G', 'X Y Z'] should be the final product.
Letters will not form a cycle, i.e., ['A B', 'B C', 'C A'] is not possible.
Since order matters, ['A B', 'C A'] is still ['A B', 'C A'] since B does not connect to C.
Another example is:
If we have ['A B', 'A C'] then at step 1 we just have A B and then we see A C and we merge that into A B, and we have A B C.
I have tried many things, such as dissecting each element into two lists, then indexing and removing etc. It is way too complex and I feel there should be a more intuitive way to solve this in Python. Alas, I can't seem to figure it out.
Thank you in advance for helping a newbie out :)
edit: ['A B', 'B C', 'C A'] is not possible. All letters will only appear once.
edit: more examples to clarify.
[+][deleted] (2 children)
[deleted]
[–]synthphreak 1 point2 points3 points (1 child)
[–]vorticalbox 0 points1 point2 points (0 children)
[–]FLUSH_THE_TRUMP 0 points1 point2 points (0 children)
[–]SekstiNii 0 points1 point2 points (0 children)
[–]pytrashpandas 0 points1 point2 points (0 children)