Among these, Varahamihira was an astrologer of eminence and his book Brihat Jataak is recokened as the ultimate authority in astrology. He was once talking with Amarasimha,another gem among the nava ratnas and the author of Sanskrit thesaurus, Amarakosha. Amarasimha wanted to know the final position of a person, who starts from the origin 0 0 and travels per following scheme.

- He first turns and travels 10 units of distance
- His second turn is upward for 20 units
- Third turn is to the left for 30 units
- Fourth turn is the downward for 40 units
- Fifth turn is to the right(again) for 50 units

And thus he travels, every time increasing the travel distance by 10 units.

```
n = int(input())
c = 'R'
x,y=0,0
for i in range(n):
if c=='R':
x = abs(x) + 10;
y = abs(y);
c ='U';
elif c=='U':
y = y + 20;
c = 'L';
elif c=='L':
x = -(x + 10);
c = 'D';
elif c=='D':
y = -(y);
c = 'R';
print(x,y)
```

]]>**Max Heap:**In max heap, every parent node must have value greater than or equal to it's child's value.**Min Heap:**In min heap, every parent node must have value less than it's child's value.

We are going to use the Max Heap for heap sort here. The sorting process includes: construction of a heap from the data, a max heap precisely, swapping of the first and last node, removing the last node from the heap and processing it for the remaining. With each cycle, the heap gets smaller and the list gets to sort.

```
1. Construct max heap from the list
2. Swap the first node with the last node
3. Remove last node from heap
4. Perform step 1 to 3 for the remaining heap
5. Stop when heap empty
```

```
heapSort(list)
n=length of list
for i from n//2-1 to -1 with inverval of -1
heapify(list,n,i)
for i from n-1 to 0 with interval -1
Swap valueAtIndex_i with valueAtIndex_0
heapify(list,i,0)
heapify(list,lengthofdata,i)
largest=i
leftchildIdx,l=2*i+1
rightchildIdx,r=2*i+2
if l<lengthofdata and valueAtlargest < valueAtl:
largest=l
if r<lengthofdata and valueAtlargest < valueAtr
largest=r
if largest!=i:
swap valueAti with valueAtlargest
perform recursion(heapify root), heapify(list,lengthofdata,largest)
```

**Time Complexity:**

- Worst Case:
**O(nlogn)** - Average Case:
**O(nlogn)** - Best Case:
**O(nlogn)**

**Space Complexity: O(1)**

```
def heapify(data, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
# Check if left child of root exists and is greater than root
if l < n and data[largest] < data[l]:
largest = l
# Check if right child of root exists and is greater than root
if r < n and data[largest] < data[r]:
largest = r
# If needed, Change the root
if largest != i:
data[i], data[largest] = data[largest], data[i] #Swap
heapify(data, n, largest) # Heapify Root.
def heapSort(data):
n = len(data)
# Building MaxHeap.
for i in range(n//2 - 1, -1, -1):
heapify(data, n, i)
# Extract elements one by one
for i in range(n-1, 0, -1):
data[i], data[0] = data[0], data[i] #Swap
heapify(data, i, 0)
inp=input("Enter the data: ").split()
data=[]
for i in inp:
data.append(int(i))
heapSort(data)
n = len(data)
print("Sorted List is")
print(data)
```

```
partition(list,lowestIndex,highestIndex)
pointerI=lowestIndex-1
pivot=Element at highestIndex
for pointerJ from lowestIndex to HighestIndex
if ElementAtpointerJ < pivot
pointerI=pointerI+1
swap ElementAtpointerI with ElementAtpointerJ
swap Element at pointerI+1 with pivot
return i+1
quickSort(list,lowestIndex,highestIndex)
if lowestIndex < highestIndex
pivotIndex=partition(list,lowestIndex,highestIndex)
recursiveCall on left part, quickSort(list,lowestIndex,pivotIndex-1)
recursiveCall on right part, quickSort(list,pivotIndex+1,highestIndex)
```

