Question

rewrite this c code in python #include <iostream> using std::cout; using std::cin; using std::endl; int charClass;...

rewrite this c code in python 

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int  charClass;
char lexeme[100];
char str[200];
char nextChar;
const int LETTER  = 0;
const int DIGIT   = 1;
const int UNKNOWN = -1;
const int OPAREN  = 2;
const int CPAREN  = 3;
const int PLUS  = 4;
const int MINUS  = 5;
const int MUL  = 6;
const int DIV  = 7;
const int ID_CODE  = 100;
const int PLUS_CODE = 101;
const int MINUS_CODE = 102;
const int AST_CODE = 103;
const int SLASH_CODE = 104;
const int LEFT_PAREN_CODE = 105;
const int RIGHT_PAREN_CODE = 106;
const int NUM_CODE = 107;
int  lexLen;
int  nextToken;
int  strcnt;
int  error = 0;

void addChar();
void getChar();
void getNonBlank();
void lex();
void expr();
void term();
void factor();
void ovalue();

int main() 
{
  int test;
  cout << "Enter an expression: ";
  cin >> str;
  strcnt=0;
  nextChar = str[strcnt++];
  lex();
  cout << "Call lex  /* returns " << nextToken << " */\n";
  /***************************************************************************** 
     THIS SEGMENT OF CODE HAS BEEN COMMENTED OUT 
     ITS PURPOSE IS TO CONTINUALLY CALL LEX UNTIL THE INPUT HAS BEEN EXHAUSTED

  while (nextChar != '\0')
  {
    test = lex();
    cout << test << endl;
  }

    END COMMENTED OUT SEGMENT OF CODE 
  *****************************************************************************/
  expr();  /* begin recursive decent parsing */
  if (nextChar == '\0')
  {
    if (error)
      cout << "PARSE FAILED\n\n";
    else
      cout << "PARSE SUCCESSFUL\n\n";
  }
  else
  {
    cout << "PARSE FAILED\n\n";
  }
  return 0;
}

/* addChar - a function to add nextChar to lexeme */
void addChar()
{
  if (lexLen <= 99)
  {
    lexeme[lexLen++] = nextChar;
  }
  else
  {
    cout << "Error - lexeme is too long\n";
  }
}

/* getChar - a function to get the next character of input and determine its character class */
void getChar()
{
  /* do whatever is required to get the next character from input and put it in nextChar */
  if (isalpha(nextChar))
  {
    charClass = LETTER;
  }
  else if (isdigit(nextChar))
  {
    charClass = DIGIT;
  }
  else if (nextChar == '(')
  {
    charClass = OPAREN;
  }
  else if (nextChar == ')')
  {
    charClass = CPAREN;
  }
  else if (nextChar == '+')
  {
    charClass = PLUS;
  }
  else if (nextChar == '-')
  {
    charClass = MINUS;
  }
  else if (nextChar == '*')
  {
    charClass = MUL;
  }
  else if (nextChar == '/')
  {
    charClass = DIV;
  }
  else 
  {
    charClass = UNKNOWN;
  }
  nextChar = str[strcnt++];
}

/* getNonBlank - a function that calles getChar until it returns a non-whitespace character */
void getNonBlank()
{
  while (isspace(nextChar))
  {
    getChar();
  }
}

/* lex - a simple lexical analyzer */
void lex()
{
  int retval;
  lexLen = 0;
  static int first = 1;
  /* If it is the first call to lex, initialize by calling getChar */
  if (first) 
  {
    getChar();
    first = 0;
  }
  getNonBlank();

  /* process identifiers */
  if (charClass == LETTER)
  {
    addChar();
    getChar();
    while ((charClass == LETTER) || (charClass == DIGIT))
    {
      addChar();
      getChar();
    }
    retval = ID_CODE;
  }
  else if (charClass == DIGIT)
  {
    addChar();
    getChar();
    while (charClass == DIGIT)
    {
      addChar();
      getChar();
    }
    retval = NUM_CODE;
  }
  else if (charClass == PLUS)
  {
    getChar();
    retval = PLUS_CODE;
  }
  else if (charClass == MINUS)
  {
    getChar();
    retval = MINUS_CODE;
  }
  else if (charClass == MUL)
  {
    getChar();
    retval = AST_CODE;
  }
  else if (charClass == DIV)
  {
    getChar();
    retval = SLASH_CODE;
  }
  else if (charClass == OPAREN)
  {
    getChar();
    retval = LEFT_PAREN_CODE;
  }
  else if (charClass == CPAREN)
  {
    getChar();
    retval = RIGHT_PAREN_CODE;
  }
  else 
  {
    retval = UNKNOWN;
  }
  nextToken = retval;
}

