Home > Enterprise >  how do I perform the following function for a given list, using python
how do I perform the following function for a given list, using python

Time:11-12

for any given list I need output as shown below

l1 = [2,3,4]

output  = [2*3  3*4   4*2] = [26]

similarly 

l2 = [3,4,5,7,8,3]

output = [3*4   4*5   5*7   7*8   8*3   3*3] = [156]

The length of the list is dynamic and so could go up to 100, and the code needs to dynamically do the calculations based on the length of the list.

Appreciate any help.

CodePudding user response:

Rotate the list by appending the first element to a slice of everything after the first element; then zip the original list with the rotated list. Use sum to generate the actual numeric sum, and str.join with f-strings to generate the rest of the output.

>>> def rot_sum(nums):
...     rot_nums = list(zip(nums, nums[1:]   [nums[0]]))
...     return f"[{'   '.join(f'{a}*{b}' for a, b in rot_nums)}] = [{sum(a * b for a, b in rot_nums)}]"
...
>>> rot_sum([2, 3, 4])
'[2*3   3*4   4*2] = [26]'
>>> rot_sum([3,4,5,7,8,3])
'[3*4   4*5   5*7   7*8   8*3   3*3] = [156]'

CodePudding user response:

Simple solution. Works for me !!!

def fun(l):
    sum=0
    for i in range(len(l)-1):
        sum  = l[i]*l[i 1]
    sum  = l[0]*l[-1]
    return sum
  • Related