How to use check_str method in refurb

Best Python code snippet using refurb_python

lexer.py

Source:lexer.py Github

copy

Full Screen

1# Compiler Construction CSF363 Assignment2# Phase 1 - Lexical Analysis3# Made by --4# Kumar Pranjal - 2018A7PS0163H5# Ashna Swaika - 2018A7PS0027H6# Abhishek Bapna - 2018A7PS0184H7# Ashish Verma - 2018A7PS0009H8# Code starts here9import sys10# Storing tokens in lists11keywords = ['int', 'float', 'real', 'void', 'boolean', 'char', 'string', 'for', 'if', 'else',12 'while', 'break', 'continue', 'switch', 'default', 'return', 'case', 'import', 'true', 'false']13operators = ['+=', '-=', '*=', '/=', '%=', '==', '<=', '>=', '!=', '<<',14 '>>', '&&', '||', '+', '-', '*', '%', '/', '=', '!', '<', '>']15delimiters = [';', ',', '(', ')', '{', '}', '\n', '\r', '\t', '\\']16string_term = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',17 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']18legal_term = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',19 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']20numeric_term = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']21sign_term = ['+', '-']22def DFA(check_str, prev_op):23 '''24 Internal function used by lexeme() function to find a token25 '''26 matches = []27 pairs = []28 # check for end of string29 if check_str[0] == "$" and len(check_str) == 1:30 return None, None, None31 # check for blank space32 if check_str[0] == " ":33 return check_str[1:], None, None34 # check for keyword35 key_match = [check_str.startswith(x) for x in keywords]36 if any(key_match):37 key = keywords[key_match.index(True)]38 matches.append(len(key))39 pairs.append(['keyword', key])40 # check for operators41 key_match = [check_str.startswith(x) for x in operators]42 if any(key_match):43 key = operators[key_match.index(True)]44 matches.append(len(key))45 if key in sign_term and prev_op == 'operator':46 pairs.append(['sign'+key, key])47 else:48 pairs.append(['operator', key])49 # check for delimiters50 key_match = [check_str.startswith(x) for x in delimiters]51 if any(key_match):52 key = delimiters[key_match.index(True)]53 matches.append(len(key))54 pairs.append(['delimiter', key])55 # check for identifier56 if check_str[0] in string_term:57 for index, letter in enumerate(check_str):58 if letter not in legal_term:59 matches.append(index)60 pairs.append(['identifier', check_str[:index]])61 break62 # check for string literal63 if check_str[0] == '"':64 for index, letter in enumerate(check_str[1:]):65 if letter == '"' and check_str[index] != '\\':66 matches.append(index+2)67 pairs.append(['string literal', check_str[:index+2]])68 break69 # check for numerical literal70 if check_str[0] in numeric_term or check_str[0] in sign_term:71 isFloat = False72 for index, letter in enumerate(check_str[1:]):73 if letter not in numeric_term:74 if letter == '.' and not isFloat:75 isFloat = True76 else:77 if prev_op == 'sign+' or prev_op == 'sign-':78 matches.append(index+2)79 orig_str = check_str[:index+1]80 if isFloat:81 pairs.append(82 ['floating literal', prev_op[-1] + orig_str])83 break84 else:85 pairs.append(86 ['integer literal', prev_op[-1] + orig_str])87 break88 else:89 matches.append(index+1)90 if isFloat:91 pairs.append(92 ['floating literal', check_str[:index+1]])93 break94 else:95 pairs.append(96 ['integer literal', check_str[:index+1]])97 break98 # check for comment99 if check_str[0] == '#':100 matches.append(len(check_str))101 pairs.append([None, None])102 # now find the token for longest matching lexeme103 # final is final index in matches which should be used for token lexeme pairs104 if(len(matches)) == 0:105 if len(check_str) > 1:106 return check_str[1:], 'invalid', check_str[0]107 else:108 return None, 'invalid', check_str[0]109 final = matches.index(max(matches))110 # SPECIAL CASE - sign operators111 if prev_op != 'operator' and check_str[0] in sign_term:112 final = 0113 end_pos = int(matches[final])114 if end_pos < len(check_str):115 return check_str[end_pos:], pairs[final][0], pairs[final][1]116 elif end_pos == len(check_str):117 return None, pairs[final][0], pairs[final][1]118 else:119 print("some error in parsing")120def lexeme(string):121 '''122 Accepts a string and returns a generator object containing tokens123 which can be accessed using a for loop or by using next() function124 '''125 lines = string.splitlines()126 for line_number, line in enumerate(lines):127 line = line.strip() + '$'128 prev_op = None129 if len(line) > 0:130 while(line != None):131 line, key, lexeme = DFA(line, prev_op)132 if key is not None:133 prev_op = key134 if key != None and key != 'invalid' and key != 'sign+' and key != 'sign-':135 yield {'line': line_number+1, 'token': key, 'lexeme': lexeme}136 elif key == 'invalid':137 yield {'line': line_number+1, 'token': 'invalid', 'lexeme': lexeme}138# Driver Code139def lexer(fname=None):140 if fname is None:141 filename = sys.argv[1]142 else:143 filename = fname144 outfile = open(f'{filename.split(".")[0]}_output.txt', 'w', encoding='utf8')145 with open(filename, 'r', encoding='utf8') as f:146 filestr = f.read()147 for lex in lexeme(filestr):148 if lex['token'] == 'invalid':149 print(150 f"!!! Error in line {lex['line']} while parsing {lex['lexeme']}")151 print(152 f"!!! Error in line {lex['line']} while parsing {lex['lexeme']}", file=outfile)153 else:154 print(155 f"Line: {lex['line']}, Token: {lex['token']}, Lexeme: {lex['lexeme']}")156 print(157 f"Line: {lex['line']}, Token: {lex['token']}, Lexeme: {lex['lexeme']}", file=outfile)158if __name__ == '__main__':...

Full Screen

Full Screen

Palindrome.py

Source:Palindrome.py Github

copy

Full Screen

1# Given a string, find if it is a palindrome2def is_palindrome(check_str: str) -> bool:3 check_str = check_str.lower()4 return check_str == check_str[::-1]5def is_palindrome_1(check_str: str) -> bool:6 check_str = check_str.lower()7 for i in range(len(check_str) // 2):8 if check_str[i] != check_str[-1 * (i + 1)]:9 return False10 return True11def is_palindrome_2(check_str: str) -> bool:12 check_str = check_str.lower()13 return next((False for i in range(len(check_str) // 2) if check_str[i] != check_str[-1 * (i + 1)]), True)14check_str = str(input('Enter the word\n'))15print(is_palindrome(check_str))16print(is_palindrome_1(check_str))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run refurb automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful