DEV Community

Discussion on: One code liner in Python 🐍

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Challenge accepted.

This is what I came up with.

# yours
print('\n'.join(['*'*(abs(i-4)+1)for i in range(1,8)]))

# mine
[print("*"*(abs(i)+1)) for i in range(-3, 4)]
****
***
**
*
**
***
****
Enter fullscreen mode Exit fullscreen mode

Background

I started range at -3.

list(range(-3, 4))
# [-3, -2, -1, 0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

And then used abs.

I started with -4, 5 as my inputs but then the pattern was weird and I fixed with -3, 4 and +1.

So now it does this:

[(abs(i) + 1) for i in range(-3, 4)]
# [4, 3, 2, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

I also skipped the join to make it even shorter.

But here is my solution with a join. It ends up being a tiny bit shorter than your solution perhaps more readable (it is easier to think about -3 as the start than 1 and then -4 to get to -3)

# yours
print('\n'.join(['*'*(abs(i-4)+1)for i in range(1,8)]))
# mine
print("\n".join(("*"*(abs(i)+1))for i in range(-3,4)))
****
***
**
*
**
***
****
Enter fullscreen mode Exit fullscreen mode

Oh and by the way I used ( instead of [ for fun but makes no practical difference here. Either way, one is needed otherwise range gives a generator (Python 3).

Collapse
 
willnode profile image
Wildan Mubarok

Impressive! I never thought that we can put print() inside a list comprehension. Seems like cheating to me 😂. Thanks for that! I learn something new today 💪.

Collapse
 
michaelcurrin profile image
Michael Currin

Since Python 3, print is a function so you can use it anywhere you'd use a function