0

can someone help me write code in Python for this problem?

x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]

Write up some code to multiply only the negative values. Print the result of these multiplications. Include a loop of some kind as well as an if-statement to grab just the negative numbers.

This is what I have so far:

x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]

for num in x:
    if num < 0:
        print (num, end = "")
Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76

3 Answers3

0

IIUC, here's one way via reduce

from functools import reduce
x = [10, -5, 6, -7, 2, 4, -9, 12, -55, 33, 44, 77, -1]

result = reduce(lambda x, y: x*y, (i for i in x if i < 0))

OUTPUT:

17325
Nk03
  • 14,699
  • 2
  • 8
  • 22
0

You almost got it. I think they want you to do a simple script:

x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]

result = 1
for num in x:
    if num < 0:
        result = result * num
        # or result *= num

print(result)
Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
0

With basic arithmetic and closest to your original version:

total = 0 if len(x)==0 else 1

for i in x:
    if i < 0:
        total *= i

print(total, end = "")

17325

borrowing from https://stackoverflow.com/a/13843424/1248974