Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

arrays - .append in Python loop is replacing all elements

I have tried looking everywhere, but seem no soliution to similar problem gave me a postitive result.

I want to make an array, where each element is "one run" of a sorting algorithm. I am using an .append in my loop and it seems at end I get all elements replaced by the last (sorted one)

My code

setSize = 10

numbers = random.sample(range(1, setSize), setSize-1)
sortArray = [numbers]

for i in range(setSize):
    run = selection_sort(numbers, i)
    sortArray.append(run)

pritn(sortArray)

this gives me

[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9],
 [1, 2, 3, 4, 5, 6, 7, 8, 9]]

I want it to give me:

[[4, 9, 7, 2, 3, 8, 6, 1, 5],
 [4, 9, 7, 2, 3, 8, 6, 1, 5],
 [4, 9, 7, 2, 3, 8, 6, 1, 5],
 [4, 7, 9, 2, 3, 8, 6, 1, 5],
 [2, 4, 7, 9, 3, 8, 6, 1, 5],
 [2, 3, 4, 7, 9, 8, 6, 1, 5],
 [2, 3, 4, 7, 8, 9, 6, 1, 5],
 [2, 3, 4, 6, 7, 8, 9, 1, 5],
 [1, 2, 3, 4, 6, 7, 8, 9, 5],
 [1, 2, 3, 4, 5, 6, 7, 8, 9]]

Code of the fuction is

def selection_sort(nums, noOfIter):
    for i in range(noOfIter):
        lowest_value_index = i
        for j in range(i + 1, noOfIter):
            if nums[j] < nums[lowest_value_index]:
                lowest_value_index = j
        nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i]
    return nums

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

like @Dylan said in the comment: replace run = selection_sort(numbers, i) with run = selection_sort(numbers[:], i)

so code should look like

for i in range(setSize):
    run = selection_sort(numbers[:], i)
    sortArray.append(run)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...