zoukankan      html  css  js  c++  java
  • 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];

  • 相关阅读:
    PAT 1097. Deduplication on a Linked List (链表)
    PAT 1096. Consecutive Factors
    PAT 1095. Cars on Campus
    PAT 1094. The Largest Generation (层级遍历)
    PAT 1093. Count PAT's
    PAT 1092. To Buy or Not to Buy
    PAT 1091. Acute Stroke (bfs)
    CSS:word-wrap/overflow/transition
    node-webkit中的requirejs报错问题:path must be a string error in Require.js
    script加载之defer和async
  • 原文地址:https://www.cnblogs.com/liumaowu/p/11672098.html
Copyright © 2011-2022 走看看