DEV Community

Sérgio Araújo

Posted on • Updated on

I share one piece of code and you comment something on it and share another snippet.

I have stumbled upon some code challenges out there and one of them is to draw this picture:

``````
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
``````

My solution

``````x = 1
operation = lambda x:x+1

while x >= 1:
print( x *  "*  ")
x = operation(x)
if x >= 5:
operation = lambda x:x-1
``````

A more pyctonic way of doing the same.

``````for i in (list(range(1,6)) + list(reversed(range(1,5)))):
print(i * "* ")
``````

By the way, it was only possible thanks to @Elscio's interaction, and this my friends, is the beauty of a great community.

And of course, if you want to generate the picture with different sizes we can introduce a limit, as Elcio has done:

``````limit = 8
for i in (list(range(1,limit+1)) + list(reversed(range(1,limit)))):
print(i * "* ")
``````

Another form

``````     *
* *
* * *
* * * *
* * * * *
``````

Solution:

``````for i in reversed(range(5)):
print(f'{i*" "}{(-i+5)*" *"}')
``````

``````def rightriangle(x):
x+=1
for i in range(1,x):
print((x-(i+1))*' ' + i * '*')
``````

Elcio Ferreira
``````lines = ['* ' * (i + 1) for i in range(5)]
lines2 = list(reversed(lines))
lines.pop()
print('\n'.join(lines + lines2))
``````

Sérgio Araújo • Edited

Hi Elcio, have a look at my "new" second and more pyctonic solution, I think you will love it. Python is as it it is, we solve a problem using it and then we say: Well, this works in python, in other languages you have to try this or that :)

Elcio Ferreira
``````size = 5

steps = list(range(1, size + 1))
steps += list(range(size - 1, 0, -1))

for step in steps:
print(step * "* ")
``````

Elcio Ferreira

Simple is better than complex ;-)

``````print('''
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
'''[1:-1])
``````

Sérgio Araújo