Python Program to print digit pattern
Last Updated :
13 Mar, 2023
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
Using List comprehension and join():
Another approach that could be used to solve this problem is to use a list comprehension to generate the desired output.
Here is an example of how this could be implemented:
Python3
def pattern(n):
n = str (n)
pattern = [ "|" + "*" * int (digit) for digit in n]
print ( "\n" .join(pattern))
pattern( 41325 )
|
Output
|****
|*
|***
|**
|*****
This approach has a time complexity of O(n) and a space complexity of O(n), as it requires one traversal of the input and creates a new list to store the generated pattern.
Please Login to comment...