-7

Write in python a list num having the following elements: num = [3 ,21 ,5 ,6 ,14 ,8 ,14 ,3] . Write a program to swap the content with the next value divisible by 7 so that the resultant list looks like: num = [3, 5, 21, 6, 8, 14, 3, 14]

This one is my code...

num = [3, 21, 5, 6, 14, 8, 14, 3]
for i in range(len(num)-1):
    if num[i] % 7 == 0:
        num[i + 1], num[i] = num[i], num[i + 1]
print(num)

output...

[3, 5, 6, 14, 8, 14, 3, 21]

After the first swap, the if statement checks 21 again and again, and it gets pushed to the end of the list in contrast with the desired output. I have to check other elements too that are divisible by 7 and swap them with the succeeding element. Can I skip one iteration after each swap?

Arjun Jayan
  • 1
  • 1
  • 5

2 Answers2

0

You can swap values by just assigning their values like this:

a, b = b, a

You can easily do this exercise with a for loop, checking every time if the next number is divisible by 7, and if so, swap them using this code

Daniel
  • 487
  • 4
  • 11
  • This is not the answer to the problem. – Mayank Porwal Nov 02 '20 at 09:29
  • 1
    @MayankPorwal why? It doesn't show exactly how to use it, but that's basically the asnwer... – Tomerikoo Nov 02 '20 at 09:30
  • 1
    This seems more like a suggestion/comment rather than an answer. When you answer someone's post, in my opinion at least solve the problem completely. Don't just give suggestions. Comments are there for such things. – Mayank Porwal Nov 02 '20 at 09:32
  • If I do this kind of swap, it shows an index error. – Arjun Jayan Nov 02 '20 at 13:01
  • In this line... num[i + 1], num[i] = num[i], num[i + 1] IndexError: list index out of range – Arjun Jayan Nov 02 '20 at 13:21
  • In the for loop, you have to iterate until the n-1 element, to prevent this error – Daniel Nov 02 '20 at 13:25
  • Thanks, but still i am not getting my desired output. it pushes 21 to the end of the the list like this [3, 5, 6, 14, 8, 14, 3, 21]. I understand why this happens. Can I skip one iteration of the for loop just after swaping? – Arjun Jayan Nov 02 '20 at 13:35
  • Thanks guys, but I traversed the list in reverse and got my results, suggested by one of of my classmate – Arjun Jayan Nov 02 '20 at 15:46
0
num = [3, 21, 5, 6, 14, 8, 14, 3]
num.reverse()
for i in range(len(num)-1):
    if num[i] % 7 == 0:
        num[i - 1], num[i] = num[i], num[i - 1]
num.reverse()
print("The required answer :", num)
Arjun Jayan
  • 1
  • 1
  • 5