Convert Python to Java
def read_fsm(filename):
fh = open('fsm.txt','r')
contents = fh.readlines()
sigma = list(contents[0].rstrip().split(' '))
table = {}
n = int(contents[1])
for i in range(n):
table[i] = {}
final = list(map(int,contents[2].rstrip().split(' ')))
for line in contents[3:]:
fro,ip,to = line.split(' ')
fro = int(fro)
to = int(to)
table[fro][ip] = to
print(table)
fh.close()
return table,final
def runString(table,final,string):
current = 0
for i in string:
current = table[current][i]
if current in final:
print(string,'--> ACCEPT')
else:
print(string,'--> REJECT')
def readInput(table,final):
fh = open('Strings.txt','r')
for line in fh.readlines():
string = line.rstrip()
runString(table,final,string)
fh.close()
def main():
table,final = read_fsm('fsm.txt')
readInput(table,final)
main()
Please find the answer below, I have mentioned all the details in the comments.
In Java, I have made all the required table and list as the class parameters so that they can be used across the methods, because in Java we can not return multiple values at the same time such as return table, final in python.
FSM.java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //class FSM where the required methods are implemented public class FSM { //table to store the transition table of the FSM int table[][]; //List to Store the fianl states of the FSM ArrayList<Integer> finall; //List to store the variables of the FSM List<String> sigma; //read_fsm method public void read_fsm(String filename) throws IOException{ //BufferedReader is used to read the content of the file BufferedReader br = new BufferedReader(new FileReader(filename)); //For sigma of the FSM // line to store the content of the line read String line = br.readLine(); //split the lien by spaces into array String [] arr = line.split(" "); //create list of sigma sigma = Arrays.asList(arr); //For number of states of the FSM line = br.readLine(); //convert it to integer int n = Integer.parseInt(line); //For final states of the FSM line = br.readLine(); //read the values in the temporary string array String[] temp = line.split(" "); //arraylist initialization finall = new ArrayList<>(); //save the states as a integer value to the list for(int i=0;i<temp.length;i++){ finall.add(Integer.parseInt(temp[i])); } //For transition table of the FSM table = new int[n][arr.length]; //read line line = br.readLine(); //while there are lines while(line!=null){ //get the values and convert it to from , to and symbol accordingly String [] values = line.split(" "); int fro = Integer.parseInt(values[0]); int to = Integer.parseInt(values[2]); int ip = sigma.indexOf(values[1]); //set table entry to the to state value table[fro][ip] = to; //get the next line line = br.readLine(); } //below is the code to print the transition table System.out.print("{"); for(int i=0;i<table.length;i++){ System.out.print(i +": {"); for (int j = 0; j < table[0].length ; j++) { System.out.print("\'" + sigma.get(j) + "\': " + table[i][j]); if(j<table[0].length-1){ System.out.print(", "); } } System.out.print("}"); if(i < table.length-1){ System.out.print(", "); } } System.out.println("}"); //close the file br.close(); } public void runString(String str){ int i; //set the current state as the 0 int current = 0; //read each symbol of the string for(i=0;i<str.length();i++){ //get the index of the symbol in the sigma list to access it's index in table int index = sigma.indexOf(str.charAt(i)+""); //update the current state based on the transition table current = table[current][index]; } //check if the current state is in the list of finall state. if(finall.contains(current)){ System.out.println(str + " --> ACCEPT" ); } else{ System.out.println(str + " --> REJECT" ); } } public void readInput() throws IOException{ //BufferedReader to read the file BufferedReader br = new BufferedReader(new FileReader("Strings.txt")); //get the line from strings file String line = br.readLine(); //read till there are lines while(line!=null){ //call the runString() method for each line runString(line); //get the next line line = br.readLine(); } //close the file br.close(); } public static void main(String[] args) throws IOException { //create object of the class FSM to use it's methods FSM obj = new FSM(); //call the method read_fsm by passing the file name obj.read_fsm("fsm.txt"); //call the method readInput to read the file Strings.txt obj.readInput(); } }
Output:
I have used files the same as provided in the question.
Convert Python to Java def read_fsm(filename): fh = open('fsm.txt','r') contents = fh.readlines() sigma...
in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...
Please use Python def findSubstrings(s): # Write your code here Consider a string, s = "abc". An alphabetically-ordered sequence of substrings of s would be {"a", "ab", "abc", "b", "bc", "c"}. If the sequence is reduced to only those substrings that start with a vowel and end with a consonant, the result is {"ab", "abc"}. The alphabetically first element in this reduced list is "ab", and the alphabetically last element is "abc". As a reminder: • Vowels: a, e, i,...
python 3 8.12 LAB: Python cross reference In addition to editors and compilers, a software developer may use tools to analyze the software they are writing to examine the names being used for variables and functions, and list the line numbers where the variables and functions names appear. For example, consider the following program savings.py used to compute the month to month interest gained from a certificate of deposit: 1: Input the CD APR, no years and initial deposit 2:...
Use python Start: def main(): gradeList = [] fileName = getFile() gradeList = getData(fileName) mean = calculateMean(gradeList) sd = calculateSD(mean, gradeList) displayHeadings(gradeList, mean, sd) curveGrades(mean, sd, gradeList) if __name__ == "__main__": main() For this program, you will create a grade curving program by reading grades from a file, calculating the mean and standard deviation. The mean is the average value of the grades and the standard deviation measures the spread or dispersal of the numbers from the...
In either Java or Python 3, write a program that simulates a deterministic FSM. It will read from two input files. The first is a file describing an FSM The first line contains the alphabet as a series of characters separated by a single space - The second line contains the number of states as an integer k 2 1; states will be numbered 0,1,..., k -1. The start state is always state O The third line contains a series...
In either Java or Python 3, write a program that simulates a deterministic FSM. It will read from two input files. The first is a file describing an FSM The first line contains the alphabet as a series of characters separated by a single space - The second line contains the number of states as an integer k 2 1; states will be numbered 0,1,..., k -1. The start state is always state O The third line contains a series...
I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...
Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...
Python help it is a grade 12 course def find astrological sign(month, date): (int, int)-str Given two int values represent ing a month and a date, return a 3-character string that gives us what star sign a person born in that month and on that date belongs to, Use the SIGNS string (already defined for you at the top of this file) to figure this out. NOTE FROM BOB: A lot of string slicing to do here. It looks like...
PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything a course uses in a grading scheme, # like a test or an assignment. It has a score, which is assessed by # an instructor, and a maximum value, set by the instructor, and a weight, # which defines how much the item counts towards a final grade. def __init__(self, weight, scored=None, out_of=None): """ Purpose: Initialize the GradeItem object. Preconditions: :param weight: the weight...