Lazy sorting hackerrank solution in python


Introduction


Lazy Sorting is a sorting algorithm that sorts an array by repeatedly finding the minimum element and swapping it with the first element of the unsorted part of the array. The algorithm maintains two subarrays in a given array.

The first sub-array is the sorted part which is initially empty. The second sub-array is the unsorted part which contains all the remaining elements in the array.

Heading: How does it work?

Expansion: At each step, the minimum element from the unsorted array is picked and swapped with the first element of the unsorted array. Then, both sorted and unsorted arrays are updated accordingly. This process continues until there are no more elements left in the unsorted array.

The following illustration will make things clearer:

lazy_sorting(arr) // sort arr lazily
min_index = find_min(arr[1..n]) // find index of min element in arr[1..n]

if min_index != 1 then // if min element is not at arr[1]
swap(arr[1], arr[min_index]) // then swap it with arr[1], i.e., place min elem at arr[1]

sorted_array = [arr[1]] // update sorted and unsorted arrays
unsorted_array = arr[2..n]

for i = 2 to n do // do for remaining elements in arr[]

min_index = find_min(unsorted_array)     // find index of min element in unsorted_array        

if min_index != 0 then                  // if found, i.e., if min element exists        

  swap(unsorted_array[0],             // swap it with first elem in Unsroted Arr[]         
        unsorted_array[min_index])      

  sorted_array += [unsroted\_\array\[0]]   // update both arrays                                  // sorted appraoch as we don't know how to update an existing list item :/                          am using this method -> append all items one by one                                                                                But appending all items one by one takes O(N^2) time                 So, we can use a temp variable, append to that variable and assign back to our original variable (here, sumlist)                temp\sumlist=[]   sumlist=[3,4...9] -> list comprehension means for loop inside for i in sumlist you get 2*i so 2*i becomes our new info inside that empty listsumlist ?> [2*i for i in sumlist ]   temp\sumlist+=[i**2 for i in sumlist ] -> this means , inside temp add list comprehension which has values as square of each lightbox> what you give becomes what's inside because now we iterate over sumlist instead of just lightbox like before               IF YOU COLLECT THE RESULT OF A LIST COMPREHENSION INSIDE A TEMPORARY VARIABLE (LISTVarable), THEN APPEND EACH OF THIS TEMPORARY VARIABLE TO YOUR ORIGINAL VARIABLE (LIST ORIGINAL),                IT WILL TAKE O(N^2) TIME IN TOTAL               BUT IF YOU APPEND EACH OF THIS VALUE DIRECTLY TO THE ORIGINAL LIST ONE BY ONE OR APPEND A NEW LIST WITH EACH VALUE APPENDED (.append()) AS WELL THEN IT'S GOOD FORMAT WHICH IS WHAT WE ARE DOING BELOW           so , § pseudo code >to make sure we don't mix up with our required answer ans append everything anew   ans+= [THE OPERATION YOU Care about FOR LOOP INSIDE FOR LOOP going over original list you want answers from ]                        IN SHORT , THE ANSWER IS DOING LIST COMPREHENSION EVERYWHERE EXCEPT WHEN Dealing With BIG DATA                   INPUT OUTPUT PRACTICE                   line= input().split()                   numElements= int( line 2019 Solution )                      outputList= [ int(x)**3 + 5 for x in input().split() ]                       print(' '.join([str(y)for y in outputList ] ))                        INTERSECTION PROBLEM                     SET OPERATIONS ARE GOOD TO KNOW !                     sets have unique values , similar to dictionaries but keys have no order here                     {} -> empty dictionary                     set([5,5,'a','b','c',5]) => {5,'a','b','c'} called as Typecasting : it automatically removes same type of duplicate input variables called as TypeCasting: same type only!                     but what we want here as output regardless is unordered unique values so we need totypecast this way set([string representationofNumberswithNoDuplicatesfor ex - str({5,5,'a','b','c',5})=> {'a', 'c', 'b', 5}    ]) noting that cuz its string represenation cuz right now its typecasted into a set thus has curly braces around it   ])                     def take Second ( elem ):                      return elem [ 1 ]                     def takeFirst ( elem ):                      return elem [ 0 ] # reads space seperated single line string inputs and converts into list                    inputList=input().split()                    lengthOfInputList= len (inputList )                    # appends an empty dictionary on last index postioned Listservice having length 2 . Laterwill be storing string character counts here on Keys and Index position on values                    ListOfDictionaries=['EMPTY DICT']*lenghtOfinputList #putting x no#empty dictionaries where x will be equal to size or lenght Of List To parition service info read into equal partition lists called ListofDictionaries                    booleanvaluesLetters={ 'A':True,'B':True,'C':True,'D':True,'E':True,'F':True }            booleanvaluesDigits={ '0':False,'1':False ,'2':False ,'3':False ,'4':False ,'5': False ,'6':False}                    Namekey='nameValue';CharacterKey='TotalCharacterMapIndexPositionValue';ServicePositionIntegerIndexKey='ServicePostionIndexInFullInputStringReadValue';partitionIndexcounterForassingingPartitionsAsStringIntegersFromStartToEnd='partitonIndexcounterForassingingPartitionsAsIntegerValuesFromBeginngingtoEndValuescounterRespectiveToEachIteretionInLoopOverInputLines from frontToBackNameKeyValues In File Being Read By Code'        ServicePositionIntegerCountincrementorForassingingPartitionsAsIntegerIndexIncrementalRightLeftValueReadbyCodeLiveIncrementedOnEveryChangeinPartitionMapRespectiveToFileBeingRead value TobeWrittenNotNeededJustThereToShowProcessLiveOn EveryIterationOnEacgLineBeinfRead;MinimumDeletionCostTillNowRespectiveTotheMinimallyDeletableCharsTillNow counting tillnow considering TheBestAttributeasPerComparisonofCountsofAllOtherAttributesWithBest OneSoFar being Stored In MinimalCostSoFarVariablevalue                         BestAttributeSoFarHaveMinimumDeletionCostMinimallyNeededTillNow;PenaltywithNew group Addition§IterationWithNewLineLvelInfoMinusPrevious CostwithOldGroupAdditionSoFarValueRecomputingBestAttribute ValueSoFarKeepingTrack In caseIfPresentAsOptimaizedPossibleWithLesserChangeRespective ToFileBeingReadComingIn;lineBeingIteratedReadingOneByOneSplitSpaceSeperated individualWordsGroupings !==> Each Newline ContainingNewInfo being readas Seperate Grouping or Words!! StringInfoType! WeHave ConsidereedThisAsOneGroupas serviceConsidered HasOnlyAlphabets SoItsLetterTypeYes cuzWeHaveOnlyStringCharacters!!!!"""</p><br /><h2>The Problem</h2><br /><p>

You are given N distinct integers. You want to sort these integers in increasing order, but you are too lazy to do it yourself. So you ask your friend to help you. He writes down a program that sorts the numbers, but he makes a small mistake: instead of sorting the numbers in increasing order, his program sorts them in decreasing order.

You realize that rather than fixing your friend’s program, you can write a new one that sorts the numbers correctly.

Your task is simply to find the error in your friend’s program and correct it. To sort the array A in ascending order, write:sort(A).

You may copy your friend’s program verbatim into your source code file; there is no need to change it before you correct it.

The Solution

def lazy_sorting(arr):
n = len(arr)
mini = min(arr)
maxi = max(arr)

ans = 0
for i in range (n):
    if arr[i] != mini and arr[i] != maxi: 
        ans += 1

return ans</p><br /><h2>Implementation</h2><br /><p>

def lazy_sorting(arr):
n = len(arr)
even_count = 0
for i in range(n):
if (arr[i] % 2 == 0):
even_count += 1
if (even_count == 0 or even_count == n):
return “YES”
else:
return “NO”

Results

  1. Sort the list in ascending order.
  2. Take the difference between each adjacent elements in the sorted list and store it in another list(say diff).
  3. Sort the diff list.
  4. If the first element of diff is equal to 0, means all the adjacent elements are same in sorted list, hence return 0.
  5. Otherwise return the last element of diff(maximum value).
    Conclusion
    In conclusion, the lazy sorting algorithm is a quick and easy way to sort a list of numbers. It is not the most efficient method, but it is fast and easy to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *