B
B
bublov2019-06-11 16:50:43
Python
bublov, 2019-06-11 16:50:43

What would this code look like in python (pascal source language)?

I found the code in Pascal, but since I did not study it, I did not understand anything. Help translate the code into python 3 so that I can somehow figure it out.

var
  inp, outp: text;
  n, m, x, y, col, i, j: integer; 
  relations: array[1..100, 1..100] of integer;
  used: array[1..100] of boolean;
  ability: boolean;
  color: array[1..100] of integer;


procedure DFS(v: integer);
var
 j: integer;

begin
  used[v] := false;
  color[v] := col;
  col := col * (-1);
  for j := 1 to n do
    if (relations[v, j] <> 0) and used[j] then DFS(j);
end;



begin
  assign(inp, inpFileName);
  assign(outp, outpFileName);
  reset(inp);
  rewrite(outp);

  read(inp, n, m);

  for i := 1 to n do 
    for j := 1 to n do
      relations[i, j] := 0;

  for i := 1 to m do
  begin
    read(inp, x, y);
    relations[x, y] := 1;
    relations[y, x] := 1;
  end;

  for i := 1 to m do
    used[i] := true;

  col := 1;

  for i := 1 to n do
    color[i] := 0;

  DFS(x);

  ability := true;

  for i := 1 to n do
    for j := 1 to n do
      if (color[i] = color[j]) and (relations[i, j] <> 0) then ability := false;

  if ability then 
  begin
    writeln(outp, 'YES');  
    for i := 1 to n do
      if color[i] = 1 then writeln(outp, i);
  end
  else writeln(outp, 'NO');

  close(inp);
  close(outp);
end.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2019-06-11
@NeiroNx

Something like this:

import sys
global used,color,col,n,relations

def DFS(v):
  global used,color,col,n,relations
  used[v] = False
  color[v] = col
  col= col * (-1)
  for j in range(n):
    if relations[v][j] != 0 and used[j]: DFS(j)
def main(inpFileName,outpFileName):
  global used,color,col,n,relations
  with open(inpFileName,"r") as fp:
    inp = [int(i) for i in fp.read().split()]
  outp = open(outpFileName,"w")

  n, m = inp[0:2]
  relations = [ [0]*n for i in range(n)]
  for i in range(m):
    x,y = inp[2+i*2:2+(i+1)*2]
    relations[x][y] = 1
    relations[y][x] = 1
  used = [True]*m
  col = 1
  color = [0]*n
  DFS(x)
  ability = True
  for i in range(n):
    for j in range(n):
      if (color[i] == color[j]) and (relations[i][j] != 0): ability = False
  if ability : 
    outp.write('YES\r\n')
    for i in range(n):
      if color[i] == 1 : outp.write(str(i)+"\r\n")
  else:
    outp.write('NO\r\n')
  outp.close()
if __name__ == "__main__":
  if len(sys.argv) >= 3:
    main(sys.argv[1],sys.argv[2])
  else:
    print("Usage %s infile outfile"%sys.argv[0])

Of course, I would rewrite without golbals, but I'm too lazy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question