主要收集了平常遇到的代码和网上的简单题目,然后尝试将代码压缩到一行,仅仅是娱乐一下~~~
−−−−−(1)−−−−−−−−−−−(1)−−−−−−
用一行python写出一个嵌套的字符串。
def plat(ch,n):return''if ~n else ' '*(n-1)+ ch+ch[::-1][1:]+'
'+plat(ch+chr(ord(ch[-1])+1),n-1)
- 1
结果如图:
上面这个返回所需要的字符串,还可以这样写,连输出都省了:
def plat(ch,n): '' if ~n else (print(' '*(n-1)+ ch+ch[::-1][1:]),plat(ch+chr(ord(ch[-1])+1),n-1))
- 1
- 2
−−−−−−−(2)−−−−−−−−−−−−(2)−−−−−:一行python解决n中取k问题:
def ck(a,r,k,now = 0,cur = 0): (now==k and print(r[:k])==None) or [ck(a,r[:now]+[a[i]]+r[now+1:],k,now+1,i+1) for i in range(cur,len(a)-k+now+1)]
- 1
−−−−(3)−−−−一行代码画出爱心曲线−−−−(3)−−−−一行代码画出爱心曲线
利用心型曲线的公式
规定一个正方形,然后可以确定每一个位置是否该画出字符。
print ('
'.join([''.join(['pybbyp'[(x-y)%6] if (x*0.04)**2+((y*0.1) - ((x*0.04)**2)**(1/3))**2 < 1 else ' ' for x in range(-30,30,1) ]) for y in range(15,-15,-1)]))
- 1
−−−[4]−−−构建一个树状字典−−−−−[4]−−−构建一个树状字典−−
当我们不知道字典需要几层的时候,我们可以这样实现:
f = lambda:defaultdict(f)
- 1
这样tree = f()就可以实现任意层次的嵌套。
PS:思考
tree = defaultdict(tree)
为什么不对.
−−−[5]−−fizzbuzz问题−−−[5]−−fizzbuzz问题
函数实现
def fizz(n=1):n== 101 or (print([n,'fizz','buzz','fizzbuzz'][(n%5 == 0)*2+(n%3 == 0)]),fizz(n+1))
- 1
循环实现:
for x in range(1, 101): print("fizz"[x % 3 * 4:]+"buzz"[x % 5 * 4:] or x)
- 1
−−−(6)−−−一行打印乘法表−−−−−(6)−−−一行打印乘法表−−
#method 1
def f(n):[ ([print('{}*{}={}'.format(x,y,x*y),end = ' ')for x in range(1,y+1)])for y in range(1,n+1)]
#method 2
def f1(n,k=1): k==n+1 or (print(' '.join('{}*{}={}'.format(x,k,x*k) for x in range(1,k+1))),f1(n,k+1))
- 1
- 2
- 3
- 4
−−−(7)−−−一行实现一个迷宫−−−(7)−−−一行实现一个迷宫
for i in range(10**3):print(random.choice('|| __'), end='')
- 1
−−−−−(8)画一个递归的三角图形−−−−−−−−−−−−(8)画一个递归的三角图形−−−−−−−
这里我暂时没有压缩成功….有兴趣的可以试一试
def rec_plot(x,y,width,height,n):
dx = width>>1
dy = height>>1
if n>1:
rec_plot(x,y,dx,dy,n-1)
rec_plot(x-(dx>>1),y+dy,dx,dy,n-1)
rec_plot(x+(dx>>1),y+dy,dx,dy,n-1)
else:
for _x,_y in zip(range(x,x-dx-1,-1),range(y,y+height+1,1)):
points[(_x,_y)] = '*'
for _x,_y in zip(range(x,x+dx+1),range(y,y+height+1,1)):
points[(_x,_y)] = '*'
for _x in range(x-dx,x+dx):
points[(_x,y+height)] = '*'
rec_plot(40,0,32,16,3)
for y in range(0,80):
for x in range(0,80):
print(points[(x,y)],end='')
print('')