• Python和Js打印心形


    看到一行Python写的代码,会用LovePython输出心形:

    print('
    '.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 + "
    ";
    }
    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];

  • 相关阅读:
    Python 容器用法整理
    C/C++中浮点数格式学习——以IEEE75432位单精度为例
    关于C/C++中的位运算技巧
    [GeekBand] C++11~14
    [GeekBand] 探讨C++新标准之新语法——C++ 11~14
    [GeekBand] 面向对象的设计模式(C++)(2)
    [GeekBand] 面向对象的设计模式(C++)(1)
    [GeekBand] STL与泛型编程(3)
    [GeekBand] STL与泛型编程(2)
    [GeekBand] STL与泛型编程(1)
  • 原文地址:https://www.cnblogs.com/liumaowu/p/11672098.html
Copyright © 2020-2023  润新知