Let's share some python snippets?!

Sérgio Araújo - May 2 '20 - - Dev Community

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:


    *
    * *
    * * *
    * * * *
    * * * * *
    * * * *
    * * *
    * *
    *
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

A more pyctonic way of doing the same.

for i in (list(range(1,6)) + list(reversed(range(1,5)))):
    print(i * "* ")
Enter fullscreen mode Exit fullscreen mode

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 * "* ")
Enter fullscreen mode Exit fullscreen mode

Another form

     *
    * *
   * * *
  * * * *
 * * * * *
Enter fullscreen mode Exit fullscreen mode

Solution:

for i in reversed(range(5)):
    print(f'{i*" "}{(-i+5)*" *"}')
Enter fullscreen mode Exit fullscreen mode

And what about this:

def rightriangle(x):
    x+=1
    for i in range(1,x):
        print((x-(i+1))*' ' + i * '*')
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .