Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function that receives an integer n>0 and tells whether its digits (in base 10) form a nondecreasing sequence (each digit is >= to the previous one)

Write a function nondec(n) that receives an integer n>0 and reports whether its digits (in base 10) form a nondecreasing sequence (that is, each digit is greater or equal to the previous one).

I am having trouble with this exercise. My code so far is:

def nondec(n):
    '''
    >>> nondec(113355779)
    True
    >>> nondec(44569)
    True
    >>> nondec(346234)
    False
    >>> nondec(222)
    True
    >>> nondec(789)
    True
    >>> nondec(55555)
    True
    >>> nondec(1234123)
    False
    >>> nondec(98765)
    False
    '''
    prev = 9
    while n>0 :
        lastdigit = n%10
        if lastdigit > prev:
            return False
        prev = lastdigit
        n = n/10
    return True

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)

It works for all cases but for those with repeated digits: 222, 55555. I tried many things but it makes my code worse. Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Maybe this is the code you are looking for:

def nondec(n):
    '''
    >>> nondec(113355779)
    True
    >>> nondec(44569)
    True
    >>> nondec(346234)
    False
    >>> nondec(222)
    True
    >>> nondec(789)
    True
    >>> nondec(55555)
    True
    >>> nondec(1234123)
    False
    >>> nondec(98765)
    False
    '''
    prev = 9
    while n>0 :
        lastdigit = n % 10
        if lastdigit > prev:
            return False
        prev = lastdigit
        n = n // 10
    return True

The only change I did to your code is to the part that you do the division with 10: n = n / 10.

The problem was that this division returned a float but you wanted an int

For example if you take 222 when it divides by 10 then the new value of n was 22.2 when you wanted it to be 22. (You can check for such problems by printing the results of every line of code you write!)

You can accomplish this by using the // instead of /.

You can check this answer Python division by 10 to see what I am talking about

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading