Solution
import string
def backwards(wordlist):
wordlist.reverse()
return wordlist
#an alternate but harder to write solution
def backwards2(wordlist):
backlist = []
for word in wordlist:
backlist.insert(0,word)
return backlist
#a third possible solution
def backwards3(wordlist):
backlist = []
for i in range(len(wordlist)-1, -1, -1):
backlist.append(wordlist[i])
return backlist
sentence = ['how', 'are', 'you']
print string.join(backwards(sentence)),'?'
#test the second solution
sentence = ['how', 'are', 'you']
print string.join(backwards2(sentence)),'?'
#test the third solution
print string.join(backwards2(sentence)),'?'
Write a program which draws a sine wave by printing out
successive lines to the terminal which contain a capital 'O' character
with a varying number of spaces in front of it. The the number of
spaces should be determined by formula 30*(1+sin(theta))
.
Make it print one full period of sine in 30 lines Hint:
the print
can print copies of a string by using the '*'
operator to "multiply" strings as follows:
>>> print "Hello"*3
HelloHelloHello
Solution
from math import pi,sin
theta=0
while theta<2*pi:
spaces=int(30*(1+sin(theta)))
print ' '*spaces,'O'
theta+=pi/30
A useful operation on vectors is the dot product. The dot product
of two vectors (Ai+Bj) and (Ci+Dj) is AC+BD, a scalar quantity. Using our convention
of representing 2D vectors as two element Python lists, write a
function called dot()
which takes two vectors as
parameters and returns the dot product. For example:
>>> vector1=[1,2]
>>> vector2=[3,4]
>>> print dot(vector1,vector2)
11
Solution
def dot(a,b):
return a[0]*b[0] + a[1]*b[1]
vector1=[1,2]
vector2=[3,4]
print dot(vector1,vector2)
#It works on words too!
wordvector = ['ha','ho']
repeatvector = [3,2]
print dot(wordvector,repeatvector)
Write a function, vecadd()
which takes as an argument
an arbitrarily long list of 2D vectors, adds them all together and returns the resultant vector.
>>> vec1 = [6,1]
>>> vec2 = [1,6]
>>> vec3 = [-7,-7]
>>> veclist = [vec1,vec2,vec3]
>>> print vecadd(veclist)
[0, 0]
Solution
def vecadd(vectors):
resultant = [0,0]
for v in vectors:
resultant = [resultant[0]+v[0], resultant[1]+v[1]]
return resultant
#Another way of writing it
def vecadd2(vectors):
resultant = [0,0]
for v in vectors:
resultant[0] = resultant[0]+v[0]
resultant[1] = resultant[1]+v[1]
return resultant
vec1 = [6,1]
vec2 = [1,6]
vec3 = [-7,-7]
veclist = [vec1,vec2,vec3]
print vecadd(veclist) # vectors should sum to [0,0]
print vecadd2(veclist)# vectors should sum to [0,0]