百科问答小站 logo
百科问答小站 font logo



程序员的你,有哪些炫技的代码写法? 第1页

  

user avatar   liu-ji-27-94 网友的相关建议: 
      

强烈建议贵乎不要推送这种钓鱼引战的问题了,认真回答有错么?回答两千个复制粘贴怎么样?大家是来交流的不是来炫技和抖机灵的,求同存异取长补短啊!看了那么多认真的答主,评论没有几个友好的,你们那么厉害怎么不来答?


我一直都对各种语言的语法糖和优雅的小技巧很痴迷。这里分享一些Python的code trick,主要来自大佬LandGrey的开源仓库,我也fork了一下并且加入了一些私货。长期积累和维护,谈不上非常炫技,但很有趣、很有用也很优雅:ThomasAtlantis/PythonTricks

命令行

非交互式执行代码

       # code-1 python -c "import os;os.popen('calc')"  # note-1 打开计算器(Windows 操作系统)   # code-2 python -m timeit -n 1 -r 1 -s "import os" "import platform" "print(platform.system())" "os.popen('calc')"  # output-2 Windows 1 loops, best of 1: 401 msec per loop  # note-2 最后会打开计算器(Windows 操作系统)     

简易HTTPServer

       # code python2 -m SimpleHTTPServer 53 python3 -m http.server 53  # note 监听的默认地址是 0.0.0.0, 对外开放, 可目录浏览     

一行代码

最值

       # code heapq.nsmallest/heapq.nlargest import heapq print(heapq.nlargest(2, [{'S': 5, 'H': 3}, {'S': 7, 'H': 1}, {'S': 0, 'H': 2}], key=lambda x: x['S']))  # output [{'H': 1, 'S': 7}, {'H': 3, 'S': 5}]  # note 取最大/最小的 N 个值     

逆序

       # code-1 reversed 逆序 print(list(reversed(['L', 'G', 'PK'])))  # output-1 ['PK', 'G', 'L']   # code-2 Slice 逆序 print(['L', 'G', 'PK'][::-1])  # output-2 ['PK', 'G', 'L']     

碾平

       # code s = [1, [2, [3, [4, [5, 6], 7], 8], (9, 0)]] f = lambda x: [y for _x in x for y in f(_x)] if isinstance(x, (list, tuple)) else [x] print(f(s))  # output [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]     

真假

       # code for python2 True -= 1 print(True) print(True == False)  # output 0 True  # note python 2.x , True  False 都是变量, 可以被改变     

去重

       # code array = ['c', 'a', 'c', 'd', 'b', 'b', 'a', 'a', 'f']  print(list(set(array)))  uniq = [] [uniq.append(x) for x in array if x not in uniq] print(uniq)  print([x for y, x in enumerate(array) if array.index(x) == y])  # output ['a', 'c', 'b', 'd', 'f'] ['c', 'a', 'd', 'b', 'f'] ['c', 'a', 'd', 'b', 'f']  # note 依次对应: 去重但不保序 去重且保序 去重且保序     

时间戳

       # code import time print(time.strftime("%Y%m%d-%H:%M:%S", time.localtime(time.time())))  # output 20190101-17:12:14     

彩蛋攻击

       # code for python2 [reload(__import__("YW50aWdyYXZpdHk=".decode("base64"))) for x in range(666)]  # code for python3 [__import__("imp").reload(__import__("antigravity")) for x in range(666)]  # note 一个内置彩蛋模块的"拒绝服务攻击", 谨慎运行!     

执行代码

       # code exec("print('love ' + s)", {'s': 'peace'})  # output love peace     

join连接

       # code print("+".join(['L', 'G', '007']))  # output L+G+007     

简易判断

       # code-1 print('bingo' if 1 > 2 else 'miss')  # output-1 miss   # code-2 print("
".join([(str(x) + ' bingo') if not x % 2 else str(x) + ' miss' for x in range(10)]))  # output-2 0 bingo 1 miss 2 bingo 3 miss 4 bingo 5 miss 6 bingo 7 miss 8 bingo 9 miss     

条件过滤

       # code print(filter(lambda x: "T" in x, ["TIT", "YoY"]))  # output ['TIT']     

