Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
9 changes: 9 additions & 0 deletions Pilshchikova/minimum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
a = [3, 2, 7, 5]
if len(a) > 0:
m = a[0]
for i in a:
if i < m:
m = i
print m
else:
print 'No'
12 changes: 12 additions & 0 deletions yalie/gen_bin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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)
16 changes: 16 additions & 0 deletions yalie/generators/generator1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def gen_bin(p, a):
if p < n:
a[p] = 0
gen_bin(p+1, a)
a[p] = 1
gen_bin(p+1, a)
else:
out.write(str(''.join((str(i) for i in a)))+'\n')
Copy link
Collaborator

Choose a reason for hiding this comment

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

тут скобочки можно опустить: '.join(str(i) for i in a)


inf = open('allvectors.in')
n = int(inf.readline().strip())
inf.close()

out = open('allvectors.out', 'w')
gen_bin(0, [0 for i in range(n)])
out.close()
28 changes: 28 additions & 0 deletions yalie/generators/generator2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
def gen_bin(p, a):
if p < n:
a[p] = 0
gen_bin(p+1, a)
a[p] = 1
gen_bin(p+1, a)
else:
v = ''.join(str(i) for i in a)
if '11' not in v:
global not11
Copy link
Collaborator

Choose a reason for hiding this comment

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

ай-ай-ай. Не используй глобальные переменные. А если используешь слова global, nonlocal, то из надо писать в начале функции:

def gen_bin(p, a)
    global not11

Вообще, эта задача решается красивее.

not11 += 1
tmp[not11-1] = str(v)
return not11

inf = open('vectors.in')
n = int(inf.readline().strip())
inf.close()

not11 = 0
tmp = [0 for i in range(2**n)]
Copy link
Collaborator

Choose a reason for hiding this comment

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

[0] * 2**n

ansver = gen_bin(0, [0 for i in range(n)])

out = open('vectors.out', 'w')
out.write(str(ansver) + '\n')
for i in tmp:
if i != 0:
out.write(str(i) + '\n')
out.close()
17 changes: 17 additions & 0 deletions yalie/generators/generator3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def gen_perm(a, p):
if p < n:
for i in range(1, n+1):
if i not in a:
a[p] = i
gen_perm(a, p+1)
a[p] = 0
else:
out.write(str(' '.join((str(i) for i in a)))+'\n')

infile = open('permutations.in', 'r')
n = int(infile.readline().strip())
infile.close()

out = open('permutations.out', 'w')
gen_perm([0 for i in range(n)], 0)
out.close()
17 changes: 17 additions & 0 deletions yalie/generators/generator4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def gen_comb(a, p):
if p < k:
for i in range(1, n+1):
if i not in a and i > a[p-1]:
a[p] = i
gen_comb(a, p+1)
a[p] = 0
else:
out.write(str(' '.join((str(i) for i in a)))+'\n')

infile = open('choose.in', 'r')
n, k = [int(i) for i in infile.readline().strip().split()]
infile.close()

out = open('choose.out', 'w')
gen_comb([0 for i in range(k)], 0)
out.close()
24 changes: 24 additions & 0 deletions yalie/generators/generator5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#WA in test 10, but this code is working!

def gen_subs(a):
ans = []
for i in range(2**n):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Опятьсовершенно не нужная глобальная переменная

tmp = []
for j in range(n):
Copy link
Collaborator

Choose a reason for hiding this comment

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

use list comprehension!

tmp = [mn[j] for j in range(n) if i & (1 << j)]

if i & (1 << j):
tmp.append(mn[j])
ans.append(' '.join(str(i) for i in tmp))
return ans


with open('subsets.in', 'r') as infile:
n = int(infile.readline().strip())
Copy link
Collaborator

Choose a reason for hiding this comment

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

.strip() не нужен


mn = range(1, n+1)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Почему это не локальная переменная функции gen_subs?

subs = gen_subs(mn)
subs.sort()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ух ты, никогда не думал о том, что для списков в питоне < разумно определено! Спасибо!


with open('subsets.out', 'w') as out:
out.write('\n'.join(subs))

