Home > Back-end >  How to multiply responding indexes of two lists
How to multiply responding indexes of two lists

Time:09-21

I have two lists:

firstList = [1,2]
secondList = [3,4]

My goal is to multiply matching indexes and add them, assuming that lists always have the same but not hard coded length.

The result:

1 * 3 2 * 4 = 11

I would like solution to don't use existing functions.

CodePudding user response:

If you don't want to use any prebuilt functions, you can do this:


def dot(firstList, secondList):
    summation = 0
    idx = 0
    for i in firstList:
        summation  = i * secondList[idx]
        idx  = 1
    return summation
        

If you're okay with range and len:

def dot(l1, l2):
    temp = [l1[i]*l2[i] for i in range(len(l1))]
    summation = 0
    for i in temp:
        summation  = i
    return summation

If your okay with the sum function:

def dot(l1, l2):
    return  sum(l1[i]*l2[i] for i in range(len(l1)))

You can also for safety add a:

assert len(l1) == len(l2)

CodePudding user response:

A simple solution is iterating over the firstList and doing the computation. Finally, sum the result. To do that, you can use the sum function, or easily using a simple loop.

# you can use `simpleLen` instead of `len`
multiplications = [i * secondList[i-1] for i in firstList if i <= len(secondList)]
# loop to sum elements of multiplications or only `sum(multiplications)`
result = 0
for j in multiplications:
    result  = j

print(result)

However, if you are not happy with the len function, easily can be implemented as of following:

def simpleLen(input_list):
    count = 0
    for i in input_list:
        count  = 1
    return count

Secondly, if you only desire the product of two lists, you can do it like the following:

# if suppose the length of arrays are the same
idx = 0
result = 0
lenght_of_arr = simpleLen(firstList)
while idx < lenght_of_arr:
    result  = (firstList[idx] * secondList[idx])
    idx  = 1

CodePudding user response:

Here's a possible solution using a simple iteration and index values.
We are clearly assuming that lists are always of the same length:

firstList = [1,2]
secondList = [3,4]

result = 0
index = 0
for item in firstList:
    result  = firstList[index] * secondList[index]
    index  = 1


print(result)

Output
11

  • Related