Python: "If" function - python

This is probably really simple but I can't figure it out.
I have a bunch of lists and I want to call certain lists if they are in the range equal to a value x and any number between x-5 and x +5. i.e. x-5,x-4,x-3,x-2,x-1,x,x+1,x+2,x+3,x+4 and x+5.
At the moment I have
if sum(listname[i])==x:
if sum(listname[i])==x-1:
if sum(listname[i])==x-2:
etc
How can I do it so that it is combined in one "if" function.
I've been thinking on the lines of something like:
if sum(listname[i])==x-5>=x>=x+5:
or
if sum(listname[i])==x or x-1 or x-2 ".. etc":
but neither work.
Can anybody shine some light on this?

A scenario like if sum(listname[i])==x or x-1 or x-2 ".. etc": (which is not valid python) is usually solved with if value in range(start, stop, step):
So you would write:
if sum(listname[i) in range(x-2, x):
# Code for this case here...

Do you simply mean
if x-5 <= sum(listname[i]) <= x+5:
...
...

It looks like you want to check if the sum of the list is between x - 5 and x + 5. To put it in one if statement is simply:
s = sum(listname[i])
if s >= x - 5 and s <= x + 5:
# do stuff

From what I understand from your question. You what to check that whether sum(listname[i]) is between (x-5, x+5)
You can do this in a single if assuming x is a possitive value:
if (sum(listname[i]) >= (x - 5)) and (sum(listname[i]) <= (x+5))

Related

How to create a while loop with tolerance

I'm trying to do some control engineering where I start with a certain value, for example, x = 5 and in the end, it should return x. The goal, in the end, is to find a value for x, where x (beginning) == x (end).
I was thinking about creating a while loop and just adding or subtracting a certain stepsize on x(beginning) till it reaches equilibrium. However, I want some tolerance in my while loop. Like x(beginning) ==x(end)+0.1 would also be fine.
I don't know how to create this in Python and I'm not sure whether this is even the right way to accomplish this
You could do something like this:
# in this example, x is the beginning value, y is the end value
x = 5
y = 10
tolerance = 0.1
while True:
if abs(y-x) <= tolerance:
break
# put your code here
x += 1 # or something else
I think what you are looking for is math.isclose(). With that you can specify both a relative and an absolute tolerance limit.
isclose(a, b, rel_tol=1e-9, abs_tol=0.0)

Python While Loop Square

I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.

Python sorting arrays to get two digit values

I have an array A = [1 - 100] and I need to find the sum of all the two digit values in this array. How would I approach this? I have tried :
def solution(A):
A =array[0-100])
while A > 9 & A < 99
total = sum(A)
print "%s" % total
)
Is there a function that given an array consisting of N integers returns the sum of all two digit numbers i.e A = [1,1000,80, -91] the function should return -11(as the two are 80 and -91). not a range, multiple array
You can use a list comprehension and check if the length of the string-format is equal to 2, like so:
sum([x if len(str(x))==2 else 0 for x in xrange(1,101)])
Use the keyword and rather than the bitwise &.
Edit: a fuller answer, as that's not the only thing wrong:
def solution():
A = range(101)
total = sum([a for a in A if 9 < a <= 99])
print total
This uses list comprehension and chained inequalities, so is pretty 'pythonic'.
There is tons of errors in your code, please next time before posting,spend some time try to figure it out yourself and be sure that your code at lest doesn't contain any obvious syntax error.
By array, I assume you're talking about a list. And change it to range(101) for every number from 0 to 100
def solution(A):
return sum([x for x in range(A) if len(str(abs(x))) == 2])
print(solution(101))
As a side note, use and instead of & since that's a bitwise-or sign.
Here are a couple of ways to go about the problem, the first is most similar to the approach you appear to be trying:
def solution1(array):
total = 0
for a in array:
if 9 < a < 100:
total += a
return total
print(solution1(range(101)))
And here's a more compact solution using a comprehension (actually, a generator expression):
def solution2(array):
return sum(a for a in array if 9 < a < 100)
print(solution2(range(101)))
Note that in your original you're confusing loops and conditionals.

