From 6c06301663a9fa37b6e40583deb362e06dc4263f Mon Sep 17 00:00:00 2001 From: iisat <4053846@gmail.com> Date: Sat, 24 Nov 2018 20:19:35 +0300 Subject: [PATCH 1/4] Lesson7 --- Lesson8/task1.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Lesson8/task1.py diff --git a/Lesson8/task1.py b/Lesson8/task1.py new file mode 100644 index 0000000..926a60b --- /dev/null +++ b/Lesson8/task1.py @@ -0,0 +1,14 @@ +# Определение количества различных подстрок с использованием хеш-функции. Пусть дана строка S длиной N. +# Например, состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок +# в этой строке. Для решения задачи рекомендую воспользоваться алгоритмом sha1 из модуля hashlib или +# встроенную функцию hash() + +def count_substrings(s): + hashesarray = [] + for i in range(0, len(s)): + for j in range(0, len(s)): + if hash(s[i:j + 1]) not in hashesarray: + hashesarray.append(hash(s[i:j + 1])) + return (len(hashesarray) - 2) + +print(count_substrings('mama')) \ No newline at end of file From 63800145e97cede655f7de4c15eed93b08e4ce50 Mon Sep 17 00:00:00 2001 From: iisat <4053846@gmail.com> Date: Sun, 25 Nov 2018 11:23:17 +0300 Subject: [PATCH 2/4] Lesson8 --- Lesson8/task1.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Lesson8/task1.py b/Lesson8/task1.py index 926a60b..5328df6 100644 --- a/Lesson8/task1.py +++ b/Lesson8/task1.py @@ -2,7 +2,9 @@ # Например, состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок # в этой строке. Для решения задачи рекомендую воспользоваться алгоритмом sha1 из модуля hashlib или # встроенную функцию hash() +import collections +# Используем обычный массив def count_substrings(s): hashesarray = [] for i in range(0, len(s)): @@ -11,4 +13,13 @@ def count_substrings(s): hashesarray.append(hash(s[i:j + 1])) return (len(hashesarray) - 2) -print(count_substrings('mama')) \ No newline at end of file +# Используем словарь +def mod_count_substrings(s): + d = collections.OrderedDict() + for i in range(0, len(s)): + for j in range(0, len(s)): + d.update({s[i:j + 1]:hash(s[i:j + 1])}) + return (len(d) - 2) + + +print(mod_count_substrings('mama')) \ No newline at end of file From 3e6ea607cd7ee015e51be0de52586f789cc33c1b Mon Sep 17 00:00:00 2001 From: iisat <4053846@gmail.com> Date: Sun, 25 Nov 2018 12:52:13 +0300 Subject: [PATCH 3/4] Lesson8 --- Lesson8/task1.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/Lesson8/task1.py b/Lesson8/task1.py index 5328df6..e312cee 100644 --- a/Lesson8/task1.py +++ b/Lesson8/task1.py @@ -2,7 +2,12 @@ # Например, состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок # в этой строке. Для решения задачи рекомендую воспользоваться алгоритмом sha1 из модуля hashlib или # встроенную функцию hash() -import collections + +import collections, cProfile, random, string + +# Генератор строки +def str_gen(size): + return ''.join(random.choice(string.ascii_lowercase) for _ in range(size)) # Используем обычный массив def count_substrings(s): @@ -13,7 +18,7 @@ def count_substrings(s): hashesarray.append(hash(s[i:j + 1])) return (len(hashesarray) - 2) -# Используем словарь +# Используем словарь с хешем в качестве индекса def mod_count_substrings(s): d = collections.OrderedDict() for i in range(0, len(s)): @@ -21,5 +26,18 @@ def mod_count_substrings(s): d.update({s[i:j + 1]:hash(s[i:j + 1])}) return (len(d) - 2) +# Генерируем строку +s = str_gen(100) +print(s) + +# Проверяем работу функции +print(count_substrings('mama')) +print(count_substrings('mama')) +print(count_substrings(s)) +print(mod_count_substrings(s)) + +# Сравниваем скорость: +#cProfile.run('count_substrings(s)') 1 0.660 0.660 0.669 0.669 task1.py:16(count_substrings) +#cProfile.run('mod_count_substrings(s)') 1 0.018 0.018 0.030 0.030 task1.py:25(mod_count_substrings) -print(mod_count_substrings('mama')) \ No newline at end of file +# Вывод: использование хешей в качестве индекса словаря - прекрасная идея From c0916801cd51d4c8d26aed2159298db5e9f1759e Mon Sep 17 00:00:00 2001 From: iisat <4053846@gmail.com> Date: Sun, 25 Nov 2018 12:54:12 +0300 Subject: [PATCH 4/4] Lesson8 --- Lesson8/task1.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lesson8/task1.py b/Lesson8/task1.py index e312cee..7ff16c0 100644 --- a/Lesson8/task1.py +++ b/Lesson8/task1.py @@ -18,7 +18,7 @@ def count_substrings(s): hashesarray.append(hash(s[i:j + 1])) return (len(hashesarray) - 2) -# Используем словарь с хешем в качестве индекса +# Используем словарь с хэшем в качестве индекса def mod_count_substrings(s): d = collections.OrderedDict() for i in range(0, len(s)): @@ -40,4 +40,4 @@ def mod_count_substrings(s): #cProfile.run('count_substrings(s)') 1 0.660 0.660 0.669 0.669 task1.py:16(count_substrings) #cProfile.run('mod_count_substrings(s)') 1 0.018 0.018 0.030 0.030 task1.py:25(mod_count_substrings) -# Вывод: использование хешей в качестве индекса словаря - прекрасная идея +# Вывод: использование хэшей в качестве индекса словаря - прекрасная идея