We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
deflilysHomework(arr):# compare the number of swaps needed for arr switching to ascending or descending array# Initialize swap counters for ascending and descending sortsnum_swaps=[0,0]# Iterate over ascending (count=0) and descending (count=1) sortsforcountinrange(2):sorted_arr=sorted(arr)ifcount==0elsesorted(arr,reverse=True)idx={n:ifori,ninenumerate(sorted_arr)}# Iterate over the original array to compare with the sorted arrayfori,ninenumerate(arr):m=sorted_arr[i]ifm!=n:j=idx[n]# Simulate swap in sorted array and update indicessorted_arr[i],sorted_arr[j]=sorted_arr[j],sorted_arr[i]idx[n],idx[m]=i,jnum_swaps[count]+=1#Incrementswapcount# Return the minimum number of swaps neededreturnmin(num_swaps)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →