Решение на Пет функции от Ивайло Дянков

Обратно към всички решения

Към профила на Ивайло Дянков

Резултати

  • 9 точки от тестове
  • 0 бонус точки
  • 9 точки общо
  • 14 успешни тест(а)
  • 2 неуспешни тест(а)

Код

def anagrams(words):
out_list = []
for word in words:
sub_list = [word_container for word_container in words \
if sorted(word) == sorted(word_container)]
if not sub_list in out_list:
out_list.append(sub_list)
return out_list
#-----------------------------------------------------------
def char_histogram(text):
histogram = dict()
for symbol in set(text):
histogram[symbol] = text.count(symbol)
return histogram
#------------------------------------------------------------
def group_by_type(dictionary):
output = dict()
unique_key_types = set()
for key in dictionary.keys():
unique_key_types.add(type(key))
for key_type in unique_key_types:
local_dict = dict()
for key in dictionary.keys():
if isinstance(key, key_type):
local_dict.update({key: dictionary.get(key)})
output.update({key_type: local_dict})
#output.update({key_type: ([{key: dictionary.get(key)} \
# for key in dictionary.keys() \
# if isinstance(key, key_type)])})
return output
#------------------------------------------------------------
CYRILlIC_ALPHABET = set("абвгдежзийклмнопрстуфхцчшщъьюя")
def is_pangram(sentence):
letters_in_input = set([])
for letter in sentence.lower():
if letter.isalpha():
letters_in_input.add(letter)
return CYRILlIC_ALPHABET <= letters_in_input
#------------------------------------------------------------
def sort_by(func, arguments):
repeat = True
while repeat:
repeat = False
for argument in arguments[:-1]:
first_index = arguments.index(argument)
second_index = arguments.index(argument) + 1
if func(arguments[first_index], arguments[second_index]) > 0:
repeat = True
arguments[first_index], arguments[second_index] = \
arguments[second_index], arguments[first_index]
return arguments

Лог от изпълнението

.FF.............
======================================================================
FAIL: test_with_different_cases (test.TestAnagrams)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140319-21201-1seid1v/test.py", line 125, in test_with_different_cases
    set(map(frozenset, solution.anagrams(words))))
AssertionError: Items in the first set but not the second:
frozenset({'Ray Adverb', 'Dave Barry'})
Items in the second set but not the first:
frozenset({'Dave Barry'})
frozenset({'Ray Adverb'})

======================================================================
FAIL: test_with_different_symbols (test.TestAnagrams)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20140319-21201-1seid1v/test.py", line 135, in test_with_different_symbols
    set(map(frozenset, solution.anagrams(words))))
AssertionError: Items in the first set but not the second:
frozenset({'I am Lord Voldemort', 'Tom Marvolo Riddle'})
frozenset({'Tom Cruise', "So I'm cuter"})
Items in the second set but not the first:
frozenset({'Tom Marvolo Riddle'})
frozenset({'I am Lord Voldemort'})
frozenset({"So I'm cuter"})
frozenset({'Tom Cruise'})

----------------------------------------------------------------------
Ran 16 tests in 0.018s

FAILED (failures=2)

История (1 версия и 1 коментар)

Ивайло обнови решението на 19.03.2014 02:43 (преди около 10 години)

+def anagrams(words):
+ out_list = []
+
+ for word in words:
+ sub_list = [word_container for word_container in words \
+ if sorted(word) == sorted(word_container)]
+ if not sub_list in out_list:
+ out_list.append(sub_list)
+
+ return out_list
+#-----------------------------------------------------------
+def char_histogram(text):
+ histogram = dict()
+ for symbol in set(text):
+ histogram[symbol] = text.count(symbol)
+
+ return histogram
+#------------------------------------------------------------
+def group_by_type(dictionary):
+ output = dict()
+
+ unique_key_types = set()
+ for key in dictionary.keys():
+ unique_key_types.add(type(key))
+
+ for key_type in unique_key_types:
+ local_dict = dict()
+ for key in dictionary.keys():
+ if isinstance(key, key_type):
+ local_dict.update({key: dictionary.get(key)})
+
+ output.update({key_type: local_dict})
+ #output.update({key_type: ([{key: dictionary.get(key)} \
+ # for key in dictionary.keys() \
+ # if isinstance(key, key_type)])})
+
+ return output
+#------------------------------------------------------------
+CYRILlIC_ALPHABET = set("абвгдежзийклмнопрстуфхцчшщъьюя")
+
+def is_pangram(sentence):
+ letters_in_input = set([])
+ for letter in sentence.lower():
+ if letter.isalpha():
+ letters_in_input.add(letter)
+
+ return CYRILlIC_ALPHABET <= letters_in_input
+#------------------------------------------------------------
+def sort_by(func, arguments):
+ repeat = True
+ while repeat:
+ repeat = False
+ for argument in arguments[:-1]:
+ first_index = arguments.index(argument)
+ second_index = arguments.index(argument) + 1
+
+ if func(arguments[first_index], arguments[second_index]) > 0:
+ repeat = True
+ arguments[first_index], arguments[second_index] = \
+ arguments[second_index], arguments[first_index]
+ return arguments
  • константите трябва да са с главни букви; CYRILlIC_ALPHABET тука едното L ти е малко; опитвай се да проследяваш малко autocomplete-a и няма да репликираш грешки
  • опитвай се да използваш прости имена; letters_in_input можеше да е просто letters, че са от input-a се вижда от кода
  • не слагай типове в имената; local_dict, out_list
  • когато трябва в даден речник на даден ключ да сложиш стойност, прави така d['key'] = 42
  • group_by_type можеш да я решиш по-добре, ако си прегледаш хитринките
  • не оставяй коментиран код, като предаваш
  • можеш да итерираш списък, като едновременно с това взимаш индексите на елементите, с enumerate()
  • за да спазищ PEP8 тая константа трябва да е най-отгоре и между функциите трябва да оставяш по 2 празни реда
  • sub_list се пише слято, но въпреки това пак не е много информативно име
  • на 5 ред \ е излишно
  • при анаграмите трябва да взимаш предвид само буквите(без каквито и да е препинателни знаци и т.н) и не трябва да има значение case-а на буквите, тоест дали са малки или главни