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

B-1 #1

Open
wants to merge 34 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
bab33ff
prog created today
sofiiako Mar 22, 2014
4ec64a4
second prog
sofiiako Mar 22, 2014
b71e7b0
Solution for B-1
sofiiako Apr 10, 2014
1223bc2
Solutions for problems from the A-block >_<
sofiiako Apr 10, 2014
5d2afa2
B2,3,4 Problems
sofiiako Apr 11, 2014
e87b66c
Cleaned up comments.
sofiiako Apr 12, 2014
84de2a3
Cleaned up comments.
sofiiako Apr 12, 2014
d66a737
Cleaned up comments.
sofiiako Apr 12, 2014
2cc5fae
B-6 :)
sofiiako Apr 12, 2014
4ce7366
B5 problem
sofiiako Apr 13, 2014
c40d1c3
algorithms: one of possible solutions for the3rd regression problem
sofiiako Apr 22, 2014
2955870
THe third regression problem (Algorithms for biologists course)
sofiiako Apr 22, 2014
de5da67
edited
sofiiako Apr 22, 2014
bc74e82
the third problem, edited once more
sofiiako Apr 22, 2014
aa60d2c
1st and 2nd problems (Algorithms)
sofiiako Apr 22, 2014
79dcd4c
bebe
sofiiako Apr 22, 2014
711f9e9
3rd hometask, unfinished
sofiiako Apr 25, 2014
9a928e4
python & ipython regression task (please do not pay attention to othe…
sofiiako May 1, 2014
6e75d8f
some editing done
sofiiako May 2, 2014
1ccef0b
Я как-то потеряла этот скрипт и вовремя не добавила в проверяющую сис…
sofiiako May 23, 2014
f4e9515
C3
Jun 1, 2014
2025d6b
improved version B8
Jun 5, 2014
b7805a1
C4 problem
Jun 5, 2014
d906f73
changed name
Jun 5, 2014
4690af0
classifiers, first attempt
Jun 5, 2014
e8f3357
some editing, vizualisation
Jun 5, 2014
01e1272
a bit more
Jun 5, 2014
5d02cc9
final?
Jun 5, 2014
5c7433f
C5
Jun 5, 2014
b3a5f2d
C7
Jun 5, 2014
f57494a
C6
Jun 6, 2014
2f931ec
debug
Jun 6, 2014
6e77e91
C6.py
Jun 6, 2014
b2cbcbb
minor additional changes, sorry
Jun 6, 2014
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
10 changes: 10 additions & 0 deletions gen_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
k = 3
def gen_bin (a,p):
if p<k:
a[p] = 0
gen_bin(a, p+1)
a[p] = 1
gen_bin (a, p+1)
else:
print (a)
gen_bin ([0 for i in range (k)], 0)
11 changes: 11 additions & 0 deletions gen_perm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
k = 3
def gen_perm (a,p,k):
if p<k:
for i in range (1, k+1):
if i not in a:
a[p] = i
gen_perm (a, p+1, k)
a[p] = 0
else:
print (a)
gen_perm ([0 for i in range (k)],0,k)
50 changes: 50 additions & 0 deletions kolchanova/A-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import sys
from collections import defaultdict
sys.setrecursionlimit(200000)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Сначала все импорты, потом всё остальное


from collections import deque
Copy link
Collaborator

Choose a reason for hiding this comment

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

from collections import deque, defaultdict

input_file = open('components.in', 'r')
output_file = open('components.out', 'w')

n_vertices, n_edges = [int(i) for i in input_file.readline().split()]
vertices = []
edges = []
for i in range(1, n_vertices+1):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не нужный цикл

vertices = list(range(1, n_vertices + 1))

vertices.append (i)
i += 1
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот это точно совершенно не нужно. Понятно, почему?

Вообще, это плохой тон -- менять перемную итерации в цикле

for j in range (n_edges):
edges.append ([int(j) for j in input_file.readline().split()])
Copy link
Collaborator

Choose a reason for hiding this comment

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

Я бы всё-таки написал в две строчки:

u, v = [int(x) for x in input_file.readline().split()]
edges.append((u, v))

Мне кажется это лучше, потому что, если вдруг в файле на строке будет не два числа, а, допустим, три, то будет исключения, а не "странное ребро". Т.е, ошибка будет замечена раньше. Ну и рёбра логичнее хранить в виде tupleов, а не listов


adj = defaultdict (lambda: defaultdict(lambda: 0))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Кажется, этот код я уже reviewил =) Не знаю, где первоисточник, но копипастить свои комменты не буду, а скину ссылку сюда: https://github.com/effect/bii-14s/pull/2/files#diff-17946aa57dd98378de0360a890962845R15


