Python | Join cycle in list
Sometimes, while dealing with graph problems in competitive programming, we have a list of pairs and we need to find if there is a possible cycle in it, and print all the elements in that cycle. Let’s discuss certain way in which this problem can be tackled.
Method : Using yield + loop + generator
The brute method to perform is to use a generator and keep printing the value if we know that the elements surely form a cycle and this is done by infinite loop and stopping when no more matches are found.
# Python3 code to demonstrate working of # Join cycle in list # Using yield + loop + generator # helper function to perform this task def cycle(test_list, val, stop = None): temp = dict(test_list) stop = stop if stop is not None else val while True: yield (val) val = temp.get(val, stop) if val == stop: break # initializing list test_list = [[6, 7], [9, 6], [7, 9]] # printing original list print("The original list is : " + str(test_list)) # Join cycle in list # Using yield + loop + generator # printing result print("The cycle elements are : ") for ele in cycle(test_list, 6): print(ele) |
The original list is : [[6, 7], [9, 6], [7, 9]] The cycle elements are : 6 7 9
Recommended Posts:
- Python | Pandas str.join() to join string/list elements with passed delimiter
- Python | Join tuple elements in a list
- Python | Ways to join pair of elements in list
- Python | Custom Cycle list
- join() function in Python
- Python | os.path.join() method
- Python program to split and join a string
- Python | Merge, Join and Concatenate DataFrames using Panda
- Python Program for Cycle Sort
- Python Program for Detect Cycle in a Directed Graph
- Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of string into sorted list of integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



