Issue with in string operator in a module in python - python

When I use the operator in to compare strings in my program it works great but if I call it in a module I created it doesn't seem to work. I know I am making some error but not certain what it is, can anyone help?
Here is my code:
Module:
def checkRoots(wordChecked, rootList):
numRoots = len(rootList);
numTypeRoots = createList(numRoots);
for z in range(0, numRoots):
root = rootList[z];
rootThere = root in word;
if rootThere == True:
numTypeRoots[z] = numTypeRoots[z] + 1;
return numTypeRoots;
code works though when not in module as shown here:
for y in range (0, numRoots):
root = roots[y];
rootThere = root in word;
if rootThere == True:
numTypeRoots[y] = numTypeRoots[y] + 1;
Basic program takes a list of words in from a file and then looks to see if a particular root is in the word.
Thanks

The function is doing root in word but I think what you actually want to do is root in wordChecked
Global variables are the devil. best to avoid them if you can help it.
Suggestion - if writing Python code that other people might look at ( hint: probably any/all code) it's a good idea to read through and follow PEP-8

Related

Traceback error in Python for homework assignment

Getting a traceback error as follows:
Traceback (most recent call last):
File "F:\Python Codes\Falling Distance\hodge_Lab5b.py", line 12, in <module>
main()
File "F:\Python Codes\Falling Distance\hodge_Lab5b.py", line 9, in main
print(get_time, '\t', format(falling_distance, '.2f'))
TypeError: unsupported format string passed to function.__format__
#file 1 named hodge_Lab5b.py
def main():
from falling_distance import falling_distance
get_time = int(input("Enter the time, in seconds, the object has been falling: "))
print("Time",'\t' "Distance")
print("--------------------------")
for get_time in range (1,11):
print(get_time, '\t', format(falling_distance(main), '.2f'))
return get_time
main()
#File 2 named falling_distance.py
def falling_distance(main):
gravity = 9.8
fallingTime = main()
distance = (1/2)*gravity*(fallingTime**2)
return distance
Cannot figure out how to get these to work together. I do not know what I have done wrong. I have read through the relevant parts on the book several times. I feel like I am overlooking something rather simple and it is just not jumping out at me.
string formatting
old python: '%s %s' % ('one', 'two')
new python: '{} {}'.format('one', 'two')
also
for get_time in range(1,11): will iterate over 1,2,3...10
you probably want to do sth like this
for sec_nb in range(1, get_time+1):
print('falling time: {} \t falling dist: {}'.format(sec_nb, falling_distance(sec_nb)))
btw you want to pass number to falling_distance function, not a function
It seems like you have a few issues here. Since it's homework, I'm reluctant to provide any code. Here are a couple of issues that I see:
Naming. You're passing the function named main into the function called falling_distance. This is probably not what you want to do (definitely not with the provided code). If you carefully rename everything, I'm guessing most of the problems will go away with some extra debugging.
Inside calling_distance, you're again calling the function main which would seem to put you in an infinite loop. This is related to issue #1, but know that you'll need to revise how you're using the passed parameter in falling distance
If you're using python 2, I think you'll run into printing problems when printing out the table results
get_time is being reassigned in the for loop, which does not seem to be intended. You'll want to replace this with a new variable here
If you're using python 2, I expect that your falling_distance function will always return 0. This is because (1/2) is going to be interpreted as 0 (due to integer division). You should instead have the division happen last, once you know the numerator.
I see a few other issues as well, plus there are some style and convention issues that are more important long term.
Good luck
This is what I finally found to work. Thanks for your help.
#file 1
def main():
print( "Time\tFalling Distance\n-----------------------" )
from falling_distance import fallingDistance
for currentTime in range(1,11):
print(currentTime, "\t", format(fallingDistance(currentTime),\
".2f"))
main()
#file 2
def fallingDistance(fallingTime):
gravity=9.8
distance=(1/2)*gravity*(fallingTime**2)
return distance
Was certainly naming issues that caused a lot of the problems.
Thank you for your help!

For statement does not repeated strings?

I what the user input to be repeated 10 times but I get an error.
no = input(' any thing typed there will x10')
for i in range(10):
print(no)
But if I change the code to int or something else it works .
no = int (input(' any thing typed there will x10'))
for i in range(10):
print(no)
I am probably missing something basic ,but thanks in advance.
I used an app called QPython on my android which might be the problem
What you have written is valid Python 3, but not valid Python 2. I suspect you are running Python 2, given the question. Python changed how the input function works between Python 3 and Python 2. But given your issue, this will fix the issue for Python 2 users (you):
no = raw_input(' any thing typed there will x10')
for i in range(10):
print(no)

Test for my topological/dependancy sort

