我从互联网上找到了这个perl脚本并试图在python中重写,但是无法做到。如果有人在perl和python中掌握,请帮助我。我希望python可以比perl更容易做到这一点。
谢谢
#!/usr/bin/perl
use Term::ANSIColor;
map(($yo=$_,map(( $y=$yo-$_/3,$l[24-$yo] .= (' ','$')[$y**2-20*$y+($_**2)/3<0]), (0..30)),),(0..24));
print color('red');
print join("\n", map(reverse($_).$_, @l)), "\n";
输出:
$$$$$$$$$ $$$$$$$$$
$$$$$$$$$$$$$$ $$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$
$$$$$$$$$$
$$$$$$
答案 0 :(得分:5)
Perl和Python都是动态语言并且共享许多类似的内置函数,这个Perl代码中使用的每个函数和/或运算符都在Python中直接映射:
Op/Function Perl Python
---------------
map map map()
exponentiation ** **
reverse reverse reverse()
concatenation . +
range x .. y range(x, y+1)
这应该是以同样方式解决问题的所有物理部分,你必须逐步完成每一行才能真正了解正在发生的事情。
此外,您永远不会显示定义@l
的位置。
答案 1 :(得分:2)
在阅读了Hunter McMillen的回答之后,我将OP的perl代码转换为python。
l = [''] * 25
for yo in range(25):
for x in range(31):
y = yo - x / 3
l[24 - yo] += (' ', '$')[y**2 - 20*y + (x**2) / 3 < 0]
print('\n'.join(line[::-1] + line for line in l))
在转换代码时我注意到perl / python之间的其他差异。
$l .= ...
。但是在Python中不允许这样做。应该事先定义。
IndexError
。应事先分配。$_
。 map
为它迭代的每个项目设置它。reverse
返回反向列表,而Python中的reversed
返回迭代器。所以我使用了[::-1]
代替。1/2
(至少在版本5.14中)生成0.5
。在Python 2.x中,它生成0
(分区)。在Python 3.x中,它产生0.5
(真正的除法);如果使用Python 2.x运行此代码,结果会略有不同。请参阅http://asciinema.org/a/6681