Search code examples
pythonnumbersdigitssizing

Getting the number of digits of nonnegative integers (Python)


The question asks:

<< BACKGROUND STORY: Suppose we’re designing a point-of-sale and order-tracking system for a new burger joint. It is a small joint and it only sells 4 options for combos: Classic Single Combo (hamburger with one patty), Classic Double With Cheese Combo (2 patties), and Classic Triple with Cheese Combo (3 patties), Avant-Garde Quadruple with Guacamole Combo (4 patties). We shall encode these combos as 1, 2, 3, and 4 respectively. Each meal can be biggie sized to acquire a larger box of fries and drink. A biggie sized combo is represented by 5, 6, 7, and 8 respectively, for the combos 1, 2, 3, and 4 respectively. >>

Write an iterative function called order_size which takes an order and returns the number of combos in the order. For example, order_size(237) -> 3.

Whereby I should have

order_size(0) = 0

order_size(6) = 1

order_size(51) = 2

order_size(682) = 3

My code is:

def order_size(order):

    # Fill in your code here
    if order > 0:
        size = 0
        while order > 0:
            size +=  1
            order = order // 10
            return size
        else:
            return 0

But I don't get the order // 10 portion. I'm guessing it's wrong but I can't think of any stuff to substitute that.


Solution

  • No need for iterative function, you can measure the length of the number by "turning" it into a string:

    num = 127
    order = len(str(num))
    print(order) # prints 3
    

    But if you really want to do it iteratively:

    def order(num):
        res = 0
        while num > 0:
            num = int(num / 10)
            res += 1
        return res
    
    print(order(127))  # prints 3