파이썬에서 T9 사전을 구현할 때 잘못된 출력

user2916886

T9.NET에서 사전 을 구현하려고합니다 python. 나는 Trie그것을 구현하는 데 사용 하고 있습니다. Trie사전에있는 단어에서 를 생성 한 다음 패턴을 찾는 이 코드가 있습니다.

import string

PHONE_LETTERS = 'abcdefghijklmnopqrstuvwxyz'
PHONE_NUMBERS = '22233344455566677778889999'
PHONE_TRANS = string.maketrans(PHONE_LETTERS, PHONE_NUMBERS)

class Node:

    def __init__(self, key):
        self.children = {}
        self.key = key
        self.values = []


def append_word(node, sequence, completeword):
    if not sequence:
        return
    key = sequence[0]
    try:
        child = node.children[key]
    except KeyError:
        child = Node(key)
        node.children[key] = child
    if len(sequence) == 1:
        child.values.append(completeword)
    else:
        append_word(child, sequence[1:], completeword)


def lookup(node, sequence=None):
    if sequence:
        # there are still numbers in the sequence: follow them in the trie
        try:
            child = node.children[sequence[0]]
            return lookup(child, sequence[1:])
        except KeyError:
            return []
    else:
        # the sequence is empty: explore the trie using a DFS
        result = node.values[:]
        for child in node.children.values():
            result.extend(lookup(child))
        return result


def main():
    root = Node(None)

    words = ['hello','hess','home','abhi','busy','disturb']
    for wlist in words:
        print wlist
        map(lambda l: append_word(root, l.strip().translate(PHONE_TRANS), l.strip()), wlist)

    words = sorted(lookup(root, '43'))
    print "Words: %s" % words


if __name__ == '__main__':
    main()

이제 이것을 실행하면 [hello,hess]출력이 올바르게 표시됩니까? 그러나 나는 빈 목록을 얻습니다. 내가 여기서 어떤 실수를하고 있는가?

Tijko

map당신의 append기능은 정말 이상 매핑하는 것을 의미하는 전체 wlist 문자열?

당신이 전화를하면 translatewlist대신에 당신이 얻을 각 개별 문자의 문자열 :

hello
hess
home
abhi
busy
disturb
Words: ['hello', 'hess']

map통화를 제거하기 만하면됩니다.

import string

PHONE_LETTERS = 'abcdefghijklmnopqrstuvwxyz'
PHONE_NUMBERS = '22233344455566677778889999'
PHONE_TRANS = string.maketrans(PHONE_LETTERS, PHONE_NUMBERS)

class Node:

    def __init__(self, key):
        self.children = {}
        self.key = key
        self.values = []


def append_word(node, sequence, completeword):
    if not sequence:
        return
    key = sequence[0]
    try:
        child = node.children[key]
    except KeyError:
        child = Node(key)
        node.children[key] = child
    if len(sequence) == 1:
        child.values.append(completeword)
    else:
        append_word(child, sequence[1:], completeword)


def lookup(node, sequence=None):
    if sequence:
        # there are still numbers in the sequence: follow them in the trie
        try:
            child = node.children[sequence[0]]
            return lookup(child, sequence[1:])
        except KeyError:
            return []
    else:
        # the sequence is empty: explore the trie using a DFS
        result = node.values[:]
        for child in node.children.values():
            result.extend(lookup(child))
        return result


def main():
    root = Node(None)

    words = ['hello','hess','home','abhi','busy','disturb']
    for wlist in words:
        print wlist
        # XXX here, you shouldn't be mapping the `translate` call onto the entire string
        append_word(root, wlist.strip().translate(PHONE_TRANS), wlist)

    words = sorted(lookup(root, '43'))
    print "Words: %s" % words


if __name__ == '__main__':
    main()

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

스레드와 병합 정렬을 구현할 때 잘못된 출력이 표시되고 무엇이 잘못되었는지 파악할 수 없습니다.

분류에서Dev

달력을 사용하여 DateFormat에서 날짜를 구문 분석 할 때 잘못된 출력

분류에서Dev

pow ()에서 이중 배열을 수행 할 때 잘못된 출력

분류에서Dev

큰 입력을 사용할 때 잘못된 출력

분류에서Dev

루프에서 사용할 때 잘못된 위치에 zip 출력

분류에서Dev

파일 a를 파일 b로 복사 할 때 파일링시 잘못된 출력

분류에서Dev

dplyr과 함께 사용할 때 statar :: xtile 함수에 대한 잘못된 출력

분류에서Dev

구조체 포인터 내부에서 문자열을 인쇄 할 때 잘못된 출력 (VC ++ 2010)

분류에서Dev

fortify () 오류 및 공간 인구 조사 데이터를 플로팅 할 때 facet_wrap의 잘못된 출력

분류에서Dev

수학 표현식 구문 분석 : + 다음에-가 올 때 잘못된 출력

분류에서Dev

fopen은 urlencode를 사용하여 인코딩 된 url에서 이름을 구문 분석 한 후 텍스트 파일 이름을 전달할 때 잘못된 인수를 출력합니다.

분류에서Dev

sizeof ()를 사용할 때 잘못된 출력

