0

I know there's library in python make it easier to produce all possible value. But i want to know the algorithm inside of it.

I expect a function that works like this

def listPossiblePair(length:int,possibleValue:set) -> list:

Consider possible value will show in my case is only 0 and 1.

If the length 3 then the function will return all possibile pair of that possible value

listPossiblePair(3,{0,1})

Will return

[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]

Here is another example

Another example:

listPossiblePair(2,{0,1,2})

Will return

[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
  • The Python itertools module is implemented in C. You can view the source code and therefore examine the underlying algorithms here:- https://github.com/python/cpython/blob/main/Modules/itertoolsmodule.c – DarkKnight Mar 29 '22 at 09:46
  • @ArthurKing Unless I misunderstand the question, I think it's `itertools.product` which is needed here, not `itertools.combinations`. – Stef Mar 29 '22 at 09:47
  • 1
    Note that `{0,1}` is not a `dict`, it is a `set`. – Stef Mar 29 '22 at 09:48

1 Answers1

1
# Python 3 program to print all
# possible strings of length k
     
# The method that prints all
# possible strings of length k.
# It is mainly a wrapper over
# recursive function printAllKLengthRec()
def printAllKLength(set, k):
 
    n = len(set)
    printAllKLengthRec(set, "", n, k)
 
# The main recursive method
# to print all possible
# strings of length k
def printAllKLengthRec(set, prefix, n, k):
     
    # Base case: k is 0,
    # print prefix
    if (k == 0) :
        print(prefix)
        return
 
    # One by one add all characters
    # from set and recursively
    # call for k equals to k-1
    for i in range(n):
 
        # Next character of input added
        newPrefix = prefix + set[i]
         
        # k is decreased, because
        # we have added a new character
        printAllKLengthRec(set, newPrefix, n, k - 1)
 
# Driver Code
if __name__ == "__main__":
     
    print("First Test")
    set1 = ['a', 'b']
    k = 3
    printAllKLength(set1, k)
     
    print("\nSecond Test")
    set2 = ['a', 'b', 'c', 'd']
    k = 1
    printAllKLength(set2, k)
 
# This code is contributed
# by ChitraNayal

Reference: https://www.geeksforgeeks.org/print-all-combinations-of-given-length/

Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84