简体   繁体   中英

how to find product of each integer with modulo in a list in python

I m trying to find the product of each element in a list. lets say containing 1000 elements with value above 200 each and taking mod(%1000000007) each time an element is multiplied with other one.Below given code works fine with smaller values but for large input I m getting Runtime Error - NZEC

    mul=1
t = int(input())
s=input()
for i in range(0,2*t,2):
    k=int(s[i])
    mul=(mul*k)%1000000007
print(mul)

INPUT is in the form:

5

1 2 3 4 5

The problem is the way the numbers are handled, and not the operation that you use.

What I mean is that when you input:

89 100 200 678 123  #EDIT- CHANGED FOR NO COMMAS

the variable that is created is then a string like this:

s = "89 100 200 678 123"

In python, when you try to iterate through a string like this:

s[i]

the string is being read as a list like so:

s = ['8','9',' ','1','0','0',' ','2','0','0',' ','6','7','8',' ','1','2','3']

So this part:

for i in range(0,2*t,2): #t=5
    k=int(s[i])

gets the following elements:

k='8'
k=' '
k='0'
k=' '
k='0' 

which is probably why you get an error.

My solution would be to get the input as a list, by using:

numbers = input().split(" ")

Then with a normal for you will get:

for i in range(t):
    k=int(numbers[i])
    mul=(mul*k)%1000000007
print(mul)

EDIT:

I have added code that works for me, please tell me if it works for you:

mul=1
t = int(input()) #5
numbers = input().split(' ') #11 2 15 3 99
for i in range(t):
    k=int(numbers[i])
    mul=(mul*k)%1000000007
print(mul) #98010

I think the non-zero return(NZEC) exists because you are trying to take multiple inputs delimited by space within a single variable.so to take multiple inputs in the array list you need to change your code to something like this.

integers_list = [int(i) for i in input().split(' ')]
integers_list

output:-[22, 33, 11]

so, now the data in our list is stored perfectly now you can manipulate them however you wish.

For multiplication of list elements you can check it out here:- How can I multiply all items in a list together with Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM