Check if the digits in the number are in increasing sequence in python












7















I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.



To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order



To this problem, there is a constraint saying



For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.



The code for increasing sequence was



  len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0 









share|improve this question




















  • 1





    Does each digit have to be exactly one bigger than the last?

    – John Gordon
    4 hours ago













  • yes @JohnGordon

    – s326280
    4 hours ago






  • 1





    The accepted answer currently seems to fail for 78901.

    – גלעד ברקן
    2 hours ago













  • Sorry, i didn't notice that !!.

    – s326280
    1 hour ago
















7















I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.



To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order



To this problem, there is a constraint saying



For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.



The code for increasing sequence was



  len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0 









share|improve this question




















  • 1





    Does each digit have to be exactly one bigger than the last?

    – John Gordon
    4 hours ago













  • yes @JohnGordon

    – s326280
    4 hours ago






  • 1





    The accepted answer currently seems to fail for 78901.

    – גלעד ברקן
    2 hours ago













  • Sorry, i didn't notice that !!.

    – s326280
    1 hour ago














7












7








7








I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.



To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order



To this problem, there is a constraint saying



For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.



The code for increasing sequence was



  len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0 









share|improve this question
















I was working on a problem that determines whether the digits in the numbers are in the increasing sequence. Now, the approach I took to solve the problem was, For instance, consider the number 5678.



To check whether 5678 is an increasing sequence, I took the first digit and the next digit and the last digit which is 5,6,8 and substitute in range function range(first,last,(diff of first digit and the next to first digit)) i.e range(5,8+1,abs(5-6)).The result is the list of digits in the ascending order



To this problem, there is a constraint saying



For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. Now my program breaks at the input 7890. I don't know how to encode this logic. Can someone help me, please?.



The code for increasing sequence was



  len(set(['5','6','7','8']) - set(map(str,range(5,8+1,abs(5-6))))) == 0 






python algorithm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 hours ago







s326280

















asked 4 hours ago









s326280s326280

826




826








  • 1





    Does each digit have to be exactly one bigger than the last?

    – John Gordon
    4 hours ago













  • yes @JohnGordon

    – s326280
    4 hours ago






  • 1





    The accepted answer currently seems to fail for 78901.

    – גלעד ברקן
    2 hours ago













  • Sorry, i didn't notice that !!.

    – s326280
    1 hour ago














  • 1





    Does each digit have to be exactly one bigger than the last?

    – John Gordon
    4 hours ago













  • yes @JohnGordon

    – s326280
    4 hours ago






  • 1





    The accepted answer currently seems to fail for 78901.

    – גלעד ברקן
    2 hours ago













  • Sorry, i didn't notice that !!.

    – s326280
    1 hour ago








1




1





Does each digit have to be exactly one bigger than the last?

– John Gordon
4 hours ago







Does each digit have to be exactly one bigger than the last?

– John Gordon
4 hours ago















yes @JohnGordon

– s326280
4 hours ago





yes @JohnGordon

– s326280
4 hours ago




1




1





The accepted answer currently seems to fail for 78901.

– גלעד ברקן
2 hours ago







The accepted answer currently seems to fail for 78901.

– גלעד ברקן
2 hours ago















Sorry, i didn't notice that !!.

– s326280
1 hour ago





Sorry, i didn't notice that !!.

– s326280
1 hour ago












5 Answers
5






active

oldest

votes


















5














You can simply check if the number, when converted to a string, is a substring of '1234567890':



str(num) in '1234567890'





share|improve this answer



















  • 1





    simple and answers perfectly. Good job.

    – Jean-François Fabre
    25 mins ago



















3














you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.



num = 7890

result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))





share|improve this answer



















  • 1





    you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

    – Jon Clements
    4 hours ago








  • 3





    This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

    – blhsing
    3 hours ago













  • @JonClements nice but in that case I would create a string beforehand.

    – Jean-François Fabre
    1 hour ago



















2














I would create a cycling generator and slice that:



from itertools import cycle, islice

num = 5678901234

num = tuple(str(num))
print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))


This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:



def digits(num):
while num:
yield num % 10
num //= 10

def check(num):
num = list(digits(num))
num.reverse()
for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
if i != j:
return False
return True