**Time Complexity:**

- Worst Case:
**O(n2)** - Average Case:
**O(nlogn)** - Best Case:
**O(nlogn)****Space Complexity: O(logn)**### Program for Quick Sort:

```
def partition(data,low,high):
i = ( low-1 ) # Index of smaller element
pivot = data[high] # Pivot Value
for j in range(low , high):
if data[j] < pivot: # If current element is smaller than the pivot
i = i+1 # Increment index of smaller element
data[i],data[j] = data[j],data[i]
data[i+1],data[high] = data[high],data[i+1]
return ( i+1 )
def quickSort(data, low, high):
if low < high:
# Select pivot position and put all the elements smaller than pivot on left and greater than pivot on right
pi = partition(data, low, high)
# Sort the elements on the left of pivot
quickSort(data, low, pi - 1)
# Sort the elements on the right of pivot
quickSort(data, pi + 1, high)
inp=input("Enter the data: ").split()
data=[]
for i in inp:
data.append(int(i))
quickSort(data, 0, len(data) - 1)
print('Sorted list in Ascending Order:')
print(data)
```

```
if length(list)>1
find point of divide,mid=length(list)//2
left sublist L,index 0 to mid
right sublist R, index mid+1 to length(list)-1
recursion,calling function itself for L
recursion,calling function itself for R
i=j=k=0
while i<length(L) and j<length(R)
if L[i] < R[j],then list[k]=L[i] and i=i+1
else, list[k]=R[j] and j=j+1
k=k+1
while i<length(L)
list[k]=L[i]
update i=i+1 and k=k+1
while i<length(R)
list[k]=R[j]
update j=j+1 and k=k+1
```

**Time Complexity:**
Worst Case: **O(nlogn)**
Average Case: **O(nlogn)**
Best Case: **O(nlogn)**
**Space Complexity: O(n)**

```
def mergeSort(data):
if len(data) > 1:
mid = len(data)//2 #point where the list is divided into two sublists
L = data[:mid]
R = data[mid:]
mergeSort(L) #sorting first half
mergeSort(R) #sorting second half
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
data[k] = L[i]
i += 1
else:
data[k] = R[j]
j += 1
k += 1
while i < len(L):
data[k] = L[i]
i += 1
k += 1
while j < len(R):
data[k] = R[j]
j += 1
k += 1
inp=input("Enter the data: ").split()
data=[]
for i in inp:
data.append(int(i))
mergeSort(data)
print("Sorted List is: ")
print(data)
```

```
for all elements in list,step=from step=0 to step=length(list)-1
min_idx=step
for i from step+1 to length(list)-1
if value at index i < value at index min_idx
min_idx = i
swap as (list[step],list[min_idx])=(list[min_idx],list[step])
```

**Time Complexity:**

- Worst Case:
**O(n2)** - Average Case:
**O(n2)** - Best Case:
**O(n2)****Space Complexity: O(1)**

```
def selectionSort(data):
for step in range(len(data)):
min_idx = step
for i in range(step + 1, len(data)):
if data[i] < data[min_idx]: #Reversing the comparison operator will result in descending order sort
min_idx = i
(data[step], data[min_idx]) = (data[min_idx], data[step])
print("Step",step+1,"--",data)
inp=input("Enter the data: ").split()
data=[]
for i in inp:
data.append(int(i))
selectionSort(data)
print('Sorted list in Ascending Order:')
print(data)
```

```
for all elements in list,step=from step=0 to step=length(list)-1
first element is sorted,when step=0
key=list[step],the element to be extracted to insert at the right index
j=step-1
while j>=0 and key < value at index j
list[j+1]=list[j]
j=j-1
list[j+1]=key
```

**Time Complexity:**

- Worst Case:
**O(n2)** - Average Case:
**O(n2)** Best Case:

