How to output permuations of 0's and 1's of a given length recursively?
I am trying to print permutations of 0's and 1's recursively in Python.
I understand there is a permutations function in itertools, but was wondering how one could do it recursively, for e.g.
function name is print_01(k)
# ...
print(permutation)
# ...
...where k is the length of each permutation to be printed, so if you call it as print_01(2)
, the output would be something like this:
00
01
10
11
The output is always of length k.
How could I get this done recursively using print
?
python python-3.x recursion permutation
add a comment |
I am trying to print permutations of 0's and 1's recursively in Python.
I understand there is a permutations function in itertools, but was wondering how one could do it recursively, for e.g.
function name is print_01(k)
# ...
print(permutation)
# ...
...where k is the length of each permutation to be printed, so if you call it as print_01(2)
, the output would be something like this:
00
01
10
11
The output is always of length k.
How could I get this done recursively using print
?
python python-3.x recursion permutation
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52
add a comment |
I am trying to print permutations of 0's and 1's recursively in Python.
I understand there is a permutations function in itertools, but was wondering how one could do it recursively, for e.g.
function name is print_01(k)
# ...
print(permutation)
# ...
...where k is the length of each permutation to be printed, so if you call it as print_01(2)
, the output would be something like this:
00
01
10
11
The output is always of length k.
How could I get this done recursively using print
?
python python-3.x recursion permutation
I am trying to print permutations of 0's and 1's recursively in Python.
I understand there is a permutations function in itertools, but was wondering how one could do it recursively, for e.g.
function name is print_01(k)
# ...
print(permutation)
# ...
...where k is the length of each permutation to be printed, so if you call it as print_01(2)
, the output would be something like this:
00
01
10
11
The output is always of length k.
How could I get this done recursively using print
?
python python-3.x recursion permutation
python python-3.x recursion permutation
edited Nov 23 '18 at 20:18
trincot
124k1587121
124k1587121
asked Nov 19 '18 at 14:50
computerprogramcomputerprogram
31
31
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52
add a comment |
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52
add a comment |
5 Answers
5
active
oldest
votes
Without giving away the code, I'll attempt to give the hints needed for you to come up with the code.
The idea is to make the recursive call to add one more digit to an accumulated string, that initially is empty.
The so-called "base case" of the recursion is where the accumulated string has the desired length. This is where you would output it (or store it somewhere)
You'll need a loop to visit the two possible digits.
Let me know if this is enough for you to get going.
Spoiler alert (only look below after having tried):
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. Sodigit
will first be "0" and in the second (last) iteration it will be "1"
– trincot
Nov 19 '18 at 15:41
add a comment |
Here is an idea:
Instead of doing that recursively, use binary development of numbers:
def print_01(k):
end = 1<<k #this is the integer with binary developpement 1 followed by k zeros
for j in range(end): # iterate until end means getting all k - 0-1 combinations
comb = bin(j)[2:].zfill(k)
print [int(x) for x in comb]
add a comment |
Do you really need to permute ... ?
If not try below
def print_01(length):
for i in range(1 << length):
print(format(i, '0{}b'.format(length)))
def main():
'''The Main'''
print_01(2)
print_01(3)
if __name__ == '__main__':
main()
add a comment |
Here's a simple recursive version:
#!/usr/bin/python -E
#string of binary 1s and 0s, all possible combinations for a given length
def swap(string, loc, val):
newstring = string[:loc]+val+string[loc+1:]
return newstring
def printperms(string,n):
length = len(string)
if n > 0:
string = swap(string, (length - n), "0")
printperms(string, (n -1))
string = swap(string, (length - n), "1")
printperms(string, (n -1))
else:
print(string)
mystring = "000"
length = len(mystring)
printperms(mystring, length)
mystring = mystring+" "
print("############################################")
printperms(mystring,length+1)
add a comment |
Let's keep it simple:
def print_01(bits, n=0):
if n.bit_length() <= bits:
print('{:0{}b}'.format(n, bits))
print_01(bits, n + 1)
The int
type has a method bit_length()
that tells you the minimum number of binary characters needed to represent this number -- we use that for control. The nested formatting allows us to pass the output width as a variable.
USAGE
>>> print_01(3)
000
001
010
011
100
101
110
111
>>>
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377124%2fhow-to-output-permuations-of-0s-and-1s-of-a-given-length-recursively%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Without giving away the code, I'll attempt to give the hints needed for you to come up with the code.
The idea is to make the recursive call to add one more digit to an accumulated string, that initially is empty.
The so-called "base case" of the recursion is where the accumulated string has the desired length. This is where you would output it (or store it somewhere)
You'll need a loop to visit the two possible digits.
Let me know if this is enough for you to get going.
Spoiler alert (only look below after having tried):
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. Sodigit
will first be "0" and in the second (last) iteration it will be "1"
– trincot
Nov 19 '18 at 15:41
add a comment |
Without giving away the code, I'll attempt to give the hints needed for you to come up with the code.
The idea is to make the recursive call to add one more digit to an accumulated string, that initially is empty.
The so-called "base case" of the recursion is where the accumulated string has the desired length. This is where you would output it (or store it somewhere)
You'll need a loop to visit the two possible digits.
Let me know if this is enough for you to get going.
Spoiler alert (only look below after having tried):
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. Sodigit
will first be "0" and in the second (last) iteration it will be "1"
– trincot
Nov 19 '18 at 15:41
add a comment |
Without giving away the code, I'll attempt to give the hints needed for you to come up with the code.
The idea is to make the recursive call to add one more digit to an accumulated string, that initially is empty.
The so-called "base case" of the recursion is where the accumulated string has the desired length. This is where you would output it (or store it somewhere)
You'll need a loop to visit the two possible digits.
Let me know if this is enough for you to get going.
Spoiler alert (only look below after having tried):
Without giving away the code, I'll attempt to give the hints needed for you to come up with the code.
The idea is to make the recursive call to add one more digit to an accumulated string, that initially is empty.
The so-called "base case" of the recursion is where the accumulated string has the desired length. This is where you would output it (or store it somewhere)
You'll need a loop to visit the two possible digits.
Let me know if this is enough for you to get going.
Spoiler alert (only look below after having tried):
edited Nov 19 '18 at 15:21
answered Nov 19 '18 at 15:03
trincottrincot
124k1587121
124k1587121
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. Sodigit
will first be "0" and in the second (last) iteration it will be "1"
– trincot
Nov 19 '18 at 15:41
add a comment |
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. Sodigit
will first be "0" and in the second (last) iteration it will be "1"
– trincot
Nov 19 '18 at 15:41
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
thank you for posting that code, is there a link where i can read about how that for loop works?
– computerprogram
Nov 19 '18 at 15:40
The loop just iterates through the string "01", taking each character in turn. So
digit
will first be "0" and in the second (last) iteration it will be "1"– trincot
Nov 19 '18 at 15:41
The loop just iterates through the string "01", taking each character in turn. So
digit
will first be "0" and in the second (last) iteration it will be "1"– trincot
Nov 19 '18 at 15:41
add a comment |
Here is an idea:
Instead of doing that recursively, use binary development of numbers:
def print_01(k):
end = 1<<k #this is the integer with binary developpement 1 followed by k zeros
for j in range(end): # iterate until end means getting all k - 0-1 combinations
comb = bin(j)[2:].zfill(k)
print [int(x) for x in comb]
add a comment |
Here is an idea:
Instead of doing that recursively, use binary development of numbers:
def print_01(k):
end = 1<<k #this is the integer with binary developpement 1 followed by k zeros
for j in range(end): # iterate until end means getting all k - 0-1 combinations
comb = bin(j)[2:].zfill(k)
print [int(x) for x in comb]
add a comment |
Here is an idea:
Instead of doing that recursively, use binary development of numbers:
def print_01(k):
end = 1<<k #this is the integer with binary developpement 1 followed by k zeros
for j in range(end): # iterate until end means getting all k - 0-1 combinations
comb = bin(j)[2:].zfill(k)
print [int(x) for x in comb]
Here is an idea:
Instead of doing that recursively, use binary development of numbers:
def print_01(k):
end = 1<<k #this is the integer with binary developpement 1 followed by k zeros
for j in range(end): # iterate until end means getting all k - 0-1 combinations
comb = bin(j)[2:].zfill(k)
print [int(x) for x in comb]
edited Nov 19 '18 at 15:11
answered Nov 19 '18 at 15:05
Matina GMatina G
577211
577211
add a comment |
add a comment |
Do you really need to permute ... ?
If not try below
def print_01(length):
for i in range(1 << length):
print(format(i, '0{}b'.format(length)))
def main():
'''The Main'''
print_01(2)
print_01(3)
if __name__ == '__main__':
main()
add a comment |
Do you really need to permute ... ?
If not try below
def print_01(length):
for i in range(1 << length):
print(format(i, '0{}b'.format(length)))
def main():
'''The Main'''
print_01(2)
print_01(3)
if __name__ == '__main__':
main()
add a comment |
Do you really need to permute ... ?
If not try below
def print_01(length):
for i in range(1 << length):
print(format(i, '0{}b'.format(length)))
def main():
'''The Main'''
print_01(2)
print_01(3)
if __name__ == '__main__':
main()
Do you really need to permute ... ?
If not try below
def print_01(length):
for i in range(1 << length):
print(format(i, '0{}b'.format(length)))
def main():
'''The Main'''
print_01(2)
print_01(3)
if __name__ == '__main__':
main()
answered Nov 19 '18 at 15:06
KrishnaKrishna
6021515
6021515
add a comment |
add a comment |
Here's a simple recursive version:
#!/usr/bin/python -E
#string of binary 1s and 0s, all possible combinations for a given length
def swap(string, loc, val):
newstring = string[:loc]+val+string[loc+1:]
return newstring
def printperms(string,n):
length = len(string)
if n > 0:
string = swap(string, (length - n), "0")
printperms(string, (n -1))
string = swap(string, (length - n), "1")
printperms(string, (n -1))
else:
print(string)
mystring = "000"
length = len(mystring)
printperms(mystring, length)
mystring = mystring+" "
print("############################################")
printperms(mystring,length+1)
add a comment |
Here's a simple recursive version:
#!/usr/bin/python -E
#string of binary 1s and 0s, all possible combinations for a given length
def swap(string, loc, val):
newstring = string[:loc]+val+string[loc+1:]
return newstring
def printperms(string,n):
length = len(string)
if n > 0:
string = swap(string, (length - n), "0")
printperms(string, (n -1))
string = swap(string, (length - n), "1")
printperms(string, (n -1))
else:
print(string)
mystring = "000"
length = len(mystring)
printperms(mystring, length)
mystring = mystring+" "
print("############################################")
printperms(mystring,length+1)
add a comment |
Here's a simple recursive version:
#!/usr/bin/python -E
#string of binary 1s and 0s, all possible combinations for a given length
def swap(string, loc, val):
newstring = string[:loc]+val+string[loc+1:]
return newstring
def printperms(string,n):
length = len(string)
if n > 0:
string = swap(string, (length - n), "0")
printperms(string, (n -1))
string = swap(string, (length - n), "1")
printperms(string, (n -1))
else:
print(string)
mystring = "000"
length = len(mystring)
printperms(mystring, length)
mystring = mystring+" "
print("############################################")
printperms(mystring,length+1)
Here's a simple recursive version:
#!/usr/bin/python -E
#string of binary 1s and 0s, all possible combinations for a given length
def swap(string, loc, val):
newstring = string[:loc]+val+string[loc+1:]
return newstring
def printperms(string,n):
length = len(string)
if n > 0:
string = swap(string, (length - n), "0")
printperms(string, (n -1))
string = swap(string, (length - n), "1")
printperms(string, (n -1))
else:
print(string)
mystring = "000"
length = len(mystring)
printperms(mystring, length)
mystring = mystring+" "
print("############################################")
printperms(mystring,length+1)
answered Nov 19 '18 at 17:03
LulzLulz
11
11
add a comment |
add a comment |
Let's keep it simple:
def print_01(bits, n=0):
if n.bit_length() <= bits:
print('{:0{}b}'.format(n, bits))
print_01(bits, n + 1)
The int
type has a method bit_length()
that tells you the minimum number of binary characters needed to represent this number -- we use that for control. The nested formatting allows us to pass the output width as a variable.
USAGE
>>> print_01(3)
000
001
010
011
100
101
110
111
>>>
add a comment |
Let's keep it simple:
def print_01(bits, n=0):
if n.bit_length() <= bits:
print('{:0{}b}'.format(n, bits))
print_01(bits, n + 1)
The int
type has a method bit_length()
that tells you the minimum number of binary characters needed to represent this number -- we use that for control. The nested formatting allows us to pass the output width as a variable.
USAGE
>>> print_01(3)
000
001
010
011
100
101
110
111
>>>
add a comment |
Let's keep it simple:
def print_01(bits, n=0):
if n.bit_length() <= bits:
print('{:0{}b}'.format(n, bits))
print_01(bits, n + 1)
The int
type has a method bit_length()
that tells you the minimum number of binary characters needed to represent this number -- we use that for control. The nested formatting allows us to pass the output width as a variable.
USAGE
>>> print_01(3)
000
001
010
011
100
101
110
111
>>>
Let's keep it simple:
def print_01(bits, n=0):
if n.bit_length() <= bits:
print('{:0{}b}'.format(n, bits))
print_01(bits, n + 1)
The int
type has a method bit_length()
that tells you the minimum number of binary characters needed to represent this number -- we use that for control. The nested formatting allows us to pass the output width as a variable.
USAGE
>>> print_01(3)
000
001
010
011
100
101
110
111
>>>
answered Nov 19 '18 at 17:50
cdlanecdlane
18.6k21144
18.6k21144
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377124%2fhow-to-output-permuations-of-0s-and-1s-of-a-given-length-recursively%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
– bene
Nov 19 '18 at 14:52