从倍数列表中计算乘积

2024-04-25 06:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python赋值,它要求我创建一个函数,返回一个倍数的数字列表。然后,编写另一个函数,获取数字列表并计算列表中所有项的乘积。函数中必须使用For循环。你知道吗

输出应如下所示:

Enter multiple of: 2
Enter an upper limit: 10
[2, 4, 6, 8, 10] 
product is 3840

但我无法让第二个函数工作,它打印0。你知道吗

#from functools import reduce # Valid in Python 2.6+, required in Python 3
#import operator

a = []
def func_list(multi,upper,a):
    for i in range (upper):
        if i % multi == 0:
            a.append(i) #DOESNT INCLUDE THE UPPER LIMIT

multi = int(input("Enter multiple of: "))
upper = int(input("Enter an upper limit: ")) 

func_list(multi,upper,a)
print(a)

#b 
#input = list of number (param)
#output = calculates the product of all the list (sum)

def prod(a):
    prod1 = 1 
    for i in a:
        prod1 *= i 
    return prod1
    #return reduce(operator.mul, a, 1)
#func_list(multi,upper)

prod(a)
print (prod(a))

我得到的结果是:

Enter multiple of: 2  
Enter an upper limit: 10
[0, 2, 4, 6, 8] I don't know how to inc. the limiter, but it's not my concern yet.
0 not right

我试着使用reduce,但我不知道我是否做了不正确的事情,因为它不起作用。你知道吗


Tags: ofthe函数inanreduce列表input
2条回答
import numpy as np

def multiples_list(numbers, upper):
    '''
    Create a function that returns a list of multiples
    with a upper limit of 10.
    '''
    numbers_list = []

    for number in numbers:
       if number <= upper and number % 2 == 0:
           numbers_list.append(number)


    return numbers_list 


def product_of_multiples(numbers):

    new_numbers = []
    for num in numbers:
        new_numbers.append(num)

    numbers_array = np.array(new_numbers)

    product = np.product(numbers_array)

    return product


#numbers_list = list(int(input('Please enter a series of numbers: ')))

numbers_list = [2, 4, 6, 8, 10]

print(multiples_list(numbers_list, 10))

print(product_of_multiples(numbers_list))

以下是输出:

[2, 4, 6, 8, 10]
3840

我在乘积函数中所做的是从作为参数传递的列表中创建一个新列表。我们使用for循环附加到新列表。我们可以把新名单传给np.数组()从for循环后的列表中创建数组。我们可以使用np.产品()函数并传递列表的数组,然后返回产品的完全格式化版本。你知道吗

Python的range()已经内置了这个功能:range(start, stop, increment)

简单地说:

def func_list(multi,upper,a):
    a = list(range(multi, upper+1, a))

如果需要使用for循环:

def func_list(multi,upper,inc):
    for i in range(multi, upper+1, inc):
        a.append(i)

你的第二个产品功能确实有效。打印0的原因是因为这一行:for i in range (upper):。这将导致0附加到列表中,使产品为0。你知道吗

相关问题 更多 >