I am trying to make a very long program much shorter by making it concise, because I need to modify it to run through several kinds of reports. Basically, it loads a list from a report in excel, and then checks to see if those values are above or below control limits. I tried using an interval comparison to see if any value in my list was not between the control limits, but that did not work. Instead, I had to go with a little bit longer method that did work. Can someone please explain to me why the second method shown below does not work? There are no errors, but it does not find the failed tests like the first one does.
############### This is the same between the two methods #############
#Loading my list with the variables to be checked
GtimeList = [37, 37, 37, 32, 32, 32,
Gtime3b, GtimeAveb]
GT = 0
#Make sure these are numbers
if any(isinstance(x, str) for x in GtimeList):
continue
######## Method one works fine, but I want it more concise ############
#Check to see if any of the variables are not between 10 to 35
elif any(10 > x for x in GtimeList) or any(35 < x for x in GtimeList):
GT = 'Gel Time'
######## Method two, this is how I want it to work ########
#Check to see if any of the variables are not between 10 to 35
elif any(10 > x > 35 for x in GtimeList):
GT = 'Gel Time'
What you are looking for is maybe this:
any(x not in range(10,36) for x in GtimeList)
This is sort of more of a logic question than a programming question. Both of your code snippets have two conditions for each value, for a total of 2n conditions. Your first code snippet just needs one out of those 2n conditions to be true. Your second requires two of them to be true, and needs the two to be for the same value. You should replace the any in the second code with not all.
Basically, your first code is "∃ x: 10 > x and ∃ x: 35 < x", while your second is ∃x: (10 > x and x < 35). You're turning "or" into "and". Using logic rules, we can do the following:
∃ x: 10 > x or ∃ x: 35 < x ≡
not (∀ x: 10 > x) or not (∀ x: 35 < x) ≡
not ((∀ x: 10 > x) and (∀ x: 35 < x)) ≡
not ((∀ x: 10 > x and 35 < x))
You could also do min(GtimeList) < 10 or max(GtimeList) > 35.
And as a side note regarding your isinstance(x, str) check, it's generally a better idea to check whether everything is what you want it to be, rather than it isn't what you don't want it to be. What if x is something other than a string or a number, such as a list?
Related
Sorry for the horrible title - I'm new to python and I'm not sure how to describe my question. So the question asks:
x plus 100 is a perfect square number, plus another 168 is also a perfect square number. Find x.
And here's my answer:
from math import sqrt
for x in range(-100,10000):
a=int(sqrt(x+100))
b=int(sqrt(x+100+168))
if (a*a!=x+100) or (b*b!=x+100+168):
continue
else:
print(x)
The problem is, I don't actually know the range. I only know that the number can't be smaller than -100, but the 10000 is only a random large number that I put in there. Is there a way for me to figure out a smaller range first? Or a way that I could make this faster?
If you want every solution in the range, this is a faster solution
for x in range(-100,10000):
if ((x+100)**.5).is_integer():
if ((x+268)**.5).is_integer():
print(x)
If only the first solution is required, you can add a break after the print statement.
There is an easily ascertainable upper bound to your problem: after a couple of numbers, the difference between perfect squares is much larger than 168. (Take a look at 100^2 and 101^2. The results are perfect squares about 200 apart. With this your number will be no larger than 10,000).
If you would like to speed up your problem, rather than checking if a number is square, you can check if by squaring numbers you can achieve a solution.
for x in range(0,100):
y=x
while y**2 - x**2 < 169 and y < 100:
y+=1
if y**2 - x**2 == 168:
print("Your number is: " + str(x**2 - 100))
Edit: code was broken, fixed. Running this gives you -99 (-99 + 100 is 1, is a perfect square, 1 + 168 is 169, which is 13^2), 21, 261, and 1581
Since the prompt assumes only one correct value of x, then there is no need to use a for loop, as we can just loop indefinitely using a while and no upper bound is known.
To check if the result of an operation is a whole number, we can check if the float and integer representation of the number are equal, i.e. int(num) == num.
>>> i = 1
>>> while True:
a, b = (i+100)**0.5, (i+268)**0.5
if int(a) == a and int(b) == b:
break
i += 1
>>> i
21
And if we check the quality of the result obtained, both results are whole numbers:
>>> (i+100)**0.5
11.0
>>> (i+268)**0.5
17.0
I am working on a new project, it is like a math site. I am trying to create a program that will solve equations.
It is working normally with simple equations for example x + 10 = 12, however when I try to do equations with exponents like x**2 + 3 = 5 it doesn't give me anything. I believe that this python code doesn't work with decimals.
Code in below
import math
def solve():
x = -1000
while x < 1001:
if x**2 + 1 == 4:
print("x = " + str(x))
x += 1
solve()
I expect the output to be 1.73205080757 and -1.73205080757.
However I get nothing (Because it couldn't find an answer).
You're expecting an answer that's between 1 & 2. You're starting at -1000 and incrementing by 1. So you'll go from -1000 to 0 to 1 to 2 to 3....skipping over your expected answer altogether.
You should be using something like: https://en.wikipedia.org/wiki/Newton%27s_method
(With floats i.e x=1.0)
Looking at your code, your minimal step is 1 (x was increased by x += 1), hence x can be only integer. There is no such integer can full-fill your condition x**2 + 1 == 4
this will only check integer values from x = - 1000 to x = 1000, ie it will ask is -1000 the answer? No, is -999 the answer? No etc, and never try 1.7 or 1.73 or 1.73...! The answer is a float not an integer, so the method as written can't possibly get it. You would need somehow to iterate closer and closer answers. This is a question of mathematical algorithm design I think, you can first look up math formulae how to approximate quadratic solutions (probably some 17th century mathematician did the formula!), then try convert this formula into Python. If you don't know about float, int, "duck typing" in Python difference, try googling this also may help you.
The code doesn't give nor will give the solution you expect because of two reasons:
The while loop increments x by 1 at each step, so there is no way x can be a float number. It will always be an integer.
The solution you expect for this case has infinite decimals, so even if x were a float, it could never be the desired value in order to solve the equation.
As a remark/suggestion, if you are trying to solve an equation in python, why don't you just create a function that give the result to an equation of the form: x^2 +a = b. The following code should be an example:
import numpy as np
def solve_prueba(a,b):
"""
The function solves a function of the form x^2 + a = b
"""
x = np.sqrt((b-a))
return x
This way is much more time effective rather than create a while loop has to pass over all the numbers with their infinite decimals to give the solution to a given equation.
Good luck!
It is not necessary to start at -1000 and go up to 1000 since you are looking for a value from 1 to 2. In your code, you increment with 1, which means that x will never be a decimal value. You could however increment with a very small number (e.g.) x += 0.0000000000001.
If you use this small increment, you should probably use math.isclose() instead of ==, because small float values tend to have some precision error. Like in your expected answer where you expect the outcome to be 1.73205080757 altough 1.73205080757**2 + 1 == 4.000000000003889 and not 4.
Using math.isclose((x**2 + 3), 4, rel_tol=1e-9) like this, it checks if the calculation from x**2 + 3 is somewhere close to 4 with a tolerance of 1e-9, which would output the values that you expect from this equation.
So for your code:
import math
def solve():
x = -1000
while x < 1001:
if math.isclose((x**2 + 1), 4, rel_rol=1e-9):
print("x = " + str(x))
x += 0.0000000000001
solve()
Hi I want to make an app that will be raise X to a power until it reaches Y.
I have for now something like this
x = 10
y = 1000000
while x <= y:
x = x**x
print(x)
I don't want it in function.
I know that probably this is simple, but I just started learning Python :)
This might be what you are looking for. In python you want to use the operators for math as such += , -=, *=, /= for same variable operations.
counter = 10
while counter <= 1000000:
counter *= counter
print(counter)
101010… (x) will never be equal to 106 (y) because 1010 is four orders of magnitude larger. Your program will interpret x = 10 as less than 106, execute xx (1010), interpret this value as greater than 106, exit the loop, and print x (now 1010).
I don't think this is what you're trying to do; please consider the comments other users have left. I have a hunch you're looking for xn=y (10 * 10 * 10 …), for which you could simply use logarithms.
When using this code:
while str.find(target,key,n) != -1 and <= len(target):
I get a syntax error on 'less than or equal to sign'. Why?
In English we can say "if X is not equal to Y and also less than Z", but Python syntax doesn't work that way.
If you want to compare a number to two other numbers, you have to repeat the original number in the second comparison.
i.e., instead of this:
if x != y and < z:
you must do this:
if x != y and x < z:
If you want to use the double operand, you could rewrite it like:
if -1 < target.find(key, n) < len(target):
pass
But that said, I don’t think find can ever return a value larger than the length of target.
The calculation of the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
The following program returns the integer part of the root
def radice(x):
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
return z
z += 1
radice(17) // 4
Will be possible to write it without using functions and break?
Here is my code witout function but I dont' know how to write the same algo with no break
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
break
z += 1
print 'The integer part of the root is: ', z
This should suffice:
>>> int(17**0.5)
4
17**0.5 generates the square root of 17, and int basically removes the decimals, leaving you with the "integer part of the root".
Without using any functions, and if you want an integer result, complex code (like your own) is needed. However, if a float will do, then you could try this:
>>> (17**0.5)//1
4.0
This essentially does the same as the int call, but will return a float if either side is a float.
As you said the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
Said that you can write the code without using function and break statements; here is the code:
n = input("insert a number: ")
r = 1
while (r * r <= n):
r = r + 1
print "the result is:", r -1
Parens are for clarity, not required
>>> (17**.5)-(17**.5)%1
4.0
Ok, let's think logically.
You cannot use break, so the only way to get out of the while loop is to break its condition.
If it's True, it cannot be broken, so we have to think about the proper condition to stop iterating. And this condition is already used in your algorithm: you exit when t > x, or z * z > x. So the condition to continue iteration should be the opposite, i.e. z * z <= x. And we have this simple solution.
x = 17
z = 0
while z * z <= x:
z += 1
print 'The integer part of the root is: ', z - 1
As a general rule, try to shy away from those while True: loops. While they are sometimes useful, they're generally harder to read and understand, this is probably why your teacher limits the use of break. The function was prohibited probably because return is just another way of escaping the loop. But those are exceptional: the normal way to end a loop is to break its condition, so this is how it should be written.