Algorithms - dichotomy

Algorithm: a highly efficient solution to the problem

1. Find an element is in a list

Common methods for i in l:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in l:
    if num == i:
        print("找到了:%s" % i)

2. dichotomy:

1. Digital container must have the order 
2 and sequentially comparing the number of intermediate size, smaller than take the left and right take greater than
sort: sort () in ascending order, sort (reverse = Ture) descending, Reverse () inverted, reverse arrangement

= L [. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8,. 9, 10] 
l.sort () re-sorted in ascending order #

DEF get_num (L, NUM):
     # list of supported intermediate-index position 
    num_middle = len (L) // 2 # this number is not in the list, to cut back the list is empty, return empty list directly IF Not L:
         return Print ( " list not found " , NUM)
     Print (L) # print each list sliced
     # determines the size IF NUM> L [num_middle]:
         # slice right portion 
        right_num = L [num_middle +. 1 :] 
        get_num (right_num , NUM) elif NUM < L [num_middle]:
         # cutout portion left 
        left_num =
    
      
    
     L [: num_middle]
        get_num (left_num, NUM)
    the else :
         Print ( " list found " , NUM) 


get_num (L, 9 )

 



Guess you like

Origin www.cnblogs.com/guyouyin123/p/11183902.html