min() arg is an empty sequence

I'm trying to find minimum element in matrix row, but there are two conditions:
1) it must be > 0
2) and this point must be not visited(is_visited[k] is False)
I'm trying to do next:
min(x for x in matr_sum[i] if x > 0 if is_visited[k] is False )
But there is an error: min() arg is an empty sequence
The full block of code:
for k in range(4):
if matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0 if is_visited[k] is False ) and i!=k:
return k
How to resolve it? Or should I write my min() function? Because it works with one condition:
min(x for x in matr_sum[i] if x > 0)
But with two conditions, it doesn't work.
If you want to avoid this ValueError in general, you can set a default argument to min(), that will be returned in case of an empty list. See described here.
min([], default="EMPTY")
# returns EMPTY
Note that this only works in Python 3.4+
There is no problem with the syntax. It's certainly unusual to have two if clauses, but it's allowed. Consider:
print(min(x for x in range(1,300) if x % 3 == 0 if x % 5 == 0))
Output:
15
However:
print(min(x for x in range(1,300) if x % 2 != 0 if x % 2 != 1))
Output:
ValueError: min() arg is an empty sequence
There are no integers that are both odd and even, so there are no values for min to see, so it throws an exception.
I deduce that in your code, there are no values that pass both conditions. Python doesn't allow you to compute "the minimum of no values", mainly because it makes no sense.
You have to decide what you want to do in the case where there is no minimum because there are no values greater than 0. For example, if you don't want to return k in that case then I might re-write your code something like this:
for k in range(4):
if k != i and is_visited[k] is False:
if matr_sum[i][k] > 0 and matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0):
return k
It might not be obvious why this helps, but assuming matr_sum[i] is a list or similar, then once we know matr_sum[i][k] > 0 then we know the generator passed to min isn't empty, so we won't get an exception. Whereas if matr_sum[i][k] <= 0, then it certainly isn't equal to the smallest positive value, so there's no need to compute the min at all. Another way to write that would be:
if matr_sum[i][k] > 0 and not any(0 < x < matr_sum[i][k] for x in matr_sum[i])
Actually, I'd normally write if not is_visited[k], but I leave it as is False since I don't know whether changing it would change the behaviour of your code.
Try this - it creates the list of x values xs and then only tries to find the min if xs is non-empty. You may need to add some logic to handle the case that xs is empty, depending on what your code is doing.
for k in range(4):
if is_visited[k] is False and i != k:
xs = [x for x in matr_sum[i] if x > 0]
if xs and matr_sum[i][k] == min(xs):
return k
Just use and operation for concatenate tow if statement :
min(x for x in matr_sum[i] if x > 0 and if is_visited[k] is False and i!=k)

Include upper bound in range()

How can I include the upper bound in range() function? I can't add by 1 because my for-loop looks like:
for x in range(1,math.floor(math.sqrt(x))):
y = math.sqrt(n - x * x)
But as I understand it will actually be 1 < x < M where I need 1 < x <= M Adding 1 will completely change the result.
I am trying to rewrite my old program from C# to Python. That's how it looked in C#:
for (int x = 1; x <= Math.Floor(Math.Sqrt(n)); x++)
double y = Math.Sqrt(n - x * x);
Just add one to the second argument of your range function:
range(1,math.floor(math.sqrt(x))+1)
You could also use this:
range(math.floor(math.sqrt(x)))
and then add one inside your loop. The former will be faster, however.
As an additional note, unless you're working with Python 3, you should be using xrange instead of range, for idiom/efficiency. More idiomatically, you could also call int instead of math.floor.
Why exactly can't you simply add one to the upper bound of your range call?
Also, it seems like you want to refer to n in your first line, i.e.:
for x in range(1,math.floor(math.sqrt(n)) + 1):
...assuming you want to have the same behavior as your C# snippet.

Categories

Resources