1

So, I have this array:

numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27]

What I want to do is to create another array from this one, but now each value of this new array must be equal to the corresponding value in the numbers array multiplied by the following.

For example: the first value of the new array should be 45, as it is the multiplication of 5 (first value) and 9 (next value). The second value of the new array should be 27, as it is the multiplication of 9 (second value) and 3 (next value), and so on. If there is no next value, the multiplication must be done by 2.

So, this array numbers should result in this other array: [45, 27, 57 ,1330, 560, 800, 200, 70, 945, 54]

I only managed to get to this code, but I'm having problems with index:

numbers = [5,9,3,19,70,8,100,2,35,27]
new_array = []
x = 0
while x <= 8: # Only got it to work until 8 and not the entire index of the array
    new_array.append(numbers[x] * numbers[x + 1])
    x += 1
print(new_array)

How can I make it work no matter what is index of the array and then if there's no next number, multiply it by 2? I've tried everything but this was the closest I could get.

3 Answers3

1

Try:

numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27]

out = [a * b for a, b in zip(numbers, numbers[1:] + [2])]
print(out)

Prints:

[45, 27, 57, 1330, 560, 800, 200, 70, 945, 54]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Andrej Kesely's approach is totally fine and would be the way to go for an experienced python developer. But I assume you are kind of new to python, so here is a more simple approach if you are a bit familiar with other programming languages:

#function called multiply, taking an int[], returns int[]
def multiply(values):
    newData = []
    valuesLength = len(values) - 1
    for i in range(valuesLength):
        newData.append(values[i] * values[i+1])
    newData.append(values[valuesLength] * 2)
    return newData

#init int[], calling multiply-function and printing the data
numbers = [5,9,3,19,70,8,100,2,35,27]
newData = multiply(numbers)
print(newData)

The multiply-Function basically initiates an empty array, then loops over the passed values, multiplying them with the following value, leaves the loop one value too early and finally adds the last value by multiplying it with 2.

Boltus
  • 9
  • 2
  • Wow, what an elegant solution. It took me less than a minute to understand it. Thx, dude. –  Aug 01 '22 at 19:51
0

With the same approach as you did, making use of len(numbers):

numbers = [5,9,3,19,70,8,100,2,35,27]
new_array = []
x = 0
while x < len(numbers):
    nxt = 2 if x+1 >= len(numbers) else numbers[x+1]
    new_array.append(numbers[x] * nxt)
    x += 1
print(new_array)

NOTE: The shorthand for nxt = 2.... is explained in the first comment of this answer: https://stackoverflow.com/a/14461963/724039

Luuk
  • 12,245
  • 5
  • 22
  • 33
  • Wow, I thought in something like that fifth line but couldn't make it work. Thank you so much. –  Aug 01 '22 at 19:36