Print digits of a number in python

Assuming strings are not strictly forbidden, here are some possible alternative solutions.

def get_digits[num]:
    return [int[i] for i in str[num]]

Another solution [1]:

import math

def get_digits[num]:
    return [[num//[10**i]]%10 for i in range[math.ceil[math.log[num, 10]]-1, -1, -1]]

This would be optimal if you just needed to print the digits directly.

print[", ".join[[i for i in str[num]]]]

If you're in a beginning Python class, your professor likely only wants to see something like this which doesn't use lists or string indexes:

num = 1203

for i, n in enumerate[str[num]]:
    if i == 0:
        print[n, end=""]
    else:
        print[', ' + n, end='']

[Out]: 1, 2, 0, 3

I want to write a simple function that prints the digits of an integer in reverse.
I think it could be done with the while loop, but I am not so sure.
I have tried this, but it didn't work.

Expand|Select|Wrap|Line Numbers

  1. def print_digits[n]:
  2.     n = abs[n]
  3.     while n > 0:
  4.         n = n % 10
  5.         print n,
  6.  

Jul 23 '08 #1

In python % is the modulo operator... I'm not sure what you are trying here...

Here's how to reverse the digits of an integer using list comprehension:

Expand|Select|Wrap|Line Numbers

  1. >>> def print_digits[n]:
  2. ...     new_n = [lett for lett in str[n]]
  3. ...     new_n.reverse[]
  4. ...     print ''.join[new_n]
  5. ...     
  6. >>> print_digits[136]
  7. 631
  8. >>> 

Jul 23 '08 #2

Oh wait.. now I see what you were trying to do...

Expand|Select|Wrap|Line Numbers

  1. >>> def print_n[n]:
  2. ...     while n > 0:
  3. ...         print n % 10,
  4. ...         n = n / 10
  5. ...     
  6. >>> print_n[492]
  7. 2 9 4
  8. >>> 

Modulus 10 will give you the remainder but you want to integer divide by 10 each time to reduce the number another digit.

Jul 23 '08 #3

Well, I am new to Python and I am reading this:
//openbookproject.net/thinkCSpy/ch06.xhtml#auto16
so the exercise is number 8

Expand|Select|Wrap|Line Numbers

  1. def print_digits[n]:
  2.     """
  3.       >>> print_digits[13789]
  4.       9 8 7 3 1
  5.       >>> print_digits[39874613]
  6.       3 1 6 4 7 8 9 3
  7.       >>> print_digits[213141]
  8.       1 4 1 3 1 2
  9.     """
  10.  

Hope this helps!

Jul 23 '08 #4

Thanks for the quick reply. I can now sleep in peace.

Jul 23 '08 #5

Sign in to post your reply or Sign up for a free account.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples:

    Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *’s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the first line. The second digit is 1 so print one *. So on and the last i.e., the fifth digit is 5 hence print five *s in the fifth line. Input : 60710 Output : |****** | |******* |* |

    Approach Read the input For each digit in the integer print the corresponding number of *s If the digit is 0 then print no *s and skip to the next line 

    Python3

    def pattern[n]:

        for i in n:

            print["|", end = ""]

            print["*" * int[i]]

    n = "41325"

    pattern[n]

    Output:

    |****
    |*
    |***
    |**
    |*****

    Time complexity: O[n] since one traversal of the array is required to complete all operations hence the overall time required by the algorithm is linear
    Auxiliary Space: O[1] since no extra array is used so the space taken by the algorithm is constant

    Alternate solution that takes integer as input : 

    Python3

    n = 41325

    x = []

    while n>0:

        x.append[n%10]

        n //= 10

    for i in range[len[x]-1,-1,-1]:

        print['|'+x[i]*'*']

    Output:

    |****
    |*
    |***
    |**
    |*****

    Time complexity: O[n] since one traversal of the array is required to complete all operations hence the overall time required by the algorithm is linear
    Auxiliary Space: O[n] since an extra list is used so in the worst case the space taken by the algorithm will be linear


    How do you print the number of digits in Python?

    The len[] function is a built-in function in Python used to calculate the number of characters inside a string variable. The len[] function takes a string as an input parameter and returns the number of characters inside that string.

    How do I print an individual digit of a number in Python?

    “get individual digits from int python” Code Answer's.
    >>> n = 43365644..
    >>> digits = [int[x] for x in str[n]].
    >>> digits..
    >>> lst. extend[digits] # use the extends method if you want to add the list to another..

    How do you print digits of numbers?

    Method 1: The simplest way to do is to extract the digits one by one and print it..
    Extract the last digit of the number N by N%10, and store that digit in an array[say arr[]]..
    Update the value of N by N/10 and repeat the above step till N is not equals to 0..

    How do you print 10 digits in Python?

    Info on str. isdigit[] : Type: method_descriptor String Form: Namespace: Python builtin Docstring: S. isdigit[] -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise.

    Chủ Đề