print '\n'.join(subs)
16 changes: 16 additions & 0 deletions yalie/generators/generator5a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def gen_subs(line, l):
ans.append(' '.join(str(i) for i in line))
for i in mn:
if i > l:
gen_subs(line + [i], i)
return ans

with open('subsets.in', 'r') as infile:
n = int(infile.readline().strip())

mn = range(1, n+1)
ans = []
gen_subs([], 0)

with open('subsets.out', 'w') as out:
out.write('\n'.join(ans))
50 changes: 50 additions & 0 deletions yalie/graphs/graph1a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from collections import deque

#file reading
ingraph = open('components.in', 'r')
s = [int(i) for i in ingraph.readline().split()]
n = s[0]
m = s[1]
smezhn = {} #dict like adjacency list
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не надо использовать транслитерацию, есть английское слово adjecency.

for j in range(m):
x = [int(i) for i in ingraph.readline().split()]
if x[0] in smezhn:
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 = [int(i)...], но тут можно было заметить проблему и так: по три раза повторяются выражения x[0], x[1]. Это маленький, но копипаст, а копипаста быть не должно

smezhn[x[0]].append(x[1])
else:
smezhn[x[0]] = [x[1]]
if x[1] in smezhn: #because here is not-directed graph
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ну и этот if тоже на самом деле пример копирования, который демонстрирует интересный эффект -- копия внутри копии приводит в итоге к четырём копиям

smezhn[x[1]].append(x[0])
else:
smezhn[x[1]] = [x[0]]
for i in range(1, n+1):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Такую инициализацию можно было сделать в начале, тогда не надо было бы разбирать случаев if x[0] in smezhn, а можно было бы сразу писать append

if i not in smezhn:
smezhn[i] = []
ingraph.close()

#depth-first search
comp = {} #dict of components
def dfs():
Copy link
Collaborator

Choose a reason for hiding this comment

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

Это же bfs?

cc = 0 #number of components
for i in range(1, n+1):
if i not in comp:
cc += 1
comp[i] = cc
queue = deque([i])
while len(queue) > 0:
for j in smezhn[queue[0]]:
if j not in comp:
comp[j] = cc
queue.append(j)
queue.popleft()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Чуть лучше было бы сделать v = queue.popleft() в начале цикла, и использовать v вместо queue[0]

out = open('components.out', 'w')
out.write(str(cc)+'\n')
out.close()

dfs()

#saving results
out = open('components.out', 'a')
a = comp.values()
for k in a:
out.write(str(k)+' ')
out.close()
44 changes: 44 additions & 0 deletions yalie/graphs/graph2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from collections import deque

smezhn = {} #dict like adjacency list
dist = {} #a dict of distances
dist[1] = 0
Copy link
Collaborator

Choose a reason for hiding this comment

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

можно было сразу проинициализировать

dist = {1 : 0}


def read(): #file reading
ingraph = open('pathbge1.in', 'r')
s = [int(i) for i in ingraph.readline().split()]
n = s[0]
m = s[1]
for j in range(m):
x = [int(i) for i in ingraph.readline().split()]
if x[0] in smezhn:
smezhn[x[0]].append(x[1])
else:
smezhn[x[0]] = [x[1]]
if x[1] in smezhn: #because here is not-directed graph
smezhn[x[1]].append(x[0])
else:
smezhn[x[1]] = [x[0]]
for i in range(1, n+1):
if i not in smezhn:
smezhn[i] = []
ingraph.close()
return smezhn

def bfs():
queue = deque([1])
while len(queue) > 0:
for i in smezhn[queue[0]]:
if i not in dist:
dist[i] = dist[queue[0]] + 1
queue.append(i)
queue.popleft()
return dist

read()
bfs()
out = open('pathbge1.out', 'w')
a = dist.values()
for k in a:
out.write(str(k)+' ')
out.close()
43 changes: 43 additions & 0 deletions yalie/graphs/graph3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#file reading
ingraph = open('pathmgep.in', 'r')
x = [int(i) for i in ingraph.readline().split()]
N = x[0] #number of nodes
S = x[1] #start
F = x[2] #finish
msm = [] #incidence matrix
for i in range(N):
y = [int(i) for i in ingraph.readline().split()]
msm.append(y)
ingraph.close()

