|
First Summer 2006 |
def scalarProduct(a, b):
sum = 0
for i in range(len(a)):
sum += a[i] * b[i]
return sum
print scalarProduct([1, -1, 2], [2, 0, 1])
If we test this it produces a 4, which is correct.
We can now move to the second problem, alternatingSum:
def alternatingSum(a):
sum = 0
for i in range(len(a)):
if i % 2 == 0:
sum = sum + a[i]
else:
sum = sum - a[i]
return sum
print alternatingSum([1, 4, 9, 16, 9, 7, 4, 9, 11])The next method can reverse a list of numbers:
def reverse(a):
result = []
for e in a:
result.insert(0, e)
return result
print reverse([1, 2, 3, 4, 5, 6])Next problem is easy:
def equals(a, b):
return a == bBut, of course, we didn't mean it that way:
def equals(a, b):
if len(a) != len(b):
return False
else:
for i in range(len(a)):
if a[i] != b[i]:
return False
return True
print [1, 2] == [2, 1]
print [1, 2] == [1, 2, 1]
print [1, 2] == [1, 2]Next problem (and the one that follows) have been posted on What's New? for Jun 8:
def sameSet(a, b):
for i in range(len(a)):
if not a[i] in b:
return False
for elem in b:
if not contains(a, elem):
return False
return True
def contains(a, elem):
for e in a:
if e == elem:
return True
return FalseHere's then the last one:
def sameElements(a, b): # other approach sort then equals
for e in a:
if count(e, a) != count(e, b):
return False
for e in b:
if count(e, a) != count(e, b):
return False
return True
def count(elem, a):
sum = 0
for i in a:
if i == elem:
sum += 1
return sumWith this we're ready for the Practical Exam (and, soon, for the Final Exam as well).