You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 line
8.2 KiB

5 years ago
{"cells":[{"cell_type":"code","execution_count":5,"metadata":{},"outputs":[],"source":"# 百钱白鸡问题1只公鸡5元1只母鸡3元3只小鸡1元100元买100只鸡公鸡母鸡小鸡各有多少\n# 经典三元一次方程求解设各有xyz只\n\n# 解法一推断每种鸡花费依次轮询运行时间最短2019-7-24最优方案\n# import time\n# start = time.perf_counter_ns() # 用自带time函数统计运行时长\nfor x in range(0, 101, 5): # 公鸡花费x元在0-100范围包括100步长为5\n for y in range(0, 101 - x, 3): # 母鸡花费y元在0到100元减去公鸡花费钱数步长为3\n z = 100 - x - y # 小鸡花费z元为100元减去x和y\n if x / 5 + y / 3 + z * 3 == 100:\n print(\"公鸡:%d只母鸡%d只小鸡%d只\" % (x / 5, y / 3, z * 3))\n # pass\n# end = time.perf_counter_ns()\n# time1 = end - start\n# print(\"解法一花费时间:\", time1)\n\n# 解法二:解法和解法一类似\n# 解题思路买一只公鸡花费5元剩余95元(注意考虑到不买公鸡的情况)再买一只母鸡花费3元剩余92元依次轮询下去钱数不断减\n# 少100元不再是固定的。假设花费钱数依次为x、y、z元\nfor x in range(0, 101, 5): # 公鸡花费x元在0-100范围包括100步长为5\n for y in range(0, 101 - x, 3): # 母鸡花费y元在0到100元减去公鸡花费钱数步长为3\n for z in range(0, 101 - x - y):\n if x / 5 + y / 3 + z * 3 == 100 and x + y + z == 100: # 花费和鸡数都是100\n print(\"公鸡:%d只母鸡%d只小鸡%d只\" % (x / 5, y / 3, z * 3))\n\n# 解法三:枚举法\n# 解题思路若只买公鸡最多20只但要买100只固公鸡在0-20之间不包括20;若只买母鸡则在0-33之间不包括33;若只买小鸡则在0-100\n# 之间不包括100\nfor x in range(0, 20):\n for y in range(0, 33):\n z = 100 - x - y # 小鸡个数z等于100只减去公鸡x只加母鸡y只\n if 5 * x + 3 * y + z / 3 == 100: # 钱数相加等于100元\n print(\"公鸡:%d只母鸡%d只小鸡%d只\" % (x, y, z))"},{"cell_type":"code","execution_count":2,"metadata":{},"outputs":[],"source":"# 经典斐波那契数列\n# 定义:https://wikimedia.org/api/rest_v1/media/math/render/svg/c374ba08c140de90c6cbb4c9b9fcd26e3f99ef56\n# 用文字来说就是斐波那契数列由0和1开始之后的斐波那契系数就是由之前的两数相加而得出\n\n# 方法一:使用递归\ndef fib1(n):\n if n<0:\n print(\"Incorrect input\")\n elif n==1:\n return 0 # 第一个斐波那契数是0\n elif n==2:\n return 1 # 第二斐波那契数是1\n else:\n return fib1(n-1)+fib1(n-2)\n\nprint(fib1(2))\n\n\n# 方法二:使用动态编程\nFibArray = [0, 1]\n\n\ndef fib2(n):\n if n < 0:\n print(\"Incorrect input\")\n elif n <= len(FibArray):\n return FibArray[n - 1]\n else:\n temp_fib = fib2(n - 1) + fib2(n - 2)\n FibArray.append(temp_fib)\n return temp_fib\n\n# 方法三:空间优化\ndef fibonacci(n):\n a = 0\n b = 1\n if n < 0:\n print(\"Incorrect input\")\n elif n == 0:\n return a\n elif n == 1:\n return b\n else:\n for i in range(2,n):\n c = a + b\n a = b\n b = c\n return b"},{"cell_type":"code","execution_count":3,"metadata":{},"outputs":[],"source":"# 水仙花数水仙花数即此数字是各位立方和等于这个数本身的数。例153 = 1**3 + 5**3 + 3**3\n# 找出1-1000之间的水仙花数\n# 分别四个数字1,2,3,4组成不重复的三位数。问题扩展对于给定数字或给定范围的数字组成不重复的n位数\n\n# 方法一:解答四个数组成不重复三位数(暂未想到更优方法)\nfor x in range(1, 5):\n for y in range(1, 5):\n for z in range(1, 5):\n if (x != y) and (x != z) and (z != y):\n print(x, y,