This is more of a puzzle than a question per se, because I think I already have the right answer - I just don't know how to test it (if it works under all scenarios).
My program takes input from user about which modules it will need to load (in the form of an unsorted list or set). Some of those modules depend on other modules. The way module-dependancy information is stored is in a dictionary like this:
all_modules = { 'moduleE':[], 'moduleD':['moduleC'], 'moduleC':['moduleB'], 'moduleB':[], 'moduleA':['moduleD'] }
Where moduleE has no dependancies, and moduleD depends on moduleC, etc...
Also, there is no definitive lists of all possible modules, since the users can generate their own, and I create new ones from time to time, so this solution has to be fairly generic (and thus tested to work in all cases).
What I want to do is to get a list of modules to run in order, such that modules that are dependant on other modules are only run after their dependancies.
So I wrote the following code to try and do this:
def sort_dependencies(modules_to_sort,all_modules,recursions):
## Takes a small set of modules the user wants to run (as a list) and
## the full dependency tree (as a dict) and returns a list of all the
## modules/dependencies needed to be run, in the order to be run in.
## Cycles poorly detected as recursions going above 10.
## If that happens, this function returns False.
if recursions == 10:
return False
result = []
for module in modules_to_sort:
if module not in result:
result.append(module)
dependencies = all_modules[module]
for dependency in dependencies:
if dependency not in result:
result.append(dependency)
else:
result += [ result.pop(result.index(dependency)) ]
subdependencies = sort_dependencies(dependencies, all_modules, recursions+1)
if subdependencies == False:
return False
else:
for subdependency in subdependencies:
if subdependency not in result:
result.append(subdependency)
else:
result += [ result.pop(result.index(subdependency)) ]
return result
And it works like this:
>>> all_modules = { 'moduleE':[], 'moduleD':['moduleC'], 'moduleC':['moduleB'], 'moduleB':[], 'moduleA':['moduleD'] }
>>> sort_dependencies(['moduleA'],all_modules,0)
['moduleA', 'moduleD', 'moduleC', 'moduleB']
Note that 'moduleE' isn't returned, since the user doesn't need to run that.
Question is - does it work for any given all_modules dictionaries and any given required modules_to_load list? Is there a dependancy graph I can put in and a number of user-module-lists to try that, if they work, I can say all graphs/user-lists will work?
After the excellent advice by Marshall Farrier, it looks like i'm trying to do is a topological sort, so after watching this and this I implemented that as the following:
EDIT: Now with cyclic dependancy checking!
def sort_dependencies(all_modules):
post_order = []
tree_edges = {}
for fromNode,toNodes in all_modules.items():
if fromNode not in tree_edges:
tree_edges[fromNode] = 'root'
for toNode in toNodes:
if toNode not in tree_edges:
post_order += get_posts(fromNode,toNode,tree_edges)
post_order.append(fromNode)
return post_order
def get_posts(fromNode,toNode,tree_edges):
post_order = []
tree_edges[toNode] = fromNode
for dependancy in all_modules[toNode]:
if dependancy not in tree_edges:
post_order += get_posts(toNode,dependancy,tree_edges)
else:
parent = tree_edges[toNode]
while parent != 'root':
if parent == dependancy: print 'cyclic dependancy found!'; exit()
parent = tree_edges[parent]
return post_order + [toNode]
sort_dependencies(all_modules)
However, a topological sort like the one above sorts the whole tree, and doesn't actually return just the modules the user needs to run. Of course having the topological sort of the tree helps solve this problem, but it's not really the same question as the OP. I think for my data, the topological sort is probably best, but for a huge graph like all packages in apt/yum/pip/npm, it's probably better to use the original algorithm in the OP (which I don't know if it actually works in all scenarios...) as it only sorts what needs to be used.
So i'm leaving the question up an unanswered, because the question is really "How do i test this?"

ANTLR4 and the Python target

