Wednesday, July 5, 2023

Maximum profit from the stock sale.

Maximum profit from a single buy and sale of stock data
def maxProfit(arr):
max_profit = 0
diff = 0
mlen = len(arr)
for i in range(mlen):
for j in range( i+1 ,mlen):
if arr[i] < arr[j]:
diff = arr[j] - arr[i]
if max_profit < diff:
max_profit = diff
return max_profit
arr = [0, 6, 10, 3, 2, 80, -1, 10, 1]
print(maxProfit(arr))

Merge two sorted arrays

Problem Merge One Sorted Array Into Another First array has n positive numbers, and they are sorted in the non-descending order. Second array has 2n numbers: first n are also positive and sorted in the same way but the last n are all zeroes. Merge the first array into the second and return the latter. You should get 2n positive integers sorted in the non-descending order. Example { "first": [1, 3, 5], "second": [2, 4, 6, 0, 0, 0] } Output: [1, 2, 3, 4, 5, 6]
def merge_one_into_another(first, second):
"""
Args:
first(list_int32)
second(list_int32)
Returns:
list_int32
"""
# Write your code here.
sindex = findex = len(first) - 1
s_end_index = len(second) - 1
while( sindex >= 0 and findex >=0 ):
if (first[findex] < second[sindex]):
second[s_end_index] = second[sindex]
sindex -= 1
else:
second[s_end_index] = first[findex]
findex -= 1
s_end_index -= 1
print(findex)
print(sindex)
print(s_end_index)
while(sindex >= 0):
second[s_end_index] = second[sindex]
sindex -= 1
s_end_index -= 1
while(findex >= 0):
second[s_end_index] = first[findex]
findex -= 1
s_end_index -= 1
return second
view raw mergearr.py hosted with ❤ by GitHub

Thursday, June 29, 2023

Mergesort algorithm in python

Mergesort algorithm is a divide and conquer algorithm. Its not efficient as Quicksort algorithm but in some cases Mergesort is better than Quicksort. For example if the data to be sorted is in a linked list then Quicksort is costly since in a linkedlist accessing random elements is costly and in Quicksort we have to access data randomly.



Asymptotic Complexity
SomethingTime ComplexitySpace Complexity
Worst Case PerformanceO (n log n)
Best Case PerformanceO (n log n )
Average Case PerformanceO(n log n)
Worst Case space Complexity
O (n)



def merge(arr, start , end):
if (start >= end):
return
mid = (end+start)//2
merge(arr, start, mid)
merge(arr, mid+1, end)
left = start
right = mid+1
aux = []
while( left<=mid and right<=end):
if (arr[left] <= arr[right]):
aux.append(arr[left])
left += 1
elif(arr[right] <= arr[left]):
aux.append(arr[right])
right += 1
while (left <= mid):
aux.append(arr[left])
left += 1
while (right <= end) :
aux.append(arr[right])
right += 1
arr[start: end+1] = aux
def merge_sort(arr):
"""
Args:
arr(list_int32)
Returns:
list_int32
"""
# Write your code here.
merge(arr, 0, len(arr)-1)
return arr
view raw merge_sort.py hosted with ❤ by GitHub
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i]<=righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j<len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
view raw MerSort.py hosted with ❤ by GitHub

Monday, February 28, 2022

NLP BERT question answering with transformers

