Today, I've made a simple project about solving simple equation by python.
like this
linear="30=10x-20"
#c=bx+a or a+bx=c
a=0
c=0
b=0
split=linear.split("=")
if len(split[0])==1 or len(split[1])==1 :
c=int(split[0]) if len(split[0])==1 else int(split[1])
if len(split[0])>1 or len(split[1])>1 :
b=int(split[0][:linear.index("x")]) if len(split[0])>1 else int(split[1][:linear.index("x")])
a=int(split[0][linear.index("x")+1:] if len(split[0])>1 elseint(split[1[linear.index("x")+1:]))
total=(c-a)/b
print(total)
So, it separates the string between "=" first. Then, it analyzes the part of
separation to get the values of a,b,c. After that, I got the error. How do i fix this ?
thank you.
a=int(split[0][linear.index("x")+1:] if len(split[0])>1 else int(split[1][linear.index("x")+1:]))
ValueError: invalid literal for int() with base 10: ''
The if and else statements are confusing may be because of that you may be having this error. The things would be simpler if you learn regex in python.
I have tried with the given linear equation. Please use it as a reference.
import re
equation = '30=10x-20'
#Checking 'c = bx+a' or 'bx+a = c'
x = re.match('[0-9]+=[0-9]+x+?-?[0-9]+',equation)
if x:
#print('True')
output_1 = equation.split('=')
c = int(output_1[0])
print('c = ',c)
# checking the operator between bx and a
#rhs = '[0-9]+x+?[0-9]+'
y = re.match('[0-9]+x-?[0-9]+',output_1[1])
if y:
#filter_b = ['x']
output_2 = output_1[1].split('-')
a = int(output_2[1])
b = int(output_2[0].replace("x",""))
print('a = ',a)
print('b = ',b)
else:
print('False')
else:
print('False')
answer:
c = 30
a = 20
b = 10
I am currently creating a loop with sikuli. My problem is that i have a fixed variables that will go up to 15 with only the numbers changing at the end. I was looking for a way to combine the string component that is fixed with the integer which will be variable in the loop but then once concatenated have it identified as the predefined variable at the top of the code.
Any help would be awesome!
Dunning1 = (Pattern("Line 1.png").similar(0.97).targetOffset(445,-2))
Balance1 = (Pattern("Line 1.png").similar(0.97).targetOffset(566,-2))
Select1 = (Pattern("Line 1.png").similar(0.97).targetOffset(38,-1))
Dunning2 = (Pattern("Line 2.png").similar(0.97).targetOffset(442,-1))
Balance2 =(Pattern("Line 2.png").similar(0.97).targetOffset(565,2))
Select2 = (Pattern("Line 2.png").similar(0.97).targetOffset(37,-1))
while n < 3:
DunningX = ("Dunning"+str(n)**
print(DunningX)**
doubleClick(DunningX)
type("c",KEY_CTRL)
doubleClick(DunningX)
type("c",KEY_CTRL)
Dunning1 = Env.getClipboard()
BalanceX = ("Balance"+str(n))
doubleClick(BalanceX)
type("c",KEY_CTRL)
doubleClick(BalanceX)
type("c",KEY_CTRL)
ContractBal = Env.getClipboard()
if Dunning1 == ContractBal:
SelectX = ("Select"+str(n))
click(SelectX)
n = n + 1
I'm not sure if I fully understand your question, but I think you're looking for this:
if some_condition:
Select1 = "Select"+str(n)
else
Select2 = "Select"+str(n)
any way, please consider using a list for this since using single variables is not scalable at all. It could look like this:
select = []
select.append(Pattern("Line 1.png").similar(0.97).targetOffset(38,-1))
select.append(Pattern("Line 2.png").similar(0.97).targetOffset(37,-1))
...
if some_condition:
m=1
else
m=2
select[m] = 'select'+str(n)
From your code shown i see a few issues.
I assume your while n < 3 is indentation issue.
error with (:
DunningX = "Dunning" + str(n)
print(DunningX)
I would recommend you to do the following:
1 - add all the variables to a class as attributes:
class Variables:
def __init__(self):
self.Dunning1 = (Pattern("Line 1.png").similar(0.97).targetOffset(445,-2))
self.Balance1 = (Pattern("Line 1.png").similar(0.97).targetOffset(566,-2))
2 - get the values dynamically by their name using getattr func:
n=1 // for example
vars = Variables()
DunningX = getattr(vars,f"Dunning{n}") //DunningX will be equal to Dunning1
Beginner programmer here:)) I am working on a school project, where the assignment is to find the roots to five functions in one file.
In one of my functions there are two roots, and my code can only find one. It seems like the second while-loop is ignored. I've tried to put only this code in a separate file, and it worked - but together with the other files it wont work...
Just ask if there is something that´s weird;)
def b(x: float):
return -x**2+x+6
def bgraf():
xlim(a1, b1)
ylim(-15, 25)
x = linspace(-5, 10, 1000)
y = b(x)
plot(x, y, 'r')
return
funksjoner = [0, 1, 2, 3, 4]
while response not in funksjoner:
i = int(input("choose a function from 0 to 4"))
response = i
if response in funksjoner:
print("you chose function ", int(funksjoner[i]))
a1 = float(input())
b1 = float(input())
z = a1
y = b1
m = a1
n = b1
NP = True
if int(funksjoner[i]) == funksjoner[1]:
while abs(y-z) > 1e-10:
null1 = (z+y)/2
if b(z)*b(null1)>0 and b(y)*b(null1)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1) == 0:
break
elif b(z)*b(null1)>0:
z = null1
else :
y = null1
while abs(n-m) > 1e-10:
null1_2 = (m+n)/2
if b(m)*b(null1_2)>0 and b(n)*b(null1_2)>0:
NP = False
print('No roots in this interval')
bgraf()
break
elif b(null1_2) == 0:
break
elif b(m)*b(null1_2)>0:
m = null1_2
else :
n = null1_2
if NP :
print('we have a root when x =', round(((z+y)/2), 1))
if null1 != null1_2:
print('and when x =', round(((m+n)/2), 1))
bgraf()
scatter(null1, 0)
if null1 != null1_2:
scatter(null1_2, 0)
It looks like python is ignoring the second while-loop I placed under the if-statement. Is there another way I could this?
Thanks for your attention!
Several things to think about:
what do you want to achieve with the following line of code:
If int(funksjoner[i]) == funksjoner[1]
You could simply check
If i == 1
i don‘t see any difference between the first and the second while loop.
z=m=a1
y=n=a2
So what should be the difference between those two?
In General the code is hard to read because of the naming of the variables, try to use variables which give you an impression what they contain.
For getting better impression what is going on in your code either use debugging, or if you are not familiar with debugging add print statements in your code to better understand what is stored in your variables at which time of the execution. And what statements are executed and which are skipped/not reached
When you give us more detailed information about your code (you could e.g. add comments to explain your code), have more detailed questions we can better support you
I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this?
Use itertools.cycle():
from itertools import cycle
myIterator = cycle(range(2))
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 1
# etc.
Note that if you need a more complicated cycle than [0, 1], this solution becomes much more attractive than the other ones posted here...
from itertools import cycle
mySmallSquareIterator = cycle(i*i for i in range(10))
# Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...
You can accomplish that with a generator like this:
>>> def alternate():
... while True:
... yield 0
... yield 1
...
>>>
>>> alternator = alternate()
>>>
>>> alternator.next()
0
>>> alternator.next()
1
>>> alternator.next()
0
You can use the mod (%) operator.
count = 0 # initialize count once
then
count = (count + 1) % 2
will toggle the value of count between 0 and 1 each time this statement is executed. The advantage of this approach is that you can cycle through a sequence of values (if needed) from 0 - (n-1) where n is the value you use with your % operator. And this technique does not depend on any Python specific features/libraries.
e.g.
count = 0
for i in range(5):
count = (count + 1) % 2
print(count)
gives:
1
0
1
0
1
You may find it useful to create a function alias like so:
import itertools
myfunc = itertools.cycle([0,1]).next
then
myfunc() # -> returns 0
myfunc() # -> returns 1
myfunc() # -> returns 0
myfunc() # -> returns 1
In python, True and False are integers (1 and 0 respectively). You could use a boolean (True or False) and the not operator:
var = not var
Of course, if you want to iterate between other numbers than 0 and 1, this trick becomes a little more difficult.
To pack this into an admittedly ugly function:
def alternate():
alternate.x=not alternate.x
return alternate.x
alternate.x=True #The first call to alternate will return False (0)
mylist=[5,3]
print(mylist[alternate()]) #5
print(mylist[alternate()]) #3
print(mylist[alternate()]) #5
from itertools import cycle
alternator = cycle((0,1))
next(alternator) # yields 0
next(alternator) # yields 1
next(alternator) # yields 0
next(alternator) # yields 1
#... forever
var = 1
var = 1 - var
That's the official tricky way of doing it ;)
Using xor works, and is a good visual way to toggle between two values.
count = 1
count = count ^ 1 # count is now 0
count = count ^ 1 # count is now 1
To toggle variable x between two arbitrary (integer) values,
e.g. a and b, use:
# start with either x == a or x == b
x = (a + b) - x
# case x == a:
# x = (a + b) - a ==> x becomes b
# case x == b:
# x = (a + b) - b ==> x becomes a
Example:
Toggle between 3 and 5
x = 3
x = 8 - x (now x == 5)
x = 8 - x (now x == 3)
x = 8 - x (now x == 5)
This works even with strings (sort of).
YesNo = 'YesNo'
answer = 'Yes'
answer = YesNo.replace(answer,'') (now answer == 'No')
answer = YesNo.replace(answer,'') (now answer == 'Yes')
answer = YesNo.replace(answer,'') (now answer == 'No')
Using the tuple subscript trick:
value = (1, 0)[value]
Using tuple subscripts is one good way to toggle between two values:
toggle_val = 1
toggle_val = (1,0)[toggle_val]
If you wrapped a function around this, you would have a nice alternating switch.
If a variable is previously defined and you want it to toggle between two values, you may use the
a if b else c form:
variable = 'value1'
variable = 'value2' if variable=='value1' else 'value1'
In addition, it works on Python 2.5+ and 3.x
See Expressions in the Python 3 documentation.
Simple and general solution without using any built-in. Just keep the track of current element and print/return the other one then change the current element status.
a, b = map(int, raw_input("Enter both number: ").split())
flag = input("Enter the first value: ")
length = input("Enter Number of iterations: ")
for i in range(length):
print flag
if flag == a:
flag = b;
else:
flag = a
Input:
3 835Output:38383
Means numbers to be toggled are 3 and 8
Second input, is the first value by which you want to start the sequence
And last input indicates the number of times you want to generate
One cool way you can do in any language:
variable = 0
variable = abs(variable - 1) // 1
variable = abs(variable - 1) // 0
I'm trying to figure what the values of xcoord_orig and ycoord_orig are when the last conditional statement is true i.e. when board[xcoordT][ycoordT] == computer. I feel that as I have it right now, I'm simply printing their values if the conditional statement is true. But what I really want are the values of xcoord_orig and ycoord_orig under the first loop at the point where the last conditional statement is true. I'm not sure if this is clear but I thought I would ask.
for num in range(8):
for i in range(len(valid_list)):
xcoord_orig = valid_list[i][0]
ycoord_orig = valid_list[i][1]
xcoord1 = valid_list[i][0] + num_list[num]
ycoord1 = valid_list[i][1] + num_list2[num]
if 0 <= xcoord1 <= 7 and 0 <= ycoord1 <= 7:
piece = board[xcoord1][ycoord1]
if piece == player:
move_list = []
for i in range(2,8):
xcoordT = xcoord_orig
ycoordT = ycoord_orig - i
print(xcoord_orig, ycoord_orig)
if board[xcoordT][ycoordT] == computer:
move_list.append([xcoordT, ycoordT])
print(xcoord_orig, ycoord_orig)
This
for i in range(len(valid_list)):
...
for i in range(2,8):
Is epic fail. It can't be correct.