how to use bitwise operator in python? - python

Description:
Input a list of numbers “num_list”.
All numbers in the list occur even times expect one number which occurs odd number of times. Find the number that occurs odd number of time in O(1) space complexity and O(n) time complexity.
Note: Use Bitwise operator.
Sample Input:
1 2 2 5 5 1 3 9 3 9 6 4 4
What I tried:
def getOddOccurrence(arr, arr_size):
for i in range(0, arr_size):
count = 0
for j in range(0, arr_size):
if arr[i] == arr[j]:
count += 1
if (count % 2 != 0):
return arr[i]
return -1# driver code
arr = [1, 2, 2, 5, 5, 1, 3, 9, 3, 9, 6, 4, 4]
n = len(arr)
print(getOddOccurrence(arr, n))

Bitwise operations consists of multiple operations like AND, OR, XOR... and so on. The one you are looking for is called XOR.
XOR of number with same number is 0. So if you XOR all elements in your array, all elements occurring even number of times cancel each other out. And you are left with with the number that occurred odd number of times.
Time Complexity: O(N)
Space Complexity: O(1)
def getOddOccurrence(arr, arr_size):
if len(arr) == 0:
return -1
xor = arr[0]
for i in range(1, arr_size):
xor = xor ^ arr[i]
return xor
arr = [1,2,2,5,5,1,3,9,3,9,6,4,4 ]
n = len(arr)
print(getOddOccurrence(arr, n))

Related

Finding number from list that respects conditions

I need to code a script that chooses a number from a user input (list) depending on two conditions:
Is a multiple of 3
Is the smallest of all numbers
Here is what I've done so far
if a % 3 == 0 and a < b:
print (a)
a = int(input())
r = list(map(int, input().split()))
result(a, r)
The problem is I need to create a loop that keeps verifying these conditions for the (x) number of inputs.
It looks like you want a to be values within r rather than its own input. Here's an example of iterating through r and checking which numbers are multiples of 3, and of finding the minimum of all the numbers (not necessarily only those which are multiples of 3):
r = list(map(int, input().split()))
for a in r:
if a % 3 == 0:
print(f"Multiple of 3: {a}")
print(f"Smallest of numbers: {min(r)}")
1 2 3 4 5 6 7 8 9 0
Multiple of 3: 3
Multiple of 3: 6
Multiple of 3: 9
Multiple of 3: 0
Smallest of numbers: 0
Doing this in one line – or through generators – can improve performance through optimizing memory allocation:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The following is a generator
# Also: you need to decide if you want 0 to be included
all_threes = (x for x in my_list if x%3==0)
min_number = min(my_list)

How to find how many values are divisible in to certain value in 2d array in python

The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1

Google Kickstart Round E 2020 Longest Arithmetic Runtime Error

I tried solving this challenge mentioned below but I got a Run Time error. I used Python
Problem
An arithmetic array is an array that contains at least two integers and the differences between consecutive integers are equal. For example, [9, 10], [3, 3, 3], and [9, 7, 5, 3] are arithmetic arrays, while [1, 3, 3, 7], [2, 1, 2], and [1, 2, 4] are not arithmetic arrays.
Sarasvati has an array of N non-negative integers. The i-th integer of the array is Ai. She wants to choose a contiguous arithmetic subarray from her array that has the maximum length. Please help her to determine the length of the longest contiguous arithmetic subarray.
Input:
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Ai.
Output:
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the length of the longest contiguous arithmetic subarray.
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
0 ≤ Ai ≤ 109.
Test Set 1
2 ≤ N ≤ 2000.
Test Set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 2000.
Sample Input
4
7
10 7 4 6 8 10 11
4
9 7 5 3
9
5 5 4 5 5 5 4 5 6
10
5 4 3 2 1 2 3 4 5 6
Output
Case #1: 4
Case #2: 4
Case #3: 3
Case #4: 6
Here's my python3 solution which gives run time error
t = int(input())
for t_case in range(t):
n = int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print(f"Case #{t_case+1}: {ans+1}")
Could anyone please help me out.
As of now Kickstart is using Python 3.5 which does not support f-strings (they were added in py3.6). Try to replace them with str.format.
t=int(input())
for test in range(t):
n=int(input())
arr = list(map(int, input().split()))
x = []
for i in range(n - 1) :
x.append((arr[i] - arr[i + 1]))
ans, temp = 1, 1
j = len(x)
for i in range(1,j):
if x[i] == x[i - 1]:
temp = temp + 1
else:
ans = max(ans, temp)
temp = 1
ans = max(ans, temp)
print('Case #{0}: {1}'.format(test+1,ans+1))

