Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@pi-to

PYthon3で線形探索&二分探索書いてみた

More than 1 year has passed since last update.

線形探索

Pythonのenumerate()関数を使うと、forループの中でリスト(配列)などのイテラブルオブジェクトの要素と同時にインデックス番号(カウント、順番)を取得できる。
計算時間 O(n)

def linear_search(li,ans):
    print(str(ans) + "を検索します")
    for i,data in enumerate(li):
        if data == ans:
            print(str(i)+ "番目にありました")
            break
        else:
            print("入力した要素は存在しませんでした")

if __name__ == '__main__':
    li=[1,4,5,6,8,9,14,19]
    print("調べるリスト")
    print(li)
    search_num = int(input("上のリストから調べたい要素を入力してください"))
    linear_search(li, search_num)

二分探索

計算時間 O ( log₂n )

def binary_search(li, ans):
    low = 0
    high = len(li) - 1 

    # 探索の下限のlowが上限のhighになるまで探索します。
    while low <= high:
        mid = (low + high) // 2 # 中央値
        guess = li[mid]
        if guess == ans:
            return mid
        if guess > ans:
            high = mid - 1
        else:
            low = mid + 1
    return None

li = [i for i in range(1,101)]
print(binary_search(li, 3))
print(binary_search(li, -1))
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
pi-to
見習い くそあほ大学生

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?