[英]how do i make function in python that check if the lists is vector
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.我的任务是实现一个 function
parallel_vec(lst1, lst2)
和 2 个 arguments lst1
和lst2
,它们是长度为n
的列表,代表两个向量。
The function will return True
if the vectors are "parallel" otherwise False
.如果向量“平行”,则 function 将返回
True
,否则返回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
parallel vectors
的定义:两个向量v1 = (n1, n2, n3)
和v2 = (k1, k2, k3)
如果所有分量之间的比率相同,则为平行向量,定义为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.我还没有 function 它,因为我想检查它是否有效,但它没有。 What am I doing wrong?
我究竟做错了什么?
Create a list of the fractions n1/k1, n2/k2, n3/k3
创建分数
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)然后使用
set
删除重复项(这意味着比率相同)
Then if this new list length is ==
to one, the vector is parallel那么如果这个新的列表长度
==
为 1,则向量是平行的
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
.您必须从 while 循环中删除 'continue' 才能
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:我对这个问题的建议是使用 numpy,如下所示:
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 .首先检查您的列表是否包含 0。如果是,则列表不是并行的。
If they don't have zeroes, go through the loop.如果它们没有零,则 go 通过循环。
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.我的算法需要检查 null 值,否则会抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.