1
n = int(input())
string = input()
string_list = list(string)

division_list = []
for i in range(n):
    if n%(i+1) == 0:
        division_list.append(i+1)
division_list.sort(reverse=True)
print(division_list)

for division in division_list:
    temp1 = string_list[:division]
    temp2 = string_list[division:]
    print('before reverse')
    print(temp1)
    temp1.sort(reverse=True)
    print('after reverse')
    print(temp1)
    string_list = temp1 + temp2

ans = ''.join(string_list)
print(ans)

I was solving problem in code forces, and realized sort function doesn't work more than one in for loop. Why? And is there any further stuffs I can do on my code?
This is the link of the question.
https://codeforces.com/problemset/problem/999/B

edited) I put 4 and abcd as a input. This is the output. I expected to see ['c', 'd'] after second temp1.sort(reverse=True). But it doesn't reversed.

4
abcd
[4, 2, 1]
before reverse
['a', 'b', 'c', 'd']
after reverse
['d', 'c', 'b', 'a']
before reverse
['d', 'c']
after reverse
['d', 'c']
before reverse
['d']
after reverse
['d']
dcba
7
  • What do you mean by "sort function doesn't work more than one in for loop"? Can you show the specific problem you're having? Commented Apr 3, 2020 at 3:56
  • Can you give an example of input where you get output you don't expect? And describe what you expect and what you get instead? Commented Apr 3, 2020 at 4:06
  • @dspencer If you run this code, you'll see temp1.sort(reverse=True) function won't work from second for loop. I do test with 4 for 1st input abcd for 2nd input Commented Apr 3, 2020 at 4:07
  • Make it easy for us, we shouldn't have to run the code to see your problem - please indicate in the question exactly what isn't working as you expect. Commented Apr 3, 2020 at 4:08
  • 4
    In all the cases after the first, the list happened to already be in reverse order - there wasn't anything for .sort() to do. If you wanted to reverse whatever order the list happened to have, that's not a job for .sort(), that's temp1 = temp1[::-1]. Commented Apr 3, 2020 at 4:13

1 Answer 1

2

Python .sort function sorts the list in ascending order. What the reverse parameter does is reverses the sorted list; so in this case in descending order, which happens to be the original list.

If you are trying to reverse the list I think temp1.reverse() would work (https://www.geeksforgeeks.org/python-list-reverse/). Otherwise, you could do something like this:

temp1 = temp1[::-1]

Sign up to request clarification or add additional context in comments.

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.