Python all possible tuples from list
I'll bet Trying to "pull out all the stops" for speed, maybe something like:
though minor tweaks might still accelerate it (needs thorough profiling with realistic sample data!). Here's your example of use:
which emits the results: View Discussion Improve Article Save Article View Discussion Improve Article Save Article Sometimes, while working with Python tuples, we might have a problem in which we need to generate all possible combination pairs till N. This can have application in mathematics domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + Python3
Output :
Method #2 : Using Python3
Output :
Given a list, the task is to write a python program that can split it into all possible tuple pairs combinations. Input : test_list = [4, 7, 5, 1, 9] Output : [[4, 7, 5, 1, 9], [4, 7, 5, (1, 9)], [4, 7, (5, 1), 9], [4, 7, (5, 9), 1], [4, (7, 5), 1, 9], [4, (7, 5), (1, 9)], [4, (7, 1), 5, 9], [4, (7, 1), (5, 9)], [4, (7, 9), 5, 1], [4, (7, 9), (5, 1)], [(4, 7), 5, 1, 9], [(4, 7), 5, (1, 9)], [(4, 7), (5, 1), 9], [(4, 7), (5, 9), 1], [(4, 5), 7, 1, 9], [(4, 5), 7, (1, 9)], [(4, 5), (7, 1), 9], [(4, 5), (7, 9), 1], [(4, 1), 7, 5, 9], [(4, 1), 7, (5, 9)], [(4, 1), (7, 5), 9], [(4, 1), (7, 9), 5], [(4, 9), 7, 5, 1], [(4, 9), 7, (5, 1)], [(4, 9), (7, 5), 1], [(4, 9), (7, 1), 5]] Explanation : All pairs partitions are formed. Input : test_list = [4, 7, 5, 1] Output : [[4, 7, 5, 1], [4, 7, (5, 1)], [4, (7, 5), 1], [4, (7, 1), 5], [(4, 7), 5, 1], [(4, 7), (5, 1)], [(4, 5), 7, 1], [(4, 5), (7, 1)], [(4, 1), 7, 5], [(4, 1), (7, 5)]] Explanation : All pairs partitions are formed. In this, we perform all pair creation from 1st element, and using recursion multiple elements are converted into pairs by appropriate partitioning. The original list is : [4, 7, 5, 1] Created partitions : [[4, 7, 5, 1], [4, 7, (5, 1)], [4, (7, 5), 1], [4, (7, 1), 5], [(4, 7), 5, 1], [(4, 7), (5, 1)], [(4, 5), 7, 1], [(4, 5), (7, 1)], [(4, 1), 7, 5], [(4, 1), (7, 5)]] |