Skip to content

Commit

Permalink
Fixed a lot of problems from all the progs we need to parse
Browse files Browse the repository at this point in the history
  • Loading branch information
L0P0P committed Jun 27, 2024
1 parent fb89b8c commit 3c4229f
Show file tree
Hide file tree
Showing 23 changed files with 336 additions and 250 deletions.
24 changes: 13 additions & 11 deletions progs/a284.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
def is_Isomorphic(str1,str2):
dict_str1 = {}
dict_str2 = {}
for i, value in enumerate(str1):
dict_str1[value] = dict_str1.get(value,[]) + [i]
for j, value in enumerate(str2):
dict_str2[value] = dict_str2.get(value,[]) + [j]
if sorted(dict_str1.values()) == sorted(dict_str2.values()):
return True
else:
return False
# FIXME: multiple variable assignment in for loop
#
# def is_Isomorphic(str1,str2):
# dict_str1 = {}
# dict_str2 = {}
# for i, value in enumerate(str1):
# dict_str1[value] = dict_str1.get(value,[]) + [i]
# for j, value in enumerate(str2):
# dict_str2[value] = dict_str2.get(value,[]) + [j]
# if sorted(dict_str1.values()) == sorted(dict_str2.values()):
# return True
# else:
# return False
51 changes: 27 additions & 24 deletions progs/a339.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
def heap_sort(arr):
heapify(arr)
end = len(arr) - 1
while end > 0:
arr[end], arr[0] = arr[0], arr[end]
shift_down(arr, 0, end - 1)
end -= 1
return arr
# FIXME: chiamata a funzione definita dopo
#
# def heap_sort(arr):
# heapify(arr)
# end = len(arr) - 1
# while end > 0:
# arr[end], arr[0] = arr[0], arr[end]
# shift_down(arr, 0, end - 1)
# end -= 1
# return arr

