Why is 0^1 = 1 in Python? [duplicate] - python

This question already has answers here:
What does the caret (^) operator do?
(5 answers)
Closed 25 days ago.
I was looking at a problem solution in Python where the only number without a pair in an array is returned. The solution is below :
def solution(A):
n = len(A)
if A is None or n == 0:
return 0
if n == 1:
return A[0]
result = 0
for i in range(0, n):
result ^= A[i]
return result
How is the loop logic returning back the unique number?

The ^ operator in python is the XOR operator
and what it means is that for each a,b:
a^b = a'b + b'a
and in truth table it looks like this:
a
b
a^b
0
0
0
0
1
1
1
0
1
1
1
0

Related

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

Python - Number of occurrence of an event [duplicate]

This question already has answers here:
Numpy mask to count number of elements satisfying a condition
(3 answers)
Closed 3 years ago.
I have an array as follow:
a = [1 2 5 3 8 7 2 9 8]
and a constant number b=4
How can I count the occurrence c of a being inferior to b?
So in this example c=4
Using numpy:
np.sum(a < 4)
Or a sum on generator:
sum(num < 4 for num in a)
If you mean "less than" by "inferior", you can use a list comprehension
c = len([x for x in a if x < b])
If you're worried about space constraints, you can use a generator like Alexander's answer.
sum(1 if num < b else 0 for num in a)

How to print i till its less than k while k is decreasing every iteration? [duplicate]

This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 3 years ago.
I want to print i and k till i is less than or equal to k.
in C++ the code can be given as:
for(i=0;i<k;i++){
cout<<i<<k;
k--;
}
I am not getting the correct output.
this is my code
k=5
for i in range(k):
print(i,k)
k-=1
the output i get is:
0 5
1 4
2 3
3 2
4 1
but i want to get:
0 5
1 4
2 3
is there someway to use the range() function for this?
For loops in Python are really for-each and suboptimal for your needs. Use while instead:
i = 0; k = 5
while i < k:
print(i,k)
i += 1
k -= 1
k=5
for i in range(k):
print(i,k)
if k<=i:
break
k-=1

Is there a way to write a recursive function that looks through all the integers in a list and sees if any two are equal to a negative sum?

So the problem is, you have a list of integers and you have to find if any two in the list sum to a negative.
right now I have this
def negsum(L):
if len(L) <= 2:
if L[0] + L[1] >= -1: #Here is my base case
return False
else:
return True
else:
if L[0] + L[1] <= -1:
return True
else:
return negsum(L[1:]) #Recursive portion
The issue with my code is it only checks the first 2 in the list. So in a list
[-10, 15, 30, -5] you get False when it should be true, because -5 + -10 is a negative sum. My function only checks:
-10 + 15
15 + 30
30 - 5
How can I get it so that it checks -10 + 30, -10 -5 and 15-5 using recursion?
Edit, I forgot to mention, only len() [] and : operators are allowed. No loops. Is this even possible without loops?
Here is one way to do it:
def negsum(L):
if len(L)<2: return False
if len(L) == 2:
if sum(L)<0: return True
else: return False
for i,elem in enumerate(L):
if elem < 0:
return negsum(L[i+1:]+[elem])
Output:
In [39]: negsum([1,2,3,4,5])
Out[39]: False
In [40]: negsum([-1,2,3,4,5])
Out[40]: False
In [41]: negsum([-1,2,3,-4,5])
Out[41]: True
The idea is to divide the list intwo parts: the first element L[0] and the rest L[1:] and apply the function recursively to the L[1:] part:
def negsum(L):
if len(L) == 2: # base case
return True if L[0] + L[1] < 0 else False
elif negsum(L[1:]): # recursion on the L[1:] part
return True
else: # check L[1:] part pairwise against the first element
return any(x + L[0]<0 for x in L[1:])
Here's a solution without loops (implicit or explicit):
def negsum(lst, sub=True):
return len(lst) > 1 \
and ((lst[0] + lst[1]) < 0
or negsum([lst[0]]+lst[2:], False)
or (sub and negsum(lst[1:])))
or, alternatively, the following version separates the process more cleanly into 2 sub-functions and doesn't need the additional parameter 'sub':
def negsum(lst):
def first_with_others(lst): # compare lst[0] with all later values
if len(lst) > 1:
#print("summing", lst[0], "and", lst[1])
return ((lst[0] + lst[1]) < 0) or first_with_others([lst[0]]+lst[2:])
def drop_first(lst): # successively drop first element
if lst:
return first_with_others(lst) or drop_first(lst[1:])
return drop_first(lst) or False # converts None to False
Uncommenting the call to the print function shows which sums are calculated:
>>> negsum([1,2,3,4,5])
summing 1 and 2
summing 1 and 3
summing 1 and 4
summing 1 and 5
summing 2 and 3
summing 2 and 4
summing 2 and 5
summing 3 and 4
summing 3 and 5
summing 4 and 5
False
>>> negsum([-1,2,3,4,5])
summing -1 and 2
summing -1 and 3
summing -1 and 4
summing -1 and 5
summing 2 and 3
summing 2 and 4
summing 2 and 5
summing 3 and 4
summing 3 and 5
summing 4 and 5
False
>>> negsum([-1,2,3,-4,5])
summing -1 and 2
summing -1 and 3
summing -1 and -4
True
>>> negsum([-2,1])
summing -2 and 1
True

What exactly does this mean in Python? [duplicate]

This question already has answers here:
What is the result of % in Python?
(20 answers)
Closed 9 years ago.
I was working on a project Euler problem and found this code online:
a = 1
b = 2
s = 0
while b <= 4000000:
if not b % 2:
s += b
a, b = b, a + b
print s
I am not entirely sure what if not b % 2: means and was wondering if someone would mind shedding some light on it for me.
From the docs:
The % (modulo) operator yields the remainder from the division of the first argument by the second.
e.g. 5/2 == 2.5 # or 2 remainder 1, 5%2 == 1
The only time a % operation will come out to 0 (which satisfies not x%y) is if it's evenly divisible. In other words, 4 % 2 == 0 because 2 divides 4 evenly.
In your code, it's saying:
while b is less than 4,000,000:
if b is even:
set s equal to s+b
The modulo % operator returns the remainder of the division of b per 2 (in your case).
So if not b % 2 is the same meaning that if b % 2 == 0: it checks if the number is even.
b % 2 is the remainder after dividing by 2. So it will be 1 if b is odd, or 0 otherwise.
if not b % 2 can thus be translated to "if b is even"
Python interprets the value 1 as True and 0 as False:
>>> 1 == True
True
>>> 0 == True
False
The modulo operation x % y returns the remainder when x is divided by y. Therefore b % 2 will be 0 when b is even, and 1 when b is odd.
Combining all this together, the statement if not b % 2: corresponds to "if b is even".
It's just a cute way of writing if b%2==0. The not operator when passed 0 will return True, and False given anything else.

Categories

Resources