哨兵循环

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'''
哨兵循环 => 线性搜索问题

L => list
T => target 
'''

def loop1():
    i = 0
    while True:
        if L[i] == T:
            print('\nbingo, the letter is in position ', i+1)
            break
        i += 1
        if i > len(L)-1:
            print('\nthe search unsuccessfully')
            break

def loop2():
    L.append(T)
    i = 0
    while True:
        if L[i] == T:
            if i < len(L)-1:
                print('\nbingo, the letter is in position ', i+1)
            else:
                print('\nthe search unsuccessfully')
            break
        i += 1

#####################################################################

L = list(input("\nPlease Enter a String [matnoble]: ") or 'matnoble')
T = input("\nPlease Enter a letter [z]: ") or 'z'

loop1()
loop2()
updatedupdated2020-05-252020-05-25
加载评论
点击刷新