share|improve this answer

































    0














    Since you already have the zip version, here is an alternative solution:



    import sys


    order = dict(enumerate(range(10)))
    order[0] = 10

    def increasing(n):
    n = abs(n)
    o = order[n % 10] + 1
    while n:
    r = n % 10
    n = n / 10
    if o - order[r] != 1:
    return False
    o = order[r]
    return True


    for n in sys.argv[1:]:
    print n, increasing(int(n))





    share|improve this answer

































      0














      Here's my take that just looks at the digits and exits as soon as there is a discrepancy:



      def f(n):
      while (n):
      last = n % 10
      n = n / 10
      if n == 0:
      return True
      prev = n % 10
      print last, prev
      if prev == 0 or prev != (10 + last - 1) % 10:
      return False

      print f(1234)
      print f(7890)
      print f(78901)
      print f(1345)





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


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54954713%2fcheck-if-the-digits-in-the-number-are-in-increasing-sequence-in-python%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









        5














        You can simply check if the number, when converted to a string, is a substring of '1234567890':



        str(num) in '1234567890'





        share|improve this answer



















        • 1





          simple and answers perfectly. Good job.

          – Jean-François Fabre
          25 mins ago
















        5














        You can simply check if the number, when converted to a string, is a substring of '1234567890':



        str(num) in '1234567890'





        share|improve this answer



















        • 1





          simple and answers perfectly. Good job.

          – Jean-François Fabre
          25 mins ago














        5












        5








        5







        You can simply check if the number, when converted to a string, is a substring of '1234567890':



        str(num) in '1234567890'





        share|improve this answer













        You can simply check if the number, when converted to a string, is a substring of '1234567890':



        str(num) in '1234567890'






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 3 hours ago









        blhsingblhsing

        36.2k41639




        36.2k41639








        • 1





          simple and answers perfectly. Good job.

          – Jean-François Fabre
          25 mins ago














        • 1





          simple and answers perfectly. Good job.

          – Jean-François Fabre
          25 mins ago








        1




        1





        simple and answers perfectly. Good job.

        – Jean-François Fabre
        25 mins ago





        simple and answers perfectly. Good job.

        – Jean-François Fabre
        25 mins ago













        3














        you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.



        num = 7890

        result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))





        share|improve this answer



















        • 1





          you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

          – Jon Clements
          4 hours ago








        • 3





          This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

          – blhsing
          3 hours ago













        • @JonClements nice but in that case I would create a string beforehand.

          – Jean-François Fabre
          1 hour ago
















        3














        you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.



        num = 7890

        result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))





        share|improve this answer



















        • 1





          you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

          – Jon Clements
          4 hours ago








        • 3





          This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

          – blhsing
          3 hours ago













        • @JonClements nice but in that case I would create a string beforehand.

          – Jean-François Fabre
          1 hour ago














        3












        3








        3







        you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.



        num = 7890

        result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))





        share|improve this answer













        you could zip the string representation of the number with a shifted self and iterate on consecutive digits together. Use all to check that numbers follow, using a modulo 10 to handle the 0 case.



        num = 7890

        result = all((int(y)-int(x))%10 == 1 for x,y in zip(str(num),str(num)[1:]))






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 4 hours ago









        Jean-François FabreJean-François Fabre

        105k955112




        105k955112








        • 1





          you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

          – Jon Clements
          4 hours ago








        • 3





          This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

          – blhsing
          3 hours ago













        • @JonClements nice but in that case I would create a string beforehand.

          – Jean-François Fabre
          1 hour ago














        • 1





          you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

          – Jon Clements
          4 hours ago








        • 3





          This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

          – blhsing
          3 hours ago













        • @JonClements nice but in that case I would create a string beforehand.

          – Jean-François Fabre
          1 hour ago








        1




        1





        you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

        – Jon Clements
        4 hours ago







        you can avoid the double str'ing and slicing by using zip(*[iter(str(num))] * 2) instead but I imagine that's got way more overhead for such use in this case anyway... just throwing it out there...

        – Jon Clements
        4 hours ago






        3




        3





        This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

        – blhsing
        3 hours ago







        This would incorrectly return True for 78901, as the OP says "0 should come after 9, and not before 1".

        – blhsing
        3 hours ago















        @JonClements nice but in that case I would create a string beforehand.

        – Jean-François Fabre
        1 hour ago





        @JonClements nice but in that case I would create a string beforehand.

        – Jean-François Fabre
        1 hour ago











        2














        I would create a cycling generator and slice that:



        from itertools import cycle, islice

        num = 5678901234

        num = tuple(str(num))
        print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))


        This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:



        def digits(num):
        while num:
        yield num % 10
        num //= 10

        def check(num):
        num = list(digits(num))
        num.reverse()
        for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
        if i != j:
        return False
        return True





        share|improve this answer






























          2














          I would create a cycling generator and slice that:



          from itertools import cycle, islice

          num = 5678901234

          num = tuple(str(num))
          print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))


          This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:



          def digits(num):
          while num:
          yield num % 10
          num //= 10

          def check(num):
          num = list(digits(num))
          num.reverse()
          for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
          if i != j:
          return False
          return True





          share|improve this answer




























            2












            2








            2







            I would create a cycling generator and slice that:



            from itertools import cycle, islice

            num = 5678901234

            num = tuple(str(num))
            print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))


            This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:



            def digits(num):
            while num:
            yield num % 10
            num //= 10

            def check(num):
            num = list(digits(num))
            num.reverse()
            for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
            if i != j:
            return False
            return True





            share|improve this answer















            I would create a cycling generator and slice that:



            from itertools import cycle, islice

            num = 5678901234

            num = tuple(str(num))
            print(num == tuple(islice(cycle(map(str, range(10))), int(num[0]), int(num[0]) + len(num))))


            This is faster than solutions that check differences between individual digits. Of course, you can sacrifice the length to make it faster:



            def digits(num):
            while num:
            yield num % 10
            num //= 10

            def check(num):
            num = list(digits(num))
            num.reverse()
            for i, j in zip(islice(cycle(range(10)), num[0], num[0] + len(num)), num):
            if i != j:
            return False
            return True






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 4 hours ago

























            answered 4 hours ago









            Tomothy32Tomothy32

            7,2871627




            7,2871627























                0














                Since you already have the zip version, here is an alternative solution:



                import sys


                order = dict(enumerate(range(10)))
                order[0] = 10

                def increasing(n):
                n = abs(n)
                o = order[n % 10] + 1
                while n:
                r = n % 10
                n = n / 10
                if o - order[r] != 1:
                return False
                o = order[r]
                return True


                for n in sys.argv[1:]:
                print n, increasing(int(n))





                share|improve this answer






























                  0














                  Since you already have the zip version, here is an alternative solution:



                  import sys


                  order = dict(enumerate(range(10)))
                  order[0] = 10

                  def increasing(n):
                  n = abs(n)
                  o = order[n % 10] + 1
                  while n:
                  r = n % 10
                  n = n / 10
                  if o - order[r] != 1:
                  return False
                  o = order[r]
                  return True


                  for n in sys.argv[1:]:
                  print n, increasing(int(n))





                  share|improve this answer




























                    0












                    0








                    0







                    Since you already have the zip version, here is an alternative solution:



                    import sys


                    order = dict(enumerate(range(10)))
                    order[0] = 10

                    def increasing(n):
                    n = abs(n)
                    o = order[n % 10] + 1
                    while n:
                    r = n % 10
                    n = n / 10
                    if o - order[r] != 1:
                    return False
                    o = order[r]
                    return True


                    for n in sys.argv[1:]:
                    print n, increasing(int(n))





                    share|improve this answer















                    Since you already have the zip version, here is an alternative solution:



                    import sys


                    order = dict(enumerate(range(10)))
                    order[0] = 10

                    def increasing(n):
                    n = abs(n)
                    o = order[n % 10] + 1
                    while n:
                    r = n % 10
                    n = n / 10
                    if o - order[r] != 1:
                    return False
                    o = order[r]
                    return True


                    for n in sys.argv[1:]:
                    print n, increasing(int(n))






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 4 hours ago

























                    answered 4 hours ago









                    khachikkhachik

                    21.1k54381




                    21.1k54381























                        0














                        Here's my take that just looks at the digits and exits as soon as there is a discrepancy:



                        def f(n):
                        while (n):
                        last = n % 10
                        n = n / 10
                        if n == 0:
                        return True
                        prev = n % 10
                        print last, prev
                        if prev == 0 or prev != (10 + last - 1) % 10:
                        return False

                        print f(1234)
                        print f(7890)
                        print f(78901)
                        print f(1345)





                        share|improve this answer




























                          0














                          Here's my take that just looks at the digits and exits as soon as there is a discrepancy:



                          def f(n):
                          while (n):
                          last = n % 10
                          n = n / 10
                          if n == 0:
                          return True
                          prev = n % 10
                          print last, prev
                          if prev == 0 or prev != (10 + last - 1) % 10:
                          return False

                          print f(1234)
                          print f(7890)
                          print f(78901)
                          print f(1345)





                          share|improve this answer


























                            0












                            0








                            0







                            Here's my take that just looks at the digits and exits as soon as there is a discrepancy:



                            def f(n):
                            while (n):
                            last = n % 10
                            n = n / 10
                            if n == 0:
                            return True
                            prev = n % 10
                            print last, prev
                            if prev == 0 or prev != (10 + last - 1) % 10:
                            return False

                            print f(1234)
                            print f(7890)
                            print f(78901)
                            print f(1345)





                            share|improve this answer













                            Here's my take that just looks at the digits and exits as soon as there is a discrepancy:



                            def f(n):
                            while (n):
                            last = n % 10
                            n = n / 10
                            if n == 0:
                            return True
                            prev = n % 10
                            print last, prev
                            if prev == 0 or prev != (10 + last - 1) % 10:
                            return False

                            print f(1234)
                            print f(7890)
                            print f(78901)
                            print f(1345)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 2 hours ago









                            גלעד ברקןגלעד ברקן

                            13k21542




                            13k21542






























                                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.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54954713%2fcheck-if-the-digits-in-the-number-are-in-increasing-sequence-in-python%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

                                A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                Calculate evaluation metrics using cross_val_predict sklearn

                                Insert data from modal to MySQL (multiple modal on website)