排序技巧

       # code-1 import heapq k = [2, 6, 1, 5, 3, 4] print(heapq.nsmallest(len(k), k))  # output-1 [1, 2, 3, 4, 5, 6]  # note-1 从小到大排序   # code-2 print(sorted(['LG', 'cdn', 'dll', 'BBQ', 'afun'], key=lambda x: (len(x), x)))  # output-2 ['LG', 'BBQ', 'cdn', 'dll', 'afun']  # note-2 先按长度、再按 ascii 值从小到大依次排序   # code-3 from collections import OrderedDict d = {'apple': 1, 'orange': 3, 'banana': 4, 'tomato': 2} print(OrderedDict((x, y) for x, y in sorted(d.items(), key=lambda x: x[1])))  # output-3 OrderedDict([('apple', 1), ('tomato', 2), ('orange', 3), ('banana', 4)])  # note-3 无序字典变有序字典 ( value 排序)     

字典合并

       # code-1 d = {'a': 1} d.update({'b': 2}) print(d)  # output-1 {'a': 1, 'b': 2}   # code-2 d1 = {'a': 1} d2 = {'b': 2} print(dict(d1, **d2))  # output-2 {'a': 1, 'b': 2}     

列表推导式

       # code print([x for x in 'LandGrey' if ord(x) > ord('d')])  # output ['n', 'r', 'e', 'y']     

zip分配生成dict

       # code print(dict(zip('AABCD', xrange(5))))  # output {'A': 1, 'C': 3, 'B': 2, 'D': 4}  # note 本质 dict(list([(k1, v1), (k2, v2)]), ...)     

switch-case写法

       # code def switch(case):     return {         0: ">",         1: "<",         2: "="     }.get(case, "?")   print(switch(1))  # output <     

Format自动解包

       # code t = [{'protocol': 'https'}, 'landgrey.me', '443'] print("{0[0][protocol]}://{0[1]}:{0[2]}".format(t))  # output https://landgrey.me:443     

输出类中无注释的函数列表

这个问题来自Python如何调用一个py文件并输出部分行内容?

已知类的定义如下

       class Foo:      def __init__(self, initial_balance=0):         self.balance = initial_balance      def deposit(self, amount):         '''Deposit amount'''         self.balance += amount      def withdraw(self, amount):         '''Withdraw amount'''         self.balance -= amount      def overdrawn(self):         return self.balance < 0     

输出无注释的函数列表

       print([func.__name__ for func in Foo.__dict__.values() if callable(func) and not func.__doc__]) # ['__init__', 'overdrawn']     

代码片段

从右向左替换字符串

       # code  def rreplace(self, old, new, *max):     count = len(self)     if max and str(max[0]).isdigit():         count = max[0]     return new.join(self.rsplit(old, count))  print rreplace("lemon tree", "e", "3") print rreplace("lemon tree", "e", "3", 1)  # output l3mon tr33 lemon tre3     

命令行调用程序中的函数

       # test_arg.py  import sys  def praise(sb):     print(f"{sb} is awesome!")  this_module = sys.modules[__name__] getattr(this_module, sys.argv[1])(*sys.argv[2:])     

sys.modules[__name__]获取当前程序的对象,get_attr()获取程序中的方法或变量,所以sys.argv[1]存储要调用的函数,而后面加括号是调用这个函数,sys.argv[2:]是这个函数的参数

       python test_arg.py praise python # python is awesome!     

神奇的列表展平方式

       x = [[1, 2, 3], [4, 5], [6]] sum(x, []) # [1, 2, 3, 4, 5, 6]     

但是注意这里只允许列表是标准的单层嵌套,也就是说每个元素都必须是列表,该方法只能展开一层

       import numpy as np x = np.array([[[1, 2], [3, 4]], [[4, 5], [6, 7]]]) x.flatten() # array([1, 2, 3, 4, 4, 5, 6, 7])     

注意这里的numpy展平方式更加局限,它要求各元素维度相同,但它可以全部展开,而以上的sum方法只能展开一层


user avatar   he-he-93-99-5 网友的相关建议: 
      

我们知道,在计算机中要显示颜色,一般都是用R、G、B三个0-255范围内的整数来描述。

这一点,即便你不是从事前端、客户端这些与界面交互相关的开发工作,也应该知道。

也就是说,你现在在屏幕上看到的任何一个像素点的颜色,都可以用RGB三个整数值来表示。

