I have an task to Implement a function parallel_vec(lst1, lst2)
with 2 arguments lst1
and lst2
that are lists of length n
which represent two vectors.
The function will return True
if the vectors are "parallel" otherwise False
.
Definition of parallel vectors
: two vectors v1 = (n1, n2, n3)
and v2 = (k1, k2, k3)
are parallel vectors if the ratio between all components is the same, which is defined as n1 / k1 = n2 / k2 = n3 / k3
This is what I wrote:
lst1 = [1,3,4]
lst2 = [2,6,8]
ind1 = 0
ind2 = 1
while ind2 < len(lst1):
if (lst1[ind1]/lst2[ind1]) == (lst1[ind2]/lst2[ind2]):
ind1 += 1
ind2 += 1
continue
print(True)
#return True
else:
print(False)
I didn't function it yet because I wanted to check if its work but it doesn't. What am I doing wrong?
Create a list of the fractions n1/k1, n2/k2, n3/k3
>>> [1.0, 1.0, 1.0]
Then use set
to remove duplicates (this means the ratios are the same)
Then if this new list length is ==
to one, the vector is parallel
lst1 = [1,3,4]
lst2 = [2,6,8]
vect = [(x/y) for x,y in zip(lst1,lst1)]
if len(set(vect)) == 1:
print(True)
else:
print(False)
You must remove 'continue' from while loop in order to print(True) works
. Your code:
lst1 = [1,3,4]
lst2 = [2,6,8]
ind1 = 0
ind2 = 1
while ind2 < len(lst1):
if (lst1[ind1]/lst2[ind1]) == (lst1[ind2]/lst2[ind2]):
ind1 += 1
ind2 += 1
print(True)
#return True
else:
print(False)
My suggestion for the problem is to use numpy, like below:
import numpy as np
n1=np.array(lst1)
n2=np.array(lst2)
print(len(set(n1/n2))==1)
which actually checks if all fractions are equal
PseudoCode
First check if your lists contain a 0. If so, the lists aren't parallel .
If they don't have zeroes, go through the loop.
lst1 = [1,3,4]
lst2 = [2,6,8]
def parallel(lst1,lst2):
k_factor = lst1[0]/lst2[0]
for i,j in zip(lst1[1:],lst2[1:]):
if i/j != k_factor:
return print("Vectors aren't parrallel")
return print("Vectors are parallel")
parallel(lst1,lst2)
My algorithm needs a check for null values, otherwise it will throw an error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.