Решение на Пет функции от Константин Паенов

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

Към профила на Константин Паенов

Резултати

  • 8 точки от тестове
  • 0 бонус точки
  • 8 точки общо
  • 12 успешни тест(а)
  • 4 неуспешни тест(а)

Код

import string
cyrlic = ['а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к',
'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х',
'ц', 'ч', 'ш', 'щ', 'ъ', 'ь', 'ю', 'я']
def is_pangram(sentnc):
sentnc.encode('utf-8')
letrs = set(cyrlic)
if letrs <= set(sentnc.lower()):
condit = True
else:
condit = False
return condit
def char_histogram(sentence):
alpha = []
occur = {}
for sym in sentence:
if sym not in alpha:
alpha.append(sym)
for letter in alpha:
if sentence.count(letter) > 0:
occur[letter] = sentence.count(letter)
return occur
def group_by_type(dic):
lst = []
new_dic = {}
fin_dic = {}
for key in dic:
if type(key) in new_dic:
new_dic[type(key)].append(key)
new_dic[type(key)].append(dic[key])
else:
new_dic[type(key)] = [key, dic[key]]
for key in new_dic:
tmp = {}
for i in range(0, len(new_dic[key]), 2):
tmp[new_dic[key][i]] = new_dic[key][i + 1]
fin_dic[key] = tmp
return fin_dic
def sort_by(func, lst):
f = func
class Custom(object):
def __init__(self, arg):
self.arg = arg
def __repr__(self):
return format(self.arg)
def __gt__(self, other):
if hasattr(other, 'arg'):
return f(self.arg, other.arg) > 0
customlist = [Custom(lst[i]) for i in range(len(lst))]
x = sorted(customlist)
op = []
for i in range(len(customlist)):
op.append(str(x[i]))
return op
def anagrams(lst):
ana_lst = []
tmp = lst
itr = len(tmp)
i = 0
while itr > 0:
ana_lst.append([])
junk = []
for j in range(0, len(tmp)):
if sorted(tmp[0]) == sorted(tmp[j]):
ana_lst[i].append(tmp[j])
else:
junk.append(tmp[j])
i = i + 1
itr = len(junk)
tmp = junk
junk = []
return ana_lst

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

.FF...........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-1q2tebk/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({'Dave Barry', 'Ray Adverb'})
Items in the second set but not the first:
frozenset({'Ray Adverb'})
frozenset({'Dave Barry'})

======================================================================
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-1q2tebk/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({"So I'm cuter"})
frozenset({'I am Lord Voldemort'})
frozenset({'Tom Cruise'})

======================================================================
FAIL: test_sort_by_one_element (test.TestSortBy)
----------------------------------------------------------------------
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-1q2tebk/test.py", line 57, in test_sort_by_one_element
    self.assertEqual([1], solution.sort_by(lambda x, y: x - y, [1]))
AssertionError: Lists differ: [1] != ['1']

First differing element 0:
1
1

- [1]
+ ['1']
?  + +


======================================================================
FAIL: test_sort_by_simple_test (test.TestSortBy)
----------------------------------------------------------------------
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-1q2tebk/test.py", line 54, in test_sort_by_simple_test
    solution.sort_by(lambda x, y: x % 2 - y % 2, [0, 1, 2, 3, 4, 5]))
AssertionError: Lists differ: [0, 2, 4, 1, 3, 5] != ['0', '2', '4', '1', '3', '5']

First differing element 0:
0
0

- [0, 2, 4, 1, 3, 5]
+ ['0', '2', '4', '1', '3', '5']
?  + +  + +  + +  + +  + +  + +


----------------------------------------------------------------------
Ran 16 tests in 0.012s

FAILED (failures=4)

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

Константин обнови решението на 18.03.2014 18:55 (преди над 10 години)

+
+
+def sort_by(func, lst):
+ f = func
+
+ class Custom(object):
+ def __init__(self, arg):
+ self.arg = arg
+
+ def __repr__(self):
+ return format(self.arg)
+
+ def __gt__(self, other):
+ if hasattr(other, 'arg'):
+ return f(self.arg, other.arg) > 0
+ customlist = [Custom(lst[i]) for i in range(len(lst))]
+ x = sorted(customlist)
+ op = []
+ for i in range(len(customlist)):
+ op.append(str(x[i]))
+ return op
+
+#При предишната версия последните 5 реда ги нямаше и просто имах return sorted(customlist) но ми дава грешна на теста защото явно се разминават типовете на елементите в двата листа

Ок, очевидно е. Обръщаш всичко към стринг, без да си сигурен, че това е така. Но в кода ти има доста объркващи неща.

  • Имаш дефиниран клас във функция!? Не правим така
  • Въобще не съм сигурен защо ти е такъв клас. Просто сравнявай елементите, вместо да ги набиваш в измислен тип, за да им предефинираш __gt__
  • f, lst, customlist, op, ...

Константин обнови решението на 19.03.2014 15:23 (преди над 10 години)

+import string
+cyrlic = ['а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к',
+ 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х',
+ 'ц', 'ч', 'ш', 'щ', 'ъ', 'ь', 'ю', 'я']
+
+def is_pangram(sentnc):
+ sentnc.encode('utf-8')
+ letrs = set(cyrlic)
+ if letrs <= set(sentnc.lower()):
+ condit = True
+ else:
+ condit = False
+ return condit
+
+
+def char_histogram(sentence):
+ alpha = []
+ occur = {}
+ for sym in sentence:
+ if sym not in alpha:
+ alpha.append(sym)
+ for letter in alpha:
+ if sentence.count(letter) > 0:
+ occur[letter] = sentence.count(letter)
+ return occur
+
+
+def group_by_type(dic):
+ lst = []
+ new_dic = {}
+ fin_dic = {}
+ for key in dic:
+ if type(key) in new_dic:
+ new_dic[type(key)].append(key)
+ new_dic[type(key)].append(dic[key])
+ else:
+ new_dic[type(key)] = [key, dic[key]]
+ for key in new_dic:
+ tmp = {}
+ for i in range(0, len(new_dic[key]), 2):
+ tmp[new_dic[key][i]] = new_dic[key][i + 1]
+ fin_dic[key] = tmp
+ return fin_dic
+
+
def sort_by(func, lst):
f = func
class Custom(object):
def __init__(self, arg):
self.arg = arg
def __repr__(self):
return format(self.arg)
def __gt__(self, other):
if hasattr(other, 'arg'):
return f(self.arg, other.arg) > 0
customlist = [Custom(lst[i]) for i in range(len(lst))]
x = sorted(customlist)
op = []
for i in range(len(customlist)):
op.append(str(x[i]))
return op
-#При предишната версия последните 5 реда ги нямаше и просто имах return sorted(customlist) но ми дава грешна на теста защото явно се разминават типовете на елементите в двата листа
+
+def anagrams(lst):
+ ana_lst = []
+ tmp = lst
+ itr = len(tmp)
+ i = 0
+ while itr > 0:
+ ana_lst.append([])
+ junk = []
+ for j in range(0, len(tmp)):
+ if sorted(tmp[0]) == sorted(tmp[j]):
+ ana_lst[i].append(tmp[j])
+ else:
+ junk.append(tmp[j])
+ i = i + 1
+ itr = len(junk)
+ tmp = junk
+ junk = []
+ return ana_lst