Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Кабанова №7,14,16 #19

Open
wants to merge 31 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file removed lab1/package
Empty file.
20 changes: 20 additions & 0 deletions lab10/Kabanova/pythagorean_triples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import sys

array_of_elements = [int(k) for k in sys.stdin.readline().split(' ')]


def triples(array):
pair = []
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

плохой нейминг, неочевидно, что там много пар

triples_array = []
for i in range(0, len(pair)):
for j in range(0, len(pair)):
if i != j:
square_sum = pair[i] ** 2 + pair[j] ** 2
pair.append(square_sum)
for i in range(0, len(array)):
for j in range(0, len(pair)):
if array[i] ** 2 == pair[j]:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

len(pair) = O(array^2)
поэтому этот цикл получается O(array^3), а нужен квадрат

triples_array.append(array[i])
return len(triples_array) // 2

sys.stdout.write(str(triples(array_of_elements)))
25 changes: 25 additions & 0 deletions lab10/Kabanova/triples_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import unittest

from pythagorean_triples import triples


class TestMaxSquare(unittest.TestCase):

def test_empty_array(self):
array = []
result = triples(array)
expected = 0
self.assertEqual(expected, result)

def test_example(self):
array = [23, 247, 19, 96, 264, 265, 132, 181]
result = triples(array)
expected = 2
self.assertEqual(expected, result)

def test_another(self):
array = [3, 4, 6, 10, 56]
result = triples(array)
expected = 0
self.assertEqual(expected, result)

28 changes: 28 additions & 0 deletions lab11/Kabanova/histogram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import sys

array_of_elements = [int(k) for k in sys.stdin.readline().split(' ')]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ваш тест не смог бы заработать из-за того, что при импорте вы пытаетесь считывать input
вам пригодилась бы такая конструкция:

if __name__ == "__main__":
    array_of_elements = [int(k) for k in sys.stdin.readline().split(' ')]
    sys.stdout.write(str(max_square(array_of_elements)))

в этом случае код этого файла вызывался бы только тогда, когда интерплетатором вызывался непосредственно histrogram.py, а не другой файл, импортирующий этот



def max_square(array):
max_elem = array[0]
square = 0
maxsquare = 0
if len(array) == 1:
return 0
else:
for i in range(1, len(array)):
if max_elem <= array[i]:
if square > maxsquare:
maxsquare = square
square = 0
max_elem = array[i]
else:
square += max_elem - array[i]
return maxsquare


sys.stdout.write(str(max_square(array_of_elements)))




34 changes: 34 additions & 0 deletions lab11/Kabanova/histogram_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import unittest

from histogram import max_square


class TestMaxSquare(unittest.TestCase):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тесты похоже не запускались, первые 3 падают
но алгоритм правильный

def test_empty_array(self):
array = []
result = max_square(array)
expected = 0
self.assertFalse(not result)
self.assertEqual(expected, result)

def test_one_elem(self):
array = [2]
result = max_square(array)
expected = 0
self.assertFalse(not result)
self.assertEqual(expected, result)

def test_three_elem(self):
array = [2, 5, 1]
result = max_square(array)
expected = 4
self.assertFalse(not result)
self.assertEqual(expected, result)

def test_example(self):
array = [2, 5, 1, 2, 3, 4, 7, 7, 6]
result = max_square(array)
expected = 10
self.assertFalse(not result)
self.assertEqual(expected, result)

35 changes: 35 additions & 0 deletions lab12/Kabanova/bst_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import unittest

import bst_tree
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

эта строка не работает, надо через from bst_tree import UnbalancedBinarySearchTree



class TestSorting(unittest.TestCase):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тесты падают


def test_first(self):
bst_tree_set = UnbalancedBinarySearchTree()
bst_tree_set.insert(5)
bst_tree_set.insert(4)
bst_tree_set.insert(6)
bst_tree_set.insert(2)
bst_tree_set.insert(1)
bst_tree_set.insert(3)
result = []
for v in bst_tree_set:
result.append(v)
expected = [1, 2, 3, 4, 5, 6]
self.assertEqual(expected, result)

def test_second(self):
bst_tree_set = UnbalancedBinarySearchTree()
bst_tree_set.insert(5)
bst_tree_set.insert(4)
bst_tree_set.insert(6)
bst_tree_set.insert(2)
bst_tree_set.insert(5)
bst_tree_set.insert(1)
bst_tree_set.insert(3)
result = []
for v in bst_tree_set:
result.append(v)
expected = [1, 2, 3, 4, 5, 5, 6]
self.assertEqual(expected, result)
73 changes: 73 additions & 0 deletions lab12/Kabanova/bst_tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
class Set:
def add(self, value):
pass

def iterate(self):
pass


class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None


class UnbalancedBinarySearchTree(Set):
def __init__(self):
self.root = None

