繁体   English   中英

Python 2.7中的Unicode字符的二进制搜索(二分法)

[英]Binary search (bisect) for a Unicode character in Python 2.7

我有一个排序列表J ,它包含2048个日语Unicode单词 ,理想情况下,我想使用二进制搜索为该索引建立索引,如本SO问题(“ Python中的二进制搜索(二分)”)所述 binary_search函数使用bisect_left bisect模块,而不是使用list.index函数索引列表。

import bisect
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
    hi = hi if hi is not None else len(a)   # hi defaults to len(a)
    pos = bisect.bisect_left(a, x, lo, hi)  # find insertion point
    return (pos if pos != hi and a[pos] == x else -1) 

现在,让我们指数每个单词words

words = "そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ"

让我们分割成一个列表:

>>> words.split()
[u'\u305d\u3064\u3046', u'\u308c\u304d\u305f\u3099\u3044', u'\u307b\u3093\u3084\u304f', u'\u308f\u304b\u3059', u'\u308a\u304f\u3064', u'\u306f\u3099\u3044\u304b', u'\u308d\u305b\u3093', u'\u3084\u3061\u3093', u'\u305d\u3064\u3046', u'\u308c\u304d\u305f\u3099\u3044', u'\u307b\u3093\u3084\u304f', u'\u308f\u304b\u3081']`)

比较binary_searchlist.index

>>> [ binary_search(J, x) for x in words.split()]
[-1, 2015, 1790, 2039, 1983, -1, 2031, 1919, -1, 2015, 1790, 2040]
>>> [ J.index(x) for x in words.split()]
[1019, 2015, 1790, 2039, 1983, 1533, 2031, 1919, 1019, 2015, 1790, 2040]

因此对于u'\そ\つ\う'そつう ),而不是索引1019, binary_search返回的索引是-1(失败),因为pos值为1027u'\そ\と\か\゙\わ' 这两个词(索引1019和1027)都以u'\そ'开头,因此这似乎是问题所在。

如何调整binary_search以查找(日语)Unicode字符的索引?

看来您的J清单有误; 它没有正确排序。

当我使用requests库加载您的测试数据文件并对信息进行排序时,它可以正常工作:

 >>> # your bisect function defined
 ...
 >>> import requests
 >>> words = u"そつう れきだい ほんやく わかす りくつ ばいか ろせん やちん そつう れきだい ほんやく わかめ"
 >>> url = 'https://raw.githubusercontent.com/trezor/python-mnemonic/master/mnemonic/wordlist/japanese.txt'
 >>> J = sorted(requests.get(url).text.splitlines())
 >>> [ J.index(x) for x in words.split()]
[1024, 2015, 1787, 2039, 1983, 1601, 2031, 1919, 1024, 2015, 1787, 2040]
>>> [ binary_search(J, x) for x in words.split()]
[1024, 2015, 1787, 2039, 1983, 1601, 2031, 1919, 1024, 2015, 1787, 2040]

请注意,索引与您的测试结果并不完全匹配。 如果索引相差超过3,则二等分无法找到结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM