python穷举法搬砖_唉,Python穷举法和二分查找法的学习

是的,我现在才开始学算法,31岁了,学了2年的Python。努力呗。

Background:

寻找任意非负数的平方根。

平方根-http://www.bing.com/knows/search?q=%E5%B9%B3%E6%96%B9%E6%A0%B9&mkt=zh-cn&FORM=BKACAI

平方根,又叫二次方根,表示为〔√ ̄〕,其中属于非负数的平方根称之为算术平方根。如:数学语言为:√ ̄16=4。语言描述为:根号下16=4

Think:

程序需要做的事是寻找平方根的一个近似解,也就是说,一个足够接近真平方根的解。这里认为的“足够接近”就是指和真实解的距离小于一个常数,这个常数称为epsilon。

这里会用到一个abs函数:

abs(x)

Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

参数可以是负数也可以为正数。只会取绝对值,不会做取整。

Round00:

#!/usr/bin/env python

x = 25

epsilon = 0.01

step = epsilon**2

numGuesses = 0

ans = 0.03.125 high= 6.25 ans= 4.6875

low= 4.6875 high=

while abs(ans**2 - x) >= epsilon and ans <= x:

ans += step

numGuesses += 1

print 'numGuesses =', numGuesses

if abs(ans**2 - x) >= epsilon:

print 'Failed on square root of', x

else:

print ans, 'is close to square root of', x

结果:

numGuesses = 49990

4.999 is close to square root of 25

结果只是近似接近于正确答案5, 一共算了49990个数字(好神奇啊!)

Round01

二分法,取最小值和给于的最大值中间的数。拿这个中间数来运算,如果结果比最大值大,说明中间数取大了,就往小的那边取。反之也成立哈。这么几个折中来回下来,很快的缩短范围了。牛!

#!/usr/bin/env python

x = 25

epsilon = 0.01

numGuess = 0

low = 0.0

high = max(1.0, x) # not less than x, other wish use 1.0 as max

ans = (high + low)/2.0 # mid-number

while abs(ans**2 - x) >= epsilon:

print 'low=', low, 'high=', high, 'ans=', ans

numGuess += 1

if ans**2 < x: # this guess is too small

low = ans # then set mid-number is the minimum

else: # conversely

high =ans

ans = (high + low)/2.0 # refresh mid-number

print 'numGuess =', numGuess

print ans, 's close to square root of', x

输出:

low= 0.0 high= 25 ans= 12.5

low= 0.0 high= 12.5 ans= 6.25

low= 0.0 high= 6.25 ans= 3.125

low= 3.125 high= 6.25 ans= 4.6875

low= 4.6875 high= 6.25 ans= 5.46875

low= 4.6875 high= 5.46875 ans= 5.078125

low= 4.6875 high= 5.078125 ans= 4.8828125

low= 4.8828125 high= 5.078125 ans= 4.98046875

low= 4.98046875 high= 5.078125 ans= 5.029296875

low= 4.98046875 high= 5.029296875 ans= 5.0048828125

low= 4.98046875 high= 5.0048828125 ans= 4.99267578125

low= 4.99267578125 high= 5.0048828125 ans= 4.99877929688

low= 4.99877929688 high= 5.0048828125 ans= 5.00183105469

numGuess = 13

5.00030517578 s close to square root of 25

好快啊,13次就找到,可以看到过程也是在第四步就锁定结果在3.125和6.25之间了。有点意思。

所以用二分法的确是个好办法,我之前一直穷举也是呵呵了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值