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

Tasks #2

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
11 changes: 11 additions & 0 deletions sergeeva/gen_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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 sergeeva/generators/allvectors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
infile = open('allvectors.in', 'r')
outfile = open('allvectors.out', 'w')
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 лишний


a=[0]*n
def gen_bin(a,p):
if p < n:
a[p] = 0
gen_bin(a, p+1)
a[p] = 1
gen_bin(a, p+1)
else:
outfile.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.

str(''.join([str(i) for i in a])) это масло масляное, ''.join([str(i) for i in a])это уже строка.

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]) это почти тоже самое, что и ''.join((str(i) for i in a)), что можно сократить до ''.join(str(i) for i in a)

gen_bin(a,0)
infile.close()
outfile.close()
20 changes: 20 additions & 0 deletions sergeeva/generators/choose.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
infile = open('choose.in', 'r')
outfile = open('choose.out', 'w')

n, k = [int(i) for i in infile.readline().split()]
seq=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.

seq объявляется тут...


def choose(seq, k):
if k == 0:
yield []
else:
for i, x in enumerate(seq):
for c in choose(seq[i+1:], k-1):
yield [x] +c

for i in choose(seq, k):
Copy link
Collaborator

Choose a reason for hiding this comment

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

А используется только тут...

Хорошо объявлять переменную как можно ближе к первому использованию.

И совершенно точно не стоит отделять объявление и использование функцией, у которой параметр называется также, как и переменная: очень просто запутаться, к чему именно относится идентификатор seq.

outfile.write(str.join(' ', (str(j) for j in i)) + '\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[j] for j in i)

Copy link
Collaborator

Choose a reason for hiding this comment

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

И лучше было бы переменную i назвать как-нибудь иначе: for j in i выглядит странно -- i и j почти всегда равноправны и почти всегда числа.


infile.close()
outfile.close()

22 changes: 22 additions & 0 deletions sergeeva/generators/permutations1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
infile = open('permutations.in', 'r')
outfile = open('permutations.out', 'w')

n = int(infile.readline().strip())
seq=range(1,n+1)

ans=[]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно было бы обойтись без этой глобальной перменной.

В такой маленькой задаче это, наверное, не очень важно, но вообще не константная глобальная перменная это очень плохо.


def permutation(seq, i):
if i == len(seq)-1:
ans.append(str(''.join([str(i) for i in seq])))
else:
for j in range(i, len(seq)):
seq[i], seq[j] = seq[j], seq[i]
permutation(seq, i+1)
seq[i], seq[j] = seq[j], seq[i]

permutation(seq, 0)
for i in sorted(ans):
outfile.write(str(' '.join([str(j) for j in i])+'\n'))
infile.close()
outfile.close()
20 changes: 20 additions & 0 deletions sergeeva/generators/permutations2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#permutations code from class work

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

n = int(infile.readline().strip())
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:
outfile.write(str.join(' ', (str(i) for i in a))+'\n')

gen_perm([0 for i in range (n)], 0)

infile.close()
outfile.close()
29 changes: 29 additions & 0 deletions sergeeva/generators/vectors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import re
infile = open('vectors.in', 'r')
outfile = open('vectors.out', 'w')

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

a = [0]*n
all_bin=[]
def gen_bin(a,p):
if p < n:
a[p] = 0
gen_bin(a, p+1)
a[p] = 1
gen_bin(a, p+1)
else:
all_bin.append(str(''.join([str(i) for i in a])))

gen_bin(a,0)

ones=[]
for i in all_bin:
for match in re.findall('11', i):
ones.append(i)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Очень сложно, если я правильно понял, как это должно работать =)

Вот так вроде проще

if i.find('11') > -1:
    ones.append(i)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Но лучше вообще использовать set comprehension

{i for i in all_bin if i.find('11') > -1}

ans=sorted(list(set(all_bin).difference(set(ones))))
Copy link
Collaborator

Choose a reason for hiding this comment

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

list не нужен, sorted принимает любую коллекцию.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Если это задача про последовательности без двух единичек подряд, то её можно проще и красивие решить)

Там даже появятся числа Фибоначчи!


outfile.write(str(len(ans))+'\n')
outfile.write(str('\n'.join([str(i) for i in ans])))
infile.close()
outfile.close()
41 changes: 41 additions & 0 deletions sergeeva/graphs/comp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from collections import deque

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

n,e = [int(i) for i in infile.readline().split()]

#edgelist
edges=[]
for i in range(e):
edges.append([int(j) for j in infile.readline().split()])

#neighbours
from collections import defaultdict
Copy link
Collaborator

Choose a reason for hiding this comment

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

Все импорты должны располагаться в начале файла.

neighbours = 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.

defaultdict(lambda: 0) == defaultdict(int)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Но вообще в данном случае не очень хорошо использовать defaultdict. Множество ключей известно зарание (range(1, n+1) видимо), так что можно написать {u: {v: 0 for v in vertexes} for u in vertexes } или, так как ключи целые числа, вообще использовать список списков.

Это будет лучше с той точки зрения что, если случайно обратиться к несуществующей вершине, будет исключение, а не silent failure.

Короче говоря, проще будет искать баги в коде

for v1, v2 in edges:
neighbours[v1][v2] += 1
Copy link
Collaborator

Choose a reason for hiding this comment

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

