Question
How can I reduce the running time of my code? Here is my original code: def cardinalitySort(nums): c_list=[] #Create another list for storing cardinality count=0
How can I reduce the running time of my code? Here is my original code:
def cardinalitySort(nums):
c_list=[] #Create another list for storing cardinality
count=0 #Initialize count =0
n=len(nums)
# Finding cardinality and store in c_list
for num in nums:
count=0
while num!=0:
if num%2==1:
count=count+1
num=int(num/2)
c_list.append(count)
# Sorting based on cardinality
for j in range(len(c_list)):
for k in range(j+1,len(c_list)):
if c_list[j]>c_list[k]:
nums[j],nums[k]=nums[k],nums[j]
c_list[j],c_list[k]=c_list[k],c_list[j]
# Return sorted num list
return nums
# Read number of elements in the list
nums=[] #Create a list nums.
n=len(nums)
# Read elements in to the list
for i in range(0,n):
x=int(n)
nums.append(x)
result=[] #Create another list result
# Call cardinality sort function.
# Return list into result
result=cardinalitySort(nums)
# Display result
print(result)
1. Cardinality Sorting The binary cardinality of a number is the total number of 1 's it contains in its binary representation. For example, the decimal integer 2010 corresponds to the binary number 101002. There are 21 's in the binary representation so its binary cardinality is 2. Given an array of decimal integers, sort it ascending first by binary cardinality, then by decimal value. Return the resulting array. Example n=4 nums =[1,2,3,4] - 11012, so 1 's binary cardinality is 1 . - 210102, so 2 's binary cardinality is 1 . - 310112, so 3 's binary cardinality is 2 . - 4101002, so 4 's binary cardinality is 1 . The sorted elements with binary cardinality of 1 are [1,2,4]. The array to return is [1,2,4,3]. Function Description
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started