Using transfomers to do question answering based on a context.
from transformers import BertForQuestionAnswering, AutoTokenizer
modelname = 'deepset/bert-base-cased-squad2'
model = BertForQuestionAnswering.from_pretrained(modelname)
tokenizer = AutoTokenizer.from_pretrained(modelname)
from transformers import pipeline
nlp = pipeline('question-answering', model=model, tokenizer=tokenizer)
context = "The Intergovernmental Panel on Climate Change (IPCC) is a scientific intergovernmental body under the auspices of the United Nations, set up at the request of member governments. It was first established in 1988 by two United Nations organizations, the World Meteorological Organization (WMO) and the United Nations Environment Programme (UNEP), and later endorsed by the United Nations General Assembly through Resolution 43/53. Membership of the IPCC is open to all members of the WMO and UNEP. The IPCC produces reports that support the United Nations Framework Convention on Climate Change (UNFCCC), which is the main international treaty on climate change. The ultimate objective of the UNFCCC is to \"stabilize greenhouse gas concentrations in the atmosphere at a level that would prevent dangerous anthropogenic [i.e., human-induced] interference with the climate system\". IPCC reports cover \"the scientific, technical and socio-economic information relevant to understanding the scientific basis of risk of human-induced climate change, its potential impacts and options for adaptation and mitigation.\""
print(nlp({'question': 'What organization is the IPCC a part of?','context': context }))
context = "The manager of the Spanx Sports is Manoj"
print(nlp({'question': 'Who is the manager of Spanx Sports?', 'context': context }))
view raw bert_squad.py hosted with ❤ by GitHub

Friday, May 21, 2021

Finding subsets with a sum of a number

Python solution
arr=[5,4,8, 10,-4]
k=6
def check_if_sum_possible(arr, k):
slate = []
index = 0
arrlen = 0
if arr:
arrlen = len(arr)
def printSubset(index, slate):
#base case
if(index==arrlen):
sum = 0
if slate:
for i in range(len(slate)):
sum = sum + slate[i]
if sum == k:
print(slate, end=" ")
return True
else:
return False
return
else:
return False
if(printSubset(index+1,slate)):
return True
slate.append(arr[index])
if(printSubset(index+1,slate)):
return True
slate.pop()
if(printSubset(index,slate)):
return True
return False
print(check_if_sum_possible(arr, k))
view raw sumsets.py hosted with ❤ by GitHub
c++ solution
#include<iostream>
#include<vector>
using namespace std;
vector<int> bag = { 2, 8, -2 };
int sum = 6, index=0;
int bagSize;
bool flag = false;
bool printSubsetSums(int index , vector<int> slate){
//basecase
if(index == bagSize){
cout << endl;
int subsetSum = 0;
int sizeSlate = slate.size();
for (auto i : slate){
//cout << i << " ";
subsetSum = subsetSum + i;
}
if(subsetSum == sum){
cout <<endl<<"sum found" <<endl;
for (auto i : slate){
cout << i << " ";
}
flag = true;
return flag;
}
return flag;
}
//recursion
printSubsetSums(index+1 , slate);
slate.push_back(bag[index]);
printSubsetSums(index+1, slate);
slate.pop_back();
}
int main(){
cout<< "Subset sums"<<endl;
bagSize = bag.size();
vector<int> slate ;
printSubsetSums(index, slate) ;
cout << std::boolalpha << flag;
}
view raw subsetsums.cpp hosted with ❤ by GitHub

Friday, April 30, 2021

Dutch Flag problem

Dutch flag is a notable problem wherein you have a array representing three colors . Red(R), Green(G) and Blue(B) which needs to be sorted with Reds coming first followed by Green and then Blue. This is achieved by lumoto partitioning scheme.
arr = ['G','B','R','G','B','G','R']
ridx=0
bidx=len(arr)-1
i=0
while(i<bidx):
if(arr[i] == 'R'):
arr[i],arr[ridx] = arr[ridx],arr[i]
ridx += 1
i = i+1
elif (arr[i] == 'B'):
arr[i],arr[bidx] = arr[bidx], arr[i]
bidx -= 1
else:
i=i+1
print(arr)
view raw dutchflag.py hosted with ❤ by GitHub

Tuesday, April 20, 2021

Printing out all combinations of string

Printing out all combinations of a string
#! /bin/env/path python
def printCombinations(slate,array):
if (len(array)==0):
print(slate)
return
printCombinations(slate,array[1:])
printCombinations(slate+array[0], array[1:])
printCombinations("", "abcd")
view raw Combinations.py hosted with ❤ by GitHub