**O(n)****Space Complexity: O(1)**### Program for insertion sort:

`def insertionSort(data): for step in range(0, len(data)): key = data[step] j = step - 1 while j >= 0 and key < data[j]: # Change key<data[j] to key>data[j] for descending order. data[j + 1] = data[j] j = j - 1 data[j + 1] = key print("step",step," -- ",data) inp=input("Enter the data: ").split() data=[] for i in inp: data.append(int(i)) insertionSort(data) print('Sorted list in Ascending Order:') print(data)`

```
for all elements in list
for adjacent elements of unsorted portion of list
if leftElement > rightElement
swap the elements
```

**Time Complexity:**

- Worst Case:
**O(n2)** - Average Case:
**O(n2)** - Best Case:
**O(n)****Space Complexity: O(1)**

```
def bubbleSort(data):
for i in range(len(data)):
for j in range(0, len(data) - i - 1):
if data[j] > data[j + 1]: #Reversing the comparison operator will result in descending order sort
(data[j], data[j + 1]) = (data[j + 1], data[j]) #Swap
inp=input("Enter the data: ").split()
data=[]
for i in inp:
data.append(int(i))
bubbleSort(data)
print('Sorted List: ')
print(data)
```

]]>```
1. Initialize the sorted list, set low=0 and high=length(list)-1
2. Set mid=low+(high-low)//2
3. Compare key with element at mid
4. If list[mid]==key, then return mid
5. Else if list[mid]>key, then low=low and high=mid-1
6. Repeat from 2 till list[mid]=key, else return= -1
7. Else low=mid+1 and high=high
8. Repeat from 2 till list[mid]=key, else return=-1
9. If return = -1, then print "Not found"
End
```

**Time Complexity:**

- Worst Case:
**O(log n)** - Average Case:
**O(log n)** - Best Case:
**O(1)**

**Space Complexity: O(1)**

```
def binarySearch (li, low, high, x): # Returns index of element in li if present, else -1
if high >= low:
mid = low + (high - low) // 2
if li[mid] == x: #if element is present at mid
return mid
elif li[mid] > x: #If element is smaller than element at mid
return binarySearch(li, low, mid-1, x) # Element can only be present in left sub part of the li
else:
return binarySearch(li, mid + 1, high, x) #Else the element can only be present in right sub part of the li
else:
return -1 #Element not present in li
inp=input("Enter a sorted list: ").split()
li=[]
for i in inp:
li.append(int(i))
x = int(input("Element to be Searched: "))
# Function call
result = binarySearch(li, 0, len(li)-1, x)
if result != -1:
print ("Element is present at index % d" % result)
else:
print ("Element is not present in the list")
```

]]>```
LinearSearch(list,key)
for each_item in list
if(item==key)
return item_index
return -1
```

**Linear Search Time Complexity:**

- Best Case :
**O(1)** - Average Case :
**O(n)** - Worst Case :
**O(n)**

**Space complexity: O(1)**

```
def search(li, n, x):
for i in range(0, n):
if (li[i] == x):
return i
return -1
inp = input("Enter the list:")
inp=inp.split()
li=[]
for i in inp:
li.append(int(i))
x = int(input("Enter the element to be searched: "))
n = len(li)
# Function call
result = search(li, n, x)
if(result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result)
```

]]>```
Height=float(input("Enter your height in centimeters: "))
Weight=float(input("Enter your Weight in Kg: "))
Height = Height/100
BMI=Weight/(Height*Height)
print("Your Body Mass Index is: ",BMI)
if(BMI<=18.5):
print("Oops! You are underweight.")
elif(BMI<=24.9):
print("Awesome! You are healthy.")
elif(BMI<=29.9):
print("You are overweight.")
else:
print("You are Obese. Start Exercise.")
```

]]>- Password should contain an UpperCase Character.
- Password should contain a LowerCase Character.
- Password should contain a Digit.
- Password should contain a Special Character.
- Password should contain at least 8 Characters.

