Home > database >  how do I multiply each element in a list by its position in the list python
how do I multiply each element in a list by its position in the list python

Time:10-17

For example if I have 2452834, then the sum = 1x2 2x4 3x5 4x2 5x8 6x3 7x4 = 2 8 15 8 40 18 28 = 119 this is what I got I think im on the right track.

base_id_num = input()

n=0
for z in range (1, len(base_id_num)):
    base_id_num[n] = base_id_num[n] * n
    n =1

print(base_id_num)

CodePudding user response:

Assuming we're passing in a string, this can be done similarly to how you're doing it, but zero-indexing your string indices:

base_id_num = input()
result = 0
for i in range(len(base_id_num)):
    result  = i * int(base_id_num[i])
print(result)

CodePudding user response:

Assuming that you are taking input as a string.

Instead of creating a new variable and accessing the item by index, you can use the built-in function enumerate() for this task.

result = 0
base_id_num = input()
for index,item in enumerate(base_id_num):
   result  = int(item) * index
print(result)

CodePudding user response:

You can use enumerate after converting it to list, which will provide you with index (at index 0) and value (at index 1). After which, use map to multiply and finally sum them

sum(map(lambda x: (x[0] 1) * int(x[1]), enumerate(list(input()))))

for 2452834, this will give you

119

CodePudding user response:

Use list comp, and built-in sum() function:

b = list(base_id_num) #assuming the base_id_number is of type str

result = sum(int(i) * (id 1)  for id, i in enumerate(b))

output:

print(result)
119
  • Related