#cheat-check a murecursion program import string #does every character of a string belong to some character set? #Usually, whitespace,letters,, etc. def allin(s,charset): for c in s: if not (c in charset): return False return True #remove whitespace from a string def remove_whitespace(s): t='' for c in s: if not (c in string.whitespace): t+=c return t #return a list of the lines of the program; ignore comments def getLines(programName): f=open(programName,'r') u=[] for nextline in f: if nextline[0] != '#': if not allin(nextline,string.whitespace):#ignore all whitespace lines #strip whitespace from start of line and newline from end j=0 while not nextline[j] in string.ascii_letters: j+=1 u.append(nextline[j:-1]) return u #Given a string, check if it is allowed in #the sublanguage. #Allowed lines start with a keyword def, for, while, return, #or they are increment lines var +=1 #or they are zero lines var=0 #or they are assignment lines var= ..and string following must be just #letters and parentheses def checkLegalLine(s): m=len(s) #print s allowed=string.ascii_letters+'(),:_' if (m>=3) and (s[0:3]=='def'): v=s[3:] v=remove_whitespace(v) #now we can only have letters, parentheses, #commas, and : if not allin(v,allowed): return False return True elif (m>=3) and (s[0:3]=='for'): v=s[3:] follow=v.split() if not len(follow)>=3: return False if not allin(follow[0],string.ascii_letters): return False if follow[1]!='in': return False x=''.join(follow[2:]) x=remove_whitespace(x) if len(x)<9: return False if x[:5]!='range': return False if x[5]!='(': return False if x[-1]!=':': return False if x[-2]!=')': return False if not allin(x[6:-2],string.ascii_letters): return False return True elif (m>=5) and (s[:5]=='while'): v=s[5:] follow=v.split() x=''.join(follow) x=remove_whitespace(x) if x[-4:]!='!=0:': return False if not allin(x[:-4],string.ascii_letters): return False return True elif (m>=6) and (s[:6]=='return'): v=s[6:] v=remove_whitespace(v) if allin(v,string.ascii_letters): return True else: return False elif (m>=4) and ('+=' in s): s=remove_whitespace(s) j=s.index('+=') if allin(s[:j],string.ascii_letters) and (s[j:]=='+=1'): return True else: return False elif (m>=3) and ('=' in s): s=remove_whitespace(s) j=s.index('=') #print 'I am here',s if allin(s[:j],string.ascii_letters) and ((allin(s[j+1:],allowed) or s[-1]=='0')): #print 'and here' return True else: return False return False #given list of lines, check to see if each is a legal line. #Return False and report the line if an illegal one is found. def check_for_badlines(linelist): for line in linelist: if not checkLegalLine(line): print ('forbidden line:',line) return False return True def cheat_check(filename): v=getLines(filename) u=check_for_badlines(v) if not u: print ('Fix forbidden lines and try again.') else: print ('ok to run program')