
Triangle Quest 2 Hackerrank Solution Python
You are given a positive integer N.
Your task is to print a palindromic triangle of size N .
For example, a palindromic triangle of size % is:
1 121 12321 1234321 123454321
You can’t take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly one print statement.
Note:
Using anything related to strings will give a score of 0.
Using more than one for-statement will give a score of 0.
Input Format
A single line of input containing the integer N.
Constraints
- 0<N<10
Output Format
Print the palindromic triangle of size as explained above.
Sample Input
5
Sample Output
1 121 12321 1234321 123454321
Code:
#Triangle Quest 2 Hackerrank solution Python for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. #Do not leave a blank line also print((int((10**i-1)/(9)))**2) #Triangle Quest 2 Hackerrank solution Python
Here’s how the code works:
- The first line reads an integer input from the user using the
input()
function and converts it to an integer usingint()
. This integer represents the number of lines in the triangular pattern to be printed. - The
range()
function generates a sequence of integers from 1 up to the value of the input integer. Thefor
loop iterates over each integer in this sequence. - The first expression inside the
print()
function calculates the value of (10^i – 1)/9, which is a mathematical formula for a string of i consecutive 1’s. For example, if i is 3, then the expression evaluates to (10^3 – 1)/9 = 111. - The second expression inside the
print()
function squares the result of the first expression, which gives the desired triangular pattern. For example, if i is 3, then the expression evaluates to 111^2 = 12321. - The
print()
function outputs the result of the second expression, which is the corresponding line of the triangular pattern.
So, in summary, the code generates a sequence of integers from 1 to the input value, calculates a string of consecutive 1’s using a mathematical formula, squares the result to form the triangular pattern, and outputs each line of the pattern using the print()
function.