void expr()
{
  cout << "Enter <expr>\n";

  term();
  while ((nextToken == PLUS_CODE) ||
         (nextToken == MINUS_CODE))
  {
    lex();
    cout << "Call lex  /* returns " << nextToken << " */\n";
    term();
  }

  cout << "Exit  <expr>\n";
}

void term()
{
  cout << "Enter <term>\n";

  factor();
  while ((nextToken == AST_CODE) ||
         (nextToken == SLASH_CODE))
  {
    lex();
    cout << "Call lex  /* returns " << nextToken << " */\n";
    factor();
  }

  cout << "Exit  <term>\n";
}

void factor()
{
  cout << "Enter <factor>\n";

  if (nextToken == ID_CODE) 
  {
    lex();
    cout << "Call lex  /* returns " << nextToken << " */\n";
  }
  else if (nextToken == LEFT_PAREN_CODE) 
  {
    lex();
    cout << "Call lex  /* returns " << nextToken << " */\n";
    expr();
    if (nextToken == RIGHT_PAREN_CODE) 
    {
      lex();
      cout << "Call lex  /* returns " << nextToken << " */\n";
    }
    else
    {
      error = 1;
    }
  }
  else
  {
    error = 1;
  }

  cout << "Exit  <factor>\n";
}
void ovalue()
{
  if (nextToken == ID_CODE)
    cout << lexeme;
  else if (nextToken == NUM_CODE)
    cout << "Number";
  else if (nextToken == PLUS_CODE)
    cout << "+";
  else if (nextToken == MINUS_CODE)
    cout << "-";
  else if (nextToken == AST_CODE)
    cout << "*";
  else if (nextToken == SLASH_CODE)
    cout << "/";
  else if (nextToken == LEFT_PAREN_CODE)
    cout << "(";
  else if (nextToken == RIGHT_PAREN_CODE)
    cout << ")";
  else if (nextToken == UNKNOWN)
    cout << "????";
}


python 3.8
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Sol:

The given C code, converted to python is given below.

charClass = 0
lexeme = ""
str1 = "" #str is a method in python
nextChar = ""

#Variables cannot be declared constants in python, to emulate that
#we define them as values returned by methods in a class
#thus they can't be modified

class Constant:
def letter(self):
return 0
def digit(self):
return 1
def unknown():
return -1
def oparen():
return 2
def cparen();
return 3
def plus():
return 4
def minus():
return 5
def mul():
return 6
def div():
return 7
def id_code():
return 100
def plus_code():
return 101
def minus_code():
return 102
def ast_code():
return 103
def slash_code():
return 104
def left_paren_code():
return 105
def right_paren_code():
return 106
def num_code():
return 107


lexLen = 0
nextToken = 0
strcnt = 0
error = False

const = Constant()

def addChar():
#declare the scope of global variables
global lexLen
global lexeme
  
if lexLen <= 99:
lexeme.append(nextChar)
lexLen = lexLen + 1
else:
print("Error - lexeme is too long\n")

def getChar():
#declare the scope of global variables
global nextChar
global const
global strcnt
  
if nextChar.isalpha():
charClass = const.letter()
elif nextChar.isdigit():
charClass = const.digit()
elif nextChar == "(":
charClass = const.oparen()
elif nextChar == ")":
charClass = const.cparen()
elif nextChar == "+":
charClass = const.plus()
elif nextChar == "-":
charClass = const.minus()
elif nextChar == "*":
charClass = const.mul()
elif nextChar == "/":
charClass = const.div()
else:
charClass = const.unknown()
nextChar = str1[strcnt]
strcnt = strcnt + 1

def getNonBlank():
#declare the scope of global variables
global nextChar
  
while nextChar.isspace():
getChar()

def lex():
#declare the scope of global variables
global charClass
global nextToken
global const
global lexLen
  