那就有一个有趣的问题:如果让程序自动来填写每一个像素点,最后会是一副什么画呢?

最近我在知乎就看到了这么一个有趣的话题,看完真的让人称奇,独乐乐不如众乐乐,分享给大家。

回答人:烧茄子 链接:zhihu.com/question/3026

事情是这么一回事:

国外有个大佬在StackExchange上发起了一个叫做 Tweetable Mathematical Art 的比赛。

参赛者需要用C++编写代表三原色的RD、GR、BL三个函数,每个函数都不能超过 140 个字符。每个函数都会接到 i 和 j 两个整型参数(0 ≤ i, j ≤ 1023),然后需要返回一个 0 到 255 之间的整数,表示位于 (i, j) 的像素点的颜色值。

举个例子,如果 RD(0, 0) 和 GR(0, 0) 返回的都是 0 ,但 BL(0, 0) 返回的是 255 ,那么图像的最左上角那个像素就是蓝色。

参赛者编写的代码会被插进下面这段程序当中(我做了一些细微的改动),最终会生成一个大小为 1024×1024 的图片。

       // NOTE: compile with g++ filename.cpp -std=c++11 #include <iostream> #include <cmath> #include <cstdlib> #define DIM 1024 #define DM1 (DIM-1) #define _sq(x) ((x)*(x)) // square #define _cb(x) abs((x)*(x)*(x)) // absolute value of cube #define _cr(x) (unsigned char)(pow((x),1.0/3.0)) // cube root   unsigned char GR(int,int); unsigned char BL(int,int);   unsigned char RD(int i,int j){    // YOUR CODE HERE } unsigned char GR(int i,int j){    // YOUR CODE HERE } unsigned char BL(int i,int j){    // YOUR CODE HERE }   void pixel_write(int,int); FILE *fp; int main(){     fp = fopen("MathPic.ppm","wb");     fprintf(fp, "P6
%d %d
255
", DIM, DIM);     for(int j=0;j<DIM;j++)         for(int i=0;i<DIM;i++)             pixel_write(i,j);     fclose(fp);     return 0; } void pixel_write(int i, int j){     static unsigned char color[3];     color[0] = RD(i,j)&255;     color[1] = GR(i,j)&255;     color[2] = BL(i,j)&255;     fwrite(color, 1, 3, fp); }     


我选了一些自己比较喜欢的作品,放在下面和大家分享。首先是一个来自 Martin Büttner 的作品:

它的代码如下:

       unsigned char RD(int i,int j){   return (char)(_sq(cos(atan2(j-512,i-512)/2))*255); }  unsigned char GR(int i,int j){   return (char)(_sq(cos(atan2(j-512,i-512)/2-2*acos(-1)/3))*255); }  unsigned char BL(int i,int j){   return (char)(_sq(cos(atan2(j-512,i-512)/2+2*acos(-1)/3))*255); }     

同样是来自 Martin Büttner 的作品:

这是目前暂时排名第一的作品。它的代码如下:

       unsigned char RD(int i,int j){   #define r(n)(rand()%n)   static char c[1024][1024];   return!c[i][j]?c[i][j]=!r(999)?r(256):RD((i+r(2))%1024,(j+r(2))%1024):c[i][j]; }  unsigned char GR(int i,int j){   static char c[1024][1024];   return!c[i][j]?c[i][j]=!r(999)?r(256):GR((i+r(2))%1024,(j+r(2))%1024):c[i][j]; }  unsigned char BL(int i,int j){   static char c[1024][1024];   return!c[i][j]?c[i][j]=!r(999)?r(256):BL((i+r(2))%1024,(j+r(2))%1024):c[i][j]; }     

下面这张图片仍然出自 Martin Büttner 之手:

难以想象, Mandelbrot 分形图形居然可以只用这么一点代码画出:

       unsigned char RD(int i,int j){   float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}   return log(k)*47; }  unsigned char GR(int i,int j){   float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}   return log(k)*47; }  unsigned char BL(int i,int j){   float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}   return 128-log(k)*23; }     

Manuel Kasten 也制作了一个 Mandelbrot 集的图片,与刚才不同的是,该图描绘的是 Mandelbrot 集在某处局部放大后的结果:

