code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python Program for Gnome Sort
# Python program to implement Gnome Sort
# A function to sort the given list using Gnome sort
def gnomeSort( arr, n):
index = 0
while index < n:
if index == 0:
index = index + 1
if arr[index] >= arr[index - 1]:
index = index + 1
else:
arr[index], arr[index-1] = arr[index-1], arr[index]
index = index - 1
return arr
# Driver Code
arr = [ 34, 2, 10, -9]
n = len(arr)
arr = gnomeSort(arr, n)
print "Sorted sequence after applying Gnome Sort :",
for i in arr:
print i,
# Contributed By Harshit Agrawal | 106 |
# Write a Python program to create a copy of its own source code.
def file_copy(src, dest):
with open(src) as f, open(dest, 'w') as d:
d.write(f.read())
file_copy("untitled0.py", "z.py")
with open('z.py', 'r') as filehandle:
for line in filehandle:
print(line, end = '')
| 41 |
# Find the second most frequent character in a given string
str=input("Enter Your String:")arr=[0]*256max=0sec_max=0i=0for i in range(len(str)): if str[i]!=' ': num=ord(str[i]) arr[num]+=1for i in range(256): if arr[i] > arr[max]: sec_max = max max = i elif arr[i]>arr[sec_max] and arr[i]!=arr[max]: sec_max = iprint("The Second Most occurring character in a string is "+(chr)(sec_max)) | 51 |
#
7.2
Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
:
class Shape(object):
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, l):
Shape.__init__(self)
self.length = l
def area(self):
return self.length*self.length
aSquare= Square(3)
print aSquare.area()
| 72 |
# Write a program that accepts a sentence and calculate the number of letters and digits.
s = raw_input()
d={"DIGITS":0, "LETTERS":0}
for c in s:
if c.isdigit():
d["DIGITS"]+=1
elif c.isalpha():
d["LETTERS"]+=1
else:
pass
print "LETTERS", d["LETTERS"]
print "DIGITS", d["DIGITS"]
| 39 |
# Write a Python program to Convert Matrix to dictionary
# Python3 code to demonstrate working of
# Convert Matrix to dictionary
# Using dictionary comprehension + range()
# initializing list
test_list = [[5, 6, 7], [8, 3, 2], [8, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# using dictionary comprehension for iteration
res = {idx + 1 : test_list[idx] for idx in range(len(test_list))}
# printing result
print("The constructed dictionary : " + str(res)) | 81 |
# Write a Python Program to find minimum number of rotations to obtain actual string
def findRotations(str1, str2):
# To count left rotations
# of string
x = 0
# To count right rotations
# of string
y = 0
m = str1
while True:
# left rotating the string
m = m[len(m)-1] + m[:len(m)-1]
# checking if rotated and
# actual string are equal.
if(m == str2):
x += 1
break
else:
x += 1
if x > len(str2) :
break
while True:
# right rotating the string
str1 = str1[1:len(str1)]+str1[0]
# checking if rotated and actual
# string are equal.
if(str1 == str2):
y += 1
break
else:
y += 1
if y > len(str2):
break
if x < len(str2):
# printing the minimum
# number of rotations.
print(min(x,y))
else:
print("given strings are not of same kind")
# Driver code
findRotations('sgeek', 'geeks') | 144 |
# Program to print the Solid Diamond Star Pattern
row_size=int(input("Enter the row size:"))
for out in range(row_size,-row_size,-1):
for in1 in range(1,abs(out)+1):
print(" ",end="")
for in2 in range(row_size,abs(out),-1):
print("* ",end="")
print("\r")
| 30 |
# Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color = [x for (i,x) in enumerate(color) if i not in (0,4,5)]
print(color)
| 39 |
# Calculate inner, outer, and cross products of matrices and vectors using NumPy in Python
# Python Program illustrating
# numpy.inner() method
import numpy as np
# Vectors
a = np.array([2, 6])
b = np.array([3, 10])
print("Vectors :")
print("a = ", a)
print("\nb = ", b)
# Inner Product of Vectors
print("\nInner product of vectors a and b =")
print(np.inner(a, b))
print("---------------------------------------")
# Matrices
x = np.array([[2, 3, 4], [3, 2, 9]])
y = np.array([[1, 5, 0], [5, 10, 3]])
print("\nMatrices :")
print("x =", x)
print("\ny =", y)
# Inner product of matrices
print("\nInner product of matrices x and y =")
print(np.inner(x, y)) | 103 |
# Write a Python program to Sort Python Dictionaries by Key or Value
# Function calling
def dictionairy():
# Declare hash function
key_value ={}
# Initializing value
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print ("Task 1:-\n")
print ("Keys are")
# iterkeys() returns an iterator over the
# dictionary’s keys.
for i in sorted (key_value.keys()) :
print(i, end = " ")
def main():
# function calling
dictionairy()
# Main function calling
if __name__=="__main__":
main() | 85 |
# Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components.
def hex_to_rgb(hex):
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
print(hex_to_rgb('FFA501'))
print(hex_to_rgb('FFFFFF'))
print(hex_to_rgb('000000'))
print(hex_to_rgb('FF0000'))
print(hex_to_rgb('000080'))
print(hex_to_rgb('C0C0C0'))
| 38 |
# Write a Python Program for Binary Insertion Sort
# Python Program implementation
# of binary insertion sort
def binary_search(arr, val, start, end):
# we need to distinugish whether we should insert
# before or after the left boundary.
# imagine [0] is the last step of the binary search
# and we need to decide where to insert -1
if start == end:
if arr[start] > val:
return start
else:
return start+1
# this occurs if we are moving beyond left\'s boundary
# meaning the left boundary is the least position to
# find a number greater than val
if start > end:
return start
mid = (start+end)/2
if arr[mid] < val:
return binary_search(arr, val, mid+1, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid-1)
else:
return mid
def insertion_sort(arr):
for i in xrange(1, len(arr)):
val = arr[i]
j = binary_search(arr, val, 0, i-1)
arr = arr[:j] + [val] + arr[j:i] + arr[i+1:]
return arr
print("Sorted array:")
print insertion_sort([37, 23, 0, 17, 12, 72, 31,
46, 100, 88, 54])
# Code contributed by Mohit Gupta_OMG | 177 |
# Pretty print Linked List in Python
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def __str__(self):
# defining a blank res variable
res = ""
# initializing ptr to head
ptr = self.head
# traversing and adding it to res
while ptr:
res += str(ptr.val) + ", "
ptr = ptr.next
# removing trailing commas
res = res.strip(", ")
# chen checking if
# anything is present in res or not
if len(res):
return "[" + res + "]"
else:
return "[]"
if __name__ == "__main__":
# defining linked list
ll = LinkedList()
# defining nodes
node1 = Node(10)
node2 = Node(15)
node3 = Node(20)
# connecting the nodes
ll.head = node1
node1.next = node2
node2.next = node3
# when print is called, by default
#it calls the __str__ method
print(ll) | 143 |
# Write a Python program to find the item with maximum frequency in a given list.
from collections import defaultdict
def max_occurrences(nums):
dict = defaultdict(int)
for i in nums:
dict[i] += 1
result = max(dict.items(), key=lambda x: x[1])
return result
nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,2,4,6,9,1,2]
print ("Original list:")
print(nums)
print("\nItem with maximum frequency of the said list:")
print(max_occurrences(nums))
| 56 |
# Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings.
def sort_mixed_list(mixed_list):
mixed_list.sort(key=lambda e: (isinstance(e, str), e))
return mixed_list
mixed_list = [19,'red',12,'green','blue', 10,'white','green',1]
print("Original list:")
print(mixed_list)
print("\nSort the said mixed list of integers and strings:")
print(sort_mixed_list(mixed_list))
| 49 |
# numpy.trim_zeros() in Python
import numpy as geek
gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))
# without trim parameter
# returns an array without leading and trailing zeros
res = geek.trim_zeros(gfg)
print(res) | 42 |
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to make a gradient color on all the values of the said dataframe.
import pandas as pd
import numpy as np
import seaborn as sns
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
print("Original array:")
print(df)
print("\nDataframe - Gradient color:")
df.style.background_gradient()
| 63 |
# Write a Python program to sum of all counts in a collections.
import collections
num = [2,2,4,6,6,8,6,10,4]
print(sum(collections.Counter(num).values()))
| 19 |
# Write a Python program to find numbers within a given range where every number is divisible by every digit it contains.
def divisible_by_digits(start_num, end_num):
return [n for n in range(start_num, end_num+1) \
if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))]
print(divisible_by_digits(1,22))
| 46 |
# Create a pandas column using for loop in Python
# importing libraries
import pandas as pd
import numpy as np
raw_Data = {'Voter_name': ['Geek1', 'Geek2', 'Geek3', 'Geek4',
'Geek5', 'Geek6', 'Geek7', 'Geek8'],
'Voter_age': [15, 23, 25, 9, 67, 54, 42, np.NaN]}
df = pd.DataFrame(raw_Data, columns = ['Voter_name', 'Voter_age'])
# //DataFrame will look like
#
# Voter_name Voter_age
# Geek1 15
# Geek2 23
# Geek3 25
# Geek4 09
# Geek5 67
# Geek6 54
# Geek7 42
# Geek8 not a number
eligible = []
# For each row in the column
for age in df['Voter_age']:
if age >= 18: # if Voter eligible
eligible.append('Yes')
elif age < 18: # if voter is not eligible
eligible.append("No")
else:
eligible.append("Not Sure")
# Create a column from the list
df['Voter'] = eligible
print(df) | 131 |
# Visualizing Quick Sort using Tkinter in Python
# Extension Quick Sort Code
# importing time module
import time
# to implement divide and conquer
def partition(data, head, tail, drawData, timeTick):
border = head
pivot = data[tail]
drawData(data, getColorArray(len(data), head,
tail, border, border))
time.sleep(timeTick)
for j in range(head, tail):
if data[j] < pivot:
drawData(data, getColorArray(
len(data), head, tail, border, j, True))
time.sleep(timeTick)
data[border], data[j] = data[j], data[border]
border += 1
drawData(data, getColorArray(len(data), head,
tail, border, j))
time.sleep(timeTick)
# swapping pivot with border value
drawData(data, getColorArray(len(data), head,
tail, border, tail, True))
time.sleep(timeTick)
data[border], data[tail] = data[tail], data[border]
return border
# head --> Starting index,
# tail --> Ending index
def quick_sort(data, head, tail,
drawData, timeTick):
if head < tail:
partitionIdx = partition(data, head,
tail, drawData,
timeTick)
# left partition
quick_sort(data, head, partitionIdx-1,
drawData, timeTick)
# right partition
quick_sort(data, partitionIdx+1,
tail, drawData, timeTick)
# Function to apply colors to bars while sorting:
# Grey - Unsorted elements
# Blue - Pivot point element
# White - Sorted half/partition
# Red - Starting pointer
# Yellow - Ending pointer
# Green - Sfter all elements are sorted
# assign color representation to elements
def getColorArray(dataLen, head, tail, border,
currIdx, isSwaping=False):
colorArray = []
for i in range(dataLen):
# base coloring
if i >= head and i <= tail:
colorArray.append('Grey')
else:
colorArray.append('White')
if i == tail:
colorArray[i] = 'Blue'
elif i == border:
colorArray[i] = 'Red'
elif i == currIdx:
colorArray[i] = 'Yellow'
if isSwaping:
if i == border or i == currIdx:
colorArray[i] = 'Green'
return colorArray | 254 |
# Write a Pandas program to generate time series combining day and intraday offsets intervals.
import pandas as pd
dateset1 = pd.date_range('2029-01-01 00:00:00', periods=20, freq='3h10min')
print("Time series with frequency 3h10min:")
print(dateset1)
dateset2 = pd.date_range('2029-01-01 00:00:00', periods=20, freq='1D10min20U')
print("\nTime series with frequency 1 day 10 minutes and 20 microseconds:")
print(dateset2)
| 49 |
# How to extract date from Excel file using Pandas in Python
# import required module
import pandas as pd;
import re;
# Read excel file and store in to DataFrame
data = pd.read_excel("date_sample_data.xlsx");
print("Original DataFrame")
data | 37 |
# Write a Python Program for Anagram Substring Search (Or Search for all permutations)
# Python program to search all
# anagrams of a pattern in a text
MAX = 256
# This function returns true
# if contents of arr1[] and arr2[]
# are same, otherwise false.
def compare(arr1, arr2):
for i in range(MAX):
if arr1[i] != arr2[i]:
return False
return True
# This function search for all
# permutations of pat[] in txt[]
def search(pat, txt):
M = len(pat)
N = len(txt)
# countP[]: Store count of
# all characters of pattern
# countTW[]: Store count of
# current window of text
countP = [0]*MAX
countTW = [0]*MAX
for i in range(M):
(countP[ord(pat[i]) ]) += 1
(countTW[ord(txt[i]) ]) += 1
# Traverse through remaining
# characters of pattern
for i in range(M, N):
# Compare counts of current
# window of text with
# counts of pattern[]
if compare(countP, countTW):
print("Found at Index", (i-M))
# Add current character to current window
(countTW[ ord(txt[i]) ]) += 1
# Remove the first character of previous window
(countTW[ ord(txt[i-M]) ]) -= 1
# Check for the last window in text
if compare(countP, countTW):
print("Found at Index", N-M)
# Driver program to test above function
txt = "BACDGABCDA"
pat = "ABCD"
search(pat, txt)
# This code is contributed
# by Upendra Singh Bartwal | 221 |
# Write a Python program to Multiply all numbers in the list (4 different ways)
# Python program to multiply all values in the
# list using traversal
def multiplyList(myList) :
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result
# Driver code
list1 = [1, 2, 3]
list2 = [3, 2, 4]
print(multiplyList(list1))
print(multiplyList(list2)) | 66 |
# Create a Pandas DataFrame from List of Dicts in Python
# Python code demonstrate how to create
# Pandas DataFrame by lists of dicts.
import pandas as pd
# Initialise data to lists.
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
{'Geeks':10, 'For': 20, 'geeks': 30}]
# Creates DataFrame.
df = pd.DataFrame(data)
# Print the data
df | 58 |
# How to inverse a matrix using NumPy in Python
# Python program to inverse
# a matrix using numpy
# Import required package
import numpy as np
# Taking a 3 * 3 matrix
A = np.array([[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])
# Calculating the inverse of the matrix
print(np.linalg.inv(A)) | 54 |
# Write a Python program to sum all the items in a dictionary.
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
| 17 |
# Program to find sum of series 1^1/1!+2^2/2!+3^3/3!...+n^n/n!
import math
print("Enter the range of number:")
n=int(input())
sum=0.0
fact=1
for i in range(1,n+1):
fact*=i
sum += pow(i, i) / fact
print("The sum of the series = ",sum) | 36 |
# Check whether number is Trimorphic Number or Not
num=int(input("Enter a number:"))
flag=0
cube_power=num*num*num
while num!=0:
if num%10!=cube_power%10:
flag=1
break
num//=10
cube_power//=10
if flag==0:
print("It is a Trimorphic Number.")
else:
print("It is Not a Trimorphic Number.") | 36 |
# Write a Python program to get date and time properties from datetime function using arrow module.
import arrow
a = arrow.utcnow()
print("Current date:")
print(a.date())
print("\nCurrent time:")
print(a.time())
| 28 |
# Python Program to Reverse a Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
def reverse_llist(llist):
before = None
current = llist.head
if current is None:
return
after = current.next
while after:
current.next = before
before = current
current = after
after = after.next
current.next = before
llist.head = current
a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))
reverse_llist(a_llist)
print('The reversed list: ')
a_llist.display() | 125 |
# Find 2nd largest digit in a given number
'''Write a Python
program to Find the 2nd largest digit in a given number. or Write a
program to Find 2nd largest digit in a given number using Python '''
print("Enter the Number :")
num=int(input())
Largest=0
Sec_Largest=0
while num > 0:
reminder=num%10
if Largest<reminder:
Sec_Largest = Largest
Largest = reminder
elif reminder >= Sec_Largest:
Sec_Largest = reminder
num =num // 10
print("The Second Largest Digit is :", Sec_Largest)
| 77 |
# Write a Python program to Convert Lists of List to Dictionary
# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using loop
# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Lists of List to Dictionary
# Using loop
res = dict()
for sub in test_list:
res[tuple(sub[:2])] = tuple(sub[2:])
# printing result
print("The mapped Dictionary : " + str(res)) | 88 |
# Write a Python program to find the maximum, minimum aggregation pair in given list of integers.
from itertools import combinations
def max_aggregate(l_data):
max_pair = max(combinations(l_data, 2), key = lambda pair: pair[0] + pair[1])
min_pair = min(combinations(l_data, 2), key = lambda pair: pair[0] + pair[1])
return max_pair,min_pair
nums = [1,3,4,5,4,7,9,11,10,9]
print("Original list:")
print(nums)
result = max_aggregate(nums)
print("\nMaximum aggregation pair of the said list of tuple pair:")
print(result[0])
print("\nMinimum aggregation pair of the said list of tuple pair:")
print(result[1])
| 78 |
# Write a Pandas program to create a histogram to visualize daily return distribution of Alphabet Inc. stock price between two specific dates.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Adj Close']]
df3 = df2.set_index('Date')
daily_changes = df3.pct_change(periods=1)
sns.distplot(daily_changes['Adj Close'].dropna(),bins=100,color='purple')
plt.suptitle('Daily % return of Alphabet Inc. stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()
| 84 |
# Write a NumPy program to find the memory size of a NumPy array.
import numpy as np
n = np.zeros((4,4))
print("%d bytes" % (n.size * n.itemsize))
| 27 |
# Write a Pandas program to split the following dataframe into groups based on customer id and create a list of order date for each group.
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': ['2012-10-05','2012-09-10','2012-10-05','2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3001,3001,3005,3001,3005,3001,3005,3001,3005,3001,3005,3005],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print("Original Orders DataFrame:")
print(df)
result = df.groupby('customer_id')['ord_date'].apply(list)
print("\nGroup on 'customer_id' and display the list of order dates in group wise:")
print(result)
| 66 |
# Convert class object to JSON in Python
# import required packages
import json
# custom class
class Student:
def __init__(self, roll_no, name, batch):
self.roll_no = roll_no
self.name = name
self.batch = batch
class Car:
def __init__(self, brand, name, batch):
self.brand = brand
self.name = name
self.batch = batch
# main function
if __name__ == "__main__":
# create two new student objects
s1 = Student("85", "Swapnil", "IMT")
s2 = Student("124", "Akash", "IMT")
# create two new car objects
c1 = Car("Honda", "city", "2005")
c2 = Car("Honda", "Amaze", "2011")
# convert to JSON format
jsonstr1 = json.dumps(s1.__dict__)
jsonstr2 = json.dumps(s2.__dict__)
jsonstr3 = json.dumps(c1.__dict__)
jsonstr4 = json.dumps(c2.__dict__)
# print created JSON objects
print(jsonstr1)
print(jsonstr2)
print(jsonstr3)
print(jsonstr4) | 114 |
# Get unique values from a column in Pandas DataFrame in Python
# Import pandas package
import pandas as pd
# create a dictionary with five fields each
data = {
'A':['A1', 'A2', 'A3', 'A4', 'A5'],
'B':['B1', 'B2', 'B3', 'B4', 'B4'],
'C':['C1', 'C2', 'C3', 'C3', 'C3'],
'D':['D1', 'D2', 'D2', 'D2', 'D2'],
'E':['E1', 'E1', 'E1', 'E1', 'E1'] }
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Get the unique values of 'B' column
df.B.unique() | 75 |
# Write a Pandas program to extract hash attached word from twitter text from the specified column of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'tweets': ['#Obama says goodbye','Retweets for #cash','A political endorsement in #Indonesia', '1 dog = many #retweets', 'Just a simple #egg']
})
print("Original DataFrame:")
print(df)
def find_hash(text):
hword=re.findall(r'(?<=#)\w+',text)
return " ".join(hword)
df['hash_word']=df['tweets'].apply(lambda x: find_hash(x))
print("\Extracting#@word from dataframe columns:")
print(df)
| 71 |
# Write a NumPy program to get the row numbers in given array where at least one item is larger than a specified value.
import numpy as np
num = np.arange(36)
arr1 = np.reshape(num, [4, 9])
print("Original array:")
print(arr1)
result = np.where(np.any(arr1>10, axis=1))
print("\nRow numbers where at least one item is larger than 10:")
print(result)
| 55 |
# Write a Python program to count the number of students of individual class.
from collections import Counter
classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)
students = Counter(class_name for class_name, no_students in classes)
print(students)
| 43 |
# Write a Python program to retrieve the current working directory and change the dir (moving up one).
import os
print('Current dir:', os.getcwd())
print('\nChange the dir (moving up one):', os.pardir)
os.chdir(os.pardir)
print('Current dir:', os.getcwd())
print('\nChange the dir (moving up one):', os.pardir)
os.chdir(os.pardir)
print('Current dir:', os.getcwd())
| 45 |
# Compare two Files line by line in Python
# Importing difflib
import difflib
with open('file1.txt') as file_1:
file_1_text = file_1.readlines()
with open('file2.txt') as file_2:
file_2_text = file_2.readlines()
# Find and print the diff:
for line in difflib.unified_diff(
file_1_text, file_2_text, fromfile='file1.txt',
tofile='file2.txt', lineterm=''):
print(line) | 44 |
# numpy string operations | upper() function in Python
# Python Program explaining
# numpy.char.upper() function
import numpy as geek
in_arr = geek.array(['p4q r', '4q rp', 'q rp4', 'rp4q'])
print ("input array : ", in_arr)
out_arr = geek.char.upper(in_arr)
print ("output uppercased array :", out_arr) | 44 |
# Write a NumPy program to test whether specified values are present in an array.
import numpy as np
x = np.array([[1.12, 2.0, 3.45], [2.33, 5.12, 6.0]], float)
print("Original array:")
print(x)
print(2 in x)
print(0 in x)
print(6 in x)
print(2.3 in x)
print(5.12 in x)
| 46 |
# Python Program to Count Set Bits in a Number
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
n = int(input('Enter n: '))
print('Number of set bits:', count_set_bits(n)) | 37 |
# Write a Python program to test whether a given path exists or not. If the path exist find the filename and directory portion of the said path.
import os
print("Test a path exists or not:")
path = r'g:\\testpath\\a.txt'
print(os.path.exists(path))
path = r'g:\\testpath\\p.txt'
print(os.path.exists(path))
print("\nFile name of the path:")
print(os.path.basename(path))
print("\nDir name of the path:")
print(os.path.dirname(path))
| 56 |
# Find indices of elements equal to zero in a NumPy array in Python
# importing Numpy package
import numpy as np
# creating a 1-D Numpy array
n_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,
6, 7, 5, 0, 8])
print("Original array:")
print(n_array)
# finding indices of null elements using np.where()
print("\nIndices of elements equal to zero of the \
given 1-D array:")
res = np.where(n_array == 0)[0]
print(res) | 72 |
# Program to Find sum of series 5^2+10^2+15^2+.....N^2
import math
print("Enter the range of number(Limit):")
n=int(input())
i=5
sum=0
while(i<=n):
sum+=pow(i,2)
i+=5
print("The sum of the series = ",sum) | 28 |
# Write a Python program to count the number of times a specific element presents in a deque object.
import collections
nums = (2,9,0,8,2,4,0,9,2,4,8,2,0,4,2,3,4,0)
nums_dq = collections.deque(nums)
print("Number of 2 in the sequence")
print(nums_dq.count(2))
print("Number of 4 in the sequence")
print(nums_dq.count(4))
| 41 |
# Write a Python program to Reverse Dictionary Keys Order
# Python3 code to demonstrate working of
# Reverse Dictionary Keys Order
# Using OrderedDict() + reversed() + items()
from collections import OrderedDict
# initializing dictionary
test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Reverse Dictionary Keys Order
# Using OrderedDict() + reversed() + items()
res = OrderedDict(reversed(list(test_dict.items())))
# printing result
print("The reversed order dictionary : " + str(res)) | 84 |
# Create a Numpy array filled with all zeros | Python
# Python Program to create array with all zeros
import numpy as geek
a = geek.zeros(3, dtype = int)
print("Matrix a : \n", a)
b = geek.zeros([3, 3], dtype = int)
print("\nMatrix b : \n", b) | 47 |
# Write a Python program to check the priority of the four operators (+, -, *, /).
from collections import deque
import re
__operators__ = "+-/*"
__parenthesis__ = "()"
__priority__ = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
}
def test_higher_priority(operator1, operator2):
return __priority__[operator1] >= __priority__[operator2]
print(test_higher_priority('*','-'))
print(test_higher_priority('+','-'))
print(test_higher_priority('+','*'))
print(test_higher_priority('+','/'))
print(test_higher_priority('*','/'))
| 53 |
# Write a NumPy program to find the most frequent value in an array.
import numpy as np
x = np.random.randint(0, 10, 40)
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.bincount(x).argmax())
| 34 |
# How to get weighted random choice in Python
import random
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
sampleList, weights=(10, 20, 30, 40, 50), k=5)
print(randomList) | 29 |
# Write a NumPy program to find common values between two arrays.
import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))
| 39 |
# Write a Pandas program to keep the rows with at least 2 NaN values in a given DataFrame.
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[np.nan,np.nan,70002,np.nan,np.nan,70005,np.nan,70010,70003,70012,np.nan,np.nan],
'purch_amt':[np.nan,270.65,65.26,np.nan,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,np.nan],
'ord_date': [np.nan,'2012-09-10',np.nan,np.nan,'2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17',np.nan],
'customer_id':[np.nan,3001,3001,np.nan,3002,3001,3001,3004,3003,3002,3001,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("\nKeep the rows with at least 2 NaN values of the said DataFrame:")
result = df.dropna(thresh=2)
print(result)
| 61 |
# Write a Pandas program to find out the alcohol consumption details in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' from the world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(w_a_con.head())
print("\nThe world alcohol consumption details in the year ‘1986’ or ‘1989’ where WHO region is ‘Americas’ or 'Europe':")
print(w_a_con[((w_a_con['Year']==1985) | (w_a_con['Year']==1989)) & ((w_a_con['WHO region']=='Americas') | (w_a_con['WHO region']=='Europe'))].head(10))
| 76 |
# Write a Python program to interleave multiple lists of the same length.
def interleave_multiple_lists(list1,list2,list3):
result = [el for pair in zip(list1, list2, list3) for el in pair]
return result
list1 = [1,2,3,4,5,6,7]
list2 = [10,20,30,40,50,60,70]
list3 = [100,200,300,400,500,600,700]
print("Original list:")
print("list1:",list1)
print("list2:",list2)
print("list3:",list3)
print("\nInterleave multiple lists:")
print(interleave_multiple_lists(list1,list2,list3))
| 48 |
# Write a Python program to access a specific item in a singly linked list using index value.
class Node:
# Singly linked node
def __init__(self, data=None):
self.data = data
self.next = None
class singly_linked_list:
def __init__(self):
# Createe an empty list
self.tail = None
self.head = None
self.count = 0
def append_item(self, data):
#Append items on the list
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.count += 1
def __getitem__(self, index):
if index > self.count - 1:
return "Index out of range"
current_val = self.tail
for n in range(index):
current_val = current_val.next
return current_val.data
items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print("Search using index:")
print(items[0])
print(items[1])
print(items[4])
print(items[5])
print(items[10])
| 122 |
# Write a Python program to Extract values of Particular Key in Nested Values
# Python3 code to demonstrate working of
# Extract values of Particular Key in Nested Values
# Using list comprehension
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
'is' : {"a" : 15, "b" : 19, "c" : 20},
'best' :{"a" : 5, "b" : 10, "c" : 2}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing key
temp = "c"
# using item() to extract key value pair as whole
res = [val[temp] for key, val in test_dict.items() if temp in val]
# printing result
print("The extracted values : " + str(res)) | 121 |
# Assign Function to a Variable in Python
def a():
print("GFG")
# assigning function to a variable
var=a
# calling the variable
var() | 23 |
# Write a Python program to find the maximum length of a substring in a given string where all the characters of the substring are same. Use itertools module to solve the problem.
import itertools
def max_sub_string(str1):
return max(len(list(x)) for _, x in itertools.groupby(str1))
str1 = "aaabbccddeeeee"
print("Original string:",str1)
print("Maximum length of a substring with unique characters of the said string:")
print(max_sub_string(str1))
str1 = "c++ exercises"
print("\nOriginal string:",str1)
print("Maximum length of a substring with unique characters of the said string:")
print(max_sub_string(str1))
| 81 |
# Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
a = raw_input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4
| 52 |
# Write a Python program to Longest Substring Length of K
# Python3 code to demonstrate working of
# Longest Substring of K
# Using loop
# initializing string
test_str = 'abcaaaacbbaa'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 'a'
cnt = 0
res = 0
for idx in range(len(test_str)):
# increment counter on checking
if test_str[idx] == K:
cnt += 1
else:
cnt = 0
# retaining max
res = max(res, cnt)
# printing result
print("The Longest Substring Length : " + str(res)) | 94 |
# Write a Python program to create Fibonacci series upto n using Lambda.
from functools import reduce
fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]],
range(n-2), [0, 1])
print("Fibonacci series upto 2:")
print(fib_series(2))
print("\nFibonacci series upto 5:")
print(fib_series(5))
print("\nFibonacci series upto 6:")
print(fib_series(6))
print("\nFibonacci series upto 9:")
print(fib_series(9))
| 48 |
# Write a NumPy program to compute e
import numpy as np
x = np.array([1., 2., 3., 4.], np.float32)
print("Original array: ")
print(x)
print("\ne^x, element-wise of the said:")
r = np.exp(x)
print(r)
| 32 |
# How to convert CSV File to PDF File using Python
import pandas as pd
import pdfkit
# SAVE CSV TO HTML USING PANDAS
csv = 'MyCSV.csv'
html_file = csv_file[:-3]+'html'
df = pd.read_csv(csv_file, sep=',')
df.to_html(html_file)
# INSTALL wkhtmltopdf AND SET PATH IN CONFIGURATION
# These two Steps could be eliminated By Installing wkhtmltopdf -
# - and setting it's path to Environment Variables
path_wkhtmltopdf = r'D:\Softwares\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
# CONVERT HTML FILE TO PDF WITH PDFKIT
pdfkit.from_url("MyCSV.html", "FinalOutput.pdf", configuration=config) | 80 |
# Write a Python program to find the values of length six in a given list using Lambda.
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
days = filter(lambda day: day if len(day)==6 else '', weekdays)
for d in days:
print(d)
| 42 |
# Write a Python program to find the first two elements of a given list whose sum is equal to a given value. Use itertools module to solve the problem.
import itertools as it
def sum_pairs_list(nums, n):
for num2, num1 in list(it.combinations(nums[::-1], 2))[::-1]:
if num2 + num1 == n:
return [num1, num2]
nums = [1,2,3,4,5,6,7]
n = 10
print("Original list:",nums,": Given value:",n)
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))
nums = [1,2,-3,-4,-5,6,-7]
n = -6
print("Original list:",nums,": Given value:",n)
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))
| 84 |
# Write a Python program to Substring presence in Strings List
# Python3 code to demonstrate working of
# Substring presence in Strings List
# Using loop
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using loop to iterate
res = []
for ele in test_list1 :
temp = False
# inner loop to check for
# presence of element in any list
for sub in test_list2 :
if ele in sub:
temp = True
break
res.append(temp)
# printing result
print("The match list : " + str(res)) | 120 |
# Write a Python program to pair up the consecutive elements of a given list.
def pair_consecutive_elements(lst):
result = [[lst[i], lst[i + 1]] for i in range(len(lst) - 1)]
return result
nums = [1,2,3,4,5,6]
print("Original lists:")
print(nums)
print("Pair up the consecutive elements of the said list:")
print(pair_consecutive_elements(nums))
nums = [1,2,3,4,5]
print("\nOriginal lists:")
print(nums)
print("Pair up the consecutive elements of the said list:")
print(pair_consecutive_elements(nums))
| 63 |
# Find the minimum element in the matrix
import sys
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
#compute the minimum element of the given 2d array
min=sys.maxsize
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]<=min:
min=matrix[i][j]
# Display the smallest element of the given matrix
print("The Minimum element of the Given 2d array is: ",min) | 89 |
# Write a Python program to create the largest possible number using the elements of a given list of positive integers.
def create_largest_number(lst):
if all(val == 0 for val in lst):
return '0'
result = ''.join(sorted((str(val) for val in lst), reverse=True,
key=lambda i: i*( len(str(max(lst))) * 2 // len(i))))
return result
nums = [3, 40, 41, 43, 74, 9]
print("Original list:")
print(nums)
print("Largest possible number using the elements of the said list of positive integers:")
print(create_largest_number(nums))
nums = [10, 40, 20, 30, 50, 60]
print("\nOriginal list:")
print(nums)
print("Largest possible number using the elements of the said list of positive integers:")
print(create_largest_number(nums))
nums = [8, 4, 2, 9, 5, 6, 1, 0]
print("\nOriginal list:")
print(nums)
print("Largest possible number using the elements of the said list of positive integers:")
print(create_largest_number(nums))
| 128 |
# Bubble sort using recursion
def BubbleSort(arr,n): if(n>0): for i in range(0,n): if (arr[i]>arr[i+1]): temp = arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp BubbleSort(arr, n - 1)arr=[]n = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,n): num = int(input()) arr.append(num)BubbleSort(arr, n - 1)print("After Sorting Array Elements are:")for i in range(0,n): print(arr[i],end=" ") | 63 |
# Write a Python program to find all anagrams of a string in a given list of strings using lambda.
from collections import Counter
texts = ["bcda", "abce", "cbda", "cbea", "adcb"]
str = "abcd"
print("Orginal list of strings:")
print(texts)
result = list(filter(lambda x: (Counter(str) == Counter(x)), texts))
print("\nAnagrams of 'abcd' in the above string: ")
print(result)
| 56 |
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and find details where "Mine Name" starts with "P".
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df[df["Mine_Name"].map(lambda x: x.startswith('P'))].head()
| 37 |
# Write a Python program to create a datetime from a given timezone-aware datetime using arrow module.
import arrow
from datetime import datetime
from dateutil import tz
print("\nCreate a date from a given date and a given time zone:")
d1 = arrow.get(datetime(2018, 7, 5), 'US/Pacific')
print(d1)
print("\nCreate a date from a given date and a time zone object from a string representation:")
d2 = arrow.get(datetime(2017, 7, 5), tz.gettz('America/Chicago'))
print(d2)
d3 = arrow.get(datetime.now(tz.gettz('US/Pacific')))
print("\nCreate a date using current datetime and a specified time zone:")
print(d3)
| 84 |
# Write a Python program to Count occurrences of an element in a list
# Python code to count the number of occurrences
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x))) | 68 |
# Write a NumPy program to test whether any array element along a given axis evaluates to True.
import numpy as np
print(np.any([[False,False],[False,False]]))
print(np.any([[True,True],[True,True]]))
print(np.any([10, 20, 0, -50]))
print(np.any([10, 20, -50]))
| 31 |
# Write a Python program to concatenate element-wise three given lists.
def concatenate_lists(l1,l2,l3):
return [i + j + k for i, j, k in zip(l1, l2, l3)]
l1 = ['0','1','2','3','4']
l2 = ['red','green','black','blue','white']
l3 = ['100','200','300','400','500']
print("Original lists:")
print(l1)
print(l2)
print(l3)
print("\nConcatenate element-wise three said lists:")
print(concatenate_lists(l1,l2,l3))
| 47 |
# Write a Python program that invoke a given function after specific milliseconds.
from time import sleep
import math
def delay(fn, ms, *args):
sleep(ms / 1000)
return fn(*args)
print("Square root after specific miliseconds:")
print(delay(lambda x: math.sqrt(x), 100, 16))
print(delay(lambda x: math.sqrt(x), 1000, 100))
print(delay(lambda x: math.sqrt(x), 2000, 25100))
| 48 |
# Write a Pandas program to get all the sighting years of the unidentified flying object (ufo) and create the year as column.
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nSighting years of the unidentified flying object:")
df["Year"] = df.Date_time.dt.year
print(df.head(10))
| 47 |
# Write a Python program to Maximum and Minimum K elements in Tuple
# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# initializing K
K = 2
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
res = []
test_tup = list(sorted(test_tup))
for idx, val in enumerate(test_tup):
if idx < K or idx >= len(test_tup) - K:
res.append(val)
res = tuple(res)
# printing result
print("The extracted values : " + str(res)) | 110 |
# Write a Python program to flatten a shallow list.
import itertools
original_list = [[2,4,3],[1,5,6], [9], [7,9,0]]
new_merged_list = list(itertools.chain(*original_list))
print(new_merged_list)
| 21 |
# Change current working directory with Python
# Python program to change the
# current working directory
import os
# Function to Get the current
# working directory
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
current_path()
# Changing the CWD
os.chdir('../')
# Printing CWD after
current_path() | 54 |
# Write a Pandas program to insert a column in the sixth position of the said excel sheet and fill it with NaN values.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.insert(3, "column1", np.nan)
print(df.head)
| 39 |
# Write a NumPy program to swap rows and columns of a given array in reverse order.
import numpy as np
nums = np.array([[[1, 2, 3, 4],
[0, 1, 3, 4],
[90, 91, 93, 94],
[5, 0, 3, 2]]])
print("Original array:")
print(nums)
print("\nSwap rows and columns of the said array in reverse order:")
new_nums = print(nums[::-1, ::-1])
print(new_nums)
| 58 |
# Program to Calculate the surface area and volume of a Hemisphere
import math
r=int(input("Enter the radius of the Hemisphere:"))
PI=3.14
surface_area=3*PI*math.pow(r,2)
volume=(2.0/3.0)*PI*math.pow(r,3)
print("Surface Area of the Hemisphere = ",surface_area)
print("Volume of the Hemisphere = ",volume)
| 36 |
# Write a Python function to check whether a number is perfect or not.
def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(6))
| 38 |
# Scrape IMDB movie rating and details using Python
from bs4 import BeautifulSoup
import requests
import re | 17 |
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)
print ','.join(value)
| 67 |
# Write a NumPy program to create a random array with 1000 elements and compute the average, variance, standard deviation of the array elements.
import numpy as np
x = np.random.randn(1000)
print("Average of the array elements:")
mean = x.mean()
print(mean)
print("Standard deviation of the array elements:")
std = x.std()
print(std)
print("Variance of the array elements:")
var = x.var()
print(var)
| 59 |
# Write a Python program to Ways to convert array of strings to array of floats
# Python code to demonstrate converting
# array of strings to array of floats
# using astype
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# converting to array of floats
# using np.astype
res = ini_array.astype(np.float)
# printing final result
print ("final array", str(res)) | 74 |
# Counting the frequencies in a list using dictionary in Python
# Python program to count the frequency of
# elements in a list using a dictionary
def CountFrequency(my_list):
# Creating an empty dictionary
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% d : % d"%(key, value))
# Driver function
if __name__ == "__main__":
my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
CountFrequency(my_list) | 90 |
# br/>
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
for row in range(row_num):
for col in range(col_num):
multi_list[row][col]= row*col
print(multi_list)
| 38 |
# Write a Python program to Count the Number of matching characters in a pair of string
# Python code to count number of matching
# characters in a pair of strings
# count function
def count(str1, str2):
c, j = 0, 0
# loop executes till length of str1 and
# stores value of str1 character by character
# and stores in i at each iteration.
for i in str1:
# this will check if character extracted from
# str1 is present in str2 or not(str2.find(i)
# return -1 if not found otherwise return the
# starting occurrence index of that character
# in str2) and j == str1.find(i) is used to
# avoid the counting of the duplicate characters
# present in str1 found in str2
if str2.find(i)>= 0 and j == str1.find(i):
c += 1
j += 1
print ('No. of matching characters are : ', c)
# Main function
def main():
str1 ='aabcddekll12@' # first string
str2 ='bb2211@55k' # second string
count(str1, str2) # calling count function
# Driver Code
if __name__=="__main__":
main() | 177 |
Subsets and Splits