PYTHON ITERATION CHAPTER 5 READ!!! THE FOR LOOP The for loop as shown below will perform the block of code 5 time and for each iteration the variable i will take on the values 0,1,2,3, and 4 Here are two examples for i in range(5): w = ‘hello’ for s in range(5) print i print w[s] >>> >>> 0 h 1 e 2 l 3 l 4 o >>> >>> THE FOR LOOP Note that the variable need not be used at all for i in range(5): print(“Hello”) >>> for _ in range(3): print() #blank lines >>> Hello Hello Hello Hello >>> Hello #note the _ ?!!? RANGE FUNCTION The range function has three ways it can be used Using one parameter range(n) ->> [0,1,2,3,…,n-1] Using two parameters range(a,n) ->> [a,a+1,a+2,…,n-1] Using three parameters range(a,n,s) ->> [a, a+s, a+2s, a+3s,… ,n-1?] range(start, end, step) is a good way to think about it. PRINTING VALUES 1 TO 10 #forward for i in range(1,11): #backwards for i in range(10,0,-1) print(i, end=‘ ’) print() print(i,end=‘ ’ ) print() >>> >>> 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1 SIDE NOTE ON PRINTING print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout,ie screen) Prints the values to screen by default. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. file: You can place a filename here if you like example print (‘Hello’,’Tom’,sep=‘:’,end=‘;\n’) Hello:Tom; >>> WHAT IS PRINTED BELOW for i in range(5): print(i,i*i, i*i*i) print(‘Done’) sum=0 for i in range(10): sum=sum+i print(‘Sum=‘,sum,sep=‘’) --------------------------------------------------------------------------------------sum=0 sum=0 for i in range(1,10,2): for i in range(1,10): sum=sum+i print(sum) sum=sum+math.sqrt(i) print(sum) A MATH APPLICATION CALCULATING PI There is a series that turns out to generate PI in the LONG run Pi = 4(1/1-1/3+1/5-1/7+1/9… )and so on. See the pattern? sum=0 sign=1 for denom in range(1,1000000,2): #in steps of 2 term=1/denom sum=sum+term*sign # what is the first term that added sign=sign*-1 # flip flop the sign print('PI is approximately=',4*sum) >>> PI is approximately= 3.141590653589692 WHAT DOES THIS MEAN X=X+1 x = 10 print (x) x=x+1 print (x) x=x+1 print (x) #output is 10 11 12 14 Increments x by 1 x=x+2 print (x) Increments x by 2 THE WHILE LOOP (NO AUTO INCREMENTING) x=1 while x < 10: # this is the condition print (x,end=‘’) x=x+1 #The body of the loop (repeated until the # while condition is false) #OUTPUT is 123456789 What if we forget this instruction! WHAT? IS 1+2+3+…+N Mathematically we have + 2 + 3 + … + (n-1) + n S= 1 S= n + (n-1) + (n-2) + … + 2 +1 2S = (n+1)+(n+1)+ (n+1) + … (n+1)+(n+1) 2S = n(n+1) S = n(n+1)/2 Sum of the numbers from 1 to n S = 100(101)/2 = 5050 Sum of the numbers from 1 to 100 LETS DO THIS IN PYTHON ( IN TWO WAYS) #using a for s=0 for i in range(100) #note in this case we start with a 0 s=s+i+1 why do I have a 1 here Because range(100) is [0,1,2,3,4,…,99] print (‘The sum from 1 to 100 is’,s) #using a while loop i=1 s=0 while i<=100: s=s+i i=i+1 print (‘The sum from 1 to 100 is’,s) ADD EVEN NUMBERS FROM 2 TO 100 i=2 # first number is 2 s=0 while i<=100: # stop looping at 100 s=s+i i=i+2 # increment by 2 print (‘The sum of evens from 2 to 100 is’,s) What about the odds.? What about the sum of squares from 1 to 100? WHAT DOES THIS WEIRD FUNCTION DO???? def sequence(n): while n!=1: print (n, end=‘’) if n%2 == 0: n = n/2 Will this always terminate? else: n=n*3+1 sequence(101) >>> 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 >>> HOMEWORK: CALCULATE THE PERCENTAGE OF EVENS IN THE SEQUENCE This is the sequence for 101 >>> 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 >>> Its percentage is 18/25.0 =72.0 I calculated the percentage of evens for all the values from 2 to 100 and graphed this in Excel? I will show you how to do this later on. 100 97 94 91 88 85 82 79 76 73 70 67 64 61 58 55 52 49 46 43 40 37 34 31 28 25 22 19 16 13 10 7 4 1 HERE IS MY OUTPUT ???? 120 100 80 60 40 20 0 CALCULATING SQUARE ROOT A very old method for calculating the square root of a number is to use Newton’s method. Suppose we would like to find the square root of a. We begin using a guess x and use the following formula to get a closer estimate y of the square root . 𝒂 𝒙+ 𝒙 𝒚= 𝟐 def sqroot(a): x = a/2.0 # our initial estimate while abs(a-x**2)> .0000001: x = (x + a/x)/2.0 return x print sqroot(4) print sqroot(16) print sqroot(25) >>> 2.0 4.0 5.00000000002 >>> READ A SET OF NUMBERS FROM THE KEYBOARD AND DO SOMETHING TO THEM (USES INFINITE LOOP AND BREAK) s=0 ct=0 while True: x = input('Enter a number ') # Remember x is a str! if x == 'done': break # The break instruction exits the loop # Do something to the values of x ct = ct+1 #count the numbers s = s+ float(x) #accumulate them and convert x to a float # Display the results print( 'The average is ',float(s)/ct) DETERMINE IF A NUMBER IS PRIME # This is a very inefficient algorithm. Can you do it better? def prime(n): if n < 2 : return False ans = True for i in range(2,n): if n%i == 0 : ans=False return ans print prime(5) print prime(64) print prime(101) print prime (1001) >>> True False True False >>> PRIMENESS OF 1000001? Suppose I would like to determine if 11, 101,1001,10001, 100001, 1000001, and so on are prime. How can I do this? First lets just print these. for i in range(1, 20): v = 10**i + 1 print (v,prime(v)) READ IN A STRING AND COUNT SPECIFIC CHARACTERS #Count the number of a’s in the string x = input('Enter a dna sequence ( i.e. actggect) ') ct_a=0 #variable we count with for i in range(len(x)): if x[i]=='a': ct_a=ct_a + 1 print (ct_a) EXAMPLE PROBLEMS 1. Read in integers until 0 is entered, then print the sum, average, largest and smallest of the entered numbers 2. Read in real numbers from the keyboard and calculate and print the square root of the numbers using Newton’s, method. See chapter 7. Stop when ‘done’ is typed. 3. Calculate PI using ( Ramanujan’s pi formula) https://crypto.stanford.edu/pbc/notes/pi/ramanujan.html 4. Write a function called prime(p) that returns true if p is prime and false otherwise. Test it carefully 5. (a little tougher) Print out the prime factorization of a number. 6. Write a function that receives and input a dna string and a char ( a,c,t,g) and then returns the number of copies of that character that exist in the string.