```
import random
import string
Details=input("Please Enter the Details for Password,such as Site and Username : ")
Length=int(input("Please Enter the password length required: "))
# Get the Characters
lcase=string.ascii_lowercase # All LowerCase Characters
ucase=string.ascii_uppercase # All UpperCase Characters
digi=string.digits # All Digits
symbo=string.punctuation # All Special Characters
# Combining All
all=lcase+ucase+digi+symbo
# Extracting a Random Character from Each
random_lcase=random.choice(lcase) # Eg: a
random_ucase=random.choice(ucase) # Eg: Z
random_digi=random.choice(digi) # Eg: 9
random_symbo=random.choice(symbo) # Eg: &
# Combining the random charcaters: Eg: aZ9&
# Now, We have a combination of random characters of each type
chars=random_lcase+random_ucase+random_digi+random_symbo
# Get a string with characters of intended length
for x in range(Length-4):
chars=chars+random.choice(all)
# Rndomize the string to get the completely random and a strong password
password=''.join(random.sample(chars,len(chars)))
print(password)
f = open("MyFile.txt", "a")# in append mode
f.write(Details+" : "+password+"\n")
f.close()
print("Details saved to MyFile.txt")
```

]]>In traditional programming, we provide input associated with a program and obtain output. The input is processed using the program(set of rules) we provided at input end which gives the output. We can say, it is logic driven.

In Machine Learning programming, the input and output both are provided to the machine. So that, machine can learn from the dataset. Learning simply means the development of program or set of rules within itself. A machine becomes capable of processing new data using its set of rules.

```
1. Select and prepare training dataset.
2. Choose an algorithm for training on dataset
3. Train algorithm to create a Model
4. Use and improve the Model
```

It is done by use of labeled datasets to train algorithms to classify data or predict outcomes. The training dataset includes Input and Output(Labels). It means the data has the labels that machine the machine is build to determine or classify. Regression and Classification problems can be performed using supervised learning algorithms.

**Regression:** It is used to understand the relationship between dependent and independent variables. Dependent variable is the one that is to be predicted and independent variable is the one that holds the features that helps decide the prediction. It is prediction on continuous data.
For example: House Price Prediction, the dependent variable is price and independent can be area. Using the training data the projections can be pulled out to predict the house price.

**Classification:** Using an algorithm to classify or accurately assign the data into specific categories. It is prediction on discrete data.
For example: We have three types of fruits- Apple, Orange, Guava. We trained our model with the training data having labels -Apple, Orange, Guava. When that model is tested against test data, particular fruit will be assigned into either of the three labeled categories.

Unsupervised learning uses unlabeled data. It requires larger amount of training data than that of required in supervised learning because unsupervised learning focuses on the pattern detection and association within the data. It discovers pattern from data which is used to solve clustering and association problems.

**Clustering:** Using an algorithm to create clusters in such a way that similar objects are grouped in same clusters. Algorithms such as K-means clustering, Mean Shift clustering, Agglomerative hierarchical clustering, etc. can be used.
Clustering can be used in places such as fraud detection: The pattern of a fraud from the data can be used to detect fraud and non-fraud transactions.

**Association:** Find some interesting relations or associations among the variables of dataset. Algorithms such as Apriori algorithm can be used.
For example: In e-commerce , we receive recommendations when we purchase an item. Suppose, the computer has seen a pattern a lot that when someone buys a laptop, the person has bought a laptop bag too. The association is found between the laptop and laptop bag. When someone buys a laptop, he gets a recommendation for a laptop bag. In similar way, associations can be find among different kinds of data.

Learning from feedback and past experiences. It is about taking suitable actions to maximize rewards in a situation. It work on trial and error to get the maximum efficiency of the function. Reinforcing and improving itself until the required optimization is achieved. Reinforcement learning can be used in different scenarios such as Robotics, Gaming, Trading, etc.

