Stuck in writing python list reduction program - python

I am stuck in writing the python code for below problem, can anyone help to find the issue with the code is much appreciated.
List Reduction:
You are given a list of integers L having size N and an integer K. You can perform the following operation on the list at most k times:
Pick any two elements of the list.
Multiply any element by 2.
Divide the other element by 2, taking the ceiling if element is odd.
Note: that after such an operation, the list is changed and the changed list will be used in subsequent operations.
You need to minimize the sum of all elements present in the list after performing at most k such operations.
Input Format:
First line contains N K as described above.
The second line contains N space separated integers, representing the list initially,
Output Format:
Print the minimum possible sum of all elements in the list at the end, after performing at most k operations.
Code:
def solve (X, arr):
Sum = 0
largestDivisible, minimum = -1, arr[0]
for i in range(0,N):
Sum += arr[i]
if(arr[i]%X == 0 and largestDivisible < arr[i]):
largestDivisible = arr[i]
if arr[i] < minimum:
minimum = arr[i]
if largestDivisible == -1:
return Sum
sumAfterOperation = (Sum-minimum-largestDivisible+(X*minimum)+(largestDivisible//X))
return min(Sum,sumAfterOperation)
N=5
X =2
#map(int, input().split())
arr = [10, 7, 4, 2, 1]
#list(map(int, input().split()))
out_ = solve(X, arr)
print (out_)
output: 20
expected output: 19

Not optimal program.
Idea: Multiplying the minimal element and dividing the maximal element gives sequence with minimal total sum. Do you want process negative numbers? Does K take negative values?
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
arr.sort()
arr[0] *= 2
arr[-1] = arr[-1] // 2 + arr[-1] % 2
print(sum(arr))
More effective solution.
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
mn, mx = min(arr), max(arr)
mn_i = arr.index(mn)
if mn != mx:
mx_i = arr.index(mx)
else:
mx_i = arr.index(mx, mn_i+1)
arr[mn_i] *= 2
arr[mx_i] = arr[mx_i] // 2 + arr[mx_i] % 2
print(sum(arr))
And algorithmic solution.
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
mn, mx = 0, 0
for i, x in enumerate(arr):
if x < arr[mn]:
mn = i
if x >= arr[mx]:
mx = i
arr[mn] *= 2
arr[mx] = arr[mx] // 2 + arr[mx] % 2
print(sum(arr))

Related

find the number of subarrays of an array with XOR sum

You are given the following array A, We need to calculate the total number of sub-arrays with XOR sum X were, The sub-array should satisfy the conditions (X+1) = (X^1). Here is my solution,
def getTotalXorOfSubarrayXors(arr, N):
X = 0
count = 0
for i in range(0, N):
for j in range(i, N):
for k in range(i, j + 1):
X = X ^ arr[k]
if X+1 == X^1:
count +=1
X = 0
return count
arr = [3, 5, 2, 4, 6]
N = len(A)
print(getTotalXorOfSubarrayXors(A, N))
But this solution has a time complexity of O(n^3) which exceeds my time limit for a large set of arrays. Is there is any way I can optimize this code to have less time complexity?
The condition (X+1) = (X^1) just means X must be even. So just count the even xors by using prefix-xor-counts. Takes O(n) time and O(1) space.
def getTotalXorOfSubarrayXors(A, _):
X = 0
counts = [1, 0]
total = 0
for a in A:
X ^= a & 1
total += counts[X]
counts[X] += 1
return total
Try it online! (with tests)
Operation X ^ 1 changes the last bit of a number. So ****1 becomes ****0 and vice versa.
So we can see that for odd values of X value of X ^ 1 is less than X, but for even X's value X ^ 1 is larger by one than X - just what we need.
Now we can count subarrays with even xor-sum. Note that we remember how many odd and even xorsums we already have for subarrays starting from zero index:
def Xors(arr, N):
oddcnt = 0
evencnt = 0
res = 0
x = 0
for p in arr:
x ^= p
if (x % 2):
res += oddcnt
oddcnt += 1
else:
evencnt += 1
res += evencnt
return res

I am not able to get the desired output for max heap array, can somebody tell me the changes to be made

the python code is:
def max_heapify(i, arr, n):
l = 2*i
r = 2*i+1
largest = i
if (2*i <= n-1 and arr[l] > arr[i]):
largest = l
if (2*i+1 <= n-1 and arr[r] > arr[largest]):
largest = r
if largest != i:
temp = arr[largest]
arr[largest] = arr[i]
arr[i] = temp
max_heapify(largest, arr, n)
return arr
arr=[16,4,10,14,7,9,3,2,8,1]
n=len(arr)
#max_heapify(i,arr,n)
for i in range(n//2):
max_heapify(n//2-1-i,arr,n)
Try this
Python Program for Heap Sort
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
Python program for implementation of heap Sort
To heapify subtree rooted at index i.
n is size of heap
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
This code is contributed by Mohit Kumra
Output:
Sorted array is
5 6 7 11 12 13

If numbers in list are equal to n, print out their indices

The Task:
You are given two parameters, an array and a number. For all the numbers that make n in pairs of two, return the sum of their indices.
input is: arr = [1, 4, 2, 3, 0, 5] and n = 7
output: 11
since the perfect pairs are (4,3) and (2,5) with indices 1 + 3 + 2 + 5 = 11
So far I have this, which prints out the perfect pairs
from itertools import combinations
def pairwise(arr, n):
for i in combinations(arr, 2): # for index in combinations in arr, 2 elements
if i[0] + i[1] == n: # if their sum is equal to n
print(i[0],i[1])
Output:
4,3 2,5
However does anyone has tips on how to print the indices of the perfect pairs? Should I use numpy or should I change the whole function?
Instead of generating combinations of array elements you can generate combinations of indices.
from itertools import combinations
def pairwise(arr, n):
s = 0
for i in combinations(range(len(arr)), 2): # for index in combinations in arr, 2 elements
if arr[i[0]] + arr[i[1]] == n: # if their sum is equal to n
# print(arr[i[0]],arr[i[1]])
# print(i[0],i[1])
s += i[0] + i[1]
# print(s)
return s
You can use a dictonary mapping the indexes:
def pairwise(arr, n):
d = {b:a for a,b in enumerate(arr)} #create indexed dict
for i in combinations(arr, 2): # for index in combinations in arr, 2 elements
if i[0] + i[1] == n: # if their sum is equal to n
print(d[i[0]],d[i[1]])
Here you have a live example
Rather than generating combinations and checking if they add up to n, it's faster to turn your list into a dict where you can look up the exact number you need to add up to n. For each number x you can easily calculate n - x and then look up the index of that number in your dict.
This only works if the input list doesn't contain any duplicate numbers.
arr = [1, 4, 2, 3, 0, 5]
n = 7
indices = {x: i for i, x in enumerate(arr)}
total = 0
for i, x in enumerate(arr):
remainder = n - x
if remainder in indices:
idx = indices[remainder]
total += i + idx
# the loop counts each pair twice (once as [a,b] and once as [b,a]), so
# we have to divide the result by two to get the correct value
total //= 2
print(total) # output: 11
If the input does contain duplicate numbers, you have rewrite the code to store more than one index in the dict:
import collections
arr = [1, 4, 2, 3, 0, 5, 2]
n = 7
indices = collections.defaultdict(list)
for i, x in enumerate(arr):
indices[x].append(i)
total = 0
for i, x in enumerate(arr):
remainder = n - x
for idx in indices[remainder]:
total += i + idx
# the loop counts each pair twice (once as [a,b] and once as [b,a]), so
# we have to divide the result by two to get the correct value
total //= 2
You should use the naive approach here:
process each element of the array with its indice
for each element test for all elements after this one (to avoid duplications) whether their sum is the expected number and if it is add the sum of their indices
Code could be:
def myfunc(arr, number):
tot = 0
for i, val in enumerate(arr):
for j in range(i+1, len(arr)):
if val + arr[j] == number:
tot += i + j
return tot
Control:
>>> myfunc([1, 4, 2, 3, 0, 5], 7)
11
>>> myfunc([2, 4, 6], 8)
2

how to apply certain list index to sort in python

I have been asked to sort a k messed array
I have below code. I have to reduce the complexity from nlogn to nlogk.
arr = [3,2,1,4,5,6,8,10,9]
k = 2
def sortKmessedarr(arr, k):
i = 1
j = 0
n = len(arr)
while i < n:
if arr[i] > arr[i-1]:
pass
else:
arr[i-1:i+k].sort() # How to sort elements between two specific indexs
i += 1
sortKmessedarr(arr, k)
print(arr)
I think if I apply this approach then it will become nlogk
But how to apply this sort() between two indexes.
I have also tried another approach like below:
arr = [3,2,1,4,5,6,8,10,9]
k = 2
def sortKmessedarr(arr, k):
def merge(arr):
arr.sort()
print(arr)
i = 1
j = 0
n = len(arr)
while i < n:
if arr[i] > arr[i-1]:
pass
else:
merge(arr[i-1:i+k])#.sort()
i += 1
sortKmessedarr(arr, k)
print(arr)
But still no luck
You can use sorted with slice assignment to get the intended effect syntactically, but I am unsure of the impact on performance (memory or speed):
arr[i-1:i+k] = sorted(a[i-1:i+k])

Competition practise task (Python)

Not sure if it's the best title. The explanation of what the program is suposed to do is below, my version only works with the first example but it doesn't work in the second when you get for example 1 1 3 1 1 2 because i can't figure out a good way to handle so much variations especially if K is bigger than 3 and the limit is 50. My version:
N, K, M = map(int, input().split())
niz = list(map(int, input().split()))
nizk = list(range(1, K+1))
izlazi = []
for r in range(0, M):
operacija = list(map(int, input().split()))
index = 0
if operacija[0] == 2:
nizkk = []
for z in range(0, len(nizk)):
if nizk[z] in niz:
continue
else:
izlazi.append(-1)
break
for p in range(0, N):
if niz[p] not in nizkk:
nizkk.append(niz[p])
nizkk.sort()
if nizkk == nizk:
index = p
izlazi.append(index+1)
break
else:
continue
else:
index, repl = map(int, operacija[1:])
niz[index - 1] = repl
print(izlazi)
In the first line of the input there should be N, K, M (1 <= N, M <= 100k, 1 <= K <= 50, you don't need to actually check this the numbers that are tested will always be in those ranges). In the second line of input you put a list of numbers which are the lenght of N you entered earlier. M is the number of operations you will do in the following lines of input. There can be 2 operations. If you enter 1 p v(p = index of number you want to replace, v the number you replace it with) or if you enter 2 it needs to find the shortest array of numbers defined by range(1, K+1) in the list of numbers you entered in line 2 and possibly changed with operation 1. If it doesn't exist it should output -1 if it does it should output lenght of numbers in the array you look in(numbers can be like 2, 1, 3 if you're looking for 1, 2, 3, also if you're looking for 1, 2, 3 etc and you have 2, 1, 1, 3 as the shortest one that is the solution and it's lenght is 4). Also the replacement operation doesnt count from 0 but from 1. So watch out when managing lists.
These are the examples you can input in the program ulaz = input, izlaz = ouput:
I have the following idea:
Min length sequence either starts from first element or does not contain first element and hence equals to min length of the same sequence without first element.
So we have recursion here.
For sequence [1,1,3,2,1,1] and [1,2,3] we will have:
Min length from start element [1,1,3,2,1,1] is 4
Min length from start element __[1,3,2,1,1] is 3
Min length from start element ____[3,2,1,1] is 3
Min length from start element ______[2,1,1] is -1
Can stop here.
Result is minimum for [4,3,3] = 3
You have already implemented the part for min length, if it starts from the first element. Need now extract it as a function and create a recursive function.
Some metacode:
function GetMinLength(seq)
{
minLengthFromFirstElement = GetMinLenthFromFirstElement(seq)
minLengthFromRest = GetMinLength(seq[1:]) //recusive call
return Min(minLengthFromFirstElement, minLengthFromRest )//-1 results should not count, add extra code to handle it
}
Unfortunately I don't know python, but I can provide code on F# in case you need it.
EDIT:
Try this:
N, K, M = map(int, input().split())
niz = list(map(int, input().split()))
nizk = list(range(1, K+1))
izlazi = []
def GetMinLengthStartingFromFirstElement(seq):
nizkk = []
for z in range(0, len(seq)):
if seq[z] in nizk:
continue
else:
return -1
for p in range(0, len(seq)):
if seq[p] not in nizkk:
nizkk.append(seq[p])
nizkk.sort()
if nizkk == nizk:
index = p
return index+1
else:
continue
return -1
def GetMinLength(seq):
if len(seq) == 0:
return -1
else:
curMinLength = GetMinLengthStartingFromFirstElement(seq)
if curMinLength == -1:
return -1
minLengthFromRest = GetMinLength(seq[1:])
if minLengthFromRest > -1:
return min(curMinLength,minLengthFromRest)
else:
return curMinLength;
for r in range(0, M):
operacija = list(map(int, input().split()))
index = 0
if operacija[0] == 2:
minLength = GetMinLength(niz)
izlazi.append(minLength)
else:
index, repl = map(int, operacija[1:])
niz[index - 1] = repl
print(izlazi)

Categories