I'm having issues getting going with a Python target in ANTLR4. There seems to be very few examples available and going to the corresponding Java code doesn't seem relevant.
I'm using the standard Hello.g4 grammar:
// Define a grammar called Hello
grammar Hello;
r : 'hello' ID ; // match keyword hello followed by an identifier
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
The example (built from the standard Hello.g4 example):
input_ = antlr4.FileStream(_FILENAME)
lexer = HelloLexer.HelloLexer(input_)
stream = antlr4.CommonTokenStream(lexer)
parser = HelloParser.HelloParser(stream)
rule_name = 'r'
tree = getattr(parser, rule_name)()
I also wrote a listener. To assert/verify that this is correct, I'll repeat it here:
class HelloListener(antlr4.ParseTreeListener):
def enterR(self, ctx):
print("enterR")
def exitR(self, ctx):
print("exitR")
def enterId(self, ctx):
print("enterId")
def exitId(self, ctx):
print("exitId")
So, first, I can't guarantee that the string I'm giving it is valid because I'm not getting any screen output. How do I tell from the tree object if anything was matched? How do I extract the matching rules/tokens?
A Python example would be great, if possible.
I hear you, having the same issues right now. The Python documentation for v4 is useless and v3 differs to much to be usable. I'm thinking about switching back to Java to implement my stuff.
Regarding your code: I think your own custom listener has to inherit from the generated HelloListener. You can do the printing there.
Also try parsing invalid input to see if the parser starts at all. I'm not sure about the line with getattr(parser, rule_name)() though. I followed the steps in the (unfortunately very short) documentation for the Antlr4 Python target: https://theantlrguy.atlassian.net/wiki/display/ANTLR4/Python+Target
You can also find some documentation about the listener stuff there. Hope it helps.
This question seems to be old, but I also had the same problems and found out how to deal with it. When using strings in python, you have to use the function antlr4.InputStream as pointed out here
So, in the end, you could get a working example with this sort of code (based on Alan's answer and an example from dzone)
from antlr4 import *
from grammar.HelloListener import HelloListener
from grammar.HelloLexer import HelloLexer
from grammar.HelloParser import HelloParser
import sys
class HelloPrintListener(HelloListener):
def enterHi(self, ctx):
print("Hello: %s" % ctx.ID())
def main():
giveMeInput = input ("say hello XXXX\n")
print("giveMeInput is {0}".format(giveMeInput))
# https://www.programcreek.com/python/example/93166/antlr4.InputStream
# https://groups.google.com/forum/#!msg/antlr-discussion/-9VJ5H9NcDs/OukVNCTQCAAJ
i_stream = InputStream(giveMeInput)
lexer = HelloLexer(i_stream)
t_stream = CommonTokenStream(lexer)
parser = HelloParser(t_stream)
tree = parser.hi()
printer = HelloPrintListener()
walker = ParseTreeWalker()
walker.walk(printer, tree)
if __name__ == '__main__':
main()
I've created an example for Python 2 using the Hello grammar.
Here's the relevant code:
from antlr4 import *
from HelloLexer import HelloLexer
from HelloListener import HelloListener
from HelloParser import HelloParser
import sys
class HelloPrintListener(HelloListener):
def enterHi(self, ctx):
print("Hello: %s" % ctx.ID())
def main():
lexer = HelloLexer(StdinStream())
stream = CommonTokenStream(lexer)
parser = HelloParser(stream)
tree = parser.hi()
printer = HelloPrintListener()
walker = ParseTreeWalker()
walker.walk(printer, tree)
if __name__ == '__main__':
main()
As fabs said, the key is to inherit from the generated HelloListener. There seems to be some pickiness on this issue, as you can see if you modify my HelloPrintListener to inherit directly from ANTLR's ParseTreeListener. I imagined that would work since the generated HelloListener just has empty methods, but I saw the same behavior you saw (listener methods never being called).
Even though the documentation for Python listeners are lacking, the available methods are similar to Java.
The antlr documentation has been updated to document the support for python 3 and python 4 targets. The examples from the antlr book converted to python3 can be found here, they are sufficient enough to get anyone started.

Writing word backwards

I know there are possibilities :
sampleword[::-1]
or
reverse(string)
but I wanted to write it by myself. I don't get why my code doesn't work. Could you help me?
h=input('word\n\n');
rev(h)
def rev(h):
counter=len(h);
reverse="";
while counter>0:
reverse+=h[counter];
counter=counter-1;
return reverse
#print (reverse); ?
input();
There are a couple issues with your code, I pointed them out in the comments of this adjusted script:
def rev(h):
counter=len(h) - 1 # indexes of h go from 0 to len(h) - 1
reverse=""
while counter>=0: # changed to >=0
reverse+=h[counter]
counter -= 1
return reverse
h=input('word\n\n');
revers = rev(h) # put rev(h) after the definition of rev!
print(revers) # actually print the result
# deleted your last line
In addition, you don't need to terminate lines with ; in python and you can write counter=counter-1 as counter -= 1.
You have some issues/problems in your code.
You call rev() before it is defined
Indexing starts at 0, so you need >= 0 instead of > 0
You want counter to equal len(h) - 1 because again, indexing starts at 0
You do not need semicolons at the end of your lines
Here is a much simpler and faster way using recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
As you use Python more you will come across the concept of "Pythonic" code ... code that uses Python features well and shows good programming style.
So, you have a good answer above showing how your code can be corrected to work correctly in Python. But the issue I want to point out is that's C style programming. Someone said you can write C in any language (especially true in C++ and C#), but if you do you are probably not using the features of the language well. In Python, writing this style of function and ignoring the available built-in, implemented in C, lightning fast methods is not Pythonic.
I guarantee you that reverse(string) or string[::-1] are both faster than your rev( ) python code. Python has a ton of built in functionality and extensive library of files you can import for extra already debugged functionality. See if you can find a good way to time the execution of reverse( string ) and your rev( ) function. There is a good way, in Python.

Categories