-1

Write a program that fills an array of 10 elements with random numbers from 1 to 10, and then swaps the first element with the second, the third with the fourth, and so on. Display the original and transformed array

Here is my solution, but Python doesn't want to sort the array and it stays the same:

from random import randint

numbers = []
for i in range(10):
    numbers.append(randint(1, 10))
    
print(numbers)
a = 0

for a in range(10):
    numbers[-1], numbers[i] = numbers[i], numbers[-1]
    a = a + 2

print(numbers)

I have tried replacing elements with a loop by numbers[a] = numbers[a+1] , But I kept getting the error:

IndexError: list index out of range
alexdev
  • 1
  • 3
  • 2
    You can't manually iterate (`a = a + 2`) and do it with a for loop at the same time with the same variable. Either use a `while` loop or don't change your iteration variable inside the loop. – Silvio Mayolo Nov 30 '22 at 14:37
  • 1
    `range` has a third optional `step` argument (e.g. `range(0, 10, 2)`) – bereal Nov 30 '22 at 14:41
  • you iterate over a and don't use it, you just use the variable i which is just leftover from previous for loop – convolutionBoy Nov 30 '22 at 14:42
  • 1
    In your code `i = 9` when you hit the second loop so `numbers[-1], numbers[i] = numbers[i], numbers[-1]` is just swapping the last element with itself. It really makes no sense to use `i` in the second loop. – John Coleman Nov 30 '22 at 14:46

2 Answers2

0

There's a couple things here: 1: as @bereal said, range() has a tird optional step argument, and I've never seen a better time to use it. Check out the documentation for range() https://docs.python.org/3/library/functions.html#func-range

2: I see you reference numbers[-1] even though I think you mean number[-i], it will still reference numbers[-1] on the first iteration, thereby giving an error.

R-Rothrock
  • 303
  • 2
  • 14
0

You can make the swap when its not an even number like this:

for a in range(10):
    if a % 2 == 1:
        tempNumber = numbers[a]
        numbers[a] = numbers[a-1]
        numbers[a-1] = tempNumber

And then you will have

First output:

[9, 7, 4, 7, 4, 3, 1, 9, 9, 9]

Final output:

[7, 9, 7, 4, 3, 4, 9, 1, 9, 9]
docksdocks
  • 108
  • 9
  • 1
    Why not just `for a in range(1, 10, 2):` and avoid the check? – Tomerikoo Nov 30 '22 at 14:48
  • 1
    Also, as the OP already used in the question, a swap in Python can be done with one line without temp variables `numbers[a-1], numbers[a] = numbers[a], numbers[a-1]` – Tomerikoo Nov 30 '22 at 14:48
  • actually way better with for a in range(1, 10, 2) as you said @Tomerikoo, I just followed the question and forgot about steps in the for loop, my bad. – docksdocks Nov 30 '22 at 14:56