list comprehension with double if condition - python-3.x

I have x = [None, 2, None] or x = None and I want to check if there is any value in a list which is greater than 1. My solution is
z = any(value > 1 for value in x if x is not None and value is not None)
and it works but only when the x is not None. Why this if x is not None is not used?

Use a ternary statement outside the generator
z = any(value > 1 for value in x if value is not None) if x is not None else False

Related

Why is the function returning value of stack as None

I'm not able to figure out why the path variable on last line of the code is being printed out as None. As you can see the second last line of the code is calling the DFS function to find the path between two nodes in a tree (I'm giving a tree as input). I've printed out the value of the stack also before returning it to make sure that it is not None and while being printed inside DFS function it is not None. But I'm not able to understand why it is None when it is returned and stored in path variable. I gave this as input
1
6 1
4 2 1 3 5 2
1 2
2 3
2 4
1 5
5 6
And the out put came as
{0: [1, 4], 1: [0, 2, 3], 2: [1], 3: [1], 4: [0, 5], 5: [4]}
[0, 1, 3]
None
Here is the code for reference
def DFS(adj,x, y,stack,vis):
stack.append(x)
if (x == y):
print(stack)
return stack
vis[x] = 1
if (len(adj[x])>0):
for j in adj[x]:
if (vis[j]==0):
DFS(adj,j,y,stack,vis)
del stack[-1]
T = int(input())
for a in range(T):
N,Q = input().split()
N = int(N)
Q = int(Q)
wt = [int(num) for num in input().split(" ")]
adj = {}
for i in range(N):
adj[i] = []
for b in range(N-1):
u,v = input().split()
u = int(u) - 1
v = int(v) - 1
adj[u].append(v)
adj[v].append(u)
print(adj)
vis = [0]*N
stack = []
path = DFS(adj,0,3,stack,vis)
print(path)
Simple equivalent of your code:
def recursive_func(x):
if x > 0:
return x
else:
x += 1
recursive_func(x)
x = 5
x = recursive_func(x)
print(x)
x = 0
x = recursive_func(x)
print(x)
Output:
5
None
What's happening here?
x, with a value of 5 is sent to recursive_func.
x is greater than 0, so 5 is returned. This is seen in the output.
x, with a value of -5 is sent to recursive_func.
x is not greater than 0, so 1 is added to x.
x, with a value of 1, is then sent to a different recursive_func.
This recursive_func returns 1 because 1 > 0.
This response gets passed to the first recursive_func where the line recursive_func(x) becomes 1, but we don't do anything with it.
recursive_function hits the end of its code, without returning a value. By default None is returned to our main body.
x = recursive_func(x) has become x = None
None is output.
Given this information, why does the following code perform differently?
Simple modification of your code:
def recursive_func_v2(x):
if x > 0:
return x
else:
x += 1
return recursive_func_v2(x)
x = 5
x = recursive_func_v2(x)
print(x)
x = 0
x = recursive_func_v2(x)
print(x)
Output:
5
1

Comparing two methods to get the same array

np.random.seed(123456)
X = np.random.normal(0,1,1000)
Y = np.random.normal(0,1,1000)
Z = np.random.normal(0.5, 1.7,1000)
W = np.random.normal(0,1,1000)
stream_A = np.concatenate((X,Y,Z,W))
Then I am running the code below: Basically I need to create a iterator to feed one sample at a time to another function.
# 4 chunks of 1000 samples, so X,Y,W and Z arrays
n = 4
iter_array = iter(stream_A) # Size 4000
result = [[] for _ in range(n)]
for _ in itertools.repeat(None, 1000):
for i in range(n):
result[i].append(next(iter_array))
The problem is:
results[0] is a list with all elements of stream X defined above.
If a compare results[0] == X I get false
If I transform the list into np.array:
y=np.array([np.array(xi) for xi in result], dtype=object)
and then:
y[0] == X I also get false
Can someone help me why I am getting False?
And they are somehow not same because the results I am getting when I apply X to the function is not the same of them result when I apply y[0] to the same function.
Just stack them:
stream_A = np.stack((X,Y,Z,W))
stream_A.shape
# (4, 1000)
np.all(stream_A[0] == X)
# True

