Home > Software engineering >  Given array size of four, minus from element 0 and plus to element 1, 2 and 3
Given array size of four, minus from element 0 and plus to element 1, 2 and 3

Time:11-28

I am just looking for ideas that I can carry out such action or a name to "Google" or to learn such ideas.

Given a set of array

a = [10,5,3,6]

My target is to minus 3 from a, and add back to a[1],a[2] and a[3] respectively.

Example

a = [10,5,3,6]
New Result:
a = [7,8,3,6]
a = [7,5,6,6]
a = [7,5,3,9]

a = [7,6,5,6]
a = [7,6,4,7]

And so on, what type of implementation can I carry out? This example is only for a[0], and -3, my ultimate goal is to implement to a[1],a[2],a[3] and variable of minus - minus 3 from a[1], a[2], and a[3], and add back to other.

CodePudding user response:

import itertools
def my_combinations(my_list, k):
    for item in itertools.product(range(k 1), repeat=len(my_list) - 1):
        if sum(item) == k:
            yield item, [my_list[0] - k]   [n   i for n, i in zip(my_list[1:], item)]


spam = [10, 5, 3, 6]
for item, lst in my_combinations(spam, 3):
    print(f'{item} --> {lst}')

output:

(0, 0, 3) --> [7, 5, 3, 9]
(0, 1, 2) --> [7, 5, 4, 8]
(0, 2, 1) --> [7, 5, 5, 7]
(0, 3, 0) --> [7, 5, 6, 6]
(1, 0, 2) --> [7, 6, 3, 8]
(1, 1, 1) --> [7, 6, 4, 7]
(1, 2, 0) --> [7, 6, 5, 6]
(2, 0, 1) --> [7, 7, 3, 7]
(2, 1, 0) --> [7, 7, 4, 6]
(3, 0, 0) --> [7, 8, 3, 6]

CodePudding user response:

I think this is the solution that you are looking for:

a = [10,5,3,6]
k = 3

for i in range(len(a)-1):
    a[i] -= k
    a[i 1]  = k
print(a)

Output:

[7, 5, 3, 9]
  • Related