|
3 | 3 |
|
4 | 4 | def combination_util(arr, n, r, index, data, i):
|
5 | 5 | """
|
6 |
| - Current combination is ready to be printed, print it |
7 |
| - arr[] ---> Input Array |
8 |
| - data[] ---> Temporary array to store current combination |
9 |
| - start & end ---> Staring and Ending indexes in arr[] |
10 |
| - index ---> Current index in data[] |
11 |
| - r ---> Size of a combination to be printed |
| 6 | + Generate and print all combinations of 'r' elements from the input list 'arr'. |
| 7 | +
|
| 8 | + Args: |
| 9 | + arr (list): The input list from which combinations are generated. |
| 10 | + n (int): The total number of elements in the input list 'arr'. |
| 11 | + r (int): The size of the combinations to be generated. |
| 12 | + index (int): The current index in the 'data' array. |
| 13 | + data (list): Temporary array to store the current combination being generated. |
| 14 | + i (int): The current index in the input list 'arr'. |
| 15 | +
|
| 16 | + Returns: |
| 17 | + None: This function prints the combinations but does not return a value. |
| 18 | +
|
| 19 | + Examples: |
| 20 | + >>> arr = [1, 2, 3, 4] |
| 21 | + >>> n = len(arr) |
| 22 | + >>> r = 2 |
| 23 | + >>> data = [0] * r |
| 24 | + >>> combination_util(arr, n, r, 0, data, 0) |
| 25 | + 1 2 |
| 26 | + 1 3 |
| 27 | + 1 4 |
| 28 | + 2 3 |
| 29 | + 2 4 |
| 30 | + 3 4 |
12 | 31 | """
|
13 | 32 | if index == r:
|
14 | 33 | for j in range(r):
|
15 | 34 | print(data[j], end=" ")
|
16 | 35 | print(" ")
|
17 | 36 | return
|
18 |
| - # When no more elements are there to put in data[] |
19 | 37 | if i >= n:
|
20 | 38 | return
|
21 |
| - # current is included, put next at next location |
22 | 39 | data[index] = arr[i]
|
23 | 40 | combination_util(arr, n, r, index + 1, data, i + 1)
|
24 |
| - # current is excluded, replace it with |
25 |
| - # next (Note that i+1 is passed, but |
26 |
| - # index is not changed) |
27 | 41 | combination_util(arr, n, r, index, data, i + 1)
|
28 |
| - # The main function that prints all combinations |
29 |
| - # of size r in arr[] of size n. This function |
30 |
| - # mainly uses combinationUtil() |
| 42 | + |
31 | 43 |
|
32 | 44 |
|
33 | 45 | def print_combination(arr, n, r):
|
34 |
| - # A temporary array to store all combination one by one |
35 | 46 | data = [0] * r
|
36 |
| - # Print all combination using temporary array 'data[]' |
37 | 47 | combination_util(arr, n, r, 0, data, 0)
|
38 | 48 |
|
39 | 49 |
|
40 | 50 | if __name__ == "__main__":
|
41 |
| - # Driver code to check the function above |
42 |
| - arr = [10, 20, 30, 40, 50] |
43 |
| - print_combination(arr, len(arr), 3) |
44 |
| - # This code is contributed by Ambuj sahu |
| 51 | + import doctest |
| 52 | + |
| 53 | + doctest.testmod() |
0 commit comments