How to solve Equation without any Modules in Python?

I want to solve this equation without any Modules(NumPy, Sympy... etc.)
Px + Qy = W
(ex. 5x + 6y = 55)
Thanks.
It is a very crude way to do this, but you can use brute-force technique, as I said in comment under your question. It can probably be optimized a lot, gives only int outputs, but overall shows the method:
import numpy as np
# Provide the equation:
print("Provide a, b and c to evaluate in equation of form {ax + by - c = 0}")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
x_range = int(input("x-searching range (-a, a): "))
y_range = int(input("y-searching range (-b, b): "))
error = float(input("maximum accepted error from the exact solution: "))
x_range = np.arange(-x_range, x_range, 1)
y_range = np.arange(-y_range, y_range, 1)
for x in x_range:
for y in y_range:
if -error <= a * x + b * y - c <= error:
print("Got an absolute error of {} or less with numbers x = {} and y = {}.".format(error, x, y))
Example output for a = 1, b = 2, c = 3, x_range = 10, y_range = 10, error = 0.001:
Got an error of 0.001 or less with numbers x = -9 and y = 6.
Got an error of 0.001 or less with numbers x = -7 and y = 5.
Got an error of 0.001 or less with numbers x = -5 and y = 4.
Got an error of 0.001 or less with numbers x = -3 and y = 3.
Got an error of 0.001 or less with numbers x = -1 and y = 2.
Got an error of 0.001 or less with numbers x = 1 and y = 1.
Got an error of 0.001 or less with numbers x = 3 and y = 0.
Got an error of 0.001 or less with numbers x = 5 and y = -1.
Got an error of 0.001 or less with numbers x = 7 and y = -2.
Got an error of 0.001 or less with numbers x = 9 and y = -3.
I am using numpy, but not a built-in function to solve the equation itself, just to create an array. This can be done without it, of course.
There are thousands of ways to solve an equation with python.
One of those is:
def myfunc (x=None, y=None):
return ((55-6*y)/5.0) if y else ((55-5*x)/6.0)
print(myfunc(x=10)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42)) # OUTPUT: -39.4, x value for y == 42
You simply define inside a function the steps required to solve the equation.
In our example, if we have y value we subtract 6*y to 55 then we divide by 5.0 (we add .0 to have a float as result), otherwise (means we have x) we subtract 5*x from 55 and then we divide by 6.0
with the same principle, you can generalize:
def myfunc (x=None, y=None, P=None, Q=None, W=None):
if not W:
return P*x + Q*y
elif not x:
return (W-Q*y)/float(P)
elif not y:
return (W-P*x)/float(Q)
elif not P:
return (W-Q*y)/float(x)
elif not Q:
return (W-P*x)/float(y)
print(myfunc(x=10, P=5, Q=6, W=55)) # OUTPUT: 0.833333333333, y value for x == 10
print(myfunc(y=42, P=5, Q=6, W=55)) # OUTPUT: -39.4, x value for y == 42
check this QA for some other interesting ways to approach this problem

Perplexed over a simple function in Python

Look at the code below:
def foo (x):
print("foo environment: x = {0}".format(x))
def bar (z, x = 0):
print("bar environment: z = {0} and x = {1}. Value to be returned: {2}".format(z, x, x+z))
return z + x
return bar(3)
foo(5)
foo environment: x = 5
bar environment: z = 3 and x = 0. Value to be returned: 3
3
Since in the foo environment x = 5, why bar uses the value 0?
You are only passing one argument here:
return bar(3)
The bar function accepts two values, one z and one x (x has a default value (0) and that is why only 1 argument is enough). By only passing the z, x=0.
Try this, and see what happens:
return bar(3, x)

Get length of range in Python List Comprehension

I wonder if it is possible to get the length of the range in a list comprehension in python 3 in order to set up a conditional as such? this code doesn't work
b = [x**2 for x in range(10) if x % 2 == 0 and x > len/2]
>>> n = 10
>>> b = [x**2 for x in range(n) if x % 2 == 0 and x > n/2]
>>> b
[36, 64]

Resources