Week2
简单算法
迭代 :多次重复方法,一遍重复利用计算多次执行。
循环结构
逐次逼近法 二分算法
当型循环
while bool值测试:
Bool值为真,顺序执行指令
循环外设置迭代变量,测试变量,改变循环内变量
命令break在一个循环中被执行,它会在这个位置停止计算这个循环,然后传递控制权到下一个表达式
num = 0
while num <= 5:
print num
num += 1
print "Outside of loop"
print num
0, 1, 2, 3, 4, 5, 'Outside of loop', 6
注意看题
n = 0
s = 0
while end > 0:
end -= 1
n += 1
s += n
print s
_________________
total = 0
current = 1
while current <= end:
total += current
current += 1
print tota
abs( )绝对值
猜测和检测:对有限可能的问题有效。
穷举:从可能值域的一端开始,顺序尝试每个值。
for 标识符in 序列:
代码块
range(n) = [0,1,2,3,...,n-1]
range(m,n) = [m,m+1,m+2,...,n-1]
school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
elif char == 'o' or char == 'M':
print char
else:
numCons -= 1
print 'numVowels is: ' + str(numVowels)
print 'numCons is: ' + str(numCons)
注意空格 正负数
十进制 二进制
比较x,y 利用绝对差
x = 23
epsilon = 0.01
step = 0.1
guess = 0.0
while abs(guess**2-x) >= epsilon:
if guess <= x:
guess += step
else:
break
if abs(guess**2 - x) >= epsilon:
print 'failed'
else:
print 'succeeded: ' + str(guess)
#x=23 情况下,guess^2-x永远大于0.01
_____________________________
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) >= epsilon:
guess += step
if abs(guess**2 - x) >= epsilon:
print 'failed'
else:
print 'succeeded: ' + str(guess)
没有设定break while部分无法返回
二分查找
最大值,最小值
减少运算次数
拥有排序属性的数据
x = #待猜测
epsilon = 0.01 #判断偏差
low = 0.0 #最小值
high = x #最大值
ans = (high + low)/2.0 #猜测值=(最小值+最大值)/2
while abs(ans**2 - x) >= epsilon:
if ans**2 < x: #猜测值^2小于x
low = ans #最小值是猜测值
else:
high = ans #最大值是猜测值
ans = (high + low)/2.0 #重新生成猜测值
print(str(ans) + ' is close to square root of ' + str(x))
———————————————————————
hige = 100
low = 0
num = (hige +low)/2
print "Please think of a number between 0 and 100!"
while not False:
print "Is your secret number ?",
print str(num)
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low.",
print "Enter 'c' to indicate I guessed correctly."
guess = raw_input(">")
if guess == 'c':
break
elif guess == 'h':
hige = num
elif guess == 'l':
low = num
else:
print "Sorry, I did not understand your input."
num = (hige +low)/2
print "Game over. Your secret number was:" + str(num)
猜测数字,可以设置安全值
guseeed = False
while not guessed:
if guess == ‘c’:
guessed = True
牛顿拉夫逊算法
epsilon = 0.01
y = #猜测值
guess = y/2.0
while abs(guess*guess - y) >= epsilon:
guess = guess - (((guess**2) - y)/(2*guess))
print(guess)
print('Square root of ' + str(y) + ' is about ' + str(guess))