Python练习(一)
分别用for、while、递归求列表的和
>>> def list_sum(argument_list): sum = 0 for arg in argument_list: sum += arg print('for =>',sum) sum = 0 count = len(argument_list) while count > 0: sum += argument_list[count-1] count -= 1 print('while =>',sum) def recursion_sum(arg_list): if len(arg_list) == 1: return arg_list[0] else: return arg_list[len(arg_list)-1] + recursion_sum(arg_list[:len(arg_list)-1]) sum = recursion_sum(argument_list) print('recursion =>', sum) >>> list_sum([1, 2, 3, 4, 5]) for => 15 while => 15 recursion => 15
交错合并列表函数
>>> def interlaced_combination_fun(a_list, b_list): result = []; for i in range(min(len(a_list), len(b_list))): if i < len(a_list): result.append(a_list[i]) if i < len(b_list): result.append(b_list[i]) print(result) >>> interlaced_combination_fun([1, 3, 5, 7, 9], [2, 4, 6, 8]) [1, 2, 3, 4, 5, 6, 7, 8]
给定非负整数列表中数字排列成最大数字
>>> def from_list_get_maxnum(arg_list): for i in range(len(arg_list)): for j in range(i): for k in range(min(arg_list[i]//10+1, arg_list[j]//10+1)): if int(str(arg_list[j])[k]) < int(str(arg_list[i])[k]): arg_list[j], arg_list[i] = arg_list[i], arg_list[j] break result = '' for arg in arg_list: result = result + str(arg) result = int(result) return result >>> from_list_get_maxnum([50, 2, 1, 9]) 95021
计算前100位的斐波那契函数
>>> def fibonacci(x): a, b = 0, 1 print(a, end=' ') while 1: if a+b > 100: break a, b = b, a+b print(b, end = ' ') >>> fibonacci(100) 0 1 2 3 5 8 13 21 34 55 89
123456789顺序不能变,数字之间插入加减或什么都不插入,使结果总在100,输出所有可能性
>>> def fun(numbers, build): if(numbers): for char in ["+","","-"]: tmp = build + char + numbers[0] fun(numbers[1:], tmp) elif(eval(build) == 100): print(build) >>> fun("23456789","1") 1+2+34-5+67-8+9 1+2+3-4+5+6+78+9 1+23-4+5+6+78-9 1+23-4+56+7+8+9 12+3+4+5-6-7+89 12+3-4+5+67+8+9 123+45-67+8-9 123+4-5+67-89 123-45-67+89 123-4-5-6-7+8-9 12-3-4+5-6+7+89