打印三角形(首行最小,靠右对齐)
补空格方式:
def triangle(n):
for i in range(1, n+1):
for j in range(n, 0, -1):
if i < j:
print(' '*len(str(j)), end=' ')
else:
print(j, end=' ')
print()
triangle(10)
向右对齐方式:
def triangle(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)
triangle(10)
打印三角形(首行最大,靠右对齐)
补空格方式:
def triangle(n):
for i in range(1, n+1):
for j in range(n, 0, -1):
if i > j:
print(' '*len(str(j)), end=' ')
else:
print(j, end=' ')
print()
triangle(10)
切片方式:
def triangle(n):
tail = " ".join([str(i) for i in range(n, 0, -1)])
print(tail)
for i in range(len(tail)):
if tail[i] == ' ':
print(' '*i, tail[i+1:])
triangle(10)
求数字N的乘阶
def cal(n):
if n == 1:
return 1
else:
return n * cal(n-1)
print(cal(5))
实现一个排序函数
def sort(iterable, reverse=False, key=None):
new_list = []
for i in iterable:
for x, y in enumerate(new_list):
flag = key(i, y) if reverse else not key(i, y)
if flag:
new_list.insert(x, i)
break
else:
new_list.append(i)
return new_list
result = sort([7, 5, 11, 9], reverse=True, key=lambda a, b: a > b)
print(result)
文档更新时间: 2020-09-20 17:19 作者:闻骏