retval = 0
lexLen = 0
first = True
if first == True:
getChar()
first = False
getNonBlank()
if charClass == const.letter():
addChar()
getChar()
while charClass == const.letter() or charClass = const.digit():
addChar()
getChar()
retval = const.id_code()
elif charClass == const.digit():
addChar()
getChar()
while charClass == const.digit():
addChar()
getChar()
retval = const.num_code()
elif charClass == const.plus():
getChar()
retval = const.plus_code()
elif charClass == const.minus():
getChar()
retval = const.minus_code()
elif charClass == const.mul():
getChar()
retval = const.ast_code()
elif charClass = const.div():
getChar()
retval = const.slash_code()
elif charClass = const.oparen():
getChar()
retval = const.left_paren_code()
elif charClass = const.cparen():
getChar()
retval = const.right_paren_code()
else:
retval = const.unknown()
nextToken = retval

def expr():
#declare the scope of global variables
global nextToken
global const
  
print("Enter <expr>\n")
term()
if nextToken == const.plus_code() or nextToken == const.minus_code():
lex()
print("call lex /* returns {} */\n".format(nextToken))
term()
print("Exit <expr>\n")
  
def term():
#declare the scope of global variables
global nextToken
global const
  
print("Enter <term>\n")
factor()
while nextToken == const.ast_code() or nextToken == const.slash_code():
lex()
print("call lex /* returns {} */\n".format(nextToken))
factor()
print("Exit <term>\n")

def factor():
#declare the scope of global variables
global nextToken
global const
global error
  
print("Enter <factor>/n")
if nextToken == const.id_code():
lex():
print("call lex /* returns {} */\n".format(nextToken))
elif nextToken == const.left_paren_code():
lex():
print("call lex /* returns {} */\n".format(nextToken))
expr()
if nextToken == const.right_paren_code():
lex():
print("call lex /* returns {} */\n".format(nextToken))
else:
error = True
else:
error = True
print("Exit <factor>\n")

def ovalue():
#declare the scope of global variables
global nextToken
global const
global lexeme
  
if nextToken == const.id_code():
print(lexeme),
elif nextToken == const.num_code():
print("Number"),
elif nextToken == const.plus_code():
print("+"),
elif nextToken == const.minus_code():
print("-"),
elif nextToken == const.ast_code():
print("*"),
elif nextToken == const.slash_code():
print("/"),
elif nextToken == const.left_paren_code():
print("("),
elif nextToken == const.right_paren_code():
print(")"),
else:
print("????")

if __name__ == "__main__": #main method
global str1
global strcnt
global nextChar
global error
test = 0
str1 = str(raw_input("Enter an expression: "))
strcnt = 0
nextChar = str1[strcnt]
strcnt = strcnt + 1
lex()
'''
/*******************************************************************
THIS SEGMENT OF CODE HAS BEEN COMMENTED OUT ITS PURPOSE IS TO
CONTINUALLY CALL LEX UNTIL THE INPUT HAS BEEN EXHAUSTED
while strcnt != len(str1):
test = lex()
print(test)
END COMMENTED OUT SEGMENT OF CODE
********************************************************************/
'''
if strcnt == len(str1):
if error == True:
print("PARSE FAILED\n\n")
else:
print("PARSE SUCCESSFUL\n\n")
else:
print("PARSE FAILED\n\n")

Indentation Screenshots:


  

