看到一行Python寫的代碼,會用LovePython輸出心形:
print('\n'.join([''.join([('LovePython'[(x-y)%10]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(15,-15,-1)]))
嘗試用js復現一遍如下:
var str = 'I Love You';var res = ""; for (var y = 15; y > -15; y--) { var line = ''; for (var x = -30; x < 30; x++) { var item = ''; if (((Math.pow((x * 0.05), 2) + Math.pow((y * 0.1), 2) - 1) ** 3 - Math.pow((x * 0.05), 2) * Math.pow((y * 0.1), 3)) <= 0) { let index = (x - y) % str.length; if (index < 0) { index = index + str.length; } item = str[index]; } else { item = ' '; } line += item; } res = res + line + "\n"; } console.log(res);
有幾點需要注意的是:
Python的 % 和 js 的 % 取模計算,在計算負數時結果不同, 如(-4%10),pyhon計算結果為6,js計算結果為 -4;
Python的 if 語句可以可以跟在一個對象后面:
如 print('aaa'if false else 'bbb') 輸出的結果是 ‘bbb’,含義是,如果if條件為真,輸出前面的值,如果未為假,輸出后面的值;
Python的for循環可以寫在表達式后面,意義為根據前面的表達式來生成list列表:
如 [x * x for x in range(1, 11)] 輸出的是 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];