Minimum turn required to modify given array to make it increasing [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
You are given an array of n integers. You want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element.
On each turn, you may increase the value of any element by one. What is the minimum number of turns required?
Example:
Input = 3 2 5 1 7
Output = 5
steps:
1 => 3 2+1 5 1 7
2 => 3 3 5 1+1 7
3 => 3 3 5 2+1 7
4 => 3 3 5 3+1 7
5 => 3 3 5 4+1 7
So it will take 5 turns to make this array increasing.
My approch in Python:
def makeIncreasingArray(arr, count=1):
temp = []
for i in range(1, len(arr)):
if arr[i] >= arr[i - 1]:
temp.append(True)
else:
arr[i] += 1
temp.append(False)
if sum(temp) == len(arr) - 1:
return count
else:
count += 1
return makeIncreasingArray(arr, count)
It's working but I think this one is more like bruteforce solution.
How can I make this code better?
Your approach is to keep adding 1 to each element that’s smaller than the one preceding it until the array is increasing.
Think about the first element that’s too small. You’ll keep adding 1 to it until it’s equal to the number before it. Because nothing is changing before this element (it’s the first element that’s wrong), once it’s equal to the number before it, it’ll never need to change again. So you can do all the steps at once (let’s say that i is the index of this first wrong element):
while arr[i] < arr[i - 1]:
arr[i] += 1
count += 1
Maybe with this smaller example, it’ll be clearer that this can be done without a loop (i.e. much faster):
if arr[i] < arr[i - 1]:
count += arr[i - 1] - arr[i]
arr[i] = arr[i - 1]
And since this does nothing on elements that are not wrong, all you need to do now is apply it to every element in order:
def make_increasing_array(arr):
count = 0
for i in range(1, len(arr)):
if arr[i] < arr[i - 1]:
count += arr[i - 1] - arr[i]
arr[i] = arr[i - 1]
return count
Finally, there’s no need to alter the input if you keep track of arr[i - 1] separately:
def make_increasing_array(arr):
if not arr:
return 0
count = 0
last = arr[0]
for i in range(1, len(arr)):
if arr[i] < last:
count += last - arr[i]
else:
last = arr[i]
return count
If you don't mind using NumPy, you can implement this as (np.maximum.accumulate(arr) - arr).sum().
E.g.
import numpy as np
def count_turns(x):
return (np.maximum.accumulate(x) - x).sum()
In action,
In [18]: x = [3, 2, 5, 1, 7]
In [19]: count_turns(x)
Out[19]: 5
If you want to stick with "pure" Python, you can do the same thing, with a little help from itertools.accumulate to replace np.maximum.accumulate. For example,
In [22]: from itertools import accumulate
In [23]: x = [3, 2, 5, 1, 7]
In [24]: list(accumulate(x, max))
Out[24]: [3, 3, 5, 5, 7]
Then the element-wise subtraction can be implemented using zip and a list comprehension:
In [25]: [cmax - t for cmax, t in zip(accumulate(x, max), x)]
Out[25]: [0, 1, 0, 4, 0]
Finally, the number of turns is the sum of those differences:
In [26]: sum(cmax - t for cmax, t in zip(accumulate(x, max), x))
Out[26]: 5
Putting that into a function gives
from itertools import accumulate
def count_turns(x):
return sum(cmax - t for cmax, t in zip(accumulate(x, max), x))

python: algorithm for swapping elements between two arrays

I am analyzing counting example in python presented by Codility
I don't understand the logic used in the last loop (5 last rows) of this algorithm.
Can anybody help please?
The problem:
You are given an integer m (1 < m < 1000000) and two non-empty,
zero-indexed arrays A and B of n integers, a0, a1, ... ,
an−1 and b0, b1, ... , bn−1 respectively (0 < ai, bi < m).
The goal is to check whether there is a swap operation which can be
performed on these arrays in such a way that the sum of elements in
array A equals the sum of elements in array B after the swap. By
swap operation we mean picking one element from array A and one
element from array B and exchanging them.
The solution:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m)
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
return True
return False
What I would recommend you is read again the explanations given in the exercise. It already explains what how the algorithm works. However, if you still have problems with it, then take a piece of paper, and some very simple example arrays and go through the solution step by step.
For example, let A = [6, 6, 1, 2, 3] and B = [1, 5, 3, 2, 1].
Now let's go through the algorithm.
I assume you understand how this method works:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
It just returns a list with counts as explained in the exercise. For list A and m = 10 it will return:
[0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0]
Then we go through the main method fast_solution(A, B, m):
n = 11 (this will be used in the loop)
The sum of A equals 18 and the sum of B equals 12.
The difference d is -6 (sum_b - sum_a), it is even. Note that if difference is odd, then no swap is available and the result is False.
Then d is divided by 2. It becomes -3.
For A we get count [0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0] (as already mentioned before).
Then we just iterate though the list B using xrange and check the conditions (The loop goes from 0 and up to but not including 11). Let's check it step by step:
i = 0, B[0] - (-3) is 1 + 3 = 4. 4 is greater than or equal to 0 and less than or equal to 10 (remember, we have chosen m to be 10). However, count[4] is 0 and it's not greater than 0 (Note the list count starts from index 0). The condition fails, we go further.
i = 1, B[1] - (-3) is 5 + 3 = 8. 8 is greater than or equal to 0 and less than or equal to 10. However, count[8] is 0 and the condition fails.
i = 2, B[2] - (-3) is 3 + 3 = 6. 6 is greater than 0 and less than 10. Also count[6] is 2 and it is greater than 0. So we found the number. The loop stops, True is returned. It means that there is such a number in B which can be swapped with a number in A, so that sum of A becomes equal to the sum of B. Indeed, if we swap 6 in A with 3 in B, then their sum become equal to 15.
Hope this helps.
I'm not sure I get your idea correctly. Here's my understanding:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count # this essentially build a counter
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m) # get the dict
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
# the first two conditions are to verify that B[i]-d exists as a key (index) in counter.
# then check if there actually exists the value.
# if count > 0, then you can swap the two to get same sum
return True
return False
Or rewriting to get:
def counting(A, m):
count = collections.Counter()
for i in A:
count[i] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m) # get the dict
for i in B:
if count[i-d]:
return True
return False
But in any case, this piece of code just check the solution existence with only single swap, be sure to check if that's what you wanted.

Categories