Python program to find all the Combinations in a list with the given condition

PythonServer Side ProgrammingProgramming

When it is required to find all the combinations in a list with a specific condition, a simple iteration, the ‘isinstance’ method, the ‘append’ method and indexing are used.

Example

Below is a demonstration of the same −

print("Method definition begins")
def merge_the_vals(my_list_1, my_list_2, K):
   index_1 = 0
   index_2 = 0
   while(index_1 < len(my_list_1)):

      for i in range(K):
         yield my_list_1[index_1]
         index_1 += 1
      for i in range(K):
         yield my_list_2[index_2]
         index_2 += 1
print("Method definition ends")

my_list_1 = [12, 56, 14, 28, 61, 73, 59, 90]
my_list_2 = [52, 16, 17, 34, 43, 16, 84, 57]
print("The first list is : " )
print(my_list_1)

print("The second list is : " )
print(my_list_2)

K = 1
print("The value of K is ")
print(K)
my_result = [element for element in merge_the_vals(my_list_1, my_list_2, K)]

print("The resultant list is : ")
print(my_result)

print("The list after sorting is : " )
my_result.sort()
print(my_result)

Output

Method definition begins
Method definition ends
The first list is :
[12, 56, 14, 28, 61, 73, 59, 90]
The second list is :
[52, 16, 17, 34, 43, 16, 84, 57]
The value of K is
2
The resultant list is :
[12, 56, 52, 16, 14, 28, 17, 34, 61, 73, 43, 16, 59, 90, 84, 57]
The list after sorting is :
[12, 14, 16, 16, 17, 28, 34, 43, 52, 56, 57, 59, 61, 73, 84, 90]

Explanation

  • A method is defined that takes two lists and a value of K as a parameter.

  • Depending on the value of index and length of list, the ‘yield’ operator is used to give result.

  • Outside the method, two lists of integers are defined and are displayed on the console.

  • The value for K is defined and displayed in the console.

  • A list comprehension is used, the method is called by passing the required parameters.

  • This is assigned to a result.

  • This is displayed as output on the console.

  • The result is sorted using a sort method and is displayed on the console.

raja
Published on 13-Sep-2021 10:35:10
Advertisements