Recognize loop for in other python scripts - python-3.x

First: sorry for my English!
I'm trying to write a python script that can recognize any loop for in other python scripts.
import re
with open('boite_a_fonctions_v3_1.py', 'r') as f:
text=f.read()
a = text.split(" ")
#print (a)
loop = re.compile(r'for"(.*):\t(.*)"')
def find_loop(a):
c = []
for line in a:
c += loop.findall(line)
print (c)
#find_loop(a)
I have nothing as a result (which already makes me happy, no mistakes !!). Anyone have any suggestions?
A part of the code 'boite_a_fonctions_v3_1.py':
fidr.seek(0)
reg = compile(fmt.get_motif())
id = 0
for line in fidr :
for seg in reg.findall(line) :
if id == tokenId :
mot, etq = seg
return mot, etq
else :
id += 1
return None
def get_tokens(fid, fmt, tokenIds):
if isinstance(tokenIds, int):
try :
return get_token(fid,fmt, tokenIds)
except :
return None
else:
n = None
for id in tokenIds:
try:
n = len(get_token(fid,fmt, id))
break
except:
pass
if not n :
return None
ret = list()
for i in range(n) :
tmp = list()
for id in tokenIds :
try:
tmp.append(get_token(fid,fmt,id)[i])
except:
pass
ret.append(tmp)
return ret

Though i am not experienced but i think this should give you output.
Make a multi line string variable with name "rr" in this case and run this code
and put all your file text in it as a multi line string
import re
rr="""All your input string here"""
print(len(re.findall(r'for(.*):(.*)',rr,re.M)))

Related

Add two numbers works in Jupyter, but generates a wrong answer in LeetCode

I'm trying the "add two numbers" (linked list) problem in leetcode. The code that I wrote works fine in Jupyter notebook and returns the correct answer:
def list_to_digits(lst):
lst.reverse()
strings = map(str, lst)
a_string = "". join(strings)
an_integer = int(a_string)
return an_integer
def Convert_IntegersToList(integers):
res = list(map(int, str(integers)))
res.reverse()
return(res)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
integered_l1 = self.list_to_digits(l1)
integered_l2 = self.list_to_digits(l2)
sum_Integers = integered_l1 + integered_l2
list_ofSum = self.Convert_IntegersToList(sum_Integers)
return(list_ofSum)
For example, for the following:
l1 = [2,4,3]
l2 = [5,6,4]
output_list = Solution().addTwoNumbers(l1,l2)
print(output_list)
this code returns: [7, 0, 8] which is the correct result. When I run the same code in leetcode however, it returns the following error:
ListNode object has no attribute reverse
this error happens in line lst.reverse() from function list_to_digits.
Then I tried using two functions for converting between nodeList and python list according to here. This time, I have something like this:
class Solution:
def listnode_to_pylist(self, listnode):
ret = []
while True:
ret.append(listnode.val)
if listnode.next != None:
listnode = listnode.next
else:
return ret
def pylist_to_listnode(self, pylist, link_count):
if len(pylist) > 1:
ret = precompiled.listnode.ListNode(pylist.pop())
ret.next = self.pylist_to_listnode(pylist, link_count)
return ret
else:
return precompiled.listnode.ListNode(pylist.pop(), None)
def list_to_digits(self, lst):
lst.reverse()
strings = map(str, lst)
a_string = "". join(strings)
an_integer = int(a_string)
return an_integer
def Convert_IntegersToList(self, integers):
res = list(map(int, str(integers)))
res.reverse()
return(res)
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l1_ = self.listnode_to_pylist(l1)
l2_ = self.listnode_to_pylist(l2)
integered_list1 = self.list_to_digits(l1_)
integered_list2 = self.list_to_digits(l2_)
sum_Integers = integered_list1 + integered_list2
list_ofSum = self.Convert_IntegersToList(sum_Integers)
return(self.pylist_to_listnode(list_ofSum, len(list_ofSum)))
This code works in leetCode, but it returns the resulting list in the reverse order. For example, for the above example it returns: [8,0,7] (and I tried removing the list reverse line, but still the returned list is in the reverse order). Interestingly, when I run the modified code in Jupyter notebook, it throws the following error:
AttributeError: 'list' object has no attribute 'val'
I cannot figure out what I'm doing wrong in each of these situations and how to fix it. Any idea how I can correct each of these two codes such that it works in leetcode and how to fix the error for the latter code in Jupyter notebook?

Simple Python File I/O spell check program

