logo资料库

麻省理工学院公开课:计算机科学及编程导论_代码..pdf

第1页 / 共36页
第2页 / 共36页
第3页 / 共36页
第4页 / 共36页
第5页 / 共36页
第6页 / 共36页
第7页 / 共36页
第8页 / 共36页
资料共36页,剩余部分请下载后查看
6.00 Handout, Lecture 2 (Not intended to make sense outside of lecture) Fall 2008 if 'x'0): y = y + x itersLeft = itersLeft - 1 #print 'y =',y,',itersLeft=',itersLeft print y x = 10 i = 1 while(i
6.00 Handout, Lecture 3 (Not intended to make sense outside of lecture) Fall 2008 #Find the square root of a perfect square x = 16 ans = 0 while ans*ans <= x: ans = ans + 1 print ans ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 print 'ans =', ans if ans*ans != x: print x, 'is not a perfect square' else: print ans else: print x, 'is a negative number' x = 10 i = 1 while(i
6.00 Handout, Lecture 4 (Not intended to make sense outside of lecture) #example code for finding square roots x = 16 ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 print 'ans =', ans if ans*ans != x: print x, 'is not a perfect square' else: print ans else: print x, 'is a negative number' def sqrt(x): """Returns the square root of x, if x is a perfect square. Prints an error message and returns None otherwise""" ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x: print x, 'is not a perfect square' return None else: return ans else: print x, 'is a negative number' return None def f(x): x = x + 1 return x x = 3 z = f(x) print x print z def solve(numLegs, numHeads): for numChicks in range(0, numHeads + 1): numPigs = numHeads - numChicks totLegs = 4*numPigs + 2*numChicks if totLegs == numLegs: return (numPigs, numChicks) return (None, None) def barnYard(): heads = int(raw_input('Enter number of heads: ')) legs = int(raw_input('Enter number of legs: ')) pigs, chickens = solve(legs, heads) if pigs == None: print 'There is no solution' else: print 'Number of pigs:', pigs print 'Number of chickens:', chickens
def solve1(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 8*numSpiders if totLegs == numLegs: return (numPigs, numChicks, numSpiders) return (None, None, None) def barnYard1(): heads = int(raw_input('Enter number of heads: ')) legs = int(raw_input('Enter number of legs: ')) pigs, chickens, spiders = solve1(legs, heads) if pigs == None: print 'There is no solution' else: print 'Number of pigs:', pigs print 'Number of chickens:', chickens print 'Number of spiders:', spiders def solve2(numLegs, numHeads): solutionFound = False for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 8*numSpiders if totLegs == numLegs: print 'Number of pigs: ' + str(numPigs) + ',', print 'Number of chickens: '+str(numChicks)+',', print 'Number of spiders:', numSpiders solutionFound = True if not solutionFound: print 'There is no solution.' def isPalindrome(s): """Returns True if s is a palindrome and False otherwise""" if len(s) <= 1: return True else: return s[0] == s[-1] and isPalindrome(s[1:-1]) def fib(x): """Return fibonacci of x, where x is a non-negative int""" if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)
6.00 Handout, Lecture 5 (Not intended to make sense outside of lecture) def squareRootBi(x, epsilon): """Return y s.t. y*y is within epsilon of x""" assert epsilon > 0, 'epsilon must be postive, not' + str(epsilon) low = 0 high = max(x, 1) guess = (low + high)/2.0 ctr = 1 while abs(guess**2 - x) > epsilon and ctr <= 100: #print 'low:', low, 'high:', high, 'guess:', guess if guess**2 < x: low = guess else: high = guess guess = (low + high)/2.0 ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'Bi method. Num. iterations:', ctr, 'Estimate:', guess return guess def squareRootNR(x, epsilon): """Return y s.t. y*y is within epsilon of x""" assert epsilon > 0, 'epsilon must be postive, not' + str(epsilon) x = float(x) guess = x/2.0 guess = 0.001 diff = guess**2 - x ctr = 1 while abs(diff) > epsilon and ctr <= 100: #print 'Error:', diff, 'guess:', guess guess = guess - diff/(2.0*guess) diff = guess**2 - x ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'NR method. Num. iterations:', ctr, 'Estimate:', guess return guess
6.00 Handout, Lecture 6 (Not intended to make sense outside of lecture) def squareRootBi(x, epsilon): """Assumes x >= 0 and epsilon > 0 Return y s.t. y*y is within epsilon of x""" assert x >= 0, 'x must be non-negative, not' + str(x) assert epsilon > 0, 'epsilon must be positive, not' + str(epsilon) low = 0 high = x guess = (low + high)/2.0 ctr = 1 while abs(guess**2 - x) > epsilon and ctr <= 100: #print 'low:', low, 'high:', high, 'guess:', guess if guess**2 < x: low = guess else: high = guess guess = (low + high)/2.0 ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'Bi method. Num. iterations:', ctr, 'Estimate:', guess return guess ------------------------------------- def squareRootNR(x, epsilon): """Assumes x >= 0 and epsilon > 0 Return y s.t. y*y is within epsilon of x""" assert x >= 0, 'x must be non-negative, not' + str(x) assert epsilon > 0, 'epsilon must be positive, not' + str(epsilon) x = float(x) guess = x/2.0 guess = 0.001 diff = guess**2 - x ctr = 1 while abs(diff) > epsilon and ctr <= 100: #print 'Error:', diff, 'guess:', guess guess = guess - diff/(2.0*guess) diff = guess**2 - x ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'NR method. Num. iterations:', ctr, 'Estimate:', guess return guess
Techs = ['MIT', 'Cal Tech'] print Techs Ivys = ['Harvard', 'Yale', 'Brown'] print Ivys Univs = [] Univs.append(Techs) print Univs Univs.append(Ivys) raw_input() print Univs raw_input() for e in Univs: print e for c in e: print c raw_input() Univs = Techs + Ivys print Univs raw_input() Ivys.remove('Harvard') print Univs Ivys[1] = -1 print Ivys L1 = [1, 2, 3] L2 = L1 L1[0] = 4 print L2 def f(L): L[0] = 4 L1 = [1,2,3] L2 = [1,2,3] L3 = L1 print L1 == L2 f(L1) print L1 == L2 print L1 print L2 print L3 EtoF = {'one': 'un', 'soccer': 'football'} print EtoF['soccer'] print EtoF[0] print EtoF NtoS = {1: 'one', 2: 'two', 'one': 1, 'two': 2} print NtoS.keys() print NtoS.keys del NtoS['one'] print NtoS L = [['un', 'one'], ['deux', 'two']] def keySearch(L, k): if elem[0] == k: return elem[1] for elem in L: return None print keySearch(L, 'deux') L1 = [1,2,3] L2 = L1[:] #makes a copy of L1 L = [['un', 'one'], ['deux', 'two']] def keySearch(L, k): for elem in L: if elem[0] == k: return elem[1] return None
Lecture 7 handout 6.00 Fall Term 2008 import math #Get base inputOK = False while not inputOK: base = input('Enter base: ') if type(base) == type(1.0): inputOK = True else: print('Error. Base must be floating point number.') #Get Height inputOK = False while not inputOK: height = input('Enter height: ') if type(height) == type(1.0): inputOK = True else: print('Error. Height must be floating point number.') hyp = math.sqrt(base*base + height*height) print 'Base: '+str(base)+',height: '+str(height)+', hyp: '+ str(hyp) def getFloat(requestMsg, errorMsg): inputOK = False while not inputOK: val = input(requestMsg) if type(val) == type(1.0): inputOK = True else: print(errorMsg) return val base = getFloat('Enter base: ', 'Error: base must be a float') height = getFloat('Enter height: ', 'Error: height must be a float') hyp = math.sqrt(base*base + height*height) print 'Base: ' + str(base) + ',height: ' + str(height) + ', hyp: ' + str(hyp) def exp1(a,b): ans = 1 while (b>0): ans *= a b -= 1 return ans def exp2(a,b): if b == 1: return a else: return a*exp2(a,b-1) def exp3(a,b):
分享到:
收藏