for x, y in edges:
adj[x][y] += 1
adj [y][x] += 1
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ну ай-ай-ай, не красиво же пробел смотрится


def search_df ():
conn_comp = {}
coconut = 0
for i in vertices:
if i not in conn_comp:
coconut += 1
conn_comp[i] = coconut
queue = deque ([i])


while len(queue) > 0:
for j in adj[queue[0]]:
if j not in conn_comp:
conn_comp[j] = coconut
queue.append (j)

queue.popleft ()
output_file.write(str(coconut)+"\n")
for i in conn_comp.values ():
output_file.write(str(i)+" ")
search_df()

input_file.close()
output_file.close ()



51 changes: 51 additions & 0 deletions kolchanova/A-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import sys
sys.setrecursionlimit(200000)

from collections import deque
from collections import defaultdict
input_file = open('pathbge1.in', 'r')
output_file = open('pathbge1.out', 'w')


def function():
Copy link
Collaborator

Choose a reason for hiding this comment

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

???

pass


n_vertices, n_edges = [int(i) for i in input_file.readline().split()]
vertices = []
edges = []
for i in range(1, n_vertices+1):
vertices.append (i)
i += 1
for j in range (n_edges):
edges.append ([int(j) for j in input_file.readline().split()])


adj = defaultdict (lambda: defaultdict(lambda: 0))

for x, y in edges:
adj[x][y] += 1
adj [y][x] += 1


distances = {1:0}
def BFS ():
Copy link
Collaborator

Choose a reason for hiding this comment

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

Функции капсом не называют, даже если это акроним

queue = deque ([1])
while len (queue):
for i in adj[queue[0]]:
if i not in distances:
distances[i] = distances[queue[0]] + 1
queue.append(i)
queue.popleft()
return distances

BFS ()

answer = distances.values()
for i in answer:
Copy link
Collaborator

Choose a reason for hiding this comment

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

лучше output_file.write(' '.join(str(i) for i in answer))

output_file.write(str(i)+ " ")
input_file.close ()
output_file.close ()



60 changes: 60 additions & 0 deletions kolchanova/A-3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import sys
sys.setrecursionlimit(100000)
#from collections import deque


infile = open('pathmgep.in', 'r')
outfile = open('pathmgep.out', 'w')

dimensions = [int(i) for i in infile.readline().split()]
n_vertices = dimensions[0]
start = dimensions[1]
end = dimensions[2]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно было написать

n_vertices, start, end = [int(i) for i in infile.readline().split()]


scope = []
Copy link
Collaborator

Choose a reason for hiding this comment

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

Зачем эта глобальная переменная?

def get_matrix (scope, infile, n_vertices):
for i in range(n_vertices):
y = [int(i) for i in infile.readline().split()]
scope.append(y)
return scope
get_matrix (scope, infile, n_vertices)



distances = {} #distance dict
Copy link
Collaborator

Choose a reason for hiding this comment

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

очевидные комментарии не нужны

Copy link
Collaborator

Choose a reason for hiding this comment

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

И опять же, зачем глобальная переменная?

def get_dist (distances, n_vertices):
for i in range(1, n_vertices+1):
distances[i] = -1
return distances
get_dist (distances, n_vertices)


#the main algorithm
vertices = []
def dijkstra_alg (distances,start,end):

distances[start] = 0
for y in range(n_vertices-1):

vertices.append(start)
for i in range(n_vertices):

if scope[start-1][i] != -1:
if distances[i+1] != -1:
distances[i+1] = min(distances[i+1], (distances[start]+scope[start-1][i]))
else:
distances[i+1] = scope[start-1][i]+distances[start]
assist = {}
for key in distances:
if key not in vertices and distances[key] != -1:
assist[key] = distances[key]
if len(assist) == 0:
break
start = min(assist, key=lambda k: assist[k])
return distances
dijkstra_alg (distances,start,end)

outfile.write(str(distances[end]))

infile.close()
outfile.close()
51 changes: 51 additions & 0 deletions kolchanova/A-5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import sys
sys.setrecursionlimit(100000)


input_file = open('pathsg.in', 'r')
output_file = open('pathsg.out', 'w')

nodes, edges = [int(i) for i in input_file.readline().split()]
dist = []
Copy link
Collaborator

Choose a reason for hiding this comment

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

зачем?


dist = [[None for i in range(nodes)] for j in range(nodes)]
Copy link
Collaborator

Choose a reason for hiding this comment

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

