For a given code:
pattern = r'(?:some_pattern)'
def find(seq):
ret = []
while True :
m= pattern_re.match(seq)
if not m :
break
myseq= m.group(2)
assert len(myseq)%3 == 0
assert len(myseq) > 6
ret.append(myseq)
pos = m.end()
return ret
sequence = 'some sequence'
my_seq = find(sequence)
this returns ret in which only first assert function is taken and not the second . Any solution for it ?
the question simply is how to make code consider both the assert function
For starters, why are you using assert?
As soon as the first assert fails an AssertionError is raised and execution of the program stops.
You should be using normal conditionals. Besides that, there is so much wrong with or unusualy with this code I seriously suggest you to read the Python tutorial at http://docs.python.org/tutorial/
Pointers:
print statement after return
usage of assert instead of conditionals
the unnecessary while loop
no proper indenting
Furthermore you pasted an example that plainly does not execute since the indenting is wrong and the function called on the last line does not exist in your code. Please be more precise if you want help :-)
Related
I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.
I am trying to write an if, elif else clause, so that depending on the German word ending, we can see is it should go with der, die or das.
Here is my code:
word = input ("Enter word: ")
if (word.endswith('er' 'ismus')):
print ("der")
elif (word.endswith('falt' 'heit' 'keit' 'schaft' 'ung')):
print ("die")
else (word.endswith('chen' 'lein')):
print ("das")
I have also tried using suffix with square brackets but everything goes grey when I do that and so I can assume it won't work. And clearly true and false are not adequate responses for what I need. Is there anything else I can try?
Thanks in advance!
The endswith method really only checks if the word ends with one thing, but you can do something like:
def word_ends_with_one_of(word, options):
for option in options:
if word.endswith(option):
return True
return False
Then call that with:
suffix_die = ['falt', 'heit', 'keit', 'schaft', 'ung']
suffix_der = ['er', 'ismus']
suffix_das = ['chen', 'lein']
if word_ends_with_one_of(word, suffix_die):
print ("die")
elif word_ends_with_one_of(word, suffix_der):
print ("der")
elif word_ends_with_one_of(word, suffix_das):
print ("das")
As an aside, your else clause is currently problematic, it should not have a condition attached to it (unless it's a typo and you meant to have an elif instead).
Now, even though that you be a useful function to have for other purposes, you may want to consider a more application focused method since you'll be introducing a function anyway. By that, I mean something more closely suited to your specific needs, such as:
def definite_article_for(word):
# Could also use word_ends_with_one_of() in here.
if word.endswith('er'): return 'der'
if word.endswith('ismus'): return 'der'
if word.endswith('falt'): return 'die'
:
if word.endswith('lein'): return 'das'
return None
}
Then use article = definite_article_for(my_word) to get the article you want.
Write the program that reads in input three integers a, b and c. If the integer c is equal to 1, then the program displays on output (prints) the value of a + b; if c is 2 then the program displays the value of a-b; if c is equal to 3 then the output will be the value of ab. Finally, if the value 4 is assigned to c, then the program displays the value of a^2 + ba. If c contains another value, the program displays the message "Error"
a = int(input())
b = int(input())
c = int(input())
if c == 1:
print(a + b)
if c == 2:
print(a - b)
if c == 3:
print(a * b)
if c == 4:
print(a**2 + b*a)
else:
print('Error')
Seems like you got it, just make use of elif instead of a chain of ifs, you can also add a message inside input('Here') that will be printed when prompting for an input
a = int(input("Enter a number: ))
b = int(input("Enter a number: ))
c = int(input("Enter a number: ))
if c == 1 :
print(a + b)
elif c == 2 :
print(a - b)
elif c == 3 :
print(a * b)
elif c == 4 :
print(a**2 + b*a)
else:
print('Error')
Your ifs work, but you have somewhat misaligned the logic.
Use if elif and else
if c==something:
print("this")
elif c==something_else:
print("that")
else:
print("error")
After the first if statement, you should use elif, which is short for "else if". There is no error message because there is no error, you just have your logic wrong. The compiler is treating every if statement independently, so else runs as long as c is not 4.
You're nearly there. The main problem with your program is your if statements are independent, where the problem statement suggests they should not be. Change them for elif statements, which will mean your Error branch only executes when c evaluates to an integer which is not in the set {1, 2, 3, 4}.
Problem 1: program has (possibly) poor control flow
In most programming languages, the if statement is a basic construct used to execute a block of code conditionally if an expression is true. In the following Python-like pseudocode, the code behind the if block is only executed if the value obtained by evaluating EXPRESSION is true:
if EXPRESSION:
# Do something only if EXPRESSION is true
# Execution continues here after the "if" block irrespective of
# whether EXPRESSION was true and the body of the "if" statement
# was executed.
You can augment if statements with else branches. In this case, we execute the body of the if statement if EXPRESSION evaluates to true, and we execute the other arm of the branch (the else branch) if the condition does not evaluate to true (by law of the excluded middle, it's false):
if EXPRESSION:
# As before, control is passed here if EXPRESSION is true.
else:
# If EXPRESSION was false, control is passed to this arm.
# After executing either the "if" arm or the "else" arm, control
# returns to the outer scope outside the "if" statement.
A more complex construct uses an else-if construct to allow you to nest "if" statements. For example, suppose we were implementing a simple call controller which tries to reach someone on their fixed telephone, calls their portable telephone if they are unavailable, and sends an email otherwise. Using the knowledge from above, we might write:
if answers(fixed_telephone):
# Connect to the fixed telephone to communicate
else:
if answers(portable_telephone):
# Connect to the portable telephone to communicate
else:
# Not available on either telephone. Send an email.
As you can imagine, this logic will become complex quickly if there are many nested "if" conditions, which is not unusual in real-world scenarios. Most programming languages provide a construct to pull the nested "if" statements to the top-level. In Python, this is elif, and the equivalent code to the above is:
if answers(fixed_telephone):
# ...
elif answers(portable_telephone):
# ...
else:
# ...
(comments elided for brevity).
In your code as currently written, each of your if statements will be executed independently except the last if c == 4, which will fall to the else branch if c is not equal to 4. As you want the tests of c to be mutually exclusive, i.e. you don't want anything to happen if an earlier case passed, and you only want to print an error if none of the cases were executed, you should use nested if statements, which are best implemented using the above elif language construct.
Problem 2: program assumes well-formed integers
Your program also assumes the values read from STDIN for a, b and c are well-formed integers. If you enter a value which cannot be parsed as an integer, it will crash on the integer conversion in the int(...) call, and will not fall through to reach your print('Error') line. This is an example of Python raising an exception because a problem has been encountered which the interpreter cannot itself recover from. Control flow will not begin executing the if blocks, so the print statement will never be executed.
If you want to fix that issue, you'll need to catch the error returned by the int(...) method when it cannot parse the provided value as an integer. This means learning to catch exceptions, which you can find out more about in the Python docs.
(Hint: Python will raise an built-in exception of type ValueError when the input to int cannot be parsed, so you need to wrap the calls which populate the three variables a, b and c with a try... catch block which catches such an error:
try:
a = int(input())
catch ValueError:
# Implement logic to handle this error, which may include
# returning an error from your function, setting a default
# value, or taking some action. You can optionally take
# some action locally, such as print a log message, and then
# re-raise the exception so it propagates to this method's
# callers (using the "raise" keyword).
I found this question on HackerRank and I am unable to understand the code(solution) that is displayed in the discussions page.
The question is:
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Even though I have solved the problem using if-else, I do not understand how this code works:
n = input()
slist = []
for _ in range(n):
s = input().split()
cmd = s[0]
args = s[1:]
if cmd !="print":
cmd += "("+ ",".join(args) +")"
eval("slist."+cmd)
else:
print slist
Well, the code takes advantage of Python's eval function. Many languages have this feature: eval, short for "evaluate", takes a piece of text and executes it as if it were part of the program instead of just a piece of data fed to the program. This line:
s = input().split()
reads a line of input from the user and splits it into words based on whitespace, so if you type "insert 1 2", s is set to the list ["insert","1","2"]. That is then transformed by the following lines into "insert(1,2)", which is then appended to "slist." and passed to eval, resulting in the method call slist.insert(1,2) being executed. So basically, this code is taking advantage of the fact that Python already has methods to perform the required functions, that even happen to have the same names used in the problem. All it has to do is take the name and arguments from an input line and transform them into Python syntax. (The print option is special-cased since there is no method slist.print(); for that case it uses the global command: print slist.)
In real-world code, you should almost never use eval; it is a very dangerous feature, since it allows users of your application to potentially cause it to run any code they want. It's certainly one of the easier features for hackers to use to break into things.
It's dirty code that's abusing eval.
Basically, when you enter, for example, "remove 1", it creates some code that looks like sList.remove(1), then gives the created code to eval. This has Python interpret it.
This is probably the worst way you could solve this outside of coding competitions though. The use of eval is entirely unnecessary here.
Actually I Find some error in the code, but I came to an understanding of how this code runs. here is it:
input :
3
1 2 3
cmd = 1 + ( 2 + 3)
then eval(cmd) i.e., eval("1 + (2 + 3)") which gives an output 6
another input:
4
4 5 6 2
cmd = 4 + ( 5 + 6 + 2)
eval(cmd)
if __name__ == '__main__':
N = int(raw_input())
lst=[]
for _ in range(N):
cmd, *line = input().split()
ele= list(map(str,line))
if cmd in dir(lst):
exec('lst.'+cmd+'('+','.join(ele)+')')
elif cmd == 'print':
print(lst)
else:
print('wrong command', cmd)
I am attempting to find objects on the screen, see if they exist, and if so, select them. Using the Sikuli library to run this little automation.
while True:
if exist("image/one.png", "image/two.png", "image/three.png"):
click ("image/one.png", or "image/two.png", or "image/three.png")
break
I get SyntaxError: mismatched input 'or' expecting RPARENa I've done a quick search but there is nothing I saw relevant to my particular issue.
I've even tried
while True:
if exist("image/one.png", or "image/two.png", or "image/three.png"):
click ("image/one.png", or "image/two.png", or "image/three.png")
break
And that results in the same error.
#Stephan: New code snippet with error.
class gameImages():
imageFiles = ["one.png", "two.png", "three,png"]
for imageFile in imageFiles:
if exists(imageFile):
click(imageFile)
The Error now, :
NameError: name 'imageFiles' is not defined
for imageFile in imageFiles:
if exists(imageFile):
click(imageFile)
Your while loop isn't doing anything, and neither is your break statement. This might do what you want, assuming I understand what you want to do.
After reading a little of the Sikuli docs, I think this might also do what you want.
for impath in ("image/one.png", "image/two.png", "image/three.png"):
match = exists(impath)
if match:
click(match.getTarget())
Even easier, this is a perfect use of filter(ifexist,imageFiles). You then know that all >=0 elements in the return of filter can be used :). And it's more concise and clearly conveys your intent - much nicer to read then a chain of for's and if's
a = range(10)
# [1,2,3,4,5,6,7,8,9]
print filter(lambda x: x > 5, a)
# [6,7,8,9]
Also the or is a logical operator:
e.g.
a = 5
b = 6
c = 5
if( (a==c) or (b==c) ):
print 'c is repeated'
# c is repeated
your use of the or here makes no sense as it doesn't have operands to operate on - these can even be two objects, e.g.
1 or 2 since anything can be cast to a boolean
a concise way to do what you want is:
//imagepaths = your list of imagepaths
map(lambda x: click(x.getTarget()), filter(exists, imagepaths))