return index of max ascending array - python

Here, I currently return the length of the max ascending array. However, I want to modify it such that I can return the index of the max ascending array. I tried setting idx = I inside the if (A[i] > A[i-1]) :but that does not seem to work. What else could I try?
def func(A):
n = len(A)
m = 1
l = 1
idx = -1
# traverse the array from the 2nd element
for i in range(1, n) :
# if current element if greater than previous
# element, then this element helps in building
# up the previous increasing subarray encountered
# so far
if (A[i] > A[i-1]) :
l =l + 1
idx = i-1
else :
# check if 'max' length is less than the length
# of the current increasing subarray. If true,
# then update 'max'
if (m < l) :
m = l
# reset 'len' to 1 as from this element
# again the length of the new increasing
# subarray is being calculated
l = 1
# comparing the length of the last
# increasing subarray with 'max'
if (m < l) :
m = l
# required maximum length
return m

I hope this is what you are looking for.
def func(A):
n = len(A)
m = 1
l = 1
index = [0,0]
flag=0
for i in range(1, n):
if (A[i] > A[i-1]) :
l =l + 1
if flag==0:
flag=1
lindex = i-1
else:
if (m < l) :
m = l
index = [lindex,i-1]
flag=0
l = 1
if (m < l) :
m = l
index = [lindex,i]
return index

Related

Need to optimize my mathematical py code with lists

Im not very sure if I will translate the assignment correctly, but the bottom line is that I need to consider the function f(i) = min dist(i, S), where S is number set of length k and dist(i, S) = sum(j <= S)(a (index i) - a(index j)), where a integer array.
I wrote the following code to accomplish this task:
n, k = (map(int, input().split()))
arr = list(map(int, input().split()))
sorted_arr = arr.copy()
sorted_arr.sort()
dists = []
returned = []
ss = 0
indexed = []
pop1 = None
pop2 = None
for i in arr:
index = sorted_arr.index(i)
index += indexed.count(i)
indexed.append(i)
dists = []
if (index == 0):
ss = sorted_arr[1:k+1]
elif (index == len(arr) - 1):
sorted_arr.reverse()
ss = sorted_arr[1:k+1]
else:
if index - k < 0:
pop1 = 0
elif index + k > n - 1:
pop2 = None
else:
pop1 = index - k
pop2 = index + k + 1
ss = sorted_arr[pop1:index] + sorted_arr[index + 1: pop2]
for ind in ss:
dists.append(int(abs(i - ind)))
dists.sort()
returned.append(str(sum(dists[:k])))
print(" ".join(returned))
But I need to speed up its execution time significantly.

check for closest greatest element in list a for every element of list b any optimization suggestion to this code for huge lists

Function:
Check for closest greatest element in 'list a' for every element of 'list b'
if element found, remove that element from original list
so the next element can be compared
list a=[2,3,4], list b=[0,0,7] =>2,3,-1
if no element found, return: -1
and finally prints the count of -1
any suggestions to optimize this code for huge lists
import sys
def next(arr, target): #method returns index of nex greater element or -1
start = 0
end = len(arr) - 1
ans = -1
while (start <= end):
mid = (start + end) // 2
if (arr[mid] <= target):
start = mid + 1
else:
ans = mid
end = mid - 1
return ans
def main():
q=list(map(int,sys.stdin.readline().split())) #list1
r=list(map(int,sys.stdin.readline().split())) #list2
q.sort()
r.sort()
var,count=0,0
for tst in r:
var=next(q,tst)
q.pop(var)
if var == -1:
count+=1
print(count)
main()
sort two list first. then compare two values. if a[i] is not grater than b[i] then go next element of a.
a = [2,3,4]
b = [0,0,7]
a.sort()
b.sort()
c = [];
x = 0;
for i in range(len(b)):
while x < len(a):
if a[x] > b[i]:
c.append(a[x])
break;
x = x + 1;
if x >= len(a):
c.append(-1)
else:
x = x + 1;
for i in c:
print(i)

Dynamic Programming: Rod cutting and remembering where cuts are made

So I have this code in python and currently it only returns the maximum value for cutting a rod. How can I modify this to also give me where the cuts were made? It takes a list of prices whose indices+1 correspond to the value of the rod at each length, and n, for length of the rod.
the problem:http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html
def cutRod(price, n):
val = [0 for x in range(n+1)]
val[0] = 0
for i in range(1, n+1):
max_val = 0
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
If this is the question : Rod cutting
Assuming code works fine, You will have to add a condition instead of Max operation to check which of two was picked and push that one in an array :
def cutRod(price, n):
val = [0 for x in range(n+1)]
val[0] = 0
output = list()
for i in range(1, n+1):
max_val = 0
cur_max_index = -1
for j in range(i):
cur_val = price[j] + val[i-j-1]
if(cur_val>max_val):
max_val = cur_val #store current max
cur_max_index = j #and index
if cur_max_index != -1:
output.append(cur_max_index) #append in output index list
val[i] = max_val
print(output) #print array
return val[n]
I know this is old but just in case someone else has a look...I was actually just looking at this problem. I think the issue is here that these dp problems can be tricky when handling indices. The previous answer is not going to print the solution correctly simply because this line needs to be adjusted...
cur_max_index = j which should be cur_max_index = j + 1
The rest...
def cut_rod(prices, length):
values = [0] * (length + 1)
cuts = [-1] * (length + 1)
max_val = -1
for i in range(1, length + 1):
for j in range(i):
temp = prices[j] + values[i - j - 1]
if temp > max_val:
max_val = prices[j] + values[i - j - 1]
cuts[i] = j + 1
values[i] = max_val
return values[length], cuts
def print_cuts(cuts, length):
while length > 0:
print(cuts[length], end=" ")
length -= cuts[length]
max_value, cuts = cut_rod(prices, length)
print(max_value)
print_cuts(cuts, length)
Well, if you need to get the actual pieces that would be the result of this process then you'd probably need a recursion.
For example something like that:
def cutRod(price, n):
val = [0 for x in range(n + 1)]
pieces = [[0, 0]]
val[0] = 0
for i in range(1, n + 1):
max_val = 0
max_pieces = [0, 0]
for j in range(i):
curr_val = price[j] + val[i - j - 1]
if curr_val > max_val:
max_val = curr_val
max_pieces = [j + 1, i - j - 1]
pieces.append(max_pieces)
val[i] = max_val
arr = []
def f(left, right):
if right == 0:
arr.append(left)
return
f(pieces[left][0], pieces[left][1])
f(pieces[right][0], pieces[right][1])
f(pieces[n][0], pieces[n][1])
return val[n], arr
In this code, there is an additional array for pieces which represents the best way to divide our Rod with some length.
Besides, there is a function f that goes through all pieces and figures out the optimal way to divide the whole Rod.

Heap sort Algorithms issue

I followed the clrs book for algo.
I'm trying make heapsort in python. But It give me the error that r falls out side of the index but I don't know why.
def Max_Heapify(A,i,size_of_array):
l = 2*i
r = l + 1
if l <= size_of_array and A[l] > A[i]:
largest = l
else:
largest = i
if r <= size_of_array and A[r] > A[largest]:
largest = r
if i != largest:
A[i], A[largest] = A[largest], A[i]
Max_Heapify(A,largest,size_of_array)
def Build_Max_Heap(A,size_of_array):
for i in range((math.floor(size_of_array/2)) - 1 , 0 ,-1):
Max_Heapify(A,i,size_of_array)
def Heapsort(A,size_of_array):
Build_Max_Heap(A,size_of_array)
for i in range(size_of_array - 1 ,0 ,-1):
A[0],A[i] = A[i],A[0]
size_of_array = size_of_array - 1
Max_Heapify(A,0,size_of_array)
In most of the programming languages, the size of the array is bigger than the last index. For example, the following array: A = [1, 2, 3], its size is 3, but the index of the last element is 2 (A[3] should return that it is out of index). You are verifying if r is less or equal to the array size, so when it is equal, it is bigger than the last index. Your verification should be:
if r < size_of_array

Reducing time complexity of contiguous subarray

I was wondering how I could reduce the time complexity of this algorithm.
It calculates the length of the max subarray having elements that sum to the k integer.
a = an array of integers
k = max integer
ex: a = [1,2,3], k= 3
possible subarrays = [1],[1,2]
length of the max subarray = 2
sys.setrecursionlimit(20000)
def maxLength(a, k):
#a = [1,2,3]
#k = 4
current_highest = 0
no_bigger = len(a)-1
for i in xrange(len(a)): #0 in [0,1,2]
current_sum = a[i]
sub_total = 1
for j in xrange(len(a)):
if current_sum <= k and ((i+sub_total)<=no_bigger) and (k>=(current_sum + a[i+sub_total])):
current_sum += a[i+sub_total]
sub_total += 1
else:
break
if sub_total > current_highest:
current_highest = sub_total
return current_highest
You can use sliding window algorithm for this.
Start at index 0, and calculate sum of subarray as you move forward. When sum exceeds k, start decrementing the initial elements till sum is again less than k and start summing up again.
Find below the python code:
def max_length(a,k):
s = 0
m_len = 0
i,j=0,0
l = len(a)
while i<l:
if s<=k and m_len<(j-i):
m_len = j-i
print i,j,s
if s<=k and j<l:
s+=a[j]
j+=1
else:
s-=a[i]
i+=1
return m_len
a = [1,2,3]
k = 3
print max_length(a,k)
OUTPUT:
2

Categories

Resources