For example: In robotics, the algorithm/ learning agent performs actions in an environment and it receives rewards which may be a positive or negative reward. On the basis of reward the agent learns by determining the effect of action in the situation/environment. The agent changes its policy, that is, decides which action benefits and which doesnt.

]]>Machine Learning is a vast subject in the field of computer science and is booming big and vast because of its applications. Machine Learning can be used from house price prediction to robotics, healthcare, self driving cars, image recognition, speech recognition, etc.

A computer program is a code that is fed as instructions to the Computer. The code is written by the programmers in a specific syntactical form known as a programming language. Computers do not understand the text-based instructions (High-level language), so, they are needed to be translated to the machine-readable form which is known as machine code (Low-level language). Machine code is in the form of binary i.e. 0s and 1s.

- Low Level Language
- High Level Language

The **high-level language** allows a programmer to write programs that are independent of a particular type of computer and are text-based. The high-level languages are considered as high-level because they are closer to human languages than machine-level languages. Eg: C, C++, Python, Java, etc.

Eg: Python program to print sum of two numbers

```
a=900
b=850
c=a+b
print(The Sum of a and b: , c)
```

**Machine language** is the low-level language that is most difficult for a human to understand and work with. Machine language uses 0s and 1s. Digital devices recognize everything in binary irrespective of data format i.e. every type of data is understood as 0s and 1s whether it is a text, video, audio, or any other command.

Eg: Hello World is understood as:

```
01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100 00001010
```

**Assembly language** is a compiled, low-level language for some microprocessors and programmable devices and it directly works with the internal structure of CPU. It lies somewhere between High-Level Language and Machine language. Assembly language program consists of mnemonics that are translated into machine code.

Eg: Addition of 8-bit numbers on 8051 microcontroller

```
MOV R0,#20H; --> set source address 20H to R0
MOV R1,#30H; --> set destination address 30H to R1
MOV A,@R0; --> take the value from source to register A
MOV R5,A; --> move the value from A to R5
MOV R4,#00H; --> clear register R4 to store carry
INCR 0; --> point to the next location
MOV A,@R0; --> take the value from source to register A
ADD A,R5; --> add R5 with A and store to register A
JNC SAVE
INC R4; --> increment R4 to get carry
MOV B,R4; --> get carry to register B
MOV @R1,B; --> store the carry first
INCR 1; --> increase R1 to point to the next address
SAVE: MOV @R1,A; --> Store the result
HALT: SJMP HALT ; --> Stop the program
```

]]>Programming is giving instructions or commands to a machine to get some task done by it.

To use OpenCV, import the library.

```
import cv2
```

Read the Image.

```
image = cv2.imread("vegeta.png")
cv2.imshow("Vegeta",image)
cv2.waitKey(0)
```

Create a new image by converting the original image to grayscale.

```
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("GrayVegeta",gray_image)
cv2.waitKey(0)
```

Invert the grayscale image. We can invert images simply by subtracting from 255, as grayscale images are 8 bit images or have a maximum of 256 tones.

```
inverted_image = 255-gray_image
cv2.imshow("InvertedVegeta",inverted_image)
cv.waitKey(0)
```

Blur the inverted image using GaussianBlur method in OpenCV library and invert the blurred image.

```
blurred = cv2.GaussianBlur(inverted_image,(21,21),0)
inverted_blurred = 255-blurred
cv2.imshow("InvertedBlurredVegeta",inverted_blurred)
cv2.waitkey(0)
```

Divide the grayscale values of the image by the values of image received from step-5 (Note: We inverted the grayscale image and we blurred this image and then again inverted it). Diving an image from its smoothed form will highlight the edges and we get the image like Pencil Sketch.

```
pencil_sketch = cv2.divide(gray_image,inverted_blurred, scale=256.0)
cv2.imshow("VegetaSketch",pencil_sketch)
cv2.waitKey(0)
```

]]>