Add a comment
Know the answer?
Add Answer to:
rewrite this c code in python #include <iostream> using std::cout; using std::cin; using std::endl; int charClass;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • i am having issues correcting an error in my program here is my code: #include <iostream>...

    i am having issues correcting an error in my program here is my code: #include <iostream> // define libraries #include <fstream> using namespace std; // Variable definitions: ifstream infp; // file handler enum Tokens {INT_LIT, IDENT, ASSIGN_OP, ADD_OP, SUB_OP, MUL_OP, DIV_OP, LEFT_PAREN, RIGHT_PAREN, LETTER, DIGIT, UNKNOWN,ENDFILE}; Tokens nextToken; // nextToken read from the file. int charClass; // char class char lexeme [100]; // number of characters per line char nextChar; // next char read from the file int lexLen; //...

  • C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl;...

    C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl; #include <cmath> #include <cstring> class nonNumber : public exception { public: /* write definition for the constructor */ -- Message is “An invalid input was entered” }; int castInput( char *s ) { char *temp = s; int result = 0, negative = 1; // check for minus sign if ( temp[ 0 ] == '-' ) negative = -1; for ( int i...

  • #include <iostream> #include <string> using std::string; using std::cout; using std::endl; void testAnswer(string testname, int answer, int...

    #include <iostream> #include <string> using std::string; using std::cout; using std::endl; void testAnswer(string testname, int answer, int expected) { if (answer == expected) cout << "PASSED: " << testname << " expected and returned " << answer << "\n"; else cout << "FAILED: " << testname << " returned " << answer << " but expected " << expected << "\n"; } // Implement printArray here void printArray(int array[],int b) { for(int i = 0; i<b;i++) { std::cout<< array[i] << "...

  • #include <iostream> #include <stack> #include <queue> using namespace std; void printFromStack(string expr){ stack<char> myStack; for(int i=0;...

    #include <iostream> #include <stack> #include <queue> using namespace std; void printFromStack(string expr){ stack<char> myStack; for(int i=0; i<expr.length(); i++){ //Insert code here to push each character onto the stack } cout << "My stack is popped in this order" << endl; while(!myStack.empty()){ //Insert code here to cout the top of the stack one by one //Pop each one after it’s printed out } cout << endl; } void printFromQueue(string expr){ queue<char> myQueue; //Insert code here to push each character onto the...

  • #include "stdafx.h" #include <iostream> using namespace std; class dateType {    private:        int dmonth;...

    #include "stdafx.h" #include <iostream> using namespace std; class dateType {    private:        int dmonth;        int dday;        int dyear;       public:       void setdate (int month, int day, int year);    int getday()const;    int getmonth()const;    int getyear()const;    int printdate()const;    bool isleapyear(int year);    dateType (int month=0, int day=0, int year=0); }; void dateType::setdate(int month, int day, int year) {    int numofdays;    if (year<=2008)    {    dyear=year;...

  • #include <iostream> #include <fstream> using namespace std; //constants const int CAP = 100; //function prototypes bool...

    #include <iostream> #include <fstream> using namespace std; //constants const int CAP = 100; //function prototypes bool openFile(ifstream &); void readData(ifstream &, int [], int &); void printData(const int [], int); void sum(const int[], int); void removeItem(int[], int &, int); int main() { ifstream inFile; int list[CAP], size = 0; if (!openFile(inFile)) { cout << "Program terminating!! File not found!" << endl; return -1; } //read the data from the file readData(inFile, list, size); inFile.close(); cout << "Data in file:" <<...

  • Find and fix errors #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int MIN...

    Find and fix errors #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int MIN = 1; const int MAX = 10; int getRandom(int low, int high); int main() {    int random_num = 0; int player_num; int tries; int seed = static_cast<int>(time(0)); bool guessed = false;    srand(seed); // call the getRandom function below       tries = 4; while ( tries > 0 && !guessed ) { cout << "Enter a number within the range 1 to...

  • #include <iostream> #include <cstddef> using std::cout; using std::endl; class Node { int value; public: Node* left;...

    #include <iostream> #include <cstddef> using std::cout; using std::endl; class Node { int value; public: Node* left; // left child Node* right; // right child Node* p; // parent Node(int data) { value = data; left = NULL; right = NULL; p = NULL; } ~Node() { } int d() { return value; } void print() { std::cout << value << std::endl; } }; int main(int argc, const char * argv[]) { } function insert(Node *insert_node, Node *tree_root){ //Your code here...

  • CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare...

    CONVERT THE FOLLOWING C/C++ PROGRAM INTO JAVA: //LinkedString.h #pragma once #include<iostream> #include<string> using namespace std; //declare a node datastruct struct Node {    char c;    Node *next; }; class LinkedString {    Node *head; public:    LinkedString();    LinkedString(char[]);    LinkedString(string);    char charAt(int) const;    string concat(const LinkedString &obj) const;    bool isEmpty() const;    int length() const;    LinkedString substring(int, int) const;    //added helper function to add to linekd list private:    void add(char c); };...

  • #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str);...

    #include <iostream> #include <cstring> #include <string> #include <istream> using namespace std; //Function prototypes int numVowels(char *str); int numConsonants(char *str); int main() {    char string[100];    char inputChoice, choice[2];    int vowelTotal, consonantTotal;    //Input a string    cout << "Enter a string: " << endl;    cin.getline(string, 100);       do    {        //Displays the Menu        cout << "   (A) Count the number of vowels in the string"<<endl;        cout << "   (B) Count...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT