lundi 27 novembre 2017

simplification of algorithm that uses if statements to incorporate efficient iteration

I have the following code that has a small error but otherwise performs what I believe is an insertion sort. I have two questions 1. Why is the index error occurring on running this? 2. How can I, for teaching and learning purposes, simplify the entire code, to incorporate the use of for loops. I would like someone to explain the places in which they are repetition and how they correspond to a solution that uses loops. *I realise that I need to use a nested loop using i and j, but can't quite work out how. I have added the outer level loop that provides i for the length of the loop.

Code:

def main():
  #test with 6125
  #test with 0142
  #test with 4312
  #test with 5432

  list=[4,2,6,1]
  print(list)
  for i in range(len(list)):
    #checking first element
    if list[i+1]<list[i]:
      temp1=list[i]
      list[i]=list[i+1]
      list[i+1]=temp1
      print("first iteration:",list)
    #Checking second element
    if list[i+2]<list[i]:
        temp1=list[i]
        list[i]=list[i+2]
        list[i+2]=temp1
        print("second iteration:",list)

    if list[i+2]>list[i]:
      if list[i+2]<list[i+1]:
        temp2=list[i+1]
        list[i+1]=list[i+2]
        list[i+2]=temp2
        print("second iteration else #1:",list)
    #Checking Third element
    if list[i+3]<list[i]:
        temp1=list[i]
        temp2=list[i+1]
        temp3=list[i+2]
        list[i]=list[i+3]
        list[i+1]=temp1
        list[i+2]=temp2
        list[i+3]=temp3

        print("third iteration:",list)
    elif list[i+3]>list[i]:
      if list[i+3]<list[i+1]:
        temp1=list[i+1]
        temp2=list[i+2]
        temp3=list[i+3]
        list[i+1]=temp2
        list[i+2]=temp3
        list[i+3]=temp1
        print("third iteration else #1:",list)
      elif list[i+3]>list[i+1]:
        if list[i+3]<list[i+2]:
          temp3=list[i+2]
          list[i+2]=list[i+3]
          list[i+3]=temp3
          print("third iteration else #2!",list)
main()

Output #1:

#Test with [4, 2, 6, 1]
('first iteration:', [2, 4, 6, 1])
('third iteration:', [1, 2, 4, 6])
**IndexError:** list index out of range on line 54 in main.py

Output Test #2

#Test with [5, 4, 3, 2]
('first iteration:', [4, 5, 3, 2])
('second iteration:', [3, 5, 4, 2])
('second iteration else #1:', [3, 4, 5, 2])
('third iteration:', [2, 3, 4, 5])

A trinket to the code can be found here (for online fixes) http://ift.tt/2n6zycI

Note: I realise python can perform this without using the temporary variables, but I wish to implement the solution using them. Please, in any answers, use the existing and my originally provided code to break down.

Aucun commentaire:

Enregistrer un commentaire