You are on page 1of 8

pd.

read_excel()

df['Type'].unique()

df[df['Type']=='BASE]

df.sort_values(by='Type',asc=False)

df.sort_values(by='Type',asc=False).head(n=5)

df['TypeD'].mean()
df['TypeD'].max()
df['TypeD'].min()

df.to_excel()

df.info()

df.Income = df.Income.fillna(0)

df['Education'].value_counts().to_frame()

u = list(df['Marital_Status'].unique())
u.sort()
u

df[['Education','Marital_Status']] =
df[['Education','Marital_Status']].astype('category')
df['Dt_Customer'] = pd.to_datetime(df['Dt_Customer'])
df[['Education','Marital_Status', 'Dt_Customer']].info()

df.describe(include='category')

pd.options.display.float_format = '{:.1f}%'.format
ed = df['Education'].value_counts(normalize=True)*100
ed

pd.crosstab(df['Education'],
df['Marital_Status'], normalize=True
)*100

pd.crosstab(df['Education'],
df['AcceptedCmp1'], normalize=True, margins=True, margins_name="Total"
)*100

pd.options.display.float_format = '{:.2f}'.format
df.pivot_table(index= "Education", columns = 'Marital_Status', values =
'AcceptedCmp1', aggfunc = "sum")

LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
LLLLLLLLLLLLLLLLLLLL

def righto(right, left, houses):


"""Express that `right` is on the right of `left` among all the houses."""
neighbors = tuple(zip(houses[:-1], houses[1:]))
return membero((left, right), neighbors)

from kanren import conde

def nexto(a, b, houses):


"""Express that `a` and `b` are next to each other."""
return conde([righto(a, b, houses)], [righto(b, a, houses)])

QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
QQQQQQQQQQQQQQQQQQQQQQQ

Python Program for Bubble Sort

import sys

def bubble_sort(arr):
# This function will sort the array in non-decreasing order.
n = len(arr)
#Traverse through all the array elements
for i in range(n):
# The inner loop will run for n-i-1 times as the
# last i elements are already in place.
for j in range(0, n-i-1):
# Swap if the present element is greater than the
# next element.
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr

# main code
if __name__=='__main__':

arr = [2, 1, 9, 3, 7, 5, 6, 4, 8, 0]
print("Sorted array: ")
print(bubble_sort(arr))

Output
Sorted array:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python program to implement insertion Sort


import sys

def insertion_sort(arr):
# This function will sort the array in non-decreasing order.
n = len(arr)
# After each iteration first i+1 elements are in sorted order.
for i in range(1, n):
key = arr[i]
j = i-1
# In each iteration shift the elements of arr[0..i-1],
# that are greater than key, to one position ahead
# of their current position
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1

arr[j+1] = key

return arr

# main code
if __name__=='__main__':

arr = [24, 17, 66, 33, 72, 47, 68, 41, 105, 30]
print("Sorted array: ")
print(insertion_sort(arr))

Python program to implement selection sort


import sys

def selection_sort(arr):
# This function will sort the array in non-decreasing order.
n = len(arr)
#The outer loop will run for n times.
for i in range(n):
min_index = i
# The inner loop will run for n-i-1 times as the
# first i elements are already in sorted.
for j in range(i+1, n):
# Compare if the present element is smaller than the
# element present at min_index in the array. If yes
# store the index of the present element in min-index.
if arr[min_index] > arr[j]:
min_index = j
# Swap the ith element with the smallest element in the
# unsorted list i.e. arr[min_index}].
if i != min_index:
temp = arr[i]
arr[i] = arr[min_index]
arr[min_index] = temp
return arr

# main code
if __name__=='__main__':

arr = [21, 15, 96, 37, 72, 54, 68, 41, 85, 30]
print("Sorted array: ")
print(selection_sort(arr))
Output
Sorted array:
[15, 21, 30, 37, 41, 54, 68, 72, 85, 96]
Python program to implement linear search
import sys

def linear_search(arr, num_find):


# This function is used to search whether the given
# element is present within the list or not. If the element
# is present in list then the function will return its
# position in the list else it will return -1.
position = -1
for index in range(0, len(arr)):
if arr[index] == num_find:
position = index
break

return (position)

# main code
if __name__=='__main__':

arr = [10, 7, 2, 13, 4, 52, 6, 17, 81, 49]


num = 52
found = linear_search(arr, num)
if found != -1:
print('Number %d found at position %d'%(num, found+1))
else:
print('Number %d not found'%num)
Output
Number 52 found at position 6

Python program to implement binary search


def binary_search(l, num_find):
'''
This function is used to search any number.
Whether the given number is present in the
list or not. If the number is present in list
the list it will return TRUE and FALSE otherwise.
'''
start = 0
end = len(l) - 1
mid = (start + end) // 2

# We took found as False that is, initially


# we are considering that the given number
# is not present in the list unless proven
found = False
position = -1

while start <= end:


if l[mid] == num_find:
found = True
position = mid
break

if num_find > l[mid]:


start = mid + 1
mid = (start + end) // 2
else:
end = mid - 1
mid = (start + end) // 2

return (found, position)

# Time Complexity : O(logn)

# main code
if __name__=='__main__':

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
num = 6
found = binary_search(l, num)
if found[0]:
print('Number %d found at position %d'%(num, found[1]+1))
else:
print('Number %d not found'%num)
Output
Number 6 found at position 7

Python program to implement breadth first search for a graph


import sys
import math

def bfs(n, edges, s):


#initialize state, distance and parent for all the vertices
state = [0 for i in range(n)]
distance = [float('inf') for i in range(n)]
parent = [-1 for i in range(n)]
#initialize state, distance and parent for the source vertex
state[s] = 1
distance[s] = 0
parent[s] = 'NIL'
queue = []
arr = []
queue.append(s)
#Start discovering the vertices starting from the source vertex
while queue:
x = queue.pop(0)
arr.append(x)
#Start discovering the vertices adjacent to x and store
#information about their parent, distance and state
for i in range(len(edges[x])):
if state[edges[x][i]] == 0:
state[edges[x][i]] = 1
distance[edges[x][i]] = distance[x] + 1
parent[edges[x][i]] = x
queue.append(edges[x][i])
state[x] = -1

return arr

def main():
#input format is described below
n, m, s = map(int, input().split())
edges = {}
for i in range(n):
edges[i] = []
for i in range(m):
a, b = map(int, input().split())
edges[a] += [b]
edges[b] += [a]
for i in range(n):
edges[i].sort()
arr = bfs(n, edges, s)
print(*arr)

if __name__ == '__main__':
main()
Input
Input format:

First line of input contains the integers n, m s where


n = number of nodes
m = number of edges
s = source node
Next m lines contain two integers which specifies that the vertices are connected
by an edge
9 13 0
0 1
0 7
1 7
1 2
2 3
2 5
2 8
3 4
3 5
4 5
5 6
6 7
7 8
Output
Output Format: Breadth first traversal starting from source node

0 1 7 2 6 8 3 5 4

Python program to reverse a string using stack and reversed() method


import sys

def push(element, size, stack):


'''
this function is used to push the elements
in the stack and it will return Error! message
if the stack is full and terminate the program.
'''
global top
if top >= size - 1:
print('Stack Overflow')
sys.exit()
else:
top += 1
stack[top] = element
def pop():
'''
this function is used to pop elements from
the stack and it will return Error! message
if the stack is empty and terminate the program.
'''
global top
if top < 0:
print('Stack Underflow')
sys.exit()
else:
element = stack[top]
print('%s' % element, end='')
top -= 1

def reverse_by_sort(string):
'''
This function is used to reverse any string
by reversed() method.
'''

string = list(string)
rev_str = ''

for i in reversed(string):
rev_str += i

return rev_str

if __name__=='__main__':

size = 11
stack = [0]*size
string = 'Includehelp'
top = -1

# Pushing value in the stack


push('I', 11, stack)
push('n', 11, stack)
push('c', 11, stack)
push('l', 11, stack)
push('u', 11, stack)
push('d', 11, stack)
push('e', 11, stack)
push('h', 11, stack)
push('e', 11, stack)
push('l', 11, stack)
push('p', 11, stack)

print('Original String = %s' % string)

print('\nUsing Stack')

# Popping values from stack and printing them


print('Reversed String = ',end='')
for i in stack:
pop()

print('\n\nUsing sort()')
print('Reversed string = %s' % reverse_by_sort(string))
Output
Original String = Includehelp

Using Stack
Reversed String = plehedulcnI

Using sort()
Reversed string = plehedulcnI

You might also like