gpt4 book ai didi

python - 在 python 中查找不同的对及其乘积

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:59 25 4
gpt4 key购买 nike

我正在学习 python,我不期望得到答案。我真的需要帮助。

我收到了多个列表,我需要检查这些列表以确保:

a) 这不是一个空列表

b) 列表中有多个整数

c) 通过检查不同的对来检查列表中的整数是否具有偶数乘积值或奇数乘积值。例如list1 = [1,2,3]。这将返回 False,因为产品是偶数。 list2 = [3,2,3] 将返回 True,因为两个奇数对的乘积是奇数。

以下是我的一些想法:

a) 要检查它是否为空列表,您可以键入:

if not myList: 
return(False)

if myList != []: 
return(True)

b)

if myList != 1: 
return(True)

if int in myList < 0 and if int in myList > 2: 
return(False)

c)

if len(myList) % 2 == 0: 
return(False)

因为如果有两个偶数 double ,那么无论哪种方式它都会返回。我只是想找到奇怪的产品。

   if len(myList) % 2 != 0:
for i in myList:
if i % i == 1:
return(True)
else:
return(False)

我应该对此进行测试,但实际上我只是想出了写这篇文章的方法。找到配对是相当困难的。

我认为如果最终结果是 1 那么它们是相同的数字 - 对吧?第一次使用这个网站,所以我不熟悉问题的标准协议(protocol)(不过我确实阅读了规则)。

抱歉,如果这很长,感谢所有帮助我的人!

最佳答案

a) It is not an empty list

您的空容器检查看起来不错(只需删除括号)

if not myList: 
return False

b) It has more than one integer within the list

这不起作用,这是数字检查而不是列表长度检查:

if myList != 1: 
return(True)

您可能想要(这也处理大小写“a”):

if len(myList) < 2:
return False

c) Check if the integers within the list has an even product value or an odd product value by checking for distinct pairs.

这个很棘手,因为您的解释似乎与您的示例不一致:

For example list1 = [1,2,3]. This would return False because the product is even. list2 = [3,2,3] would return True because the product of the two odd pairs is odd.

两个列表的乘积均为偶数,但您为其中一个返回 True,为另一个返回 False

您随后的解释似乎暗示您想要确定奇偶性,而不需要通过注意所有奇数元素=奇数乘积(True)和任何偶数元素=偶数乘积(False)来确定奇偶性,这会导致两个可能的谓词:

def are_all_odd(myList):  # odd product True; even product False
return all(element % 2 for element in myList)

def is_any_even(myList): # even product True; odd product False
return any(element % 2 == 0 for element in myList)

但是模运算符%是除法,它和乘法一样昂贵。为了避免这种情况,我们可以逐位执行此操作:

def are_all_odd(myList):  # odd product True; even product False
return all(element & 1 for element in myList)

def is_any_even(myList): # even product True; odd product False
return any(~element & 1 for element in myList)

使用生成器作为 any()all() 的输入意味着一旦确定答案,它们就会停止。但是,数据可能不是最佳顺序,以最大限度地减少测试数量。

关于python - 在 python 中查找不同的对及其乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41752725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com