DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on • Edited on

Let's share some python snippets?!

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

Top comments (5)

Collapse
 
elcio profile image
Elcio Ferreira
lines = ['* ' * (i + 1) for i in range(5)]
lines2 = list(reversed(lines))
lines.pop()
print('\n'.join(lines + lines2))
Collapse
 
voyeg3r profile image
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 :)

Collapse
 
elcio profile image
Elcio Ferreira
size = 5

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

for step in steps:
    print(step * "* ")
Collapse
 
elcio profile image
Elcio Ferreira

Simple is better than complex ;-)

print('''
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
'''[1:-1])
Collapse
 
voyeg3r profile image
Sérgio Araújo

Increadible!!!