Most Can't Write This Function in ONE Line of Python Code (Prove Me Wrong Please)

preview_player
Показать описание
Dear viewer, I challenge you to write this function in ONE line of code WITHOUT looking at the answer behind.

But if you didn't manage to, I've got a step-by-step tutorial on how I managed to achieve this in ONE line of Python. Also, don't be disheartened if you didn't manage to, for there is always the next challenge

My coding setup:

Cheers
Рекомендации по теме
Комментарии
Автор

Well My First Try :
def pyramid(S):
start = end = 0
while end < len(S)-1:
print(S[start : end + 1])
gap = end - start
start += gap + 1
end += gap + 2
print(S[start:] + '*'*(end-len(S)+1))

adityaram
Автор

I have managed to do this, took me too long haha... Rip nested lambdas.

pyramid = lambda x: [
print(x[start:start+i+1])
if ((start := int((i*(i+1))/2))+i+1) <= len(x)
else print(x[start:start+i+1] + '*' * (start+i+1 - len(x)))
for i in range((lambda f: lambda a: f(f, a, 1))(lambda self, str_len, num_of_lines: num_of_lines if (str_len-num_of_lines) <= 0 else self(self, str_len-num_of_lines, num_of_lines+1))(len(x)))
]

adamkoxxl
Автор

And here is the second version, consuming the word instead of algebraically calculating the indices:
```python
pyramid_1_liner = lambda word: print('\n'.join((f'{word[:i]:*<{i}}', (word := word[i:]))[0] for i in range(1, len(word)+1) if word))
```

Now I think I'll actually watch the video.

EDIT
I just watched the video. I would advise walrusing it a bit, as the same thing is being calculated many times on each iteration. All in all, I'm compelled to say mine is perhaps better.

ricardoreis
Автор

Here is another approach:

def pyramid(s):print(s[sum(range(k)):][:k].ljust(k, '*') for k in range(1, round(len(2*s)**.5)+1))

dfen
Автор

Here's my solution. I can finally watch your solution :)

from itertools import count

def pyramid(s):
index = 0

for i in count(1):
if index > len(s):
break
print(f"{s[index:index + i]:*<{i}}")
index += i

sudoggo
Автор

at least golf it properly, that's just ugly
pyramid=lambda i, x in enumerate(filter(bool, [s[sum(range(i)):][:i]for i in range(1, len(s))]))]

this i suppose is better, it could be improved but im lazy

also I didn't watch the video, and I'm too lazy to figure out how to actually get the number of splits properly, i could maybe get that from the formula for a sum of an arithmetic series, idk idc

EDIT: This is a proper one:
pyramid=lambda i, x in i in range(1, round((2*len(s))**0.5)+1))]

random