In [1]:
def sumOfN(n):
theSum = 0
for i in range(1,n+1):
theSum = theSum + i
return theSum
print(sumOfN(10))
In [2]:
def foo(tom):
fred = 0
for bill in range(1,tom+1):
barney = bill
fred = fred + barney
return fred
print(foo(10))
In [3]:
import time
def sumOfN2(n):
start = time.time()
theSum = 0 # 1 assignment
for i in range(1,n+1):
theSum = theSum + i # n assignments
end = time.time()
return theSum, end-start # (1 + n) assignements
In [10]:
for i in range(5):
print("Sum is %d required %10.7f seconds " % sumOfN2(10000) )
In [11]:
for i in range(5):
print("Sum is %d required %10.7f seconds " % sumOfN2(100000) )
In [12]:
for i in range(5):
print("Sum is %d required %10.7f seconds " % sumOfN2(1000000) )
In [15]:
def sumOfN3(n):
start=time.time()
theSum = (n*(n+1))/2
end=time.time()
return theSum, end-start
print(sumOfN3(10))
In [17]:
for i in range(5):
print("Sum is %d required %10.7f seconds " % sumOfN3(10000*10**(i)) )
A good basic unit of computation for comparing the summation algorithms might be to count the number of assignment statements performed.
In [28]:
def findmin(X):
start=time.time()
minval= X[0]
for ele in X:
if minval > ele:
minval = ele
end=time.time()
return minval, end-start
In [29]:
def findmin2(X):
start=time.time()
L = len(X)
overallmin = X[0]
for i in range(L):
minval_i = X[i]
for j in range(L):
if minval_i > X[j]:
minval_i = X[j]
if overallmin > minval_i:
overallmin = minval_i
end=time.time()
return overallmin, end-start
In [21]:
import random
In [30]:
for i in range(5):
print("findmin is %d required %10.7f seconds" % findmin( [random.randrange(1000000) for _ in range(10000*10**i)] ) )
In [31]:
for i in range(5):
print("findmin2 is %d required %10.7f seconds" % findmin2( [random.randrange(1000000) for _ in range(10000*10**i)] ) )
In [34]:
def anagramSolution(s1,s2):
""" @fn anagramSolution
@details 1 string is an anagram of another if the 2nd is simply a rearrangement of the 1st
'heart' and 'earth' are anagrams
'python' and 'typhon' are anagrams
"""
A = list(s2) # Python strings are immutable, so make a list
pos1 = 0
stillOK = True
while pos1 < len(s1) and stillOK:
pos2 = 0
found = False
while pos2 < len(A) and not found:
if s1[pos1] == A[pos2]: # given s1[pos1], try to find it in A, changing pos2
found = True
else:
pos2 = pos2+1
if found:
A[pos2] = None
else:
stillOK = False
pos1 = pos1 + 1
return stillOK
In [35]:
anagramSolution("heart","earth")
Out[35]:
In [36]:
anagramSolution("python","typhon")
Out[36]:
In [37]:
anagramSolution("anagram","example")
Out[37]:
2.4.2. Sort and Compare Solution 2
In [ ]:
def anagramSolution2(s1,s2):