How represent the following code in mathematical notation?

145 Views Asked by At

I'm trying to represent the following code in one equation, But I'm confused about that

a=[1,2,3]
b=[1,2]
for i in a:
  temp = []
  for j in b:
    temp.append(i+j)
  result=sum(temp)/len(b)

the result should not be as vector like first iteration the result will be 2.5 , the second 3.5 and third iteration the result will be 4.5

4

There are 4 best solutions below

6
On BEST ANSWER

As a programmer. I would treat both a and b as two finite sets since their domains are finite.

Define set $a$ of length $n$ as $a(n) = a_n$ for $a=\{1,2,3\}$.

Define set $b$ of length $m$ as $b(m) = b_m$ for $b=\{1,2\}$.

Define an sequence of $c$ with length $n$: $$c_i=\frac{\sum_{i=0}^{n}\sum_{j=0}^{m} (a_i+b_j)}{m}$$

I dunno if this notation is mathematically acceptable though.

1
On

For element result[i] (if you start counting i by 1) you have simple:

result[i] = $\frac{1}{2}(\sum_{j=1}^{2} (i + j))$

0
On

As has been noted, $\text{result}$ contains one item per item in $a$, obtained as said item plus the mean of $b$. So we can write $\text{result}_i=a_i+\bar{b}$ or, if we work with vectors, $\text{result}=a+\bar{b}1$, with $1$ a vector whose entries are each equal to one. This is by no means the only way to describe the outcome in mathematical notation, but it is one way.

0
On

Assuming you start with vectors $a$ and $b$, with lengths $len(a)$ and $len(b)$ respectively, and where $a[i]$ and $b[j]$ represent the $i$-th and $j$-element from $a$ and $b$ respectively, the result would be a vector $c$ of length $len(a)$, and such that:

$$\text{for all} \ 1 \leq i \leq len(a): c[i]=\frac{1}{len(b)}\cdot \sum_{j=1}^{len(b)} (a[i]+b[j])$$

And if you don't like vectors:

The first result will be:

$$\frac{1}{len(b)}\cdot \sum_{j=1}^{len(b)} (a[1]+b[j])$$

The second result will be:

$$\frac{1}{len(b)}\cdot \sum_{j=1}^{len(b)} (a[2]+b[j])$$

Etc.

I.e. in general, the $i$-th result will be:

$$\frac{1}{len(b)}\cdot \sum_{j=1}^{len(b)} (a[i]+b[j])$$