它的代码如下:

       unsigned char RD(int i,int j){   double a=0,b=0,c,d,n=0;   while((c=a*a)+(d=b*b)<4&&n++<880)   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}   return 255*pow((n-80)/800,3.); }  unsigned char GR(int i,int j){   double a=0,b=0,c,d,n=0;   while((c=a*a)+(d=b*b)<4&&n++<880)   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}   return 255*pow((n-80)/800,.7); }  unsigned char BL(int i,int j){   double a=0,b=0,c,d,n=0;   while((c=a*a)+(d=b*b)<4&&n++<880)   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}   return 255*pow((n-80)/800,.5); }     

这是 Manuel Kasten 的另一作品:

生成这张图片的代码很有意思:函数依靠 static 变量来控制绘画的进程,完全没有用到 i 和 j 这两个参数!

       unsigned char RD(int i,int j){   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; }  unsigned char GR(int i,int j){   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; }  unsigned char BL(int i,int j){   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; }     

这是来自 githubphagocyte 的作品:

它的代码如下:

       unsigned char RD(int i,int j){   float s=3./(j+99);   float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;   return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127; }  unsigned char GR(int i,int j){   float s=3./(j+99);   float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;   return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127; }  unsigned char BL(int i,int j){   float s=3./(j+99);   float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;   return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127; }     

这是来自 githubphagocyte 的另一个作品:

这是一张使用 diffusion-limited aggregation 模型得到的图片,程序运行起来要耗费不少时间。代码很有意思:巧妙地利用宏定义,打破了函数与函数之间的界限,三段代码的字数限制便能合在一起使用了。

       unsigned char RD(int i,int j){ #define D DIM #define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D] #define R rand()%D #define B m[x][y] return(i+j)?256-(BL(i,j))/2:0; }  unsigned char GR(int i,int j){ #define A static int m[D][D],e,x,y,d,c[4],f,n;if(i+j<1){for(d=D*D;d;d--){m[d%D][d/D]=d%6?0:rand()%2000?1:255;}for(n=1 return RD(i,j); }  unsigned char BL(int i,int j){ A;n;n++){x=R;y=R;if(B==1){f=1;for(d=0;d<4;d++){c[d]=M;f=f<c[d]?c[d]:f;}if(f>2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j]; }     

最后这张图来自 Eric Tressler:

这是由 logistic 映射得到的 Feigenbaum 分岔图。和刚才一样,对应的代码也巧妙地利用了宏定义来节省字符:

       unsigned char RD(int i,int j){ #define A float a=0,b,k,r,x #define B int e,o #define C(x) x>255?255:x #define R return #define D DIM R BL(i,j)*(D-i)/D; }  unsigned char GR(int i,int j){ #define E DM1 #define F static float #define G for( #define H r=a*1.6/D+2.4;x=1.0001*b/D R BL(i,j)*(D-j/2)/D; }  unsigned char BL(int i,int j){ F c[D][D];if(i+j<1){A;B;G;a<D;a+=0.1){G b=0;b<D;b++){H;G k=0;k<D;k++){x=r*x*(1-x);if(k>D/2){e=a;o=(E*x);c[e][o]+=0.01;}}}}}R C(c[j][i])*i/D; }     

怎么样,短短几行代码,就能画出如此绚烂的图像,你有没有什么脑洞大开的想法,可以复制上面的代码来试一试啊!




  

相关话题

  为什么不能乱点技能树? 
  如何评价“中国码农996的原因是中国产品经理水平太差”?996的根本原因是什么? 
  知乎上有哪些好的程序员可以关注? 
  谁能用通俗的语言解释一下什么是 RPC 框架? 
  初中文凭可以学习编程吗?如果可以,是去靠谱的培训机构还是自学?学习方向都有哪些?就业环境如何? 
  程序员对待社会问题的观点是否相对比较Liberal? 
  未来会不会出现这样的编程语言? 
  在中国程序员能不能干一辈子? 
  写代码应该本着什么原则,才能写出优秀的代码? 
  有没有人考虑付费金额与代码量成反比会发生什么? 

前一个讨论
Python 语言有什么奇技淫巧吗?
下一个讨论
Python如何调用一个py文件并输出部分行内容?





© 2024-05-17 - tinynew.org. All Rights Reserved.
© 2024-05-17 - tinynew.org. 保留所有权利