опять не нужный глобал



def get_dist (dist,nodes):
cumulative_w = 0


for j in range (edges):

x,y,z = [int (w) for w in input_file.readline().split()]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Плохие названия переменных. x, y, w было бы лучше, потому что третья отличается по смыслу от первых двух

dist [x-1][y-1] = z
cumulative_w += z

for j in range (nodes):
for i in range (nodes):
if j == i:
dist[j][i] = 0
elif dist[j][i] is None:
dist [j][i] = cumulative_w +1
return dist


def F_W (nodes, dist):
for i in range (nodes):
for j in range (nodes):
for x in range (nodes):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Опять не самые лучшие названия, потому что особая тут как раз внешняя переменная

if dist[j][i] + dist[i][x] < dist [j][x]:
Copy link
Collaborator

Choose a reason for hiding this comment

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

ifы вида

if a > b:
    a = b

понятнее смотрятся в виде a = min(a, b)

dist [j][x] = dist [j][i] + dist [i][x]
return dist

get_dist (dist,nodes)

F_W (nodes,dist)

for line in dist:

output_file.write(' '.join(str(i) for i in line) + '\n' )


input_file.close()
output_file.close()
16 changes: 16 additions & 0 deletions kolchanova/B-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/python

outdata = open("allvectors.out", "w")

def gen_bin(vector, position):
if position < len(vector):
for nextvalue in ["0", "1"]:
vector[position] = nextvalue
gen_bin(vector, position + 1)
else:
outdata.write("".join(vector) + "\n")

with open("allvectors.in", "r") as indata:
n = int(indata.readline().strip())

gen_bin(["0"] * n, 0)
31 changes: 31 additions & 0 deletions kolchanova/B-6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/python

def nextvector (seq):
result = seq[:]
for x,y in reversed(list(enumerate(seq))):
Copy link
Collaborator

Choose a reason for hiding this comment

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

мило =)

if y == '0':
result[x] = '1'
return result
else:
result[x] = '0'
return ['-']

def previousvector (seq):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Эта функция почти копипаст предыдущей.

Лучше было бы сделать одну

def nextvector(seq, reverse_diraction=False):
    pass

result = seq[:]
for x,y in reversed(list(enumerate(seq))):
if y == '1':
result[x] = '0'
return result
else:
result[x] = '1'
return ['-']

with open ('nextvector.in', 'r') as infile:
seq = list(infile.readline().strip())

preceding = previousvector(seq)
following = nextvector(seq)

with open ('nextvector.out', 'w') as outfile:
outfile.write(''.join(preceding) + '\n')
outfile.write(''.join(following) + '\n')
26 changes: 26 additions & 0 deletions kolchanova/B2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/python

indata = open ("vectors.in","r")
outdata = open ("vectors.out",'w')

n = int (indata.readline().strip())
vectors = []

def gener_vect (vector, position):
if position < len (vector):
for next in ["0","1"]:
if position > 0 and next == "1" and vector[position-1] == "1":
pass
Copy link
Collaborator

Choose a reason for hiding this comment

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

зачем?

else:
vector[position] = next
gener_vect(vector, position + 1)
else :
vectors.append (vector[:])
return vectors


gener_vect (["0"] * n, 0)

outdata.write (str(len(vectors))+"\n")
for vector in vectors:
outdata.write("".join(vector) + "\n")
19 changes: 19 additions & 0 deletions kolchanova/B3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
infile = open ("permutations.in","r")
outfile = open ("permutations.out",'w')

n = int (infile.readline().strip())

def generate_permutations (seq, loc):
if loc < len (seq):
for i in range (1, n+1):
if i not in seq:
seq[loc] = i
generate_permutations (seq, loc+1)
seq[loc] = 0
else:
outfile.write(" ".join([str(i) for i in seq]) + "\n")

generate_permutations (["0"] * n, 0)



27 changes: 27 additions & 0 deletions kolchanova/B4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/python

infile = open ("choose.in",'r')
outfile = open ("choose.out",'w')

n, k = (int(x) for x in infile.readline().split())
variants = []

def gener_comb (combination, position, n):
if position < k:
for i in range (1, n+1):
if i not in combination:
if position > 0 and i < combination[position-1]:
pass
Copy link
Collaborator

Choose a reason for hiding this comment

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

аналогично, зачем?

else:
combination[position] = i
gener_comb (combination, position+1, n)
combination[position] = 0
else:
variants.append(combination[:])
return variants
gener_comb ([0]*k, 0, n)

for v in variants:
outfile.write(" ".join([str(x) for x in v]) + "\n")