How to output permuations of 0's and 1's of a given length recursively?











up vote
-2
down vote

favorite












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?










share|improve this question
























  • I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
    – bene
    Nov 19 at 14:52















up vote
-2
down vote

favorite












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?










share|improve this question
























  • I'm not sure if it's such a good idea to use a recursion due to the (maximal) recursion depth.. .
    – bene
    Nov 19 at 14:52













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











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?










share|improve this question















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 at 20:18









trincot

115k1478109




115k1478109










asked Nov 19 at 14:50









computerprogram

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 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 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 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 at 14:52












5 Answers
5






active

oldest

votes

















up vote
2
down vote



accepted










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):




enter image description here







share|improve this answer























  • thank you for posting that code, is there a link where i can read about how that for loop works?
    – computerprogram
    Nov 19 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 at 15:41


















up vote
2
down vote













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]





share|improve this answer






























    up vote
    0
    down vote













    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()





    share|improve this answer




























      up vote
      0
      down vote













      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)





      share|improve this answer




























        up vote
        0
        down vote













        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
        >>>





        share|improve this answer





















          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',
          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
          });


          }
          });














          draft saved

          draft discarded


















          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








          up vote
          2
          down vote



          accepted










          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):




          enter image description here







          share|improve this answer























          • thank you for posting that code, is there a link where i can read about how that for loop works?
            – computerprogram
            Nov 19 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 at 15:41















          up vote
          2
          down vote



          accepted










          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):




          enter image description here







          share|improve this answer























          • thank you for posting that code, is there a link where i can read about how that for loop works?
            – computerprogram
            Nov 19 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 at 15:41













          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          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):




          enter image description here







          share|improve this answer














          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):




          enter image description here








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 at 15:21

























          answered Nov 19 at 15:03









          trincot

          115k1478109




          115k1478109












          • thank you for posting that code, is there a link where i can read about how that for loop works?
            – computerprogram
            Nov 19 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 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 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 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 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 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 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 at 15:41












          up vote
          2
          down vote













          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]





          share|improve this answer



























            up vote
            2
            down vote













            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]





            share|improve this answer

























              up vote
              2
              down vote










              up vote
              2
              down vote









              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]





              share|improve this answer














              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]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 19 at 15:11

























              answered Nov 19 at 15:05









              Matina G

              50119




              50119






















                  up vote
                  0
                  down vote













                  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()





                  share|improve this answer

























                    up vote
                    0
                    down vote













                    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()





                    share|improve this answer























                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      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()





                      share|improve this answer












                      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()






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 19 at 15:06









                      Krishna

                      5921315




                      5921315






















                          up vote
                          0
                          down vote













                          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)





                          share|improve this answer

























                            up vote
                            0
                            down vote













                            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)





                            share|improve this answer























                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              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)





                              share|improve this answer












                              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)






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 19 at 17:03









                              Lulz

                              11




                              11






















                                  up vote
                                  0
                                  down vote













                                  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
                                  >>>





                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote













                                    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
                                    >>>





                                    share|improve this answer























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      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
                                      >>>





                                      share|improve this answer












                                      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
                                      >>>






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 19 at 17:50









                                      cdlane

                                      16.8k21043




                                      16.8k21043






























                                          draft saved

                                          draft discarded




















































                                          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.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • 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.




                                          draft saved


                                          draft discarded














                                          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





















































                                          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







                                          Popular posts from this blog

                                          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                          Alcedinidae

                                          Origin of the phrase “under your belt”?