d = {} #distance dict
for i in range(1, N+1):
d[i] = -1
n = [] #list of nodes

def Dejkstra(d,S,F): # Dejkstra algorithm
Copy link
Collaborator

Choose a reason for hiding this comment

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

Дейкстра молодец, но это не повод называть функцию с большой буквы. Также, он всё-таки Dijkstra

Copy link
Collaborator

Choose a reason for hiding this comment

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

пробелы после ,

d[S] = 0
for y in range(N-1):
n.append(S)
for i in range(N):
if msm[S-1][i] != -1:
if d[i+1] != -1:
d[i+1] = min(d[i+1], (d[S]+msm[S-1][i]))
else:
d[i+1] = msm[S-1][i]+d[S]
a = {} #only help in finding a min node
for key in d:
Copy link
Collaborator

Choose a reason for hiding this comment

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

можно переписать цикл в виде comprehension

if key not in n and d[key] != -1:
a[key] = d[key]
if len(a) == 0:
break
S = min(a, key=lambda k: a[k])
return d

Dejkstra(d,S,F)

out = open('pathmgep.out', 'w')
out.write(str(d[F]))
out.close()

print d[F]
37 changes: 37 additions & 0 deletions yalie/graphs/graph5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#file reading
ingraph = open('pathsg.in', 'r')
s = [int(i) for i in ingraph.readline().split()]
n = s[0]
m = s[1]
smezhn = {} #dict of dicts like adjacency list, with weights
for j in range(m):
x = [int(i) for i in ingraph.readline().split()]
if x[0] not in smezhn:
smezhn[x[0]] = {x[1]: x[2]}
else:
smezhn[x[0]][x[1]] = x[2]
ingraph.close()

#distance matrix
d = [[1e100 for i in range(n)] for i in range(n)]
Copy link
Collaborator

Choose a reason for hiding this comment

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

[1e100] * n

for i in range(n):
Copy link
Collaborator

Choose a reason for hiding this comment

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

странный цикл, почему не просто

for i in range(n):
    d[i][i] = 0

for j in range(n):
if i == j:
d[i][j] = 0
for key in smezhn:
for kk in smezhn[key]:
d[key-1][kk-1] = smezhn[key][kk]

def floyd(d): #Floyd algorithm
Copy link
Collaborator

Choose a reason for hiding this comment

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

Комментарии повторяющие код не нужны

for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], (d[i][k]+d[k][j]))

floyd(d)

out = open('pathsg.out', 'w')
for l in d:
out.write(' '.join(str(i) for i in l))
out.write('\n')
out.close()
50 changes: 50 additions & 0 deletions yalie/graphs/graph6a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#reading a file
ingraph = open('spantree.in','r')
n = int(ingraph.readline().strip())
p = [] #a list of lists with all points
for i in range(n):
t = [int(i) for i in ingraph.readline().split()]
p.append(t)
ingraph.close()

#calculation of length of the edge
def le(a,b):
Copy link
Collaborator

Choose a reason for hiding this comment

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

почему эта функция называется le? Обычно это сокращение для less or equal

import math
Copy link
Collaborator

Choose a reason for hiding this comment

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

импорты всегда в начале файла

m = math.sqrt((p[a][0] - p[b][0])**2 + (p[a][1] - p[b][1])**2)
return m

#saving a graph to the matrix
def sm(p):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лучше нормальное название функции, чем комментарий

smezhn = [['x' for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
smezhn[i][j] = le(i,j)
return smezhn

#Prim algorithm
def Prim(smezhn):
used = []
mine = []
for i in range(n):
Copy link
Collaborator

Choose a reason for hiding this comment

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

list comprehencion, а лучше [False] * n, ['x'] * n

used.append(False)
mine.append('x')
used[0] = True
mine[0] = 0
idx = 0
for i in range(n-1):
tmp = {}
for j in range(n):
if not used[j]:
mine[j] = min(mine[j], smezhn[idx][j])
tmp[j] = mine[j]
idx = min(tmp, key=tmp.get) #finding an index (node) of edge with min weight
used[idx] = True
return mine

smezhn = sm(p)
wedge = Prim(smezhn)
ans = sum(wedge)

out = open('spantree.out', 'w')
out.write(str(ans))
out.close()