1

I am curious if there is a way of somehow recreating such code as a math statement.

S = [1,2,3,4]
output = 0

for x in S:

N = S.copy()
N[x-1] = 0

for y in N:
    output = output + y

The only thing that I could think of is reminiscent of something like this, but I have no clue how I could change the numbers in the second array, nor how to duplicate the array. $$\sum_{x \in S}{\sum_{y \in N}{y}}$$

The solution is 30. ( 0+2+3+4+1+0+3+4+1+2+0+4+1+2+3+0)

abno525
  • 13

2 Answers2

0

Let me rewrite your code a bit:

S = [1,2,3,4]
output = 0

for x in S: output += sum(S) - S[x - 1]

Or equivalently, output = len(S) * sum(S) - sum(S[x - 1] for x in S). Therefore, we can write it as (0-indexed)

$$|S|\sum S - \sum_{x\in S} S[x - 1]$$

Though as you can tell, it depends very specifically on what $S$ is, and that order matters.

Gareth Ma
  • 3,725
0

This code can be written as \begin{align*} \color{blue}{\sum_{x=1}^4\sum_{{y=1}\atop{y\ne x}}^4 y}\tag{1} &=\sum_{x=1}^4\left(\sum_{y=1}^4y-x\right)\\ &=4\sum_{y=1}^4y-\sum_{x=1}^4x\\ &=3\sum_{x=1}^4 x\\ &=3\,\frac{4\cdot 5}{2}\\ &\,\,\color{blue}{=30} \end{align*} resulting in $30$ as stated by OP. Here the left-hand sum of (1) represents rather verbatim the two for-loops written as double sum.

Markus Scheuer
  • 108,315