程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python line of code to print hearts

編輯:Python

我正在參加「創意開發 投稿大賽」詳情請看:掘金創意開發大賽來了!

1. 先放代碼

print('\n'.join([''.join([('o'[(x-y) % len('o')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))
復制代碼

2. 語法講解

2.1 代碼邏輯梳理

首先,In order to more clearly analyze the logical relationship of the above line of code,We disassemble it into the following logically more intuitive and clear code writing method:

str = "o"
for y in range(30, -30, -1):
for x in range(-30, 30):
if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0:
print(str[(x-y) % len(str)], end='')
else:
print(' ', end='')
print()
復制代碼

蕪湖,The idea suddenly became clear,In fact, the idea of ​​drawing graphics is one30️30的區域內,對於符合x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0Constrained lattice,按順序填入str中的字母.

Know the general process of drawing graphics,We can do it一行代碼Some of the grammar and usage skills involved are sorted out.

2.2 .join()

Python join() 方法用於將序列中的元素以指定的字符連接生成一個新的字符串,用法如下:

str = "-"
seq = ("a", "b", "c") # 字符串序列 
print str.join( seq )
復制代碼

The result of this output is shown below:

a-b-c
復制代碼

通過上面的例子,我們可以清楚的了解到,str.join(seq)The usage of the method is as abovestr為間隔,連接seqeach element in the string sequence.

So we can sort out the first layer of a line of code:

'/n'.join(seq1)
復制代碼

Let's see laterseq1中的內容:

[''.join(seq2)
復制代碼

seq1There is another layer of syntax similar to the above,Then let's focus directly on itseq2中:

[('o'[(x-y) % len('o')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]
復制代碼

Here is a two-level loop in the list,outer layer fory的循環是從-30到30的循環,內層是對x的從-30到30的循環,在每一位,On the basis of judgment,打印o或者.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved