PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] Why can't I reassign variables in this function?

 July 20, 2022     integer, list, mutability, python     No comments   

Issue

Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array

When I test it, it does this:

>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?


Solution

You just need to save the positions of the odd integers as well to replace them:

def sort_array(source_array):
    odd_ints = []
    positions = []
    counter = 0 #need counter to get positions
    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i) #keep the values
            positions.append(counter) #keep the position
        counter += 1
    odd_ints.sort() #sort for replacement
    counter2 = 0 #need second counter to place sorted list
    for pos in positions:
        source_array[pos] = odd_ints[counter2] #place the sorted values
        counter2 += 1
    return source_array

print(sort_array([5, 3, 2, 8, 1, 4]))

Output:

[1, 3, 2, 8, 5, 4]


Answered By - Eli Harold
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing