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

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

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')
6 khi khởi động (hoặc bất cứ khi nào phù hợp):

Nội dung chính ShowShow

  • Nếu X không phù hợp với bất kỳ yếu tố nào, hãy trả về -1.
  • Nếu X không phù hợp với bất kỳ yếu tố nào, hãy trả về -1.
  • Làm thế nào để bạn thực hiện tìm kiếm tuyến tính trong Python?
  • Làm thế nào để bạn tìm kiếm một từ điển trong Python?
  • Tìm kiếm tuyến tính trong Python với ví dụ là gì?
  • Trường hợp tốt nhất cho tìm kiếm tuyến tính trong Python là gì?

# 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

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, 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[].

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

    • 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 []

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

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

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

    Iterative Approach:

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

    Python

    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
    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')
    
    9

    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')
    
    12
    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.

    Iterative Approach:

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

    Python

    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
    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')
    
    9

    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
    O(1) for iterative and O(n) for recursive.

    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

    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?

    def get_value(word):
        return lookup.get(word)
    
    02
    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.

    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.

    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 ..

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

    Tìm kiếm tuyến tính trong Python với ví dụ là gì?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ì?

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

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

    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: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).