0

I have an array nums. I perform following operations:

   nums = [1,1,2,2,2,3]

   nums.sort(reverse=True)

   nums2 = sorted(nums, key=nums.count)

   nums.sort(key=nums.count)

After performing these operations.I have following values of nums and nums2:

nums = [3, 2, 2, 2, 1, 1]  
nums2 = [3, 1, 1, 2, 2, 2]

Can anyone tell me why nums and nums2 are not equal?I am confused.

1

1 Answer 1

1

This doesn't work because sort modifies nums in place while using it to calculate the counts. It works fine if you use a copy:

nums = [1,1,2,2,2,3]
nums_copy = nums.copy()
nums.sort(key=nums_copy.count)
nums
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.