Hướng dẫn linear search in dictionary python - tìm kiếm tuyến tính trong python từ điển

Một tìm kiếm nhị phân sẽ là một cách hiệu quả để làm một cái gì đó như thế này, nhưng bạn vẫn sẽ phải chuyển dữ liệu từ văn bản (chỉ là một loạt các byte, sau tất cả) vào một số cấu trúc dữ liệu khác như một danh sách. Nếu bạn có một chương trình có thời gian ngắn hoặc không có hạn chế bộ nhớ dài hạn, nó sẽ (có thể) thậm chí còn nhanh hơn để tải toàn bộ vào Python dict khi khởi động (hoặc bất cứ khi nào phù hợp):

# This may not work exactly right for your file format, but you get the idea.
lookup = {}
for line in f:
    if line:
        value, key = line.trim().split():
        lookup[key] = value

Sau đó, bạn truy cập nó bằng cách sử dụng từ điển xây dựng của Python, rất hay và nhanh:

def get_value(word):
    return lookup.get(word)

CHỈNH SỬA

Nếu tùy chọn duy nhất của bạn là đọc trong toàn bộ tệp cho mỗi từ và bạn đang tìm kiếm nhiều từ, thì thời gian bạn lưu bằng cách thực hiện một thuật toán tìm kiếm thông minh có thể sẽ có phần khác biệt so với thời gian bạn mở và Đọc các tập tin nhiều lần. Những gì bạn thực sự muốn là một cơ sở dữ liệu, thực sự có thể xử lý loại điều này một cách nhanh chóng. Điều đó nói rằng, với các tham số này, có lẽ tôi sẽ làm điều gì đó như thế này nếu tôi phải sử dụng hệ thống tập tin:

import bisect

# Define searchable (word, value) tuples for every word in the file.
# I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]

# Binary search for the word and return its associated value.
def get_value(word):
    idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
    if idx != len(words) and words[idx][0] == word:
        return words[idx][1]
    raise ValueError('word not found')

Cuối cùng, tôi nhận thấy bạn đang sử dụng các tệp Gzipped, điều này là hợp lý nếu không gian lưu trữ là một vấn đề, nhưng nó sẽ làm chậm quá trình của bạn hơn nữa. Một lần nữa tôi phải đề xuất một cơ sở dữ liệu. Trong mọi trường hợp, tôi không biết liệu bạn có gặp sự cố ở đây không, nhưng chỉ trong trường hợp, việc đọc các tệp Gzipped không thực sự là "khó hơn" so với đọc các tệp bình thường. Chỉ cần xem mô -đun GZIP. Về cơ bản, các tệp GZIP hoạt động giống như các tệp thông thường, vì vậy bạn vẫn có thể viết for line in file, v.v.

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc Given an array arr[] of n elements, write a function to search a given element x in arr[]. 

    Bàn luận

    Input : arr[] = {10, 20, 80, 30, 60, 50, 
                         110, 100, 130, 170}
              x = 110;
    Output : 6
    Element x is present at index 6
    
    Input : arr[] = {10, 20, 80, 30, 60, 50, 
                         110, 100, 130, 170}
               x = 175;
    Output : -1
    Element x is not present in arr[].

    Vấn đề: Cho một mảng mảng [] của n phần tử, hãy viết một hàm để tìm kiếm một phần tử X đã cho trong ARR []. & NBSP;linear search, i.e

    • Ví dụ:
    • Một cách tiếp cận đơn giản là thực hiện tìm kiếm tuyến tính, tức là
    • Bắt đầu từ phần tử ngoài cùng bên trái của ARR [] và từng người một so sánh x với mỗi phần tử của ARR []

    Nếu x khớp với một phần tử, hãy trả về chỉ mục.

    Hướng dẫn linear search in dictionary python - tìm kiếm tuyến tính trong python từ điển
    Iterative Approach:

    Nếu X không phù hợp với bất kỳ yếu tố nào, hãy trả về -1.

    Ví dụ: Cách tiếp cận lặp:

    Python

    def search(arr, x):

    def get_value(word):
        return lookup.get(word)
    
    6
    def get_value(word):
        return lookup.get(word)
    
    7
    def get_value(word):
        return lookup.get(word)
    
    8
    def get_value(word):
        return lookup.get(word)
    
    9
    def get_value(word):
        return lookup.get(word)
    
    9
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    1

    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    2
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    3
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    4

    Nếu X không phù hợp với bất kỳ yếu tố nào, hãy trả về -1.

    Ví dụ: Cách tiếp cận lặp:

    Python

    def search(arr, x):

    def get_value(word):
        return lookup.get(word)
    
    6
    def get_value(word):
        return lookup.get(word)
    
    7
    def get_value(word):
        return lookup.get(word)
    
    8
    def get_value(word):
        return lookup.get(word)
    
    9
    def get_value(word):
        return lookup.get(word)
    
    9
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    1

    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    2
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    3
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    4

        

    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    3
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    7
    import bisect
    
    # Define searchable (word, value) tuples for every word in the file.
    # I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
    words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]
    
    # Binary search for the word and return its associated value.
    def get_value(word):
        idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
        if idx != len(words) and words[idx][0] == word:
            return words[idx][1]
        raise ValueError('word not found')
    
    8

    Cách tiếp cận đệ quy: & nbsp;O(1) for iterative and O(n) for recursive.

    def

    Input : arr[] = {10, 20, 80, 30, 60, 50, 
                         110, 100, 130, 170}
              x = 110;
    Output : 6
    Element x is present at index 6
    
    Input : arr[] = {10, 20, 80, 30, 60, 50, 
                         110, 100, 130, 170}
               x = 175;
    Output : -1
    Element x is not present in arr[].
    0


    Làm thế nào để bạn thực hiện tìm kiếm tuyến tính trong Python?

    Thuật toán cho tìm kiếm tuyến tính..
    Bắt đầu từ chỉ mục 0 của danh sách ..
    Kiểm tra xem phần tử có mặt ở vị trí hiện tại không ..
    Nếu có, hãy trả lại chỉ số hiện tại. Goto 8 ..
    Kiểm tra xem phần tử hiện tại có phải là phần tử cuối cùng của danh sách không ..
    Nếu có, trả lại -1. Goto 8. Nếu không, Goto 6 ..
    Di chuyển đến chỉ mục tiếp theo của danh sách ..
    Goto 2 ..

    Làm thế nào để bạn tìm kiếm một từ điển trong Python?

    Để kiểm tra xem một chìa khóa có tồn tại trong từ điển Python, bạn có thể sử dụng toán tử trong để tìm kiếm thông qua các khóa từ điển như thế này: Thú cưng = {'Mèo': 1, 'Chó': 2, 'Cá': 3} nếu 'chó'Trong thú cưng: In (' Chó tìm thấy! ') # Dogs tìm thấy!Một từ điển có thể là một cấu trúc dữ liệu thuận tiện để đếm sự xuất hiện của các mục.use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

    Tìm kiếm tuyến tính trong Python với ví dụ là gì?

    # Tìm kiếm tuyến tính trong python def linearSearch (mảng, n, x), 4, 0, 1, 9] x = 1 n = len (mảng) result = linearSearch (mảng, n, x) if (result == -1): in ("phần tử không tìm thấy") khác: in ("Phần tử được tìm thấy tại Index: ", ...

    Trường hợp tốt nhất cho tìm kiếm tuyến tính trong Python là gì?

    Đối với một danh sách chứa N các mục, trường hợp tốt nhất cho tìm kiếm tuyến tính là khi giá trị đích bằng với phần tử đầu tiên của danh sách.Trong những trường hợp như vậy, chỉ cần một so sánh là cần thiết.Do đó, hiệu suất trường hợp tốt nhất là O (1).when the target value is equal to the first element of the list. In such cases, only one comparison is needed. Therefore, the best case performance is O(1).