打印三角形
cat >show.py <<EOF
#!/usr/bin/env python
def show(n):
tail=" ".join([str(i) for i in range(n,0,-1)])
width=len(tail)
for i in range(1,n):
print("{:>{}}".format(" ".join([str(j) for j in range(i,0,-1)]),width))
print(tail)
show(12)
EOF
执行代码
打印三角形
cat >showtail.py<<EOF
#!/usr/bin/env python
def show(n):
tail=" ".join([str(i) for i in range(n,0,-1)])
for i in range(len(tail)):
if tail[i] == ' ':
print(" "*i+tail[i+1: ])
show(12)
EOF
执行代码
列表正序排列
cat >sort.py<<EOF
#!/usr/bin/env pthon
def sort(lst,asc=False):
newlst=[]
for x in lst:
for i,y in enumerate(newlst):
flag=x<y if asc else x>y
if flag:
newlst.insert(i,x)
break
else:
newlst.append(x)
return newlst
lst=[2,1,3]
print(sort(lst))
print(sort(lst,asc=True))
执行
python sort.py
[3, 2, 1]
[1, 2, 3]
列表排序
cat >sortfun.py<<EOF
#!/usr/bin/env pthon
def sort(lst,asc=False):
def compare(a,b):
return a<b if asc else a>b
newlst=[]
for x in lst:
for i,y in enumerate(newlst):
if compare(x,y):
newlst.insert(i,x)
break
else:
newlst.append(x)
return newlst
lst=[2,1,3]
print(sort(lst))
print(sort(lst,asc=True))
EOF
python sortfun.py
[3, 2, 1]
[1, 2, 3]
列表倒序排序
cat> sortfun2.py<<EOF
#!/usr/bin/env pthon
def compare(a,b):
return a>b
def sort(lst):
newlst=[]
for x in lst:
for i,y in enumerate(newlst):
if compare(x,y):
newlst.insert(i,x)
break
else:
newlst.append(x)
return newlst
lst=[2,1,3]
EOF
执行代码
print(sort(lst))
python sortfun2.py
[3, 2, 1]
列表倒序排列 sort(fn)
cat sortfunfn.py
#!/usr/bin/env pthon
def compare(a,b):
return a>b
def sort(lst,fn):
newlst=[]
for x in lst:
for i,y in enumerate(newlst):
if fn(x,y):
newlst.insert(i,x)
break
else:
newlst.append(x)
return newlst
lst=[2,1,3]
print(sort(lst,compare))
执行代码
python sortfunfn.py
[3, 2, 1]
列表排序(sort结合lambda)
cat >sortfunlambda.py<<EOF
#!/usr/bin/env pthon
def sort(lst,fn=lambda a,b:a>b):
newlst=[]
for x in lst:
for i,y in enumerate(newlst):
if fn(x,y):
newlst.insert(i,x)
break
else:
newlst.append(x)
return newlst
lst=[2,1,3]
print(sort(lst))
EOF
执行代码
python sortfunlambda.py
[3, 2, 1]