i=k=input()
while i:i-=1;print(" "*(k+~i)+"\\"+i*' / |\ '[i%2::2])[:k-~i]+"_/"[i>0:]
在线尝试!
Erik的花样之一使我可以打3个字节!由于乔纳森·艾伦节省了3个字节。
如何运作
首先,它从STDIN获取输入,并将其分配给两个单独的变量i
和k
。然后,当变量i
为真时,我们将其递减并相应地生成字符串。这是从输入开始循环的简写-从1一直到0。
生成字符串
我将其分成更多部分:
首先,通过获得领先的间距" "*(k+~i)
。由于i
是通过范围(input,0]映射的,因此必须从k
(安全存储的原始输入)中减去它,然后递减并重复多次。
+"\\"
-将字符添加"\"
到上方空格。
' / |\ '[i%2::2]
- 以以下方式生成我们的两个字符串,即"/ \ "
和" | "
:
+~-i*
-重复上面生成的字符串,"/ \ "
或者" | "
,i-1次,并将其附加到其他字符串。按位运算符(~
-按位补码,等价于-1减去i)的好处是,在这种情况下,不需要括号。
[:k-~i]
-获取上面串联的字符串的所有字符,直到索引k-〜i = k-(-1-i)= k +1 + i为止。
+"_/"[i>0:]
-仅"/"
当i≥1时才加,否则追加_/
。
完整的示例/执行细节
让我们举一个例子,说明输入4时事物如何工作:
i=k=input() # i and k are assigned to 4.
while i: # Starts the loop. The initial value of i is 4.
i-=1; # Decrement i. i is now 3.
" "*(k+~i) # A space repeated k - 1 - i = 4 - 1 - 3 = 0 times.
+"\\" # Plus the character "\". CS (Current string): "\".
' / |\ '[i%2::2] # The string ' / |\ '[3%2::2] = ' / |\ '[1::2] = "/ \ ".
i* # ^ repeated i = 3 times: "/ \ / \ / \ ".
+ # And concatenate. CS: "\/ \ / \ / \ "
[:k-~i] # Get the characters of ^ up to index k + 1 + i = 4 + 1 + 3 = 8.
# CS: "\/ \ / \".
+"_/"[i>0:] # Append "_/"[i>0:] = "_/"[3>0:] = "_/"[1:] = "/".
# CS: "\/ \ / \/".
print # Output the result "\/ \ / \/".
while i: # i is truthy (> 0), thus we loop again.
i-=1; # Decrement i. i becomes 2.
" "*(k+~i) # " " repeated 4 - 2 - 1 = 1 time.
+"\\" # Plus "\". CS: " \".
' / |\ '[i%2::2] # ' / |\ '[2%2::2] = ' / |\ '[::2] = " | ".
+i* # Repeat i = 2 times and append: " | ". CS: " \ | |".
[:k-~i] # CS up until k + 1 + i = 4 + 2 + 1 = 7. CS: " \ | ".
+"_/"[i>0:] # Append "/". CS: " \ | /".
print # Outputs the CS: " \ | /".
while i: # i is truthy (> 0), thus we loop again.
i-=1; # Decrement i. i is now 1.
" "*(k+~i) # " " repeated 4 - 1 - 1 = 2 times.
+"\\" # Plus "\". CS: " \".
' / |\ '[i%2::2] # ' / |\ '[2%2::2] = ' / |\ '[::2] = "/ \ ".
+i* # Repeat i = 1 time and append: "/ \ ". CS: " \/ \ ".
[:k-~i] # CS up until k + i + 1 = 4 + 2 = 6. CS: " \/ \".
+"_/"[i>0:] # Append "/". CS: " \/ \/".
print # Outputs the CS: " \/ \/".
while i: # i is truthy (> 0), thus we loop again.
i-=1; # Decrement i. i is now 0.
" "*(k+~i) # " " repeated 4 - 1 - 0 = 3 times.
+"\\" # Plus "\". CS: " \".
' / |\ '[i%2::2] # ' / |\ '[1%2::2] = ' / |\ '[1::2] = " | ".
+i* # Repeat i = 0 times and append: " \". CS: " \".
[:k-~i] # CS up until k + i + 1 = 4 + 0 + 1 = 5. CS: " \".
+"_/"[i>0:] # Append "_/" (because i > 0 is False since i == 0). CS: " \_/".
print # Outputs the CS: " \_/".
while i: # i == 0, hence the condition is falsy and the loop ends.
# Program terminates.