Python技术问询:不使用乘号求列表元素乘积能否用推导式及单循环?
Hey there! Great question—let's break this down clearly for you as a Python newbie.
Can we use a comprehension for this?
Short answer: Not a standalone comprehension, but you can combine a generator expression with a reduction function to get the job done. Here's why:
- List/dict/set comprehensions are designed to generate collections (lists, etc.), not single scalar values like a product.
- But we can use a generator expression (similar to a list comprehension but lazy) alongside
functools.reduceto aggregate the product step by step—all while avoiding the*operator.
Example code:
from functools import reduce def multiply_no_star(a, b): # Helper function to multiply without using * result = 0 # Handle negative signs first sign = 1 if a < 0: a = -a sign *= -1 if b < 0: b = -b sign *= -1 # Optimize by looping the smaller number of times if b < a: a, b = b, a for _ in range(b): result += a return result * sign # Your target list nums = [2, 3, -4, 5] # Use reduce with a generator expression (or just the list directly) product = reduce(multiply_no_star, (num for num in nums), 1) print(product) # Output: -120
The generator expression (num for num in nums) is optional here (you can pass nums directly to reduce), but it shows how you could pre-process elements if needed—all within a comprehension-style syntax.
Can we get the result with just one loop?
Absolutely! If by "one loop" you mean a single loop over the input list (the most common interpretation), here's how:
- Initialize a
productvariable to 1 (the multiplicative identity). - Loop through each element in the list once, updating
productby multiplying it with the current element (using our no-*helper function each time).
Example code:
def multiply_no_star(a, b): # Same helper as above result = 0 sign = 1 if a < 0: a = -a sign *= -1 if b < 0: b = -b sign *= -1 if b < a: a, b = b, a for _ in range(b): result += a return result * sign nums = [2, 3, -4, 5] product = 1 # Single loop over the list for num in nums: product = multiply_no_star(product, num) print(product) # Output: -120
If you wanted to eliminate even the small inner loop in multiply_no_star, that's trickier (you'd need bitwise operations or math hacks), but for most practical purposes, this counts as "one loop" over your input list—and it's easy to understand as a newbie.
内容的提问来源于stack exchange,提问作者Hussein Al-Obaidy

