Python Alignment Questions

Asked 2 years ago, Updated 2 years ago, 100 views

N=int(input())                           #N=5
N_list=list(map(int,input().split()))    #N_list=[2,1,4,5,3]
new_N_list=[]
cnt=0
for i in range(len(N_list)):    
    if N_list.index(i+1)==N_list[i]:    
        new_N_list.insert(i+1,i)
        cnt+=1
print(cnt)

What I want is to rearrange [2,1,4,5,3] to [1,2,3,4,5] I want to find the number of times the numbers go to their original positions [2,1,4,5,3] If it's 2, you'll get the exact [2,1,4,3,5]If you also run this example, you get a zero. What should I do if I can get the correct value in other examples...

python sorting

2022-09-20 21:29

1 Answers

The code you wrote is not to rearrange the list into 1, 2, 3, 4, 5 It seems to be a code that extracts n+1 only if the position of the number n+1 in the N_list matches the nth number in the N_list.

There is a difference from the program you wanted.

Check the sorting algorithm and how to use the list again.

It's a coincidence that it came out as the second episode because it wasn't sorted.

if N_list.index(i+1) == N_list[i]:

if N_list.index(i+1) == i:

If you are curious about the number of times you transferred it, you can compare the order and the number if you simply change the check part as above,

You can count the number of times (cnt) of numbers in the correct position.

The number of numbers that need to be moved if subtracted by the number of numbers in the correct position from the whole (len(N_list).

Thank you.


2022-09-20 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.