python get majority element using divide and conquer - python-3.x

your textHello can someone explain the code with sample 1 input(specially recursive call) . i am confused with these 2 recursive call lines,
left_maj = get_majority_element(a, left, mid)
right_maj = get_majority_element(a, mid, right)
Task. The goal in this code problem is to check whether an input sequence contains a majority element.
Input Format. The first line contains an integer 𝑛, the next one contains a sequence of 𝑛 non-negative
integers 𝑎0, 𝑎1, . . . , 𝑎𝑛−1.
Constraints. 1 ≤ 𝑛 ≤ 105
; 0 ≤ 𝑎𝑖 ≤ 109
for all 0 ≤ 𝑖 < 𝑛.
Output Format. Output 1 if the sequence contains an element that appears strictly more than 𝑛/2 times,
and 0 otherwise.
Sample 1.
Input:
5
2 3 9 2 2
Output:
1
2 is the majority element.
code :
import sys, math
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
mid = (left + right) // 2
half_element_count = (right - left) // 2
left_maj = get_majority_element(a, left, mid)
right_maj = get_majority_element(a, mid, right)
left_maj_count = get_element_count(a, left, right, left_maj)
if left_maj_count > half_element_count:
return left_maj
right_maj_count = get_element_count(a, left, right, right_maj)
if right_maj_count > half_element_count:
return right_maj
return -1
def get_element_count(a, left, right, x):
maj_count = 0
for i in range(left, right):
if a[i] == x:
maj_count += 1
return maj_count
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element(a, 0, n) != -1:
print(1)
else:
print(0)
i tried to debug using pdb but got confused during recursive call

Related

Python(AI Constraint satisfaction problem) Fitting square and/or rectangular (2d) tiles onto a rectangular ground

I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3

Directed Graph: How to find the longest path of Node A to N Considering the ff code:

I have considered using DFS for tracking the vertex for each edges present to find the longest path but the problem is it gives only the L input to it and the edge corresponding to it. I want to find the longest path traversed by these vertices as a alphabetically nondecreasing string and if the string playes indefenitely it outputs infinite. Here is my initial working code:
from collections import defaultdict
def DFS(G,v,seen=None, path=None):
if seen is None: seen = []
if path is None: path = [v]
seen.append(v)
paths =[]
for i in G[v]:
if i not in seen:
i_path = path + [i]
paths.append(tuple(i_path))
paths.extend(DFS(G, i, seen[:], i_path))
return paths
t = int(input())
i,j = 1,0
graph = defaultdict(list)
while i < t:
n, a = [int(i) for i in input().split()]
while j < a:
n1,n2,l = input().split()
graph[l].append(n1)
graph[l].append(n2)
j+= 1
print(graph)
print(DFS(graph, 'A'))
i+=1
i want to know where i did wrong or maybe i missed something essential since the given output for the sample input is:
INPUT:
1 // test case
5 7 // n, a
2 3 B
3 1 E
1 2 A
1 2 R
2 4 D
3 5 E
4 3 D
Expected : ADDER
ACTUAL: D, D

Unique Paths II