분류에서Dev

배열 내용을 인쇄 할 때 awk를 사용하여 잘못된 출력을 제공하는 이유

분류에서Dev

SyntaxError : 잘못된 구문-셀러리를 사용할 때 iterable에서 산출

분류에서Dev

파이썬에서 잘못된 출력

분류에서Dev

R에서 이미지 위에 플로팅 할 때 잘못된 출력 크기

분류에서Dev

이 사전의 잘못된 출력

분류에서Dev

잘못된 출력 : Java를 사용한 이진 검색 트리 구현

분류에서Dev

do while 루프를 사용하여 다이아몬드를 인쇄 할 때 잘못된 출력

분류에서Dev

사용자가 잘못된 입력을 할 때 내 파이썬 체중 계산기에 오류 마사지를 표시하는 방법

분류에서Dev

while 루프 내에서 break 문을 사용할 때 Python 프로그램이 잘못된 출력을 제공합니다.

분류에서Dev

다른 함수로 전달할 때 PHP 시간대 잘못된 출력

분류에서Dev

입력 함수 내에서 is.na를 사용할 때 Reduce 함수가 잘못된 논리 출력을 반환합니다.

분류에서Dev

cout, C ++를 사용하여 ASCII로 변환 된 텍스트를 출력 할 때 잘못된 출력

분류에서Dev

출력을 파일로 파이핑 할 때 stderr 및 stdout의 순서가 잘못된 이유는 무엇입니까?

분류에서Dev

var_dump ()를 사용할 때 잘못된 문자 세트 출력

분류에서Dev

때때로 SqlException : 웹 사이트에서 양식을 제출할 때 "XML 구문 분석 : 잘못된 xml 문자"가 발생합니다.

분류에서Dev

Post에서 이미지를 요청할 때 잘못된 호출

분류에서Dev

파이썬에서 문자열을 인쇄 할 때 출력 오류

Related 관련 기사

  1. 1

    스레드와 병합 정렬을 구현할 때 잘못된 출력이 표시되고 무엇이 잘못되었는지 파악할 수 없습니다.

  2. 2

    달력을 사용하여 DateFormat에서 날짜를 구문 분석 할 때 잘못된 출력

  3. 3

    pow ()에서 이중 배열을 수행 할 때 잘못된 출력

  4. 4

    큰 입력을 사용할 때 잘못된 출력

  5. 5

    루프에서 사용할 때 잘못된 위치에 zip 출력

  6. 6

    파일 a를 파일 b로 복사 할 때 파일링시 잘못된 출력

  7. 7

    dplyr과 함께 사용할 때 statar :: xtile 함수에 대한 잘못된 출력

  8. 8

    구조체 포인터 내부에서 문자열을 인쇄 할 때 잘못된 출력 (VC ++ 2010)

  9. 9

    fortify () 오류 및 공간 인구 조사 데이터를 플로팅 할 때 facet_wrap의 잘못된 출력

  10. 10

    수학 표현식 구문 분석 : + 다음에-가 올 때 잘못된 출력

  11. 11

    fopen은 urlencode를 사용하여 인코딩 된 url에서 이름을 구문 분석 한 후 텍스트 파일 이름을 전달할 때 잘못된 인수를 출력합니다.

  12. 12

    sizeof ()를 사용할 때 잘못된 출력

  13. 13

    배열 내용을 인쇄 할 때 awk를 사용하여 잘못된 출력을 제공하는 이유

  14. 14

    SyntaxError : 잘못된 구문-셀러리를 사용할 때 iterable에서 산출

  15. 15

    파이썬에서 잘못된 출력

  16. 16

    R에서 이미지 위에 플로팅 할 때 잘못된 출력 크기

  17. 17

    이 사전의 잘못된 출력

  18. 18

    잘못된 출력 : Java를 사용한 이진 검색 트리 구현

  19. 19

    do while 루프를 사용하여 다이아몬드를 인쇄 할 때 잘못된 출력

  20. 20

    사용자가 잘못된 입력을 할 때 내 파이썬 체중 계산기에 오류 마사지를 표시하는 방법

  21. 21

    while 루프 내에서 break 문을 사용할 때 Python 프로그램이 잘못된 출력을 제공합니다.

  22. 22

    다른 함수로 전달할 때 PHP 시간대 잘못된 출력

  23. 23

    입력 함수 내에서 is.na를 사용할 때 Reduce 함수가 잘못된 논리 출력을 반환합니다.

  24. 24

    cout, C ++를 사용하여 ASCII로 변환 된 텍스트를 출력 할 때 잘못된 출력

  25. 25

    출력을 파일로 파이핑 할 때 stderr 및 stdout의 순서가 잘못된 이유는 무엇입니까?

  26. 26

    var_dump ()를 사용할 때 잘못된 문자 세트 출력

  27. 27

    때때로 SqlException : 웹 사이트에서 양식을 제출할 때 "XML 구문 분석 : 잘못된 xml 문자"가 발생합니다.

  28. 28

    Post에서 이미지를 요청할 때 잘못된 호출

  29. 29

    파이썬에서 문자열을 인쇄 할 때 출력 오류

뜨겁다태그

보관