def heapify(arr):
start = len(arr) // 2
while start >= 0:
shift_down(arr, start, len(arr) - 1)
start -= 1
def shift_down(arr, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child += 1
if child <= end and arr[root] < arr[child]:
arr[root], arr[child] = arr[child], arr[root]
root = child
else:
return
# def heapify(arr):
# start = len(arr) // 2
# while start >= 0:
# shift_down(arr, start, len(arr) - 1)
# start -= 1

# def shift_down(arr, start, end):
# root = start
# while root * 2 + 1 <= end:
# child = root * 2 + 1
# if child + 1 <= end and arr[child] < arr[child + 1]:
# child += 1
# if child <= end and arr[root] < arr[child]:
# arr[root], arr[child] = arr[child], arr[root]
# root = child
# else:
# return
46 changes: 24 additions & 22 deletions progs/a394.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
def func(nums, k):
import collections
d = collections.defaultdict(int)
for row in nums:
for i in row:
d[i] += 1
temp = []
import heapq
for key, v in d.items():
if len(temp) < k:
temp.append((v, key))
if len(temp) == k:
heapq.heapify(temp)
else:
if v > temp[0][0]:
heapq.heappop(temp)
heapq.heappush(temp, (v, key))
result = []
while temp:
v, key = heapq.heappop(temp)
result.append(key)
return result
# FIXME: multiple variable assignment in for loop
#
# def func(nums, k):
# import collections
# d = collections.defaultdict(int)
# for row in nums:
# for i in row:
# d[i] += 1
# temp = []
# import heapq
# for key, v in d.items():
# if len(temp) < k:
# temp.append((v, key))
# if len(temp) == k:
# heapq.heapify(temp)
# else:
# if v > temp[0][0]:
# heapq.heappop(temp)
# heapq.heappush(temp, (v, key))
# result = []
# while temp:
# v, key = heapq.heappop(temp)
# result.append(key)
# return result
2 changes: 1 addition & 1 deletion progs/a403.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from itertools import chain
def freq_element(nums):
result = Counter(chain.from_iterable(nums))
return result
return result
14 changes: 8 additions & 6 deletions progs/a52.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from collections import defaultdict
def grouping_dictionary(l):
d = defaultdict(list)
for k, v in l:
d[k].append(v)
return d
# FIXME: multiple variable assignment in for loop
#
# from collections import defaultdict
# def grouping_dictionary(l):
# d = defaultdict(list)
# for k, v in l:
# d[k].append(v)
# return d
12 changes: 7 additions & 5 deletions progs/a641.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
def count_first_elements(test_tup):
for count, ele in enumerate(test_tup):
if isinstance(ele, tuple):
break
return (count)
# FIXME: multiple variable assignment in for loop
#
# def count_first_elements(test_tup):
# for count, ele in enumerate(test_tup):
# if isinstance(ele, tuple):
# break
# return (count)
32 changes: 17 additions & 15 deletions progs/a745.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
def find_rotation_count(A):
(left, right) = (0, len(A) - 1)
while left <= right:
if A[left] <= A[right]:
return left
mid = (left + right) // 2
next = (mid + 1) % len(A)
prev = (mid - 1 + len(A)) % len(A)
if A[mid] <= A[next] and A[mid] <= A[prev]:
return mid
elif A[mid] <= A[right]:
right = mid - 1
elif A[mid] >= A[left]:
left = mid + 1
return -1
# FIXME: unpacking assignment
#
# def find_rotation_count(A):
# (left, right) = (0, len(A) - 1)
# while left <= right:
# if A[left] <= A[right]:
# return left
# mid = (left + right) // 2
# next = (mid + 1) % len(A)
# prev = (mid - 1 + len(A)) % len(A)
# if A[mid] <= A[next] and A[mid] <= A[prev]:
# return mid
# elif A[mid] <= A[right]:
# right = mid - 1
# elif A[mid] >= A[left]:
# left = mid + 1
# return -1
4 changes: 2 additions & 2 deletions src/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static void main(String[] args) {
try {
// String fileStr = file.getPath();
// FIXME: use the fileStr above
String fileStr = "./test/1a.py";
String fileStr = "./progs/a600.py";
System.out.println(fileStr);
System.out.println(readFile(fileStr));
CharStream cs = CharStreams.fromFileName(fileStr);
Expand All @@ -41,7 +41,7 @@ public static void main(String[] args) {
JPanel panel = new JPanel();
TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()),
tree);
viewer.setScale(1.5); // Zoom factor
viewer.setScale(1); // Zoom factor
panel.add(viewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Expand Down
75 changes: 18 additions & 57 deletions src/ParseAll.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Objects;
import javax.swing.*;
import org.antlr.v4.gui.TreeViewer;
import org.antlr.v4.runtime.*;

import parser.*;
import ast.Python3VisitorImpl;
import ast.nodes.*;
import parser.Python3Lexer;
import parser.Python3Parser;
import semanticanalysis.SemanticError;
import semanticanalysis.SymbolTable;

public class ParseAll {
@SuppressWarnings("unused")
Expand All @@ -22,12 +22,8 @@ public static void main(String[] args) {
if (!file.isFile() || !getExtension(file.getName()).equals("py")) {
System.err.println("Wont parse: " + fileStr);
continue;
} else {
System.out.println(fileStr);
}

// System.out.println(readFile(fileStr));

CharStream cs = CharStreams.fromFileName(fileStr);
Python3Lexer lexer = new Python3Lexer(cs);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
Expand All @@ -37,11 +33,17 @@ public static void main(String[] args) {
String treeStr = tree.toStringTree();
// System.out.println(treeStr);

TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree);
viewer.setScale(1.5);
saveTree(viewer, "./trees/" + removeExtension(file.getName()) + ".png");
if (parser.getNumberOfSyntaxErrors() != 0) {
System.err.println("Parse errors: " + fileStr);
Python3VisitorImpl visitor = new Python3VisitorImpl();
SymbolTable ST = new SymbolTable();
Node ast = visitor.visit(tree);
ArrayList<SemanticError> errors = ast.checkSemantics(ST, 0);
if (errors.size() > 0) {
System.out.println();
System.out.println(fileStr);
System.out.println("You had " + errors.size() + " errors:");
for (SemanticError e : errors) {
System.out.println("\t" + e);
}
}

} catch (Exception e) {
Expand All @@ -51,47 +53,6 @@ public static void main(String[] args) {
}
}

@SuppressWarnings("unused")
private static String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}

@SuppressWarnings("unused")
private static void showTree(TreeViewer viewer) {
JFrame frame = new JFrame("Parse Tree");
JPanel panel = new JPanel();
panel.add(viewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}

private static void saveTree(TreeViewer viewer, String name) {
try {
viewer.save(name);
} catch (Exception e) {
System.err.println(name);
e.printStackTrace();
}
}

public static String removeExtension(String fileName) {
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
return fileName;
} else {
return fileName.substring(0, extensionIndex);
}
}

public static String getExtension(String fileName) {
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
Expand Down
30 changes: 27 additions & 3 deletions src/ast/Python3VisitorImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -264,10 +264,28 @@ public Node visitAugassign(AugassignContext ctx) {
x = new AugassignNode(ctx.SUB_ASSIGN());
} else if (ctx.MULT_ASSIGN() != null) {
x = new AugassignNode(ctx.MULT_ASSIGN());
} else if (ctx.AT_ASSIGN() != null) {
x = new AugassignNode(ctx.AT_ASSIGN());
} else if (ctx.DIV_ASSIGN() != null) {
x = new AugassignNode(ctx.DIV_ASSIGN());
} else if (ctx.MOD_ASSIGN() != null) {
x = new AugassignNode(ctx.MOD_ASSIGN());
} else if (ctx.AND_ASSIGN() != null) {
x = new AugassignNode(ctx.AND_ASSIGN());
} else if (ctx.OR_ASSIGN() != null) {
x = new AugassignNode(ctx.OR_ASSIGN());
} else if (ctx.XOR_ASSIGN() != null) {
x = new AugassignNode(ctx.XOR_ASSIGN());
} else if (ctx.LEFT_SHIFT_ASSIGN() != null) {
x = new AugassignNode(ctx.LEFT_SHIFT_ASSIGN());
} else if (ctx.RIGHT_SHIFT_ASSIGN() != null) {
x = new AugassignNode(ctx.RIGHT_SHIFT_ASSIGN());
} else if (ctx.POWER_ASSIGN() != null) {
x = new AugassignNode(ctx.POWER_ASSIGN());
} else if (ctx.IDIV_ASSIGN() != null) {
x = new AugassignNode(ctx.IDIV_ASSIGN());
}

return x;
}

Expand Down Expand Up @@ -495,7 +513,7 @@ public Node visitTrailer(TrailerContext ctx) {
methodCall = ctx.NAME();
}

return new TrailerNode(arglist, exprs, methodCall);
return new TrailerNode(arglist, exprs, methodCall, ctx.OPEN_PAREN() != null);
}

/**
Expand All @@ -507,7 +525,13 @@ public Node visitTrailer(TrailerContext ctx) {
* ```
*/
public Node visitExprlist(ExprlistContext ctx) {
Node exp = visit(ctx.expr(0));
Node exp;

if (ctx.expr(0).expr(0) != null){
exp = visit(ctx.expr(0).expr(0));
} else {
exp = visit(ctx.expr(0));
}

return exp;
}
Expand Down
Loading

0 comments on commit 3c4229f

Please sign in to comment.