在计算机的各种算法中有一种名为“迭代”(Iteration)的算法。这种算法利用了计算机“一个球落地时能计算10亿次”的特性,不断地对问题进行循环验证。这又被抽象为“猜想-验证"(Guess and Check)方法。
About Guess and Check Method:
- Guess and check methods can work on problems with a finite number of possibilities
进一步,猜想-验证方法的本质是穷举法(Exhaustive enumeration)。人脑的特性决定了在计算方面我们使用穷举法的代价非常大,可是计算机却可以轻易地实现。
About Exhaustive Enumeration:
- Exhaustive enumeration is a good way to generate guesses in an organized manner
- literally walk through all possible values of some parameter, some elements of the computation
- test everything until find the right answer
那么这些思想反映到计算机编程内体现出什么样子呢?并且教学语言为Python,更为准确的说,是反映到Python语言里是什么样子呢?答案:循环(loop)
about loop characteristics:
- Need a loop variable
- Initialized outside loop
- Change within loop
- Test for termination depends on variable
- Useful to think about a decrementing function
- Maps set of program variables into an interger
- When loop is entered, value is non-negative (use absolute <abs>)
- When value is <= 0, loop terminates
- Value is decreased every time through loop
Looping structure compares to branching structure:
- Branching structure (conditionals) let us jump to different pieces of code based on a test
- program are constant time
- Looping structure (e.g. while) let us repeat pieces of code until a condition is satisfied (be false)
- programs now take time depends on values of varibles as well as length of program
Instances of while loop:
num = 10
while True:
if num < 7:
print ('Breaking out of loop')
break
print (num)
num -= 1
print ('Outside of loop')
num = 0
while num <= 5:
print (num)
num += 1
print ("Outside of loop")
print (num)
num = 2
while num < 12:
print (num)
num += 2
print ('Goodbye!')
num = 10
print ('Hello!')
while num >0:
print (num)
num -= 2
total = 0
current =1
end = int(input('enter your postive num:'))
while current <= end:
total += current
current += 1
print(total)
网友评论