一. Python 冒泡法排序 def sequence(arrays=list()): def desc(): for i in range(1, len(arrays)): for j in range(len(arrays) - i): if arrays[j] < arrays[j + 1]: arrays[j], arrays[j + 1] = arrays[j + 1], arrays[j] return arrays def asc(): for i in range(1, len(arrays)): for j in range(len(arrays) - i): if arrays[j] > arrays[j + 1]: arrays[j], arrays[j + 1] = arrays[j + 1], arrays[j] return arrays print desc() print asc() if __name__ == "__main__": sequence([1, 2, -1, 10, 12, 9, 13, 14]) 二. 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
def combinations(): num = [1, 2, 3, 4] # 列表解析 res = [i * 100 + j * 10 + k for i in num for j in num for k in num if(j != i and k != j and k != i)] print (res) if __name__ == "__main__": combinations() 三、输出100以内的质数(大于1的且因数只有它自身与1的自然数)
def prime_num(): count = 0 for i in range(2, 100): for j in range(2, i): if i % j == 0: break else: print i, count += 1 print print "total: " + str(count) if __name__ == "__main__": prime_num()
四、打印九九乘法表
def multiplication_tables(): for i in range(1, 10): print for j in range(1, i + 1): print "%d*%d=%d" % (i, j, i * j), if __name__ == "__main__": multiplication_tables()
五、斐波那契数列 def recur_fibo(n): """递归函数 输出斐波那契数列""" if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # 获取用户输入 nterms = int(input("您要输出几项? ")) # 检查输入的数字是否正确 if nterms <= 0: print("输入正数") else: print("斐波那契数列:") for i in range(nterms): print(recur_fibo(i))