I am using python and trying to speed up the process of checking what is inside strings for a q & a program. I want to do the following for a variable amount of conditions:
a = input("Any question")
if "a condition" in a:
print("the condition is in the question")
So here I'm checking if a condition is in a question to see what kind of question it is, and here was my idea for doing multiple conditions:
def ifs(a,b,c):
b=[d,e,f,g,h,i,j,k]
while a < 8:
b.remove(b[a])
a = a - 1
print("c")
Here, a is the number of conditions you want to check and b are the conditions being checked while c, the final, is the something to print afterwards. (c does not have anything to do with the problem). That second part b=[d,e,f,g,h,i,j,k] is a list that is meant to be inserted where b is so you can assign a certain amount of values, which varies depending on a, which counts down to zero, as shown in a = a - 1 removing variables one by one b.remove(b[a]).
I'm wondering if there's any way to be able to list off conditions without making a specifically defined command for each amount of conditions... below is what i mean:
def if1(a,b,c):
if a in b:
print(c)
def if2(a,b,c,d):
if a in c:
print(d)
if b in c:
print(d)
def if3(a,b,c,d,e):
if a in d:
print(e)
if b in d:
print(e)
if c in d:
print(e)
And so on...
Any help is appreciated, THANKS!
why not pack the arguments in a list instead of writing many functions?
e.g. something like this:
def condition_met(condition, to_check):
if condition in to_check:
print(condition)
data = list(range(4)) # [0, 1, 2, 3]
condition_met(3, data) # ok
condition_met(7, data) # nope
Related
I'm creating a python program that given any angles/sides of a triangle will solve for all other applicable sides. to do this I have a dictionary of lists with lengths a,b,c and sides aa,ba,ca. the dictionary is structured so the first item in the list is the value of the key and the second item is a 0 or a 1, depending on if it is answered or not.
The program takes the second value of the list and puts it into another dictionary i called eqdict. for eqdict the value is either a 1 or a 0, depending if the value is known or not. With this we can do Pythagorean theorem, so if a+b+c=2, then we know 1 value is missing so it starts a function to find the missing side. After this function the answer gets saved with the saveanswer function, and the equation finder function is called again. However when the program goes back through equation finder, the eqdict for whichever character it found is not set to 0, so it has a continuous loop.
import math
def main():
#creating terms in strings because I cant find an answer on how
#to make floats with a non zero no value
global terms
terms={"a":[0,0],"b":[0,0],"c":[0,0],"aa":[0,0],"ba":[0,0],"ca":[0,0]}
selectterms()
def selectterms():
"""takes user input for terms"""
doneterm=False
while not doneterm:
print("Please select the variable and then write it's value")
print("When done, please press enter with command prompt empty")
term1=input("Variable: ")
#to start program need to enter no command
if term1=="":
doneterm=True
appender()
#to end program after its finished
if doneterm ==False:
term2=float(input("Number: "))
terms[term1]=[term2]
terms[term1].append(1)
return
def addtoeqdict(term):
eqdict[term]=1
return
def saveanswer(term,num):
"""saves answer to answers dict, makes second term 1 and sends back the number"""
answers={}
print("saveanswer")
answers[term]=num
#print("answers",answers)
terms[term][1]=1
terms[term][0]=num
eqdict[term]=1
print(answers)
print(eqdict)
eqfinder(**eqdict)
def appender():
"""Append a 0 on to terms that have only 1 item in list"""
global eqdict
eqdict={}
keys=terms.keys()
for i in keys:
i = str(i)
eqdict[i]=int(terms[i][1])
eqfinder(**eqdict)
return
def eqfinder(a,b,c,aa,ba,ca):
"""runs through given terms to find any possible equations.
looks for possible equations by adding appended values"""
nomoreterms=False
while nomoreterms == False:
print(terms)
if terms["aa"][0]!=0 or terms["ba"][0]!=0 or terms["ca"][0]!=0:
if terms["aa"][0]<0 or terms["ba"][0]<0 or terms["ca"][0]<0:
posangles(terms["aa"][0],terms["ba"][0],terms["ca"][0])
print(a,b,c,aa,ba,ca)
if c+a+b==2:
cab(terms["c"][0],terms["a"][0],terms["b"][0])
else:
nomoreterms=True
def posangles(aa,ba,ca):
print("Posangles")
if aa<0:
aa=aa*(-1)
saveanswer("aa",aa)
elif ba<0:
ba=ba*(-1)
saveanswer("ba",ba)
elif ca<0:
ca=ca*(-1)
saveanswer("ca",ca)
def cab(c,a,b):
print("cab")
if c==0:
c=math.sqrt(a**2+b**2)
saveanswer("c",c)
elif a==0:
a=math.sqrt(c**2-b**2)
saveanswer("a", a)
elif b==0:
b=math.sqrt(c**2-a**2)
saveanswer("b",b)
main()
So the issue is your eqfinder function. You pass in a, b, c find the missing value using cab, and save the answer. It then gets back to eqfinder and checks if a + b + c == 2 which it does since you never updated the a, b, c variables. There are number of fixes you could do to make this break out of the for loop. Here's one (added line marked with >>>):
def eqfinder(a,b,c,aa,ba,ca):
"""runs through given terms to find any possible equations.
looks for possible equations by adding appended values"""
nomoreterms=False
while nomoreterms == False:
print(terms)
if terms["aa"][0]!=0 or terms["ba"][0]!=0 or terms["ca"][0]!=0:
if terms["aa"][0]<0 or terms["ba"][0]<0 or terms["ca"][0]<0:
posangles(terms["aa"][0],terms["ba"][0],terms["ca"][0])
print(a,b,c,aa,ba,ca)
if c+a+b==2:
cab(terms["c"][0],terms["a"][0],terms["b"][0])
>>> c, a, b = terms["c"][1],terms["a"][1],terms["b"][1]
else:
nomoreterms=True
I'm not sure if this is even possible but I'm trying to create a python program that identifies polynomials and identifies all the properties of them. I was trying to make a function similar to the switch() function, and the way that I was going to get around making hundreds of functions for each number of cases for arguments, I wanted to make one of the arguments an array, currently it's throwing me a bunch of errors and I really don't know what I'm supposed to be doing because they don't explain themselves, I've looked around and haven't found anything that works, any help would be greatly appreciated, I'm fairly certain there is a similar function in python but any articles on it are quite confusing, thank you, below is the function I was trying to make.
def switch(checked, check):
for(item in check):
if(item == check):
return True
return False
If you need to simulate a switch statement you can use a helper function like this one:
def switch(v): yield lambda *c: v in c
You can then use it in a C-like style:
x = 3
for case in switch(x):
if case(1,2):
# do something
break
if case(3):
# do something else
break
if case(4,5,7):
# do some other thing
break
else:
# handle other cases
Or you can use if/elif/else statements:
x = 3
for case in switch(x):
if case(1,2): # do something
elif case(3): # do something else
elif case(4,5,7): # do some other thing
else: # handle other cases
To check if something is an item of a list, you don't need to loop through the list. You can just use the in operator:
d = ['abc', 'xyz', 1, 99]
if 'abc' in d:
# True
# do something
if 'mno' in d:
# False
# do something
Did you mean this?
def switch(checked, check):
for item in check:
if item == checked:
return True
return False
Sometimes I get confused as to where to use the return statement. I get what it does, it's just that I don't get its placement properly.
Here's a short example of the same code.
Correct way:
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Wrong way (which I did initially):
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Can someone clarify what's the difference between the two and where should the return be when using a loop in a function?
return in a function means you are leaving the function immediately and returning to the place where you call it.
So you should use return when you are 100% certain that you wanna exit the function immediately.
In your example, I think you don't want to exit the function until you get the final value of c, so you should place the return outside of the loop.
You're putting too much emphasis on the impact of return on controlling the behaviour of the for loop. Instead, return applies to the function and happens to terminate the for loop prematurely by primarily bringing an end to the function.
Instead, you can control the behaviour of the for loop independently from the function itself using break. In addition, you can have multiple return statements in a function depending on what action should be taken in response to particular criteria (as in my_func1). Consider the following:
import random
def my_func1(my_list, entry):
'''
Search a list for a specific entry. When found, terminate search
and return the list index immediately
Return False if not found
'''
print "\n Starting func1"
index = 0
for item in my_list:
if item != entry:
print "Not found yet at index: {}".format(index)
index += 1
else:
print "found item, at index {}".format(index)
print "Terminating function AND loop at same time"
return index
print "########### ENTRY NOT IN LIST. RETURN FAlSE #############"
return False
a = my_func1(['my', 'name', 'is', 'john'], 'is')
b = my_func1(['my', 'name', 'is', 'john'], 'harry')
def my_func2(my_list):
''' Iterate through a list
For first 4 items in list, double them and save result to a list that will
be returned, otherwise terminate the loop
Also, return another list of random numbers
'''
print '\n starting func2'
return_list = []
for i in range(len(my_list)):
if i < 4:
print 'Value of i is {}'.format(i)
return_list.append(my_list[i] * 2)
else:
print 'terminating for loop, but ** keep the function going **'
break
other_list = [random.randint(1, 10) for x in range(10)]
print 'Returning both lists'
return return_list, other_list
c = my_func2([x for x in range(10)])
First, I have this function:
def change_pos(a, b):
temp = a
a = b
b = temp
print 'Done'
And I call it in another function but it just print 'Done' and do nothing.
I write the code directly:
a = 1
b = 2
temp = a
a = b
b = temp
It works fine. Any suggestion here?
Second, this is my code
def check_exception(list):
for element in list:
# Take list of numbers
# \s*: Skip space or not (\t\n\r\f\v), \d: Number [0-9]
# ?: Non-capturing version of regular parentheses
first = re.compile("\s*(?:\[)(\d+)\s*(?:,)").findall(element)
last = re.compile("\s*(?:,)(\d+)\s*(?:\])").findall(element)
# Convert string to integer
first_int = map(int, first)
last_int = map(int, last)
# Check and code above works
i = 0
print first_int[i]
change_pos(first_int[i],first_int[i+1])
print first_int[i+1]
print len(first_int)
#print type(first_int[0])
# Sort
# Error: list index out of range at line 47 and more
i = 0
while i < len(first_int):
if first_int[i] > first_int[i+1]:
change_pos(first_int[i], first_int[i+1])
change_pos(last_int[i], last_int[i+1])
i += 1
# Check exception
j = 0
while j < len(last_int):
if last_int[j] < first_int[j+1]:
return false
break
else:
j += 1
continue
return true
And I see: IndexError: list index out of range at conditions after # Error
Thanks for any help. :)
Your change_pos function does nothing useful as it only swaps the variables inside the function, not the variables that was used to call the function. One method of accomplishing what you want is this:
def change_pos(a, b):
print 'DONE'
return b, a
and then using it becomes:
a, b = change_pos(a,b)
Or even without a function:
a, b = b, a
Secondly, I'm sure you can figure out why you're getting an index error on your own. But here's why anyways. Arrays are zero indexed and you are using the length of last_int in your while loop. Now imagine last_int has a length of 5. That means it has index values ranging from 0-4. In the last iteration of the loop you are attempting to access last_int[5] in your if statement (last_int[j+1]) which of course will give you an index error.
You may have been told that variables are locations in memory with data in it. This is not true for Python. Variables are just names that point to objects.
Hence, you can not in Python write a function such as the change_pos function you attempt to write, because the names you change will be the names used in the function, not the names used when calling.
Instead of this:
a = 1
b = 2
change_pos(a, b)
You will have to do this:
a = 1
b = 2
a, b = change_pos(a, b)
The function needs to look like this:
def change_pos(a, b):
return b, a
This give you a hint that there is an easier way, and indeed there is. You can do this:
a = 1
b = 2
a, b = b, a
So no need for a function at all.
Since you actually want to swap integers in a list, you can make a function like this:
def change_pos(lst, p):
lst[p], lst[p+1] = lst[p+1], lst[p]
But I don't think that adds significantly the the readability of the code.
Also your usage of this is prefixed with the comment #sort. But your code does not sort. It's a bit like a half-assed bubble sort, but I don't know why you would want to do that.
Numbers are immutable in python. His when you pass them to a function, the function works with copies of the variables. This can be tricky if you try this with mutable types like Lists. But python has this function covered with some neat syntax tricks.
a, b = b, a
This swaps two variables with no need for any additional functions.
Noob wondering how to improve his code.
a, b, c = string.split(enteredDate, "/")
m31s = [1, 3, 5, 7, 8, 10, 12]
m30s = [4, 6, 9, 11]
for x in range(len(m31s)):
x = int(m31s[x])
if x != int(a) and b != 31:
print "Invalid date."
for x in range(len(m30s)):
et cetera...
In case it isn't clear, I am testing an inputted date to see if it is valid. This is only part of the program. The main question is: what is the best way to test if an element matches ANY element in a list?
My method works... But, I suspect there is a better way to do this. I said boolean in the title because I envision something like:
if secretCode(m31s, int(a)) == True:
Could be a pipedream. Just curious.
Thanks to anyone who takes the time to help.
You can use the syntax if elem in list. For example:
>>> if 1 in [1,2,3,4,5]:
... print 'found 1'
...
found 1
You should use python datetime library.
try:
datetime.datetime.strptime(enteredDate, "%m/%d/%Y")
except:
print 'Invalid date'
I suggest:
replace
a, b, c = string.split(enteredDate, "/")
with
a, b, c = enteredDate.split("/")
Not that it matters much, but the first version needs to import the string module, the second not.
replace int(m31s[x]) with m31s[x] (you know those are int already, why the extra int( ... ) then?
in case secretCode( ... ) returns true or false you can simply write if secretCode( ... ):, no need to compare with == True.
instead of calling int(a), int(b) or int(c) you can simply write a, b, c = map(int, enteredDate.split("\")) and forget about those int( ... ) later since you know they are int. Additionally, if those are not int you will immediately get an exception without unnecessarily progressing in your code.