'List all possible value algorithm with given length [duplicate]
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]]
Solution 1:[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/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tlaloc-ES |