Related
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
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
For example, I have 2 lists:
list1 = [6,6,6,6,6,6,6]
list2 = [0,2,4]
If there are the same indexes in the list1 and list2, I need to remove these indexes from the list1, because I should sum the unique indexes from the list1, for example:
a = [1,2,3,4,5]
b = [0,2,4]
x = [a.index(i) for i in a]
y = [b.index(j) for j in b]
for idx in y:
if idx in x:
x.remove(idx)
print(sum(x))
printed is >> 7
I tried this but did not work if there are the same values in list1
a = [6,6,6,6,6,6,6]
b = [0,2,4]
x = [a.index(i) for i in a]
y = [b.index(j) for j in b]
for idx in y:
if idx in x:
x.remove(idx)
printed is >> 0
Indexes and values are different. There will never be the same index twice in one list. You get their index by their value, however index(value) function gives you the first index which matches your value. Have a look at:
a, b, x = [1,2,3,4,5,6,7], [1,2,3], 0
c, d = len(a), len(b)
if d < c:
d, c = len(a), len(b)
for i in range(c, d):
x += i
print(x)
Your question is not very clear, so here are two answers:
If you want to sum the elements from the first list that do not appear in the second list, here is a way to do it:
a = [1,2,3,4,5]
b = [0,2,4]
# We create a set in order to have O(1) operations to check if an element is in b
b_set = set(b)
# We sum on the values of a that are not in b
res = sum(x for x in a if x not in b_set)
print(res)
>>> 9
If you want to sum the elements of the first list that do not have their rank/index in the second list, a way to do that could be:
a = [1,2,3,4,5]
b = [0,2,4]
# We create a set in order to have O(1) operations to check if an element is in b
b_set = set(b)
# We sum on the values of a that don't have their rank/index in b
res = sum(x for (i, x) in enumerate(a) if i not in b_set)
print(res)
>>> 6
b = [3,2,6]
hid = []
#print(b[0] * b[1])
#print(b[1] * b[2])
#print(b[2] * b[3])
for n in range(len(b)):
print(b[n-1] * b[n])
The result I am expecting is
6, 12
But I am getting
18, 6, 12
Where is the mistake?
range(len(b)) which evaluate as (0,1,2)
so b[n-1] is b[-1] which is 6 so (6 * 3) =18 it give result
18, 6, 12
try This one:
for n in range(len(b)-1):
print(b[n] * b[n+1])
Your list has three elements only, so there's no b[3], what you're trying to achieve (multiplying combinations of size 2) can be done using two nested loops:
b = [3, 2, 6]
for i in range(len(b) - 1):
for j in range(i + 1, len(b)):
print(b[i] * b[j])
Output:
6
18
12
However, a more Pythonic way would be to use itertools.combinations:
b = [3, 2, 6]
from itertools import combinations
for x, y in combinations(b, 2):
print(x * y)
Output:
6
18
12
for n in range(len(b)):
print(b[n-1] * b[n])
in first iteration when n =0 you have:
print(b[n-1] * b[n])
what means:
print(b[0-1] * b[0])
b[0-1] will gave you last element in the list, because of that you have
6*3 = 18
you should do it:
b = [3,2,6]
hid = []
for n in range(1,len(b)):
print(b[n-1] * b[n])
range(3) will generate numbers from 0 to 2 (3 numbers). You can also
define the start, stop and step size as range(start,stop,step size).
step size defaults to 1 if not provided.
or
b = [3,2,6]
hid = []
for n in range(len(b)-1):
print(b[n] * b[n+1])
output:
6
12
In a for loop, the iteration starts at zero
for n in range(len(b)):
print(b[n-1] * b[n]) doing "n-1" means b[-1] which is last element of your list "6" and this with b[n] which b[0] is 18.
So, your code translates to :
print b[-1]*b[0]
print b[0]*b[1]
print b[1]*b[2]
Correct way to code this would be :
#!/usr/bin/python
b = [3,2,6]
i = 0
while i < len(b)-1:
print b[i]*b[i+1]
i+=1
Output:
6
12
I am new to python and was trying to find a way to organize a specific function so I can take a list, apply special criteria to it, and then return another list.
I want to:
1) square a number if it is even
2) cube a number if it is odd
3) and then store those results in a list and return that list
Here is my code:
def square_function(x):
if i % 2 == 0:
x = [i ** (2)]
else:
y = [i ** (3)]
func = [x, y]
return func
I am very new to programming with python so any help you can give would be fantastic.
take a list - apply special criteria to it - and then return another list.
You're looking for the map() function
def foo(x):
return x**2 if x%2==0 else x**3
l = [1,2,3]
I = list(map(foo, l))
Using list comprehension:
>>> a = [1,2,3,4,5]
>>> [x ** 2 if x % 2 == 0 else x ** 3 for x in a]
[1, 4, 27, 16, 125]
I think that this could be what you are looking for:
from math import sqrt
def square_or_cube_function(x):
result = []
for i in x:
if i % 2 == 0:
result.append(sqrt(i))
else:
result.append(i ** 3)
return result
print(square_or_cube_function([1, 4, 5, 8]))
print(square_or_cube_function([5, 7, 16, 32]))
OUTPUT:
[1, 2.0, 125, 2.8284271247461903]
[125, 343, 4.0, 5.656854249492381]
A shorter solution could be:
from math import sqrt
def square_or_cube_function(x):
return [sqrt(i) if i % 2 == 0 else i **3 for i in x]
print(square_or_cube_function([1, 4, 5, 8]))
print(square_or_cube_function([5, 7, 16, 32]))
Same output.
Another LC solution, but using a bit of cleverness:
[x ** (x % 2 + 2) for x in L]