看到一行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循环可以写在后面:

01-19 20:23
查看更多