Здравейте,
Пиша тази тема с цел да пропагандирам Python като език с удивителни възможности за решаване на задачи от най-различни области.
В случая ще го направя на гърба на една от задачите по информатика за студенти. Ето условието на задача В за имплементиране на ограничен T9:
Следва решение в 35 реда на Python:
from sys import stdin
# simple data for reverse maping of words to strokes
map_key = {" ":1, "A":2, "B":2, "C":2, "D":3, "E":3, "F":3, "G":4, "H":4, "I":4,
"J":5, "K":5, "L":5, "M":6, "N":6, "O":6, "P":7, "Q":7, "R":7, "S":7,
"T":8, "U":8, "V":8, "W":9, "X":9, "Y":9, "Z":9};
def get_next(convert = lambda x: x): # the default convertion is no convertion
return convert( stdin.readline().strip() )
def find_word (clicks): # the main search function
if(clicks) :
if( g_dict.has_key( clicks )):
return g_dict[ clicks ]
else:
return find_word(clicks[:-1]) # try smaller word recursively
else:
return "*"
for test_number in range (get_next(int)):
g_dict = {"1": " "} # store all words and start with 'space' for 1
lx = [ get_next() for i in range (get_next(int))]
lx.reverse() # reverse word list to have lexical sort in dictionary
for word in lx: # load words to dictionary, sequence of strokes is the key
g_dict[ "".join([ str(map_key[e]) for e in word]) ] = word
useless = get_next() #useless number of clicks, throw it away
clicks = "".join( get_next().split() ) # load as string, throw spaces
print
while(clicks ):
word = find_word(clicks)
print word, # pretty printing
clicks = clicks[len(word):] # slice and try the rest
Поздрави,
Лук
Редактирано от eфp. Лyk на 22.05.06 20:24.