0

My problem is this.
1. Input N
2. Input N numbers are entered in the list. For example, N is 5 means 3,2,1,2,4 or 1,2,9,7,5 or 4,2,1,3,8 whatever, N is 3 means 1,2,3 or 7,4,8 or 2,13,26 whatever.

3. Input A and B

4. Sort descending order list only in index A to B. For example, N = 7 , input numbers are 3 2 0 6 7 9 1, A=2, B=5, the output is [3, 2, 9, 7, 6, 0, 1]

my output is like this
[3, 2, 6, 0, 7, 9, 1]
[3, 2, 7, 0, 6, 9, 1]
[3, 2, 9, 0, 6, 7, 1]
[3, 2, 9, 6, 0, 7, 1]
[3, 2, 9, 7, 0, 6, 1]
[3, 2, 9, 0, 7, 6, 1]
[3, 2, 9, 0, 6, 7, 1]

The problem is last 2 output is so weird, I don't know what am i doing wrong.

n = int(input())
list = []
for i in range(n):
    list.append(int(input()))

a = int(input())
b = int(input())
b+=1
tmp=0

for i in range(a,b):
    for j in range(a+1,b):
        if list[i]<list[j]:
            tmp=list[i]
            list[i]=list[j]
            list[j]=tmp
            print(list)
1

3 Answers 3

1

You can try the following:

n = int(input())
list = []
for i in range(n):
    list.append(int(input()))

a = int(input())
b = int(input())
b+=1
tmp=0

for i in range(a,b):
    for j in range(i+1,b):
        if list[i]<list[j]:
            tmp=list[i]
            list[i]=list[j]
            list[j]=tmp
            print(list)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. a+1 was wrong. really appreciate it
1

You can swap two values in a list like this:

list_[i], list_[j] = list_[j], list_[i]

One suggestion to you: Don't use built-in data-type names as variable names.

Comments

0

I would try to simplify this for yourself, and maybe try without loops.

Your list generation, only with added input-directions and changing the list-name to "main":

n = int(input("n:"))
main = []
for i in range(n):
    main.append(int(input(f'{i+1} of {n}:')))
a = int(input("a:"))
b = int(input("b:"))

Now split your list into the respective parts, and use the built in .sort() function.

# Slice into three parts
start = main[:a]
mid = main[a:b+1]
end = main[b+1:]
# Sort the middle, descending
mid.sort(reverse = True)
# Re-combine the lists
main = start + mid + end
print(main)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.