def insert(self, value):
z = Node(value)
y = None
x = self.root
while x is not None:
y = x
if value < x.val:
x = x.left
else:
x = x.right
z.parent = y
if y is None:
self.root = z
else:
if value < y.val:
y.left = z
else:
y.right = z

def search(self, x, value):
if x is None:
return False
elif x.value == value:
return True
if value < x.value:
return self.search(x.left, value)
else:
return self.search(x.right, value)

def __iter__(self):
return TreeIterator(self)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

рассмотрите использование yield в этом коде, это очень мощная и уникальная конструкция, упрощающая программирование и чтение кода



class TreeIterator:
def __init__(self, root):
self.root = root
self.min = None

def has_next(self):
return self.root is not None

def next(self):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у этого генератора нет завершения

self.min = None
self.root = self.find_smallest(self.root)
return self.min

def find_smallest(self, root):
if root.left:
root.left = self.find_smallest(root.left)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь хвостовая рекурсия и питон её, к сожалению, не соптимизирует самостоятельно. Из-за выделений стека вы получаете O(h) памяти. Поправьте, пожалуйта

return root
else:
self.min = root.val
return root.right
79 changes: 79 additions & 0 deletions lab16/Kabanova/dejkstra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from heapq import heappush as insert, heappop as extract_minimum


class WeightedGraph:

def __init__(self):
self.vertex = []

def add_vertex(self, v):
self.vertex.append(Vertex(v))

def add_direct_link(self, v1, v2, weight):
self.vertex[v1 - 1].edges.append(Edge(v1-1, v2-1, weight))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

форматирование кода. нет пробелов между знаками. если пользуетесь pycharm/idea, то воспользуйтесь code->reformat code, чтобы они автоматически исправлялись


def paths(self, w):
for v in self.vertex:
if v == w:
return v.path_to
else:
dejkstra_search(self, w)
return w.path_to


def initiate_path(array):
for i in range(0, len(array)):
array[i].path.append(i)


class Vertex:

def __init__(self, value):
self.value = value
self.edges = []
self.path = []
self.path_to = []


class Edge:

def __init__(self, start, end, weight):
self.start = start
self.end = end
self.weight = weight


def dejkstra_search(graph, s):
initialize(graph.vertex, s)
initiate_path(graph.vertex)
set = []
pqueue = []
for i in range(0, len(graph.vertex)):
insert(pqueue, (graph.vertex[i].value, i))
while len(pqueue) != 0:
u = extract_minimum(pqueue)
set.append(u)
for v in range(0, len(graph.vertex[u[1]].edges)):
relax(graph.vertex[u[1]], graph.vertex[graph.vertex[u[1]].edges[v].end], graph.vertex[u[1]].edges[v])


def initialize(vertex, s):
for v in vertex:
v.value = float('Inf')
v.path_to = []
s.value = 0


def relax(u, v, edge):
if v.value > u.value + edge.weight:
v.value = u.value + edge.weight
v.path_to = u.path_to + v.path


graph = WeightedGraph()
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это должно быть в тестах

graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_direct_link(1, 2, 2)
graph.add_direct_link(1, 3, 2)
print(graph.paths(graph.vertex[1]))
27 changes: 27 additions & 0 deletions lab16/Kabanova/test_dejkstra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import unittest

import dejkstra

__author__ = 'catherinekabanova'

class TestSorting(unittest.TestCase):
def test_first(self):
graph = dejkstra.WeightedGraph()
graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_direct_link(1, 2, 2)
graph.add_direct_link(1, 3, 2)
result = graph.paths(graph.vertex[1])
expected = [0, 1]
self.assertEqual(expected, result)

def test_second(self):
graph = dejkstra.WeightedGraph()
graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_direct_link(1, 2, 2)
result = graph.paths(graph.vertex[2])
expected = [2]
self.assertEqual(expected, result)
12 changes: 12 additions & 0 deletions lab2/Kabanova/eratosthen_sieve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def sieve(n):
pros = [True for i in range(n + 1)]
pros[0] = False
pros[1] = False
for i in range(2, n + 1):
if pros[i]:
for k in range(2, n + 1):
if i * k < (n + 1):
pros[i * k] = False
return pros

print sieve(10)
18 changes: 18 additions & 0 deletions lab3/Kabanova/coins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import sys
first_line = sys.stdin.readline()
second_line = sys.stdin.readline()
number = int(first_line)
array_coins = [int(k) for k in second_line.split(' ')]


def methods(quantum, n, coins):
if quantum == 0:
return 1
elif quantum < 0 or n == 0:
return 0
else:
return methods(quantum, n - 1, coins) + methods(quantum - coins[n - 1], n, coins)

sys.stdout.write(str(methods(number, len(array_coins), array_coins)))


Loading