А зачем тут счётчики количества рёбер? Вроде бы кратность нигде не используется, и было бы достаточно True/False.

Ну или вообще для каждой вершинки хранить set соседей.

neighbours[v2][v1] += 1

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

num_component ={}
comp = 0
for i in range(1, n+1):
if i not in num_component:
comp += 1
num_component[i] = comp
queue = deque([i])
while len(queue) > 0:
Copy link
Collaborator

Choose a reason for hiding this comment

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

while len(x) > 0 == while x

for v in neighbours[queue[0]]:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лучше сказать

u = queue.popleft()
for v in neighbours[u]:
    ...

чем сначала итерироваться по queue[0], а потом делать popleft

if v not in num_component:
num_component[v] = comp
queue.append(v)
queue.popleft()
outfile.write(str(comp)+ '\n')
for i in num_component.values():
outfile.write(str(i)+' ')
dfs()


infile.close()
outfile.close()
44 changes: 44 additions & 0 deletions sergeeva/graphs/pathbge1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
infile = open('pathbge1.in', 'r')
outfile = open('pathbge1.out', 'w')

n,e = [int(i) for i in infile.readline().split()]

#edgelist
edges=[]
for i in range(e):
edges.append([int(j) for j in infile.readline().split()])

#linking edges
def link(u, v):
if u not in graph:
graph[u] = {}
(graph[u])[v] = 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 v not in graph:
graph[v] = {}
(graph[v])[u] = 1
return graph

graph = {}
for (x,y) in edges:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно проще

vertexes = range(1, n+1)
graph = {v: set() for v in vertexes}
for u, v in edges:
    graph[v].add(u)
    graph[u].add(v)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Главная проблема в link -- то, что используется глобальная переменная graph. Это не очень хорошо.

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

def build_graph_from_edges(edges):
    graph = {}
    bla-bla-bla
    return graph

link(x,y)
dist = {} #distance

def bfs (s, v):
q = [s] #queue
dist[s] = 0
while len(q) > 0:
current = q.pop(0)
Copy link
Collaborator

Choose a reason for hiding this comment

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

вроде можно сказать просто .pop(), без аргумента

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 graph[current].keys():
if i not in dist:
dist[i] = dist[current] + 1
if i == v:
return dist[v]
q.append(i)
return dist

bfs(1,n+1)
for j in dist.values():
outfile.write(str(j) + ' ')

infile.close()
outfile.close()
35 changes: 35 additions & 0 deletions sergeeva/graphs/pathmgep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
infile = open('pathmgep.in', 'r')
outfile = open('pathmgep.out', 'w')

n, S, F = [int(i) for i in infile.readline().split()]

dist = []

sum=0
Copy link
Collaborator

Choose a reason for hiding this comment

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

плохое имя для переменной, потому что есть buildin функция sum

for line in infile.read().splitlines():
values = [int(i) for i in line.split()]
dist.append(values)
for i in values:
Copy link
Collaborator

Choose a reason for hiding this comment

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

лучше вместо цикла записать

sum += sum(i for i in values if i > 0)

где первый sum это переменная, а второй -- та самая build-in функция

if i>0:
sum+=i
Copy link
Collaborator

Choose a reason for hiding this comment

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

kill it with fire: http://evadeflow.com/wp-content/uploads/2011/03/TabsSpacesBoth.png

Смешивать табы и пробелы в питоне очень плохо.

Кстати, у вас же вроде бы третий питон? В нём смесь табов и пробелов вообще не должна работать.


for i in range(n):
for j in range(n):
if dist[i][j] == -1:
dist[i][j] = sum +1
Copy link
Collaborator

Choose a reason for hiding this comment

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

sum+1 это такая бесконечность?

Вообще, с учётом ограничений на задачу, можно в начале сказать

inf = 10**9 и использовать inf вместо sum -- вроде должно чуть упросить код, и название переменной будет более самодокументирующиеся


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


floyd(dist)

if dist[S-1][F-1]>=sum:
dist[S-1][F-1]=-1

outfile.write(str(dist[S-1][F-1]))
infile.close()
outfile.close()
33 changes: 33 additions & 0 deletions sergeeva/graphs/pathsg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#floyd
infile = open('pathsg.in', 'r')
outfile = open('pathsg.out', 'w')

n,e = [int(i) for i in infile.readline().split()]

dist = [[float('inf') for i in range(n)] 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.

[float('inf')] * n

Copy link
Collaborator

Choose a reason for hiding this comment

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

также есть convention, если перменная не используется, называть её _

dist = [[float('inf')] * n for _ in range(n)]


sum=0
for i in range(e):
Copy link
Collaborator

Choose a reason for hiding this comment

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

аналогично, тут

for _ in range(e)

u, v, weight = [int(x) for x in infile.readline().split()]
dist[u-1][v-1] = weight
sum += weight

for i in range(n):
for j in range(n):
if i == j:
dist[i][j] = 0
elif dist[i][j] == float('inf'):
dist[i][j] = sum +1

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

floyd(dist)

for row in dist:
outfile.write(' '.join(str(i) for i in row) + '\n')
infile.close()
outfile.close()
6 changes: 6 additions & 0 deletions sergeeva/minimum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
a = [10,5,9,7]
m = a[0]
for i in a:
if i < m:
m = i
print(m)