-
Notifications
You must be signed in to change notification settings - Fork 11
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
base: master
Are you sure you want to change the base?
Tasks #2
Changes from 11 commits
848aad6
5dd3ff3
2a41252
43a7177
ffcd196
ded44bc
b8a2e69
9112e68
a434425
fe92dac
fa4debc
b1ceac7
546d8b6
4f59c18
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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) |
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()) | ||
|
||
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') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
gen_bin(a,0) | ||
infile.close() | ||
outfile.close() |
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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
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): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А используется только тут... Хорошо объявлять переменную как можно ближе к первому использованию. И совершенно точно не стоит отделять объявление и использование функцией, у которой параметр называется также, как и переменная: очень просто запутаться, к чему именно относится идентификатор seq. |
||
outfile.write(str.join(' ', (str(j) for j in i)) + '\n') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лучше There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. И лучше было бы переменную |
||
|
||
infile.close() | ||
outfile.close() | ||
|
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=[] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
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() |
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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Очень сложно, если я правильно понял, как это должно работать =) Вот так вроде проще if i.find('11') > -1:
ones.append(i) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Но лучше вообще использовать set comprehension
|
||
ans=sorted(list(set(all_bin).difference(set(ones)))) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Все импорты должны располагаться в начале файла. |
||
neighbours = defaultdict(lambda: defaultdict(lambda: 0)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Но вообще в данном случае не очень хорошо использовать Это будет лучше с той точки зрения что, если случайно обратиться к несуществующей вершине, будет исключение, а не silent failure. Короче говоря, проще будет искать баги в коде |
||
for v1, v2 in edges: | ||
neighbours[v1][v2] += 1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А зачем тут счётчики количества рёбер? Вроде бы кратность нигде не используется, и было бы достаточно True/False. Ну или вообще для каждой вершинки хранить set соседей. |
||
neighbours[v2][v1] += 1 | ||
|
||
def dfs(): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
for v in neighbours[queue[0]]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. вроде можно сказать просто There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лучше вместо цикла записать
где первый sum это переменная, а второй -- та самая build-in функция |
||
if i>0: | ||
sum+=i | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Вообще, с учётом ограничений на задачу, можно в начале сказать 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() |
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)] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [float('inf')] * n There was a problem hiding this comment. Choose a reason for hiding this commentThe 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): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. аналогично, тут
|
||
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() |
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
strip
лишний