A robot is located at the top-left corner of a m x n grid.
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
class Solution:
"""
#param obstacleGrid: A list of lists of integers
#return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
if not obstacleGrid:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
li = [[0] * n] * m
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
li[i][j] = 0 ######## why do I have to add this line ???########
continue
elif i == 0 and j == 0:
li[i][j] = 1
elif i == 0:
li[i][j] = li[i][j - 1]
elif j == 0:
li[i][j] = li[i - 1][j]
else:
li[i][j] = li[i - 1][j] + li[i][j - 1]
return li[m - 1][n - 1]
The question is in the coding. I already set the matrix of m*n filling with zeros. Why should I assign the zero to the position one more time??? It seems that it won't work if I del that line. Can anyone tell me the reason why??? Thx!!!
The problem is this line:
li = [[0] * n] * m
The syntax [a] * n creates shallow copies, not deep copies of a.
Example:
n = m = 2
li[0][0] = 3
print(li) # prints [[3, 0], [3, 0]]
Link to question with discussion of possible solutions.

Knapsack algorithm, weird behavior (python3)

I have been working on recursion and tried to solve the Knapsack problem [https://en.wikipedia.org/wiki/Knapsack_problem]. I came up with the algorithm below which works just fine:
cost_array = [2,3,4,5,9]
value_array = [3,4,8,8,10]
def KP(Weight, C, V):
if Weight < 2:
return 0
q = 0
for i in range(len(C)):
q = max(q, (KP(Weight-C[i], [x for j,x in enumerate(C) if j!=i], \
[x for j,x in enumerate(V) if j!=i]) + V[i]*(Weight-C[i] >= 0)))
return q
print(KP(25,cost_array,value_array))
However when I change the value of q to q < 0 and call print(KP(25,cost_array,value_array)) the result I get is 33 - q. With 33 being the max value the knapsack can have.
What is weird here is that I only get this behavior if I call the initial function with a Weight > 23 and here 23=2+3+4+5+9.
I can't figure out at what point the negative q gets added to my result for me this line never performs such an operation, can you guys enlighten me ?
q = max(q, (KP(W-C[i], [x for j,x in enumerate(C) if j!=i], [x for j,x in enumerate(V) if j!=i]) + V[i]*(W-C[i] >= 0)))
Thanks,
d_darric
Suppose q=-2 (a negative value)
Therefore you are filling your base cases with -2 . That is -2 is returned for base cases of your function which is then getting added to the answer on each step in recursion. Try a bottom up approach with a 2D array. You can look at that here https://www.youtube.com/watch?v=8LusJS5-AGo . In your case you are filling matrix base cases with -2.
def knapSack(W, wt, val, n):
K = [[0 for x in range(W+1)] for x in range(n+1)]
q=-2 #Make it zero for correct answer
# Build table K[][] in bottom up manner
for i in range(n+1):
for w in range(W+1):
if i==0 or w==0:
K[i][w] = q #Here you are assigning negative value
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
# Driver program to test above function
value_array = [3,4,8,8,10]
cost_array = [2,3,4,5,9]
Weight = 25
n = len(val)
print(knapSack(Weight, cost_array, value_array, n))

Time and memory limit exceeded - Python3 - Number Theory

I am trying to find the sum of the multiples of 3 or 5 of all the numbers upto N.
This is a practise question on HackerEarth. I was able to pass all the test cases except 1. I get a time and memory exceeded error. I looked up the documentation and learnt that int can handle large numbers and the type bignum was removed.
I am still learning python and would appreciate any constructive feedback.
Could you please point me in the right direction so I can optimise the code myself?
test_cases = int(input())
for i in range(test_cases):
user_input = int(input())
sum = 0
for j in range (0, user_input):
if j % 3 == 0:
sum = sum + j
elif j % 5 == 0:
sum = sum + j
print(sum)
In such problems, try to use some math to find a direct solution rather than brute-forcing it.
You can calculate the number of multiples of k less than n, and calculate the sum of the multiples.
For example, with k=3 and n=13, you have 13 // 3 = 4 multiples.
The sum of these 4 multiples of 3 is 3*1 + 3*2 + 3*3 + 3*4 = 3 * (1+2+3+4)
Then, use the relation: 1+2+....+n = n*(n+1)/2
To sum the multiples of 3 and 5, you can sum the multiples of 3, add the sum of the multiples of 5, and subtract the ones you counted twice: the multiples of 15.
So, you could do it like this:
def sum_of_multiples_of(k, n):
"""
Returns the sum of the multiples of k under n
"""
# number of multiples of k between 1 and n
m = n // k
return k * m * (m+1) // 2
def sum_under(n):
return (sum_of_multiples_of(3, n)
+ sum_of_multiples_of(5, n)
- sum_of_multiples_of(15, n))
# 3+5+6+9+10 = 33
print(sum_under(10))
# 33
# 3+5+6+9+10+12+15+18 = 78
print(sum_under(19))
# 78

Resources