Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading