Computer............
Python...........
Write a python code for the following pyramid.
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
Answers
#include <stdio.h>
int main()
{
int i, space, rows, k=0, count = 0, count1 = 0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(space=1; space <= rows-i; ++space)
{
printf(" ");
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
printf("%d ", i+k);
++count;
}
else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
Here is the thing to notice, people while coding, get scared when they see a question like this, it is tricky though but if we think, it is simple.
1 = 1²
121 = 11²
12321 = 111²
1234321 = 1111²
123454321 = 11111²
Now, we have the logic to get these numbers and there are two other things we are missing.
(1) The code itself
(2) Observe that the pattern in the question is a reverse of what we have done. So, 11111² should come first and the number of '1''s should decrease from there.
But here is another problem. How many ones do we ask python to take? It would be confused for sure.
Here is an other way to get around this:
We can use '//' function in python to get this done.
For example, how can '1' be written? 1 = 10//9
And 10//9 is 1
11 = 100//9
111 = 1000//9
So, we will take a range for 5(inclusive) and then we raise 10 to the power of the number taken in range and square the whole thing.
For example, let's say we we need to get 12321
The range number is 3 in this case:
10**3 = 1000
1000// 9 = 111
111^2 = 12321
That is!
Now, for the reversed range we use the function reversed()
Here is the code:
for i in reversed(range(1,6)):
print((10**i//9)**2)