“”“一个更好的Python代码,可以在一个范围内的两个整数序列中查找公共元素的和??”“”你知道吗
#F() constructs a sequence:
def F():
bot=int(input("Enter start value:"))
#start value
top = int(input("Enter stop value:"))
#stop value
L=range(bot,top+1)
return(L)
# Let L1 and L2 two sequences
L1=F()
L2=F()
print(L1, L2)
#G()returns the sum of the common elements in L1 and L2:
def G(L1, L2):
res = []
for x in L1:
if x in L2:
res.append(x)
return sum(res)
print(G(L1, L2))
# Example: L1=range(1,11), L2=range(5,21): 45(=5+6+7+8+9+10)
如果您的解决方案有效,为什么要寻找“更好的Python代码”?你的代码足够好了。我要做的唯一改变就是列表
res
。你并不真的需要它:如果您确信L1和L2中的所有元素都是唯一的,那么使用
set
的解决方案是好的。在本例中,因为您使用range
生成了它们,所以它们是唯一的,您可以使用:如果存在重复项,则可以过滤元素:
或者你也可以使用列表理解:
但我再说一遍:我认为您的解决方案是好的Python代码。你知道吗
相关问题 更多 >
编程相关推荐