For a class I have to create a simple spell checking program that takes two files as inputs, one containing correctly spelled words and one containing a paragraph with a few misspelled words. I thought I had it figured out but I am getting an error I have never seen before. When the program finishes it gives the error:
<function check_words at 0x7f99ba6c60d0>
I have never seen this nor do I know what it means, any help in getting this program working would be appreciated. Program code is below:
import os
def main():
while True:
dpath = input("Please enter the path to your dictionary:")
fpath = input("Please enter the path to the file to spell check:")
d = os.path.isfile(dpath)
f = os.path.isfile(fpath)
if d == True and f == True:
check_words(dpath, fpath)
break
print("The following words were misspelled:")
print(check_words)
def linecheck(word, dlist):
if word in dlist:
return None
else:
return word
def check_words(dictionary, file_to_check):
d = dictionary
f = file_to_check
dlist = {}
wrong = []
with open(d, 'r') as c:
for line in c:
(key) = line.strip()
dlist[key] = ''
with open(f, 'r') as i:
for line in i:
line = line.strip()
fun = linecheck(line, dlist)
if fun is not None:
wrong.append(fun)
return wrong
if __name__ == '__main__':
main()
It's not an error, it's doing exactly what you are telling it to.
This line:
print(check_words)
You are telling it to print a function. The output you are seeing is just Python printing the name of the function and it's address: "printing the function".
Yes, don't do print(check_words), do print(check_words())
Furthermore, change check_words(dpath, fpath) to misspelled_words = check_words(dpath, fpath)
And change print(check_words) to print(misspelled_words)
Final code (with a few modifications):
import os
def main():
while True:
dpath = input("Please enter the path to your dictionary: ")
fpath = input("Please enter the path to the file to spell check: ")
d = os.path.isfile(dpath)
f = os.path.isfile(fpath)
if d == True and f == True:
misspelled_words = check_words(dpath, fpath)
break
print("\nThe following words were misspelled:\n----------")
#print(misspelled_words) #comment out this line if you are using the code below
#optional, if you want a better looking output
for word in misspelled_words: # erase these lines if you don't want to use them
print(word) # erase these lines if you don't want to use them
#------------------------
def linecheck(word, dlist):
if word in dlist:
return None
else:
return word
def check_words(dictionary, file_to_check):
d = dictionary
f = file_to_check
dlist = {}
wrong = []
with open(d, 'r') as c:
for line in c:
(key) = line.strip()
dlist[key] = ''
with open(f, 'r') as i:
for line in i:
line = line.strip()
fun = linecheck(line, dlist)
if fun is not None:
wrong.append(fun)
return wrong
if __name__ == '__main__':
main()

Format output right to left

I am trying to learn how to format print to make it look neat. My program would count how many vowels are in a piece of text. But wont print the way I would like which is right to left
As example -
I would like it to print as:
a : 100
e : 50
i : 31
o : 10
u : 1
Currently I have it printing as the following:
a : 100
e : 50
i : 31
o : 10
u : 1
Here is my code and the printing option so far....
import sys
vowels = {i:0 for i in 'aeiou'}
def check(string):
for char in string:
if char in vowels:
vowels[char] +=1
return vowels
def main():
for line in sys.stdin:
lines = line.lower().strip()
check(lines)
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print(' {:} {} {:>d}'.format(r,":",vowels[r]))
#for keys, values in sorted(vowels.items(),reverse=False):
# print('{} : {:d}'.format(keys, vowels[maximum]))
if __name__ == '__main__':
main()
I solved this problem by obtaining the max value from my dictionary,
I had to add the additional code,
formt = max(vowels.values())
finalformat = len(str(formt))
I did this by formt = max(vowels.values())
In order to actually use this, I had to convert that into a string.
I did this by finalformat = len(str(formt))
To finally be able to print I did the following:
sortvowels = sorted(vowels, key=vowels.get, reverse=True)
for r in sortvowels:
print('{} {} {:>{}}'.format(r,":",vowels[r],finalformat))

generating random strings and matching them in python

this is a python program to generate a random string and to match it with a user given output and to get a return on the amount of attempts by the computer but i cant get the try count
import random
class txt:
def __init__(self):
self.txt = None
trycount = 0
def maketxt(self,txt):
txt = ""
a = []
a.append(txt.split())
# return a
# def match(self):
tokenlist = ["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"]
matchlist =[]
while (len(matchlist) <=24):
x =random.choice(tokenlist)
matchlist.append(x)
if matchlist == a:
print(trycount)
else :
trycount += 1
match()
t = txt()
t.maketxt("hagjkrshgujrahg")
I keep getting the error
File "C:/Users/#####/AppData/Local/Programs/Python/Python36/test1.py", line 25, in maketxt
trycount += 1
UnboundLocalError: local variable 'trycount' referenced before assignment

Return a list of vegans

def vegan(something):
list of Foods is returned
data = []
for line in something:
if line.is_vegan == True:
data.append(line)
return data
How can I make this into a recursive function, anything i try just makes it worse, this is the older function.
A simple version could be:
def veggies(foods):
if not foods:
return []
if foods[0].is_vegetarian:
return [foods[0]] + veggies(foods[1:])
return veggies(foods[1:])
Basically you treat the first element, then pass the rest to the next call of the function, until there is no element.
Here is another way
f = open("foods.txt",'r')
def doStuff(f):
line = f.readline()
if line: # While there are lines to read, readline
if "True" in line:
print(line)
# Do formatting and storing into object here
doStuff(f)
doStuff(f)
Hope this helps,
veggie= []
counter = 0
def foodie(counter, foods):
if counter < len(foods):
if foods[counter].split("|")[2] == 'True':
veggie.append(foods[counter])
counter = counter + 1
foodie(counter, foods)
else:
return;
foodie(foods)
Thanks,

Resources