Problem,Solution
0,Write a NumPy program to repeat elements of an array. ,"import numpy as np
x = np.repeat(3, 4)
print(x)
x = np.array([[1,2],[3,4]])
print(np.repeat(x, 2))
"
1,Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included). ,"def printValues():
l = list()
for i in range(1,31):
l.append(i**2)
print(l)
printValues()
"
2,Write a Python program to remove duplicates from a list of lists. ,"import itertools
num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
print(""Original List"", num)
num.sort()
new_num = list(num for num,_ in itertools.groupby(num))
print(""New List"", new_num)
"
3,Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib. ,"import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.2)
y = np.sin(x)
print(""Plot the points using matplotlib:"")
plt.plot(x, y)
plt.show()
"
4,Write a Python program to alter a given SQLite table. ,"import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
cursorObj.execute(""CREATE TABLE agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);"")
print(""\nagent_master file has created."")
# adding a new column in the agent_master table
cursorObj.execute(""""""
ALTER TABLE agent_master
ADD COLUMN FLAG BOOLEAN;
"""""")
print(""\nagent_master file altered."")
conn.commit()
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
print(""\nThe SQLite connection is closed."")
"
5,Write a Python program to extract specified size of strings from a give list of string values using lambda. ,"def extract_string(str_list1, l):
result = list(filter(lambda e: len(e) == l, str_list1))
return result
str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
print(""Original list:"")
print(str_list1)
l = 8
print(""\nlength of the string to extract:"")
print(l)
print(""\nAfter extracting strings of specified length from the said list:"")
print(extract_string(str_list1 , l))
"
6,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))
"
7,Write a Python program to sort unsorted numbers using Strand sort. ,"#Ref:https://bit.ly/3qW9FIX
import operator
def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list:
_operator = operator.lt if reverse else operator.gt
solution = solution or []
if not arr:
return solution
sublist = [arr.pop(0)]
for i, item in enumerate(arr):
if _operator(item, sublist[-1]):
sublist.append(item)
arr.pop(i)
# merging sublist into solution list
if not solution:
solution.extend(sublist)
else:
while sublist:
item = sublist.pop(0)
for i, xx in enumerate(solution):
if not _operator(item, xx):
solution.insert(i, item)
break
else:
solution.append(item)
strand_sort(arr, reverse, solution)
return solution
lst = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(lst)
print(""After applying Strand sort the said list becomes:"")
print(strand_sort(lst))
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(lst)
print(""After applying Strand sort the said list becomes:"")
print(strand_sort(lst))
lst = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(lst)
print(""After applying Strand sort the said list becomes:"")
print(strand_sort(lst))
"
8,Write a Python program to insert a specified element in a given list after every nth element. ,"def inset_element_list(lst, x, n):
i = n
while i < len(lst):
lst.insert(i, x)
i+= n+1
return lst
nums = [1, 3, 5, 7, 9, 11,0, 2, 4, 6, 8, 10,8,9,0,4,3,0]
print(""Original list:"")
print(nums)
x = 20
n = 4
print(""\nInsert"",x,""in said list after every"",n,""th element:"")
print(inset_element_list(nums, x, n))
chars = ['s','d','f','j','s','a','j','d','f','d']
print(""\nOriginal list:"")
print(chars)
x = 'Z'
n = 3
print(""\nInsert"",x,""in said list after every"",n,""th element:"")
print(inset_element_list(chars, x, n))
"
9,rite a Pandas program to create a Pivot table and find the maximum and minimum sale value of the items. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=[np.max, np.min])
print(table)
"
10,Write a NumPy program to extract upper triangular part of a NumPy matrix. ,"import numpy as np
num = np.arange(18)
arr1 = np.reshape(num, [6, 3])
print(""Original array:"")
print(arr1)
result = arr1[np.triu_indices(3)]
print(""\nExtract upper triangular part of the said array:"")
print(result)
result = arr1[np.triu_indices(2)]
print(""\nExtract upper triangular part of the said array:"")
print(result)
"
11,Write a Python program to find the maximum occurring character in a given string. ,"def get_max_occuring_char(str1):
ASCII_SIZE = 256
ctr = [0] * ASCII_SIZE
max = -1
ch = ''
for i in str1:
ctr[ord(i)]+=1;
for i in str1:
if max < ctr[ord(i)]:
max = ctr[ord(i)]
ch = i
return ch
print(get_max_occuring_char(""Python: Get file creation and modification date/times""))
print(get_max_occuring_char(""abcdefghijkb""))
"
12,"Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user. ","num = int(input(""Enter a number: ""))
mod = num % 2
if mod > 0:
print(""This is an odd number."")
else:
print(""This is an even number."")"
13,Write a NumPy program to create a new vector with 2 consecutive 0 between two values of a given vector. ,"import numpy as np
nums = np.array([1,2,3,4,5,6,7,8])
print(""Original array:"")
print(nums)
p = 2
new_nums = np.zeros(len(nums) + (len(nums)-1)*(p))
new_nums[::p+1] = nums
print(""\nNew array:"")
print(new_nums)
"
14,Write a Python program to count the occurrences of each word in a given sentence. ,"def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count('the quick brown fox jumps over the lazy dog.'))
"
15,Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically. ,"items=[n for n in input().split('-')]
items.sort()
print('-'.join(items))
"
16,Write a Pandas program to insert a column at a specific index in a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'weight': [35, 32, 33, 30, 31, 32]},
index = [1, 2, 3, 4, 5, 6])
print(""Original DataFrame with single index:"")
print(df)
date_of_birth = ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997']
idx = 3
print(""\nInsert 'date_of_birth' column in 3rd position of the said DataFrame:"")
df.insert(loc=idx, column='date_of_birth', value=date_of_birth)
print(df)
"
17,Write a Python program to remove the last N number of elements from a given list. ,"def remove_last_n(nums, N):
result = nums[:len(nums)-N]
return result
nums = [2,3,9,8,2,0,39,84,2,2,34,2,34,5,3,5]
print(""Original lists:"")
print(nums)
N = 3
print(""\nRemove the last"",N,""elements from the said list:"")
print(remove_last_n(nums, N))
N = 5
print(""\nRemove the last"",N,""elements from the said list:"")
print(remove_last_n(nums, N))
N = 1
print(""\nRemove the last"",N,""element from the said list:"")
print(remove_last_n(nums, N))
"
18,Write a Python program to find index position and value of the maximum and minimum values in a given list of numbers using lambda. ,"def position_max_min(nums):
max_result = max(enumerate(nums), key=(lambda x: x[1]))
min_result = min(enumerate(nums), key=(lambda x: x[1]))
return max_result,min_result
nums = [12,33,23,10.11,67,89,45,66.7,23,12,11,10.25,54]
print(""Original list:"")
print(nums)
result = position_max_min(nums)
print(""\nIndex position and value of the maximum value of the said list:"")
print(result[0])
print(""\nIndex position and value of the minimum value of the said list:"")
print(result[1])
"
19,Write a NumPy program to find the k smallest values of a given NumPy array. ,"import numpy as np
array1 = np.array([1, 7, 8, 2, 0.1, 3, 15, 2.5])
print(""Original arrays:"")
print(array1)
k = 4
result = np.argpartition(array1, k)
print(""\nk smallest values:"")
print(array1[result[:k]])
"
20,"Write a NumPy program to add one polynomial to another, subtract one polynomial from another, multiply one polynomial by another and divide one polynomial by another. ","from numpy.polynomial import polynomial as P
x = (10,20,30)
y = (30,40,50)
print(""Add one polynomial to another:"")
print(P.polyadd(x,y))
print(""Subtract one polynomial from another:"")
print(P.polysub(x,y))
print(""Multiply one polynomial by another:"")
print(P.polymul(x,y))
print(""Divide one polynomial by another:"")
print(P.polydiv(x,y))
"
21,Write a Python program to check common elements between two given list are in same order or not. ,"def same_order(l1, l2):
common_elements = set(l1) & set(l2)
l1 = [e for e in l1 if e in common_elements]
l2 = [e for e in l2 if e in common_elements]
return l1 == l2
color1 = [""red"",""green"",""black"",""orange""]
color2 = [""red"",""pink"",""green"",""white"",""black""]
color3 = [""white"",""orange"",""pink"",""black""]
print(""Original lists:"")
print(color1)
print(color2)
print(color3)
print(""\nTest common elements between color1 and color2 are in same order?"")
print(same_order(color1, color2))
print(""\nTest common elements between color1 and color3 are in same order?"")
print(same_order(color1, color3))
print(""\nTest common elements between color2 and color3 are in same order?"")
print(same_order(color2, color3))
"
22,Write a Python program to find numbers divisible by nineteen or thirteen from a list of numbers using Lambda. ,"nums = [19, 65, 57, 39, 152, 639, 121, 44, 90, 190]
print(""Orginal list:"")
print(nums)
result = list(filter(lambda x: (x % 19 == 0 or x % 13 == 0), nums))
print(""\nNumbers of the above list divisible by nineteen or thirteen:"")
print(result)
"
23,Write a NumPy program to multiply two given arrays of same size element-by-element. ,"import numpy as np
nums1 = np.array([[2, 5, 2],
[1, 5, 5]])
nums2 = np.array([[5, 3, 4],
[3, 2, 5]])
print(""Array1:"")
print(nums1)
print(""Array2:"")
print(nums2)
print(""\nMultiply said arrays of same size element-by-element:"")
print(np.multiply(nums1, nums2))
"
24,"Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. ","def last(n): return n[-1]
def sort_list_last(tuples):
return sorted(tuples, key=last)
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
"
25,Write a Pandas program to replace the missing values with the most frequent values present in each column of 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nReplace the missing values with the most frequent values present in each column:"")
result = df.fillna(df.mode().iloc[0])
print(result)
"
26,"Write a NumPy program to split an array of 14 elements into 3 arrays, each of which has 2, 4, and 8 elements in the original order. ","import numpy as np
x = np.arange(1, 15)
print(""Original array:"",x)
print(""After splitting:"")
print(np.split(x, [2, 6]))
"
27,Write a Python program to create a deep copy of a given dictionary. Use copy.copy,"import copy
nums_x = {""a"":1, ""b"":2, 'cc':{""c"":3}}
print(""Original dictionary: "", nums_x)
nums_y = copy.deepcopy(nums_x)
print(""\nDeep copy of the said list:"")
print(nums_y)
print(""\nChange the value of an element of the original dictionary:"")
nums_x[""cc""][""c""] = 10
print(nums_x)
print(""\nSecond dictionary (Deep copy):"")
print(nums_y)
nums = {""x"":1, ""y"":2, 'zz':{""z"":3}}
nums_copy = copy.deepcopy(nums)
print(""\nOriginal dictionary :"")
print(nums)
print(""\nDeep copy of the said list:"")
print(nums_copy)
print(""\nChange the value of an element of the original dictionary:"")
nums[""zz""][""z""] = 10
print(""\nFirst dictionary:"")
print(nums)
print(""\nSecond dictionary (Deep copy):"")
print(nums_copy)
"
28,Write a Pandas program to create a subset of a given series based on value and condition. ,"import pandas as pd
s = pd.Series([0, 1,2,3,4,5,6,7,8,9,10])
print(""Original Data Series:"")
print(s)
print(""\nSubset of the above Data Series:"")
n = 6
new_s = s[s < n]
print(new_s)
"
29,Write a Python program to get the items from a given list with specific condition. ,"def first_index(l1):
return sum(1 for i in l1 if (i> 45 and i % 2 == 0))
nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83]
print(""Original list:"")
print(nums)
n = 45
print(""\nNumber of Items of the said list which are even and greater than"",n)
print(first_index(nums))
"
30,Write a Python program to read a file line by line store it into a variable. ,"def file_read(fname):
with open (fname, ""r"") as myfile:
data=myfile.readlines()
print(data)
file_read('test.txt')
"
31,Write a Python program to get the current value of the recursion limit. ,"import sys
print()
print(""Current value of the recursion limit:"")
print(sys.getrecursionlimit())
print()
"
32,Write a Python program to swap cases of a given string. ,"def swap_case_string(str1):
result_str = """"
for item in str1:
if item.isupper():
result_str += item.lower()
else:
result_str += item.upper()
return result_str
print(swap_case_string(""Python Exercises""))
print(swap_case_string(""Java""))
print(swap_case_string(""NumPy""))
"
33,"Write a Python program to convert an address (like ""1600 Amphitheatre Parkway, Mountain View, CA"") into geographic coordinates (like latitude 37.423021 and longitude -122.083739). ","import requests
geo_url = 'http://maps.googleapis.com/maps/api/geocode/json'
my_address = {'address': '21 Ramkrishana Road, Burdwan, East Burdwan, West Bengal, India',
'language': 'en'}
response = requests.get(geo_url, params = my_address)
results = response.json()['results']
my_geo = results[0]['geometry']['location']
print(""Longitude:"",my_geo['lng'],""\n"",""Latitude:"",my_geo['lat'])
"
34,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)
"
35,Write a Python program to create a two-dimensional list from given list of lists. ,"def two_dimensional_list(nums):
return list(zip(*nums))
print(two_dimensional_list([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]))
print(two_dimensional_list([[1, 2], [4, 5]]))
"
36,Write a Python program to invert a dictionary with unique hashable values. ,"def test(students):
return { value: key for key, value in students.items() }
students = {
'Theodore': 10,
'Mathew': 11,
'Roxanne': 9,
}
print(test(students))
"
37,Write a NumPy program to access last two columns of a multidimensional columns. ,"import numpy as np
arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arra)
result = arra[:,[1,2]]
print(result)
"
38,Write a Python program to create Cartesian product of two or more given lists using itertools. ,"import itertools
def cartesian_product(lists):
return list(itertools.product(*lists))
ls = [[1,2],[3,4]]
print(""Original Lists:"",ls)
print(""Cartesian product of the said lists: "",cartesian_product(ls))
ls = [[1,2,3],[3,4,5]]
print(""\nOriginal Lists:"",ls)
print(""Cartesian product of the said lists: "",cartesian_product(ls))
ls = [[],[1,2,3]]
print(""\nOriginal Lists:"",ls)
print(""Cartesian product of the said lists: "",cartesian_product(ls))
ls = [[1,2],[]]
print(""\nOriginal Lists:"",ls)
print(""Cartesian product of the said lists: "",cartesian_product(ls))
"
39,Write a NumPy program to find the first Monday in May 2017. ,"import numpy as np
print(""First Monday in May 2017:"")
print(np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon'))
"
40, Write a Python program to get the number of people visiting a U.S. government website right now. ,"#https://bit.ly/2lVhlLX
import requests
from lxml import html
url = 'https://www.us-cert.gov/ncas/alerts'
doc = html.fromstring(requests.get(url).text)
print(""The number of security alerts issued by US-CERT in the current year:"")
print(len(doc.cssselect('.item-list li')))
"
41,Write a NumPy program to remove the leading and trailing whitespaces of all the elements of a given array. ,"import numpy as np
x = np.array([' python exercises ', ' PHP ', ' java ', ' C++'], dtype=np.str)
print(""Original Array:"")
print(x)
stripped = np.char.strip(x)
print(""\nRemove the leading and trailing whitespaces: "", stripped)
"
42,Write a Python program to find the first repeated character of a given string where the index of first occurrence is smallest. ,"def first_repeated_char_smallest_distance(str1):
temp = {}
for ch in str1:
if ch in temp:
return ch, str1.index(ch);
else:
temp[ch] = 0
return 'None'
print(first_repeated_char_smallest_distance(""abcabc""))
print(first_repeated_char_smallest_distance(""abcb""))
print(first_repeated_char_smallest_distance(""abcc""))
print(first_repeated_char_smallest_distance(""abcxxy""))
print(first_repeated_char_smallest_distance(""abc""))))
"
43,Write a Python program to create a table and insert some records in that table. Finally selects all rows from the table and display the records. ,"import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute(""CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));"")
# Insert records
cursorObj.executescript(""""""
INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);
INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
"""""")
conn.commit()
cursorObj.execute(""SELECT * FROM salesman"")
rows = cursorObj.fetchall()
print(""Agent details:"")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
print(""\nThe SQLite connection is closed."")
"
44,Write a Pandas program to calculate the number of characters in each word in a given series. ,"import pandas as pd
series1 = pd.Series(['Php', 'Python', 'Java', 'C#'])
print(""Original Series:"")
print(series1)
result = series1.map(lambda x: len(x))
print(""\nNumber of characters in each word in the said series:"")
print(result)
"
45,"Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + q(3). ","import numpy as np
p = np.array([[0, 0, 0],
[1, 2, 3],
[4, 5, 6]])
q= np.array([10, 11, 12])
print(""Original arrays:"")
print(""Array-1"")
print(p)
print(""Array-2"")
print(q)
print(""\nNew Array:"")
new_array1 = p + q
print(new_array1)
"
46,Write a Python program to check if a given function returns True for at least one element in the list. ,"def some(lst, fn = lambda x: x):
return any(map(fn, lst))
print(some([0, 1, 2, 0], lambda x: x >= 2 ))
print(some([5, 10, 20, 10], lambda x: x < 2 ))
"
47,Write a NumPy program to create an array using generator function that generates 15 integers. ,"import numpy as np
def generate():
for n in range(15):
yield n
nums = np.fromiter(generate(),dtype=float,count=-1)
print(""New array:"")
print(nums)
"
48,Write a Python program to find four elements from a given array of integers whose sum is equal to a given number. The solution set must not contain duplicate quadruplets. ,"#Source: https://bit.ly/2SSoyhf
from bisect import bisect_left
class Solution:
def fourSum(self, nums, target):
""""""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
""""""
N = 4
quadruplets = []
if len(nums) < N:
return quadruplets
nums = sorted(nums)
quadruplet = []
# Let top[i] be the sum of largest i numbers.
top = [0]
for i in range(1, N):
top.append(top[i - 1] + nums[-i])
# Find range of the least number in curr_n (0,...,N)
# numbers that sum up to curr_target, then find range
# of 2nd least number and so on by recursion.
def sum_(curr_target, curr_n, lo=0):
if curr_n == 0:
if curr_target == 0:
quadruplets.append(quadruplet[:])
return
next_n = curr_n - 1
max_i = len(nums) - curr_n
max_i = bisect_left(
nums, curr_target // curr_n,
lo, max_i)
min_i = bisect_left(
nums, curr_target - top[next_n],
lo, max_i)
for i in range(min_i, max_i + 1):
if i == min_i or nums[i] != nums[i - 1]:
quadruplet.append(nums[i])
next_target = curr_target - nums[i]
sum_(next_target, next_n, i + 1)
quadruplet.pop()
sum_(target, N)
return quadruplets
s = Solution()
nums = [-2, -1, 1, 2, 3, 4, 5, 6]
target = 10
result = s.fourSum(nums, target)
print(""\nArray values & target value:"",nums,""&"",target)
print(""Solution Set:\n"", result)
"
49,Write a Python program to extract specified size of strings from a give list of string values. ,"def extract_string(str_list1, l):
result = [e for e in str_list1 if len(e) == l]
return result
str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
print(""Original list:"")
print(str_list1)
l = 8
print(""\nlength of the string to extract:"")
print(l)
print(""\nAfter extracting strings of specified length from the said list:"")
print(extract_string(str_list1 , l))
"
50,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))
"
51,Write a Pandas program to check the empty values of UFO (unidentified flying object) Dataframe. ,"import pandas as pd
df = pd.read_csv(r'ufo.csv')
print(df.isnull().sum())
"
52,"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()
"
53,Write a Python program to find the difference between consecutive numbers in a given list. ,"def diff_consecutive_nums(nums):
result = [b-a for a, b in zip(nums[:-1], nums[1:])]
return result
nums1 = [1, 1, 3, 4, 4, 5, 6, 7]
print(""Original list:"")
print(nums1)
print(""Difference between consecutive numbers of the said list:"")
print(diff_consecutive_nums(nums1))
nums2 = [4, 5, 8, 9, 6, 10]
print(""\nOriginal list:"")
print(nums2)
print(""Difference between consecutive numbers of the said list:"")
print(diff_consecutive_nums(nums2))
"
54,Write a Pandas program to extract only words from a given column of a given DataFrame. ,"import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'address': ['9910 Surrey Ave.','92 N. Bishop Ave.','9910 Golden Star Ave.', '102 Dunbar St.', '17 West Livingston Court']
})
print(""Original DataFrame:"")
print(df)
def search_words(text):
result = re.findall(r'\b[^\d\W]+\b', text)
return "" "".join(result)
df['only_words']=df['address'].apply(lambda x : search_words(x))
print(""\nOnly words:"")
print(df)
"
55,"Write a Python program to replace hour, minute, day, month, year and timezone with specified value of current datetime using arrow. ","import arrow
a = arrow.utcnow()
print(""Current date and time:"")
print(a)
print(""\nReplace hour and minute with 5 and 35:"")
print(a.replace(hour=5, minute=35))
print(""\nReplace day with 2:"")
print(a.replace(day=2))
print(""\nReplace year with 2021:"")
print(a.replace(year=2021))
print(""\nReplace month with 11:"")
print(a.replace(month=11))
print(""\nReplace timezone with 'US/Pacific:"")
print(a.replace(tzinfo='US/Pacific'))
"
56,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))
"
57,Write a Pandas program to find and drop the missing values from 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(""\nMissing values:"")
print(w_a_con.isnull())
print(""\nDropping the missing values:"")
print(w_a_con.dropna())
"
58,Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number. ,"
def sieve_of_Eratosthenes(num):
limitn = num+1
not_prime_num = set()
prime_nums = []
for i in range(2, limitn):
if i in not_prime_num:
continue
for f in range(i*2, limitn, i):
not_prime_num.add(f)
prime_nums.append(i)
return prime_nums
print(sieve_of_Eratosthenes(100));
"
59,Write a Python program to create non-repeated combinations of Cartesian product of four given list of numbers. ,"import itertools as it
mums1 = [1, 2, 3, 4]
mums2 = [5, 6, 7, 8]
mums3 = [9, 10, 11, 12]
mums4 = [13, 14, 15, 16]
print(""Original lists:"")
print(mums1)
print(mums2)
print(mums3)
print(mums4)
print(""\nSum of the specified range:"")
for i in it.product([tuple(mums1)], it.permutations(mums2), it.permutations(mums3), it.permutations(mums4)):
print(i)
"
60,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)
"
61,Write a Pandas program to replace NaNs with the value from the previous row or the next row 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nReplacing NaNs with the value from the previous row (purch_amt):"")
df['purch_amt'].fillna(method='pad', inplace=True)
print(df)
print(""\nReplacing NaNs with the value from the next row (sale_amt):"")
df['sale_amt'].fillna(method='bfill', inplace=True)
print(df)
"
62,Write a Python program to sort a list of elements using the merge sort algorithm. ,"def mergeSort(nlist):
print(""Splitting "",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print(""Merging "",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
"
63," latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map.","from lxml import html
import requests
response = requests.get('http://catalog.data.gov/dataset?q=&sort=metadata_created+desc')
doc = html.fromstring(response.text)
title = doc.cssselect('h3.dataset-heading')[0].text_content()
print(""The name of the most recently added dataset on data.gov:"")
print(title.strip())
"
64,Write a NumPy program to create an array of ones and an array of zeros. ,"import numpy as np
print(""Create an array of zeros"")
x = np.zeros((1,2))
print(""Default type is float"")
print(x)
print(""Type changes to int"")
x = np.zeros((1,2), dtype = np.int)
print(x)
print(""Create an array of ones"")
y= np.ones((1,2))
print(""Default type is float"")
print(y)
print(""Type changes to int"")
y = np.ones((1,2), dtype = np.int)
print(y)
"
65,Write a Python program to find the value of the first element in the given list that satisfies the provided testing function. ,"def find(lst, fn):
return next(x for x in lst if fn(x))
print(find([1, 2, 3, 4], lambda n: n % 2 == 1))
print(find([1, 2, 3, 4], lambda n: n % 2 == 0))
"
66,Write a Python program to remove duplicates from Dictionary. ,"student_data = {'id1':
{'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id2':
{'name': ['David'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id3':
{'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id4':
{'name': ['Surya'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
}
result = {}
for key,value in student_data.items():
if value not in result.values():
result[key] = value
print(result)
"
67,Write a Python program to find the list in a list of lists whose sum of elements is the highest. ,"num = [[1,2,3], [4,5,6], [10,11,12], [7,8,9]]
print(max(num, key=sum))
"
68,Write a Python program to get the top stories from Google news. ,"import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
news_url=""https://news.google.com/news/rss""
Client=urlopen(news_url)
xml_page=Client.read()
Client.close()
soup_page=soup(xml_page,""xml"")
news_list=soup_page.findAll(""item"")
# Print news title, url and publish date
for news in news_list:
print(news.title.text)
print(news.link.text)
print(news.pubDate.text)
print(""-""*60)
"
69,Write a Python program to check all values are same in a dictionary. ,"def value_check(students, n):
result = all(x == n for x in students.values())
return result
students = {'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12}
print(""Original Dictionary:"")
print(students)
n = 12
print(""\nCheck all are "",n,""in the dictionary."")
print(value_check(students, n))
n = 10
print(""\nCheck all are "",n,""in the dictionary."")
print(value_check(students, n))
"
70,Write a Python program to compare two given lists and find the indices of the values present in both lists. ,"def matched_index(l1, l2):
l2 = set(l2)
return [i for i, el in enumerate(l1) if el in l2]
nums1 = [1, 2, 3, 4, 5 ,6]
nums2 = [7, 8, 5, 2, 10, 12]
print(""Original lists:"")
print(nums1)
print(nums2)
print(""Compare said two lists and get the indices of the values present in both lists:"")
print(matched_index(nums1, nums2))
nums1 = [1, 2, 3, 4, 5 ,6]
nums2 = [7, 8, 5, 7, 10, 12]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""Compare said two lists and get the indices of the values present in both lists:"")
print(matched_index(nums1, nums2))
nums1 = [1, 2, 3, 4, 15 ,6]
nums2 = [7, 8, 5, 7, 10, 12]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""Compare said two lists and get the indices of the values present in both lists:"")
print(matched_index(nums1, nums2))
"
71,Write a Python program to create a 24-hour time format (HH:MM ) using 4 given digits. Display the latest time and do not use any digit more than once. ,"import itertools
def max_time(nums):
for i in range(len(nums)):
nums[i] *= -1
nums.sort()
for hr1, hr2, m1, m2 in itertools.permutations(nums):
hrs = -(10*hr1 + hr2)
mins = -(10*m1 + m2)
if 60> mins >=0 and 24 > hrs >=0:
result = ""{:02}:{:02}"".format(hrs, mins)
break
return result
nums = [1,2,3,4]
print(""Original array:"",nums)
print(""Latest time: "",max_time(nums))
nums = [1,2,4,5]
print(""\nOriginal array:"",nums)
print(""Latest time: "",max_time(nums))
nums = [2,2,4,5]
print(""\nOriginal array:"",nums)
print(""Latest time: "",max_time(nums))
nums = [2,2,4,3]
print(""\nOriginal array:"",nums)
print(""Latest time: "",max_time(nums))
nums = [0,2,4,3]
print(""\nOriginal array:"",nums)
print(""Latest time: "",max_time(nums))
"
72,"Sum a list of numbers. Write a Python program to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on. ","#Source: shorturl.at/csxLM
def test(list1):
result = [(x + y) / 2.0 for (x, y) in zip(list1[:-1], list1[1:])]
return list(result)
nums = [1,2,3,4,5,6,7]
print(""\nOriginal list:"")
print(nums)
print(""\nSum the said list of numbers:"")
print(test(nums))
nums = [0,1,-3,3,7,-5,6,7,11]
print(""\nOriginal list:"")
print(nums)
print(""\nSum the said list of numbers:"")
print(test(nums))
"
73,Write a Python program to test whether all numbers of a list is greater than a certain number. ,"num = [2, 3, 4, 5]
print()
print(all(x > 1 for x in num))
print(all(x > 4 for x in num))
print()
"
74,Write a NumPy program to test whether a given 2D array has null columns or not. ,"import numpy as np
print(""Original array:"")
nums = np.random.randint(0,3,(4,10))
print(nums)
print(""\nTest whether the said array has null columns or not:"")
print((~nums.any(axis=0)).any())
"
75,Write a NumPy program to convert angles from degrees to radians for all elements in a given array. ,"import numpy as np
x = np.array([-180., -90., 90., 180.])
r1 = np.radians(x)
r2 = np.deg2rad(x)
assert np.array_equiv(r1, r2)
print(r1)
"
76,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)
"
77,rogram to display the name of the most recently added dataset on data.gov. ,"from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.example.com/')
bsh = BeautifulSoup(html.read(), 'html.parser')
print(bsh.h1)
"
78,Write a NumPy program to extract all numbers from a given array which are less and greater than a specified number. ,"import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 4.38, 6.99],
[1.54, 2.39, 9.29]])
print(""Original array:"")
print(nums)
n = 5
print(""\nElements of the said array greater than"",n)
print(nums[nums > n])
n = 6
print(""\nElements of the said array less than"",n)
print(nums[nums < n])
"
79,Write a NumPy program to extract second and fourth elements of the second and fourth rows from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: Second and fourth elements of the second and fourth rows "")
print(arra_data[1::2, 1::2])
"
80,Write a NumPy program to split a given array into multiple sub-arrays vertically (row-wise). ,"import numpy as np
print(""\nOriginal arrays:"")
x = np.arange(16.0).reshape(4, 4)
print(x)
new_array1 = np.vsplit(x, 2)
print(""\nSplit an array into multiple sub-arrays vertically:"")
print(new_array1)
"
81,Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters. ,"def count_k_dist(str1, k):
str_len = len(str1)
result = 0
ctr = [0] * 27
for i in range(0, str_len):
dist_ctr = 0
ctr = [0] * 27
for j in range(i, str_len):
if(ctr[ord(str1[j]) - 97] == 0):
dist_ctr += 1
ctr[ord(str1[j]) - 97] += 1
if(dist_ctr == k):
result += 1
if(dist_ctr > k):
break
return result
str1 = input(""Input a string (lowercase alphabets):"")
k = int(input(""Input k: ""))
print(""Number of substrings with exactly"", k, ""distinct characters : "", end = """")
print(count_k_dist(str1, k))
"
82,Write a Python program to create a list reflecting the run-length encoding from a given list of integers or a given list of characters. ,"from itertools import groupby
def encode_list(s_list):
return [[len(list(group)), key] for key, group in groupby(s_list)]
n_list = [1,1,2,3,4,4.3,5, 1]
print(""Original list:"")
print(n_list)
print(""\nList reflecting the run-length encoding from the said list:"")
print(encode_list(n_list))
n_list = 'automatically'
print(""\nOriginal String:"")
print(n_list)
print(""\nList reflecting the run-length encoding from the said string:"")
print(encode_list(n_list))
"
83,Write a Pandas program to check whether only numeric values present in a given column of a DataFrame.,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Company','Company a001', '2055', 'abcd', '123345'],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]})
print(""Original DataFrame:"")
print(df)
print(""\nNumeric values present in company_code column:"")
df['company_code_is_digit'] = list(map(lambda x: x.isdigit(), df['company_code']))
print(df)
"
84,Write a Python program to check if a specific Key and a value exist in a dictionary. ,"def test(dictt, key, value):
if any(sub[key] == value for sub in dictt):
return True
return False
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
]
print(""\nOriginal dictionary:"")
print(students)
print(""\nCheck if a specific Key and a value exist in the said dictionary:"")
print(test(students,'student_id', 1))
print(test(students,'name', 'Brian Howell'))
print(test(students,'class', 'VII'))
print(test(students,'class', 'I'))
print(test(students,'name', 'Brian Howelll'))
print(test(students,'student_id', 11))
"
85,Write a Pandas program to split a given dataset using group by on multiple columns and drop last n rows of from 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':[3002,3001,3001,3003,3002,3002,3001,3004,3003,3002,3003,3001],
'salesman_id':[5002,5003,5001,5003,5002,5001,5001,5003,5003,5002,5003,5001]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nSplit the said data on 'salesman_id', 'customer_id' wise:"")
result = df.groupby(['salesman_id', 'customer_id'])
for name,group in result:
print(""\nGroup:"")
print(name)
print(group)
n = 2
#result1 = df.groupby(['salesman_id', 'customer_id']).tail(n).index, axis=0)
print(""\nDroping last two records:"")
result1 = df.drop(df.groupby(['salesman_id', 'customer_id']).tail(n).index, axis=0)
print(result1)
"
86,"Write a NumPy program to find point by point distances of a random vector with shape (10,2) representing coordinates. ","import numpy as np
a= np.random.random((10,2))
x,y = np.atleast_2d(a[:,0], a[:,1])
d = np.sqrt( (x-x.T)**2 + (y-y.T)**2)
print(d)
"
87,Write a Python program to create the next bigger number by rearranging the digits of a given number. ,"def rearrange_bigger(n):
#Break the number into digits and store in a list
nums = list(str(n))
for i in range(len(nums)-2,-1,-1):
if nums[i] < nums[i+1]:
z = nums[i:]
y = min(filter(lambda x: x > z[0], z))
z.remove(y)
z.sort()
nums[i:] = [y] + z
return int("""".join(nums))
return False
n = 12
print(""Original number:"",n)
print(""Next bigger number:"",rearrange_bigger(n))
n = 10
print(""\nOriginal number:"",n)
print(""Next bigger number:"",rearrange_bigger(n))
n = 201
print(""\nOriginal number:"",n)
print(""Next bigger number:"",rearrange_bigger(n))
n = 102
print(""\nOriginal number:"",n)
print(""Next bigger number:"",rearrange_bigger(n))
n = 445
print(""\nOriginal number:"",n)
print(""Next bigger number:"",rearrange_bigger(n))
"
88,Write a Python program to filter a dictionary based on values. ,"marks = {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190}
print(""Original Dictionary:"")
print(marks)
print(""Marks greater than 170:"")
result = {key:value for (key, value) in marks.items() if value >= 170}
print(result)
"
89,Write a Python program to count the frequency of the elements of a given unordered list. ,"from itertools import groupby
uno_list = [2,1,3,8,5,1,4,2,3,4,0,8,2,0,8,4,2,3,4,2]
print(""Original list:"")
print(uno_list)
uno_list.sort()
print(uno_list)
print(""\nSort the said unordered list:"")
print(uno_list)
print(""\nFrequency of the elements of the said unordered list:"")
result = [len(list(group)) for key, group in groupby(uno_list)]
print(result)
"
90,Write a Pandas program to find out the alcohol consumption details in the year '1987' or '1989' 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 where year is 1987 or 1989:"")
print((w_a_con[(w_a_con['Year']==1987) | (w_a_con['Year']==1989)]).head(10))
"
91,Write a Python program to count the number of even and odd numbers from a series of numbers. ,"numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print(""Number of even numbers :"",count_even)
print(""Number of odd numbers :"",count_odd)
"
92,Write a Python code to send some sort of data in the URL's query string. ,"import requests
payload = {'key1': 'value1', 'key2': 'value2'}
print(""Parameters: "",payload)
r = requests.get('https://httpbin.org/get', params=payload)
print(""Print the url to check the URL has been correctly encoded or not!"")
print(r.url)
print(""\nPass a list of items as a value:"")
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
print(""Parameters: "",payload)
r = requests.get('https://httpbin.org/get', params=payload)
print(""Print the url to check the URL has been correctly encoded or not!"")
print(r.url)
"
93,Write a Pandas program to split the following dataframe into groups and calculate monthly purchase amount. ,"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': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'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)
df['ord_date']= pd.to_datetime(df['ord_date'])
print(""\nMonth wise purchase amount:"")
result = df.set_index('ord_date').groupby(pd.Grouper(freq='M')).agg({'purch_amt':sum})
print(result)
"
94,Write a Pandas program to add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit. ,"import pandas as pd
nums = {'amount': ['10', '250', '3000', '40000', '500000']}
print(""Original dataframe:"")
df = pd.DataFrame(nums)
print(df)
print(""\nAdd leading zeros:"")
df['amount'] = list(map(lambda x: x.zfill(10), df['amount']))
print(df)
"
95,Write a NumPy program to compute the reciprocal for all elements in a given array. ,"import numpy as np
x = np.array([1., 2., .2, .3])
print(""Original array: "")
print(x)
r1 = np.reciprocal(x)
r2 = 1/x
assert np.array_equal(r1, r2)
print(""Reciprocal for all elements of the said array:"")
print(r1)
"
96,Write a NumPy program to calculate the QR decomposition of a given matrix. ,"import numpy as np
m = np.array([[1,2],[3,4]])
print(""Original matrix:"")
print(m)
result = np.linalg.qr(m)
print(""Decomposition of the said matrix:"")
print(result)
"
97,Write a NumPy program to extract first and second elements of the first and second rows from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: First and second elements of the first and second rows "")
print(arra_data[0:2, 0:2])
"
98,Write a Python program to compute sum of digits of a given string. ,"def sum_digits_string(str1):
sum_digit = 0
for x in str1:
if x.isdigit() == True:
z = int(x)
sum_digit = sum_digit + z
return sum_digit
print(sum_digits_string(""123abcd45""))
print(sum_digits_string(""abcd1234""))
"
99,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to make a gradient color mapping on a specified column. ","import pandas as pd
import numpy as np
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(subset=['C'])
"
100,Write a Python program to find the nth Hamming number. User itertools module. ,"import itertools
from heapq import merge
def nth_hamming_number(n):
def num_recur():
last = 1
yield last
x, y, z = itertools.tee(num_recur(), 3)
for n in merge((2 * i for i in x), (3 * i for i in y), (5 * i for i in z)):
if n != last:
yield n
last = n
result = itertools.islice(num_recur(), n)
return list(result)[-1]
print(nth_hamming_number(8))
print(nth_hamming_number(14))
print(nth_hamming_number(17))
"
101,Write a Python program to find the last occurrence of a specified item in a given list. ,"def last_occurrence(l1, ch):
return ''.join(l1).rindex(ch)
chars = ['s','d','f','s','d','f','s','f','k','o','p','i','w','e','k','c']
print(""Original list:"")
print(chars)
ch = 'f'
print(""Last occurrence of"",ch,""in the said list:"")
print(last_occurrence(chars, ch))
ch = 'c'
print(""Last occurrence of"",ch,""in the said list:"")
print(last_occurrence(chars, ch))
ch = 'k'
print(""Last occurrence of"",ch,""in the said list:"")
print(last_occurrence(chars, ch))
ch = 'w'
print(""Last occurrence of"",ch,""in the said list:"")
print(last_occurrence(chars, ch))
"
102,Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4. ,"import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print(""Original String:"")
print(j_str)
print(""\nJSON data:"")
print(json.dumps(j_str, sort_keys=True, indent=4))
"
103,Write a Python program to create the combinations of 3 digit combo. ,"numbers = []
for num in range(1000):
num=str(num).zfill(3)
print(num)
numbers.append(num)
"
104,Write a Python program to create an iterator to get specified number of permutations of elements. ,"import itertools as it
def permutations_data(iter, length):
return it.permutations(iter, length)
#List
result = permutations_data(['A','B','C','D'], 3)
print(""\nIterator to get specified number of permutations of elements:"")
for i in result:
print(i)
#String
result = permutations_data(""Python"", 2)
print(""\nIterator to get specified number of permutations of elements:"")
for i in result:
print(i)
"
105,Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string. ,"def first_three(str):
return str[:3] if len(str) > 3 else str
print(first_three('ipy'))
print(first_three('python'))
print(first_three('py'))
"
106,Write a Python program to get hourly datetime between two hours. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nString representing the date, controlled by an explicit format string:"")
print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
"
107,Write a Python program to display formatted text (width=50) as output. ,"import textwrap
sample_text = '''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
print()
print(textwrap.fill(sample_text, width=50))
print()
"
108,Write a Python function to find the maximum and minimum numbers from a sequence of numbers. ,"def max_min(data):
l = data[0]
s = data[0]
for num in data:
if num> l:
l = num
elif num< s:
s = num
return l, s
print(max_min([0, 10, 15, 40, -5, 42, 17, 28, 75]))
"
109,Write a Pandas program to create a sequence of durations increasing by an hour. ,"import pandas as pd
date_range = pd.timedelta_range(0, periods=49, freq='H')
print(""Hourly range of perods 49:"")
print(date_range)
"
110,Write a NumPy program to sort the specified number of elements from beginning of a given array. ,"import numpy as np
nums = np.random.rand(10)
print(""Original array:"")
print(nums)
print(""\nSorted first 5 elements:"")
print(nums[np.argpartition(nums,range(5))])
"
111,"Write a Python program to extract year, month, date and time using Lambda. ","import datetime
now = datetime.datetime.now()
print(now)
year = lambda x: x.year
month = lambda x: x.month
day = lambda x: x.day
t = lambda x: x.time()
print(year(now))
print(month(now))
print(day(now))
print(t(now))
"
112,"Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no common letters print ""No common characters"". ","from collections import Counter
def common_chars(str1,str2):
d1 = Counter(str1)
d2 = Counter(str2)
common_dict = d1 & d2
if len(common_dict) == 0:
return ""No common characters.""
# list of common elements
common_chars = list(common_dict.elements())
common_chars = sorted(common_chars)
return ''.join(common_chars)
str1 = 'Python'
str2 = 'PHP'
print(""Two strings: ""+str1+' : '+str2)
print(common_chars(str1, str2))
str1 = 'Java'
str2 = 'PHP'
print(""Two strings: ""+str1+' : '+str2)
print(common_chars(str1, str2))
"
113,Write a Python program to remove a newline in Python. ,"str1='Python Exercises\n'
print(str1)
print(str1.rstrip())
"
114,"Write a Pandas program to extract the column labels, shape and data types of the dataset (titanic.csv). ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
print(""List of columns:"")
print(df.columns)
print(""\nShape of the Dataset:"")
print(df.shape)
print(""\nData types of the Dataset:"")
print(df.dtypes)
"
115,Write a Pandas program to replace arbitrary values with other values in a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['A','B', 'C', 'D', 'A'],
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print(""Original DataFrame:"")
print(df)
print(""\nReplace A with c:"")
df = df.replace(""A"", ""C"")
print(df)
"
116,"Write a NumPy program to calculate mean across dimension, in a 2D numpy array. ","import numpy as np
x = np.array([[10, 30], [20, 60]])
print(""Original array:"")
print(x)
print(""Mean of each column:"")
print(x.mean(axis=0))
print(""Mean of each row:"")
print(x.mean(axis=1))
"
117,"Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Add the fare as a dimension of columns and partition fare column into 2 categories based on the values present in fare columns. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
fare = pd.qcut(df['fare'], 2)
age = pd.cut(df['age'], [0, 10, 30, 60, 80])
result = df.pivot_table('survived', index=['sex', age], columns=[fare, 'pclass'])
print(result)
"
118,Write a Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list. ,"from functools import reduce
from operator import getitem
def get(d, selectors):
return reduce(getitem, selectors, d)
users = {
'freddy': {
'name': {
'first': 'Fateh',
'last': 'Harwood'
},
'postIds': [1, 2, 3]
}
}
print(get(users, ['freddy', 'name', 'last']))
print(get(users, ['freddy', 'postIds', 1]))
"
119,Write a Python program to sort unsorted numbers using Recursive Bubble Sort. ,"#Ref.https://bit.ly/3oneU2l
def bubble_sort(list_data: list, length: int = 0) -> list:
length = length or len(list_data)
swapped = False
for i in range(length - 1):
if list_data[i] > list_data[i + 1]:
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
swapped = True
return list_data if not swapped else bubble_sort(list_data, length - 1)
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Insertion Sort the said list becomes:"")
bubble_sort(nums, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Bubble Sort the said list becomes:"")
bubble_sort(nums, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Bubble Sort the said list becomes:"")
bubble_sort(nums, len(nums))
print(nums)
nums = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Bubble Sort the said list becomes:"")
bubble_sort(nums, len(nums))
print(nums)
"
120,Write a Python program to count the values associated with key in a dictionary. ,"student = [{'id': 1, 'success': True, 'name': 'Lary'},
{'id': 2, 'success': False, 'name': 'Rabi'},
{'id': 3, 'success': True, 'name': 'Alex'}]
print(sum(d['id'] for d in student))
print(sum(d['success'] for d in student))
"
121,"Write a NumPy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2). ","import numpy as np
nums1 = np.ones((2,2,3))
nums2 = 3*np.ones((2,2))
print(""Original array:"")
print(nums1)
new_array = nums1 * nums2[:,:,None]
print(""\nNew array:"")
print(new_array)
"
122,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)
"
123,"Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array. ","import numpy as np
array_nums = np.arange(0, 40, 2)
print(""Original array:"")
print(array_nums)
print(""\nNew array of shape(5, 4):"")
new_array = array_nums.reshape(5, 4)
print(new_array)
print(""\nRestore the reshaped array into a 1-D array:"")
print(new_array.flatten())
"
124,Write a Python program to sort a list of elements using Tree sort. ,"# License https://bit.ly/2InTS3W
# Tree_sort algorithm
# Build a BST and in order traverse.
class node():
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self,val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive travesal
if root:
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
def treesort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1,len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root,res)
return res
print(treesort([7,1,5,2,19,14,17]))
"
125,"Write a NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays. ","import numpy as np
x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100])
y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001])
print(""Original numbers:"")
print(x)
print(y)
print(""Comparison - equal:"")
print(np.equal(x, y))
print(""Comparison - equal within a tolerance:"")
print(np.allclose(x, y))
"
126,Write a Pandas program to split a given dataframe into groups with multiple aggregations. ,"import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s001'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(df)
print(""\nGroup by with multiple aggregations:"")
result = df.groupby(['school_code','class']).agg({'height': ['max', 'mean'],
'weight': ['sum','min','count']})
print(result)
"
127,Write a NumPy program to find a matrix or vector norm. ,"import numpy as np
v = np.arange(7)
result = np.linalg.norm(v)
print(""Vector norm:"")
print(result)
m = np.matrix('1, 2; 3, 4')
result1 = np.linalg.norm(m)
print(""Matrix norm:"")
print(result1)
"
128,Write a Python program to delete the first item from a singly linked list. ,"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 delete_item(self, data):
# Delete an item from the list
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def iterate_item(self):
# Iterate the list.
current_item = self.tail
while current_item:
val = current_item.data
current_item = current_item.next
yield val
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(""Original list:"")
for val in items.iterate_item():
print(val)
print(""\nAfter removing the first item from the list:"")
items.delete_item('PHP')
for val in items.iterate_item():
print(val)
"
129,Write a Python program to find the difference between two list including duplicate elements. Use collections module. ,"from collections import Counter
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print(""Original lists:"")
c1 = Counter(l1)
c2 = Counter(l2)
diff = c1-c2
print(list(diff.elements()))
"
130,Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number. ,"def sum_of_cubes(n):
n -= 1
total = 0
while n > 0:
total += n * n * n
n -= 1
return total
print(""Sum of cubes smaller than the specified number: "",sum_of_cubes(3))
"
131,Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and find a list of specified customers by name. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.query('Mine_Name == [""Shoal Creek Mine"", ""Piney Woods Preparation Plant""]').head()
"
132,"Write a Python program to create a new Arrow object, cloned from the current one. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
cloned = a.clone()
print(""\nCloned datetime:"")
print(cloned)
"
133,Write a NumPy program to create a 3-D array with ones on a diagonal and zeros elsewhere. ,"import numpy as np
x = np.eye(3)
print(x)
"
134,Write a NumPy program to extract first element of the second row and fourth element of fourth row from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: First element of the second row and fourth element of fourth row "")
print(arra_data[[1,3], [0,3]])
"
135,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())
"
136,Write a Python program to get the size of a file. ,"import os
file_size = os.path.getsize(""abc.txt"")
print(""\nThe size of abc.txt is :"",file_size,""Bytes"")
print()
"
137,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display bar charts in dataframe on specified columns. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
print(""\nBar charts in dataframe:"")
df.style.bar(subset=['B', 'C'], color='#d65f5f')
"
138,Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) sighted by month. ,"import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
df[""ufo_yr""] = df.Date_time.dt.month
months_data = df.ufo_yr.value_counts()
months_index = months_data.index # x ticks
months_values = months_data.get_values()
plt.figure(figsize=(15,8))
plt.xticks(rotation = 60)
plt.title('UFO sighted by Month')
plt.xlabel(""Months"")
plt.ylabel(""Number of sighting"")
months_plot = sns.barplot(x=months_index[:60],y=months_values[:60], palette = ""Oranges"")
"
139,Write a Python program to sort unsorted numbers using Recursive Quick Sort. ,"def quick_sort(nums: list) -> list:
if len(nums) <= 1:
return nums
else:
return (
quick_sort([el for el in nums[1:] if el <= nums[0]])
+ [nums[0]]
+ quick_sort([el for el in nums[1:] if el > nums[0]])
)
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Quick Sort the said list becomes:"")
print(quick_sort(nums))
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Quick Sort the said list becomes:"")
print(quick_sort(nums))
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Quick Sort the said list becomes:"")
print(quick_sort(nums))
"
140,"Write a Python program to convert timezone from local to utc, utc to local or specified zones. ","import arrow
utc = arrow.utcnow()
print(""utc:"")
print(utc)
print(""\nutc to local:"")
print(utc.to('local'))
print(""\nlocal to utc:"")
print(utc.to('local').to('utc'))
print(""\nutc to specific location:"")
print(utc.to('US/Pacific'))
"
141,Write a Python program to find the difference between two list including duplicate elements. ,"def list_difference(l1,l2):
result = list(l1)
for el in l2:
result.remove(el)
return result
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print(""Original lists:"")
print(l1)
print(l2)
print(""\nDifference between two said list including duplicate elements):"")
print(list_difference(l1,l2))
"
142,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in Heatmap style. ","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 - Heatmap style:"")
cm = sns.light_palette(""red"", as_cmap=True)
df.style.background_gradient(cmap='viridis')
"
143,Write a Python program to remove a tag from a given tree of html document and destroy it and its contents. ,"from bs4 import BeautifulSoup
html_content = 'Python exercisesw3resource'
soup = BeautifulSoup(html_content, ""lxml"")
print(""Original Markup:"")
a_tag = soup.a
print(a_tag)
new_tag = soup.a.decompose()
print(""After decomposing:"")
print(new_tag)
"
144,Write a Python program to convert a given number (integer) to a list of digits. ,"def digitize(n):
return list(map(int, str(n)))
print(digitize(123))
print(digitize(1347823))
"
145,rite a Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output (all characters in lower case). ,"lines = []
while True:
l = input()
if l:
lines.append(l.upper())
else:
break;
for l in lines:
print(l)
"
146,Write a Python program to remove a tag or string from a given tree of html document and replace it with the given tag or string. ,"from bs4 import BeautifulSoup
html_markup= 'Python exercisesw3resource'
soup = BeautifulSoup(html_markup, ""lxml"")
print(""Original markup:"")
a_tag = soup.a
print(a_tag)
new_tag = soup.new_tag(""b"")
new_tag.string = ""PHP""
b_tag = a_tag.i.replace_with(new_tag)
print(""New Markup:"")
print(a_tag)
"
147,Write a Pandas program to extract the unique sentences from a given column of a given DataFrame. ,"import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'address': ['9910 Surrey Avenue\n9910 Surrey Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.\n102 Dunbar St.', '17 West Livingston Court']
})
print(""Original DataFrame:"")
print(df)
def find_unique_sentence(str1):
result = re.findall(r'(?sm)(^[^\r\n]+$)(?!.*^\1$)', str1)
return result
df['unique_sentence']=df['address'].apply(lambda st : find_unique_sentence(st))
print(""\nExtract unique sentences :"")
print(df)
"
148,Write a Pandas program to filter all records where the average consumption of beverages per person from .5 to 2.50 in 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(""\nFilter all records where the average consumption of beverages per person from .5 to 2.50.:"")
print(w_a_con[(w_a_con['Display Value'] < 2.5) & (w_a_con['Display Value']>.5)].head())
"
149,Write a Pandas program to extract elements in the given positional indices along an axis of a dataframe. ,"import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale3', 'sale3', 'sale2', 'sale2', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print(""\nConstruct a Dataframe using the said MultiIndex levels:"")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)
print(""\nSelect 1st, 2nd and 3rd row of the said DataFrame:"")
positions = [1, 2, 5]
print(df.take([1, 2, 5]))
print(""\nTake elements at indices 1 and 2 along the axis 1 (column selection):"")
print(df.take([1, 2], axis=1))
print(""\nTake elements at indices 4 and 3 using negative integers along the axis 1 (column selection):"")
print(df.take([-1, -2], axis=1))
"
150,Write a Python program to find a pair with highest product from a given array of integers. ,"def max_Product(arr):
arr_len = len(arr)
if (arr_len < 2):
print(""No pairs exists"")
return
# Initialize max product pair
x = arr[0]; y = arr[1]
# Traverse through every possible pair
for i in range(0, arr_len):
for j in range(i + 1, arr_len):
if (arr[i] * arr[j] > x * y):
x = arr[i]; y = arr[j]
return x,y
nums = [1, 2, 3, 4, 7, 0, 8, 4]
print(""Original array:"", nums)
print(""Maximum product pair is:"", max_Product(nums))
nums = [0, -1, -2, -4, 5, 0, -6]
print(""\nOriginal array:"", nums)
print(""Maximum product pair is:"", max_Product(nums))
"
151,Write a Python program to move all zero digits to end of a given list of numbers. ,"def test(lst):
result = sorted(lst, key=lambda x: not x)
return result
nums = [3,4,0,0,0,6,2,0,6,7,6,0,0,0,9,10,7,4,4,5,3,0,0,2,9,7,1]
print(""\nOriginal list:"")
print(nums)
print(""\nMove all zero digits to end of the said list of numbers:"")
print(test(nums))
"
152,Write a NumPy program to compute cross-correlation of two given arrays. ,"import numpy as np
x = np.array([0, 1, 3])
y = np.array([2, 4, 5])
print(""\nOriginal array1:"")
print(x)
print(""\nOriginal array1:"")
print(y)
print(""\nCross-correlation of the said arrays:\n"",np.cov(x, y))
"
153,Write a Python program to get the actual module object for a given object. ,"from inspect import getmodule
from math import sqrt
print(getmodule(sqrt))
"
154,Write a Python program to extract the nth element from a given list of tuples using lambda. ,"def extract_nth_element(test_list, n):
result = list(map (lambda x:(x[n]), test_list))
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print (""Original list:"")
print(students)
n = 0
print(""\nExtract nth element ( n ="",n,"") from the said list of tuples:"")
print(extract_nth_element(students, n))
n = 2
print(""\nExtract nth element ( n ="",n,"") from the said list of tuples:"")
print(extract_nth_element(students, n))
"
155,Write a NumPy program to add an extra column to a NumPy array. ,"import numpy as np
x = np.array([[10,20,30], [40,50,60]])
y = np.array([[100], [200]])
print(np.append(x, y, axis=1))
"
156,Write a Python program to calculate the product of a given list of numbers using lambda. ,"import functools
def remove_duplicates(nums):
result = functools.reduce(lambda x, y: x * y, nums, 1)
return result
nums1 = [1,2,3,4,5,6,7,8,9,10]
nums2 = [2.2,4.12,6.6,8.1,8.3]
print(""list1:"", nums1)
print(""Product of the said list numbers:"")
print(remove_duplicates(nums1))
print(""\nlist2:"", nums2)
print(""Product of the said list numbers:"")
print(remove_duplicates(nums2))
"
157,Write a Python program to parse a string representing a time according to a format. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\ntime.struct_time, in the current timezone:"")
print(arrow.utcnow().timetuple())
"
158,Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable. ,"import numpy as np
x = np.random.rand(10, 4)
print(""Original array: "")
print(x)
y= x[:5, :]
print(""First 5 rows of the above array:"")
print(y)
"
159,Write a Pandas program to find average consumption of wine per person greater than 2 in 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(""\nAverage consumption of wine per person greater than 2:"")
print(w_a_con[(w_a_con['Beverage Types'] == 'Wine') & (w_a_con['Display Value'] > .2)].count())
"
160,Write a Pandas program to convert Series of lists to one Series. ,"import pandas as pd
s = pd.Series([
['Red', 'Green', 'White'],
['Red', 'Black'],
['Yellow']])
print(""Original Series of list"")
print(s)
s = s.apply(pd.Series).stack().reset_index(drop=True)
print(""One Series"")
print(s)
"
161,Write a Python program to sort a list of elements using Time sort. ,"# License https://bit.ly/2InTS3W
def binary_search(lst, item, start, end):
if start == end:
if lst[start] > item:
return start
else:
return start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index+1:]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def time_sort(lst):
runs, sorted_runs = [], []
length = len(lst)
new_run = [lst[0]]
sorted_array = []
for i in range(1, length):
if i == length - 1:
new_run.append(lst[i])
runs.append(new_run)
break
if lst[i] < lst[i - 1]:
if not new_run:
runs.append([lst[i - 1]])
new_run.append(lst[i])
else:
runs.append(new_run)
new_run = []
else:
new_run.append(lst[i])
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
print(time_sort(nums))
"
162,"Write a Python program to convert timezone from local to utc, utc to local or specified zones. ","import arrow
utc = arrow.utcnow()
print(""utc:"")
print(utc)
print(""\nutc to local:"")
print(utc.to('local'))
print(""\nlocal to utc:"")
print(utc.to('local').to('utc'))
print(""\nutc to specific location:"")
print(utc.to('US/Pacific'))
"
163,Write a NumPy program to subtract the mean of each row of a given matrix. ,"import numpy as np
print(""Original matrix:\n"")
X = np.random.rand(5, 10)
print(X)
print(""\nSubtract the mean of each row of the said matrix:\n"")
Y = X - X.mean(axis=1, keepdims=True)
print(Y)
"
164,Write a NumPy program to test whether two arrays are element-wise equal within a tolerance. ,"import numpy as np
print(""Test if two arrays are element-wise equal within a tolerance:"")
print(np.allclose([1e10,1e-7], [1.00001e10,1e-8]))
print(np.allclose([1e10,1e-8], [1.00001e10,1e-9]))
print(np.allclose([1e10,1e-8], [1.0001e10,1e-9]))
print(np.allclose([1.0, np.nan], [1.0, np.nan]))
print(np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True))
"
165,Write a Pandas program to create a Pivot table and count the manager wise sale and mean value of sale amount. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=[""Manager""],values=[""Sale_amt""],aggfunc=[np.mean,len]))
"
166,Write a Python program to select all the Sundays of a specified year. ,"from datetime import date, timedelta
def all_sundays(year):
# January 1st of the given year
dt = date(year, 1, 1)
# First Sunday of the given year
dt += timedelta(days = 6 - dt.weekday())
while dt.year == year:
yield dt
dt += timedelta(days = 7)
for s in all_sundays(2020):
print(s)
"
167,Write a Pandas program to print a concise summary of the dataset (titanic.csv). ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.info()
print(result)
"
168,Write a Python program to create an object for writing and iterate over the rows to print the values. ,"import csv
import sys
with open('temp.csv', 'wt') as f:
writer = csv.writer(f)
writer.writerow(('id1', 'id2', 'date'))
for i in range(3):
row = (
i + 1,
chr(ord('a') + i),
'01/{:02d}/2019'.format(i + 1),)
writer.writerow(row)
print(open('temp.csv', 'rt').read())
"
169,Write a Python program to remove duplicate dictionary from a given list. ,"def remove_duplicate_dictionary(list_color):
result = [dict(e) for e in {tuple(d.items()) for d in list_color}]
return result
list_color = [{'Green': '#008000'}, {'Black': '#000000'}, {'Blue': '#0000FF'}, {'Green': '#008000'}]
print (""Original list with duplicate dictionary:"")
print(list_color)
print(""\nAfter removing duplicate dictionary of the said list:"")
print(remove_duplicate_dictionary(list_color))
"
170,Write a Pandas program to create a Pivot table and compute survival totals of all classes along each group. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index='sex', columns='class', margins=True)
print(result)
"
171,Write a Python program to remove first specified number of elements from a given list satisfying a condition. ,"def condition_match(x):
return ((x % 2) == 0)
def remove_items_con(data, N):
ctr = 1
result = []
for x in data:
if ctr > N or not condition_match(x):
result.append(x)
else:
ctr = ctr + 1
return result
nums = [3,10,4,7,5,7,8,3,3,4,5,9,3,4,9,8,5]
N = 4
print(""Original list:"")
print(nums)
print(""\nRemove first 4 even numbers from the said list:"")
print(remove_items_con(nums, N))
"
172,Write a Python program to convert a list of multiple integers into a single integer. ,"L = [11, 33, 50]
print(""Original List: "",L)
x = int("""".join(map(str, L)))
print(""Single Integer: "",x)
"
173,Write a Python program to find the value of the last element in the given list that satisfies the provided testing function. ,"def find_last(lst, fn):
return next(x for x in lst[::-1] if fn(x))
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 1))
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 0))
"
174,Write a Python program to change the position of every n-th value with the (n+1)th in a list. ,"from itertools import zip_longest, chain, tee
def replace2copy(lst):
lst1, lst2 = tee(iter(lst), 2)
return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))
n = [0,1,2,3,4,5]
print(replace2copy(n))
"
175,Write a Python program to multiply all the numbers in a given list using lambda. ,"from functools import reduce
def mutiple_list(nums):
result = reduce(lambda x, y: x*y, nums)
return result
nums = [4, 3, 2, 2, -1, 18]
print (""Original list: "")
print(nums)
print(""Mmultiply all the numbers of the said list:"",mutiple_list(nums))
nums = [2, 4, 8, 8, 3, 2, 9]
print (""\nOriginal list: "")
print(nums)
print(""Mmultiply all the numbers of the said list:"",mutiple_list(nums))
"
176,Write a Python program to remove unwanted characters from a given string. ,"def remove_chars(str1, unwanted_chars):
for i in unwanted_chars:
str1 = str1.replace(i, '')
return str1
str1 = ""Pyth*^on Exercis^es""
str2 = ""A%^!B#*CD""
unwanted_chars = [""#"", ""*"", ""!"", ""^"", ""%""]
print (""Original String : "" + str1)
print(""After removing unwanted characters:"")
print(remove_chars(str1, unwanted_chars))
print (""\nOriginal String : "" + str2)
print(""After removing unwanted characters:"")
print(remove_chars(str2, unwanted_chars))
"
177,Write a Python program to compute the average of n,"import itertools as it
nums = [[0, 1, 2],
[2, 3, 4],
[3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14]]
print(""Original list:"")
print(nums)
def get_avg(x):
x = [i for i in x if i is not None]
return sum(x, 0.0) / len(x)
result = map(get_avg, it.zip_longest(*nums))
print(""\nAverage of n-th elements in the said list of lists with different lengths:"")
print(list(result))
"
178,Write a Python program to find the details of a given zip code using Nominatim API and GeoPy package. ,"from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent=""geoapiExercises"")
zipcode1 = ""99501""
print(""\nZipcode:"",zipcode1)
location = geolocator.geocode(zipcode1)
print(""Details of the said pincode:"")
print(location.address)
zipcode2 = ""CA9 3HX""
print(""\nZipcode:"",zipcode2)
location = geolocator.geocode(zipcode2)
print(""Details of the said pincode:"")
print(location.address)
zipcode3 = ""61000""
print(""\nZipcode:"",zipcode3)
location = geolocator.geocode(zipcode3)
print(""Details of the said pincode:"")
print(location.address)
zipcode4 = ""713101""
print(""\nZipcode:"",zipcode4)
location = geolocator.geocode(zipcode4)
print(""Details of the said pincode:"")
print(location.address)
"
179,Write a NumPy program to insert a space between characters of all the elements of a given array. ,"import numpy as np
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
print(""Original Array:"")
print(x)
r = np.char.join("" "", x)
print(r)
"
180,Write a Python program to merge some list items in given list using index value. ,"def merge_some_chars(lst,merge_from,merge_to):
result = lst
result[merge_from:merge_to] = [''.join(result[merge_from:merge_to])]
return result
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(""Original lists:"")
print(chars)
merge_from = 2
merge_to = 4
print(""\nMerge items from"",merge_from,""to"",merge_to,""in the said List:"")
print(merge_some_chars(chars,merge_from,merge_to))
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
merge_from = 3
merge_to = 7
print(""\nMerge items from"",merge_from,""to"",merge_to,""in the said List:"")
print(merge_some_chars(chars,merge_from,merge_to))
"
181,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))
"
182,"Write a Pandas program to split a given dataset, group by two columns and convert other columns of the dataframe into a dictionary with column header as key. ","import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(df)
dict_data_list = list()
for gg, dd in df.groupby(['school_code','class']):
group = dict(zip(['school_code','class'], gg))
ocolumns_list = list()
for _, data in dd.iterrows():
data = data.drop(labels=['school_code','class'])
ocolumns_list.append(data.to_dict())
group['other_columns'] = ocolumns_list
dict_data_list.append(group)
print(dict_data_list)
"
183,Write a Python program to find the most common elements and their counts of a specified text. ,"from collections import Counter
s = 'lkseropewdssafsdfafkpwe'
print(""Original string: ""+s)
print(""Most common three characters of the said string:"")
print(Counter(s).most_common(3))
"
184,Write a NumPy program to round array elements to the given number of decimals. ,"import numpy as np
x = np.round([1.45, 1.50, 1.55])
print(x)
x = np.round([0.28, .50, .64], decimals=1)
print(x)
x = np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
print(x)
"
185,Write a Pandas program to find the index of the first occurrence of the smallest and largest value of a given series. ,"import pandas as pd
nums = pd.Series([1, 3, 7, 12, 88, 23, 3, 1, 9, 0])
print(""Original Series:"")
print(nums)
print(""Index of the first occurrence of the smallest and largest value of the said series:"")
print(nums.idxmin())
print(nums.idxmax())
"
186,Write a NumPy program to generate a random number between 0 and 1. ,"import numpy as np
rand_num = np.random.normal(0,1,1)
print(""Random number between 0 and 1:"")
print(rand_num)
"
187,Write a Python program to count number of unique sublists within a given list. ,"def unique_sublists(input_list):
result ={}
for l in input_list:
result.setdefault(tuple(l), list()).append(1)
for a, b in result.items():
result[a] = sum(b)
return result
list1 = [[1, 3], [5, 7], [1, 3], [13, 15, 17], [5, 7], [9, 11]]
print(""Original list:"")
print(list1)
print(""Number of unique lists of the said list:"")
print(unique_sublists(list1))
color1 = [[""green"", ""orange""], [""black""], [""green"", ""orange""], [""white""]]
print(""\nOriginal list:"")
print(color1)
print(""Number of unique lists of the said list:"")
print(unique_sublists(color1))
"
188,Write a Python program to calculate the time runs (difference between start and current time) of a program. ,"from timeit import default_timer
def timer(n):
start = default_timer()
# some code here
for row in range(0,n):
print(row)
print(default_timer() - start)
timer(5)
timer(15)
"
189,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))
"
190,Write a Python program to delete a specific row from a given SQLite table. ,"import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute(""CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));"")
# Insert records
cursorObj.executescript(""""""
INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);
INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
"""""")
cursorObj.execute(""SELECT * FROM salesman"")
rows = cursorObj.fetchall()
print(""Agent details:"")
for row in rows:
print(row)
print(""\nDelete Salesman of ID 5003:"")
s_id = 5003
cursorObj.execute(""""""
DELETE FROM salesman
WHERE salesman_id = ?
"""""", (s_id,))
conn.commit()
cursorObj.execute(""SELECT * FROM salesman"")
rows = cursorObj.fetchall()
print(""\nAfter updating Agent details:"")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
print(""\nThe SQLite connection is closed."")
"
191,Write a Python program to find the list with maximum and minimum length using lambda. ,"def max_length_list(input_list):
max_length = max(len(x) for x in input_list )
max_list = max(input_list, key = lambda i: len(i))
return(max_length, max_list)
def min_length_list(input_list):
min_length = min(len(x) for x in input_list )
min_list = min(input_list, key = lambda i: len(i))
return(min_length, min_list)
list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
print(""Original list:"")
print(list1)
print(""\nList with maximum length of lists:"")
print(max_length_list(list1))
print(""\nList with minimum length of lists:"")
print(min_length_list(list1))
"
192,Write a Python program to convert a given string to camelcase. ,"from re import sub
def camel_case(s):
s = sub(r""(_|-)+"", "" "", s).title().replace("" "", """")
return ''.join([s[0].lower(), s[1:]])
print(camel_case('JavaScript'))
print(camel_case('Foo-Bar'))
print(camel_case('foo_bar'))
print(camel_case('--foo.bar'))
print(camel_case('Foo-BAR'))
print(camel_case('fooBAR'))
print(camel_case('foo bar'))
"
193,Write a Python program to find common items from two lists. ,"color1 = ""Red"", ""Green"", ""Orange"", ""White""
color2 = ""Black"", ""Green"", ""White"", ""Pink""
print(set(color1) & set(color2))
"
194,"Write a Python program to create a doubly linked list, append some items and iterate through the list (print forward). ","class Node(object):
# Doubly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def print_foward(self):
for node in self.iter():
print(node)
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print(""Items in the Doubly linked list: "")
items.print_foward()
"
195,Write a NumPy program to rearrange the dimensions of a given array. ,"import numpy as np
x = np.arange(24).reshape((6,4))
print(""Original arrays:"")
print(x)
new_array = np.transpose(x)
print(""After reverse the dimensions:"")
print(new_array)
"
196,Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns. ,"import pandas as pd
df = pd.DataFrame({'year': [2018, 2019, 2020],
'month': [2, 3, 4],
'day': [4, 5, 6],
'hour': [2, 3, 4]})
print(""Original dataframe:"")
print(df)
result = pd.to_datetime(df)
print(""\nSeries of Timestamps from the said dataframe:"")
print(result)
print(""\nSeries of Timestamps using specified columns:"")
print(pd.to_datetime(df[['year', 'month', 'day']]))
"
197,"Write a Python program to create datetime from integers, floats and strings timestamps using arrow module. ","import arrow
i = arrow.get(1857900545)
print(""Date from integers: "")
print(i)
f = arrow.get(1857900545.234323)
print(""\nDate from floats: "")
print(f)
s = arrow.get('1857900545')
print(""\nDate from Strings: "")
print(s)
"
198,"Write a Python program to merge two or more lists into a list of lists, combining elements from each of the input lists based on their positions. ","def merge_lists(*args, fill_value = None):
max_length = max([len(lst) for lst in args])
result = []
for i in range(max_length):
result.append([
args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))
])
return result
print(""After merging lists into a list of lists:"")
print(merge_lists(['a', 'b'], [1, 2], [True, False]))
print(merge_lists(['a'], [1, 2], [True, False]))
print(merge_lists(['a'], [1, 2], [True, False], fill_value = '_'))
"
199,Write a NumPy program to stack arrays in sequence horizontally (column wise). ,"import numpy as np
print(""\nOriginal arrays:"")
x = np.arange(9).reshape(3,3)
y = x*3
print(""Array-1"")
print(x)
print(""Array-2"")
print(y)
new_array = np.hstack((x,y))
print(""\nStack arrays in sequence horizontally:"")
print(new_array)
"
200,rite a Python program to find the first repeated word in a given string. ,"def first_repeated_word(str1):
temp = set()
for word in str1.split():
if word in temp:
return word;
else:
temp.add(word)
return 'None'
print(first_repeated_word(""ab ca bc ab""))
print(first_repeated_word(""ab ca bc ab ca ab bc""))
print(first_repeated_word(""ab ca bc ca ab bc""))
print(first_repeated_word(""ab ca bc""))
"
201,"Create a dataframe of ten rows, four columns with random values. Convert some values to nan values. Write a Pandas program which will highlight the nan values. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
def color_negative_red(val):
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
print(""\nNegative numbers red and positive numbers black:"")
df.style.highlight_null(null_color='red')
"
202,Write a Python program to generate a number in a specified range except some specific numbers. ,"from random import choice
def generate_random(start_range, end_range, nums):
result = choice([i for i in range(start_range,end_range) if i not in nums])
return result
start_range = 1
end_range = 10
nums = [2, 9, 10]
print(""\nGenerate a number in a specified range (1, 10) except [2, 9, 10]"")
print(generate_random(start_range,end_range,nums))
start_range = -5
end_range = 5
nums = [-5,0,4,3,2]
print(""\nGenerate a number in a specified range (-5, 5) except [-5,0,4,3,2]"")
print(generate_random(start_range,end_range,nums))
"
203,Write a Python program to add to a tag's contents in a given html document. ,"from bs4 import BeautifulSoup
html_doc = 'HTMLw3resource.com'
soup = BeautifulSoup(html_doc, ""lxml"")
print(""\nOriginal Markup:"")
print(soup.a)
soup.a.append(""CSS"")
print(""\nAfter append a text in the new link:"")
print(soup.a)
"
204,Write a NumPy program to create an array with 10^3 elements. ,"import numpy as np
x = np.arange(1e3)
print(x)
"
205,Write a NumPy program to suppresses the use of scientific notation for small numbers in NumPy array. ,"import numpy as np
x=np.array([1.6e-10, 1.6, 1200, .235])
print(""Original array elements:"")
print(x)
print(""Print array values with precision 3:"")
np.set_printoptions(suppress=True)
print(x)
"
206,Write a Python program to join adjacent members of a given list. ,"def test(lst):
result = [x + y for x, y in zip(lst[::2],lst[1::2])]
return result
nums = ['1','2','3','4','5','6','7','8']
print(""Original list:"")
print(nums)
print(""\nJoin adjacent members of a given list:"")
print(test(nums))
nums = ['1','2','3']
print(""\nOriginal list:"")
print(nums)
print(""\nJoin adjacent members of a given list:"")
print(test(nums))
"
207,Write a Python program to compare two unordered lists (not sets). ,"from collections import Counter
def compare_lists(x, y):
return Counter(x) == Counter(y)
n1 = [20, 10, 30, 10, 20, 30]
n2 = [30, 20, 10, 30, 20, 50]
print(compare_lists(n1, n2))
"
208,Write a Pandas program to get the length of the string present of a given column in a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'skfsalf', 'sdfslew', 'safsdf'],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]})
print(""Original DataFrame:"")
print(df)
print(""\nLength of the string in a column:"")
df['company_code_length'] = df['company_code'].apply(len)
print(df)
"
209,"Write a Python program to create a new Arrow object, representing the ""floor"" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute. ","import arrow
print(arrow.utcnow())
print(""Hour ceiling:"")
print(arrow.utcnow().floor('hour'))
print(""\nMinute ceiling:"")
print(arrow.utcnow().floor('minute'))
print(""\nSecond ceiling:"")
print(arrow.utcnow().floor('second'))
"
210,Write a Python program to cast the provided value as a list if it's not one. ,"def cast_list(val):
return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
d1 = [1]
print(type(d1))
print(cast_list(d1))
d2 = ('Red', 'Green')
print(type(d2))
print(cast_list(d2))
d3 = {'Red', 'Green'}
print(type(d3))
print(cast_list(d3))
d4 = {1: 'Red', 2: 'Green', 3: 'Black'}
print(type(d4))
print(cast_list(d4))
"
211,Write a Python program to convert a list of dictionaries into a list of values corresponding to the specified key. ,"def test(lsts, key):
return [x.get(key) for x in lsts]
students = [
{ 'name': 'Theodore', 'age': 18 },
{ 'name': 'Mathew', 'age': 22 },
{ 'name': 'Roxanne', 'age': 20 },
{ 'name': 'David', 'age': 18 }
]
print(""Original list of dictionaries:"")
print(students)
print(""\nConvert a list of dictionaries into a list of values corresponding to the specified key:"")
print(test(students, 'age'))
"
212,Write a Python program to get the factorial of a non-negative integer. ,"def factorial(n):
if n <= 1:
return 1
else:
return n * (factorial(n - 1))
print(factorial(5))
"
213,"Write a Pandas program to create a Pivot table and find survival rate by gender, age wise of various classes. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index=['sex','age'], columns='class')
print(result)
"
214,"Write a NumPy program to compute xy, element-wise where x, y are two given arrays. ","import numpy as np
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 2], [1, 2]])
print(""Array1: "")
print(x)
print(""Array1: "")
print(y)
print(""Result- x^y:"")
r1 = np.power(x, y)
print(r1)
"
215,Write a Python program to search the country name from given state name using Nominatim API and GeoPy package. ,"from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent=""geoapiExercises"")
state1 = ""Uttar Pradesh""
print(""State Name:"",state1)
location = geolocator.geocode(state1)
print(""State Name/Country Name: "")
print(location.address)
state2 = "" Illinois""
print(""\nState Name:"",state2)
location = geolocator.geocode(state2)
print(""State Name/Country Name: "")
print(location.address)
state3 = ""Normandy""
print(""\nState Name:"",state3)
location = geolocator.geocode(state3)
print(""State Name/Country Name: "")
print(location.address)
state4 = ""Jerusalem District""
print(""\nState Name:"",state4)
location = geolocator.geocode(state4)
print(""State Name/Country Name: "")
print(location.address)
"
216,Write a Python program to append items from a specified list. ,"from array import *
num_list = [1, 2, 6, -8]
array_num = array('i', [])
print(""Items in the list: "" + str(num_list))
print(""Append items from the list: "")
array_num.fromlist(num_list)
print(""Items in the array: ""+str(array_num))
"
217,Write a NumPy program to create an array of the integers from 30 to70. ,"import numpy as np
array=np.arange(30,71)
print(""Array of the integers from 30 to70"")
print(array)
"
218,Write a Python function to check whether a number is divisible by another number. Accept two integers values form the user. ,"def multiple(m, n):
return True if m % n == 0 else False
print(multiple(20, 5))
print(multiple(7, 2))
"
219,Write a NumPy program to generate a matrix product of two arrays. ,"import numpy as np
x = [[1, 0], [1, 1]]
y = [[3, 1], [2, 2]]
print(""Matrices and vectors."")
print(""x:"")
print(x)
print(""y:"")
print(y)
print(""Matrix product of above two arrays:"")
print(np.matmul(x, y))
"
220,Write a NumPy program to find elements within range from a given array of numbers. ,"import numpy as np
a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29])
print(""Original array:"")
print(a)
result = np.where(np.logical_and(a>=7, a<=20))
print(""\nElements within range: index position"")
print(result)
"
221,Write a Pandas program to find which years have all non-zero values and which years have any non-zero values from 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(""\nFind which years have all non-zero values:"")
print(w_a_con.loc[:,w_a_con.all()])
print(""\nFind which years have any non-zero values:"")
print(w_a_con.loc[:,w_a_con.any()])
"
222,Write a Pandas program to generate sequences of fixed-frequency dates and time spans intervals. ,"import pandas as pd
print(""Sequences of fixed-frequency dates and time spans (1 H):\n"")
r1 = pd.date_range('2030-01-01', periods=10, freq='H')
print(r1)
print(""\nSequences of fixed-frequency dates and time spans (3 H):\n"")
r2 = pd.date_range('2030-01-01', periods=10, freq='3H')
print(r2)
"
223,Write a Python program to display a number with a comma separator. ,"x = 3000000
y = 30000000
print(""\nOriginal Number: "", x)
print(""Formatted Number with comma separator: ""+""{:,}"".format(x));
print(""Original Number: "", y)
print(""Formatted Number with comma separator: ""+""{:,}"".format(y));
print()
"
224,"Write a NumPy program to convert a given list into an array, then again convert it into a list. Check initial list and final list are equal or not. ","import numpy as np
a = [[1, 2], [3, 4]]
x = np.array(a)
a2 = x.tolist()
print(a == a2)
"
225,Write a Python program to reverse a string. ,"def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('1234abcd'))
"
226,Write a Pandas program to find integer index of rows with missing data in a given dataframe. ,"import pandas as pd
import numpy as np
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, None, 33, 30, 31, None]},
index = ['t1', 't2', 't3', 't4', 't5', 't6'])
print(""Original DataFrame:"")
print(df)
index = df['weight'].index[df['weight'].apply(np.isnan)]
df_index = df.index.values.tolist()
print(""\nInteger index of rows with missing data in 'weight' column of the said dataframe:"")
print([df_index.index(i) for i in index])
"
227,Write a Python program to combine each line from first file with the corresponding line in second file. ,"with open('abc.txt') as fh1, open('test.txt') as fh2:
for line1, line2 in zip(fh1, fh2):
# line1 from abc.txt, line2 from test.txtg
print(line1+line2)
"
228,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))
"
229,Write a Pandas program to create a Pivot table and find survival of both gender and class affected. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.groupby(['sex', 'class'])['survived'].aggregate('mean').unstack()
print(result)
"
230,Write a Python program to find the maximum and minimum product from the pairs of tuple within a given list. ,"def tuple_max_val(nums):
result_max = max([abs(x * y) for x, y in nums] )
result_min = min([abs(x * y) for x, y in nums] )
return result_max,result_min
nums = [(2, 7), (2, 6), (1, 8), (4, 9)]
print(""The original list, tuple : "")
print(nums)
print(""\nMaximum and minimum product from the pairs of the said tuple of list:"")
print(tuple_max_val(nums))
"
231,Write a Python program to interleave multiple lists of the same length. Use itertools module. ,"import itertools
def interleave_multiple_lists(list1,list2,list3):
result = list(itertools.chain(*zip(list1, list2, list3)))
return result
list1 = [100,200,300,400,500,600,700]
list2 = [10,20,30,40,50,60,70]
list3 = [1,2,3,4,5,6,7]
print(""Original list:"")
print(""list1:"",list1)
print(""list2:"",list2)
print(""list3:"",list3)
print(""\nInterleave multiple lists:"")
print(interleave_multiple_lists(list1,list2,list3))
"
232,"Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix. ","import numpy as np
nums = np.random.randint(0,4,(6,3))
print(""Original vector:"")
print(nums)
new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1)
result = nums[~new_nums]
print(""\nRows with unequal values:"")
print(result)
"
233,Write a Python script that takes input from the user and displays that input back in upper and lower cases. ,"user_input = input(""What's your favourite language? "")
print(""My favourite language is "", user_input.upper())
print(""My favourite language is "", user_input.lower())
"
234,Write a Python program to find the siblings of tags in a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
This is an example HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
LacieTillie
""""""
soup = BeautifulSoup(html_doc,""lxml"")
print(""\nSiblings of tags:"")
print(soup.select(""#link1 ~ .sister""))
print(soup.select(""#link1 + .sister""))
"
235,Write a Python program to extract and display all the image links from en.wikipedia.org/wiki/Peter_Jeffrey_(RAAF_officer). ,"import requests
r = requests.get(""https://analytics.usa.gov/data/live/browsers.json"")
print(""90 days of visits broken down by browser for all sites:"")
print(r.json()['totals']['browser'])
"
236,Write a NumPy program to add a new row to an empty NumPy array. ,"import numpy as np
arr = np.empty((0,3), int)
print(""Empty array:"")
print(arr)
arr = np.append(arr, np.array([[10,20,30]]), axis=0)
arr = np.append(arr, np.array([[40,50,60]]), axis=0)
print(""After adding two new arrays:"")
print(arr)
"
237,Write a Python program to find the href of the first tag of a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
""""""
soup = BeautifulSoup(html_doc, ""lxml"")
print(soup.find( href=""https://www.w3resource.com/css/CSS-tutorials.php""))
"
631,"Write a Python program to create a time object with the same hour, minute, second, microsecond and a timestamp representation of the Arrow object, in UTC time. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nTime object with the same hour, minute, second, microsecond:"")
print(arrow.utcnow().time())
print(""\nTimestamp representation of the Arrow object, in UTC time:"")
print(arrow.utcnow().timestamp)
"
632,Write a Python program to swap comma and dot in a string. ,"amount = ""32.054,23""
maketrans = amount.maketrans
amount = amount.translate(maketrans(',.', '.,'))
print(amount)
"
633,Write a Python program to find the shortest distance from a specified character in a given string. Return the shortest distances through a list and use itertools module to solve the problem. ,"import itertools as it
def char_shortest_distancer(str1, char1):
result = [len(str1)] * len(str1)
prev_char = -len(str1)
for i in it.chain(range(len(str1)),reversed(range(len(str1)))):
if str1[i] == char1:
prev_char = i
result[i] = min(result[i], abs(i-prev_char))
return result
str1 = ""w3resource""
chr1='r'
print(""Original string:"",str1,"": Specified character:"",chr1)
print(char_shortest_distancer(str1,chr1))
str1 = ""python exercises""
chr1='e'
print(""\nOriginal string:"",str1,"": Specified character:"",chr1)
print(char_shortest_distancer(str1,chr1))
str1 = ""JavaScript""
chr1='S'
print(""\nOriginal string:"",str1,"": Specified character:"",chr1)
print(char_shortest_distancer(str1,chr1))
"
634,Write a Python program to check whether a file path is a file or a directory. ,"import os
path=""abc.txt""
if os.path.isdir(path):
print(""\nIt is a directory"")
elif os.path.isfile(path):
print(""\nIt is a normal file"")
else:
print(""It is a special file (socket, FIFO, device file)"" )
print()
"
635,Write a Python program to create the smallest 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=False,
key=lambda i: i*( len(str(min(lst))) * 2 // len(i))))
return result
nums = [3, 40, 41, 43, 74, 9]
print(""Original list:"")
print(nums)
print(""Smallest 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(""Smallest 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(""Smallest possible number using the elements of the said list of positive integers:"")
print(create_largest_number(nums))
"
636,Write a Python program to count the occurrence of each element of a given list. ,"from collections import Counter
colors = ['Green', 'Red', 'Blue', 'Red', 'Orange', 'Black', 'Black', 'White', 'Orange']
print(""Original List:"")
print(colors)
print(""Count the occurrence of each element of the said list:"")
result = Counter(colors)
print(result)
nums = [3,5,0,3,9,5,8,0,3,8,5,8,3,5,8,1,0,2]
print(""\nOriginal List:"")
print(nums)
print(""Count the occurrence of each element of the said list:"")
result = Counter(nums)
print(result)
"
637,Write a NumPy program to extract all the elements of the second and third columns from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: All the elements of the second and third columns"")
print(arra_data[:,[1,2]])
"
638,Write a Pandas program to check if a day is a business day (weekday) or not. ,"import pandas as pd
def is_business_day(date):
return bool(len(pd.bdate_range(date, date)))
print(""Check busines day or not?"")
print('2020-12-01: ',is_business_day('2020-12-01'))
print('2020-12-06: ',is_business_day('2020-12-06'))
print('2020-12-07: ',is_business_day('2020-12-07'))
print('2020-12-08: ',is_business_day('2020-12-08'))
"
639,Write a Python program to get the powerset of a given iterable. ,"from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
nums = [1, 2]
print(""Original list elements:"")
print(nums)
print(""Powerset of the said list:"")
print(powerset(nums))
nums = [1, 2, 3, 4]
print(""\nOriginal list elements:"")
print(nums)
print(""Powerset of the said list:"")
print(powerset(nums))
"
640,Write a Python program to create a dictionary from a string. ,"from collections import defaultdict, Counter
str1 = 'w3resource'
my_dict = {}
for letter in str1:
my_dict[letter] = my_dict.get(letter, 0) + 1
print(my_dict)
"
641,Write a Pandas program to convert a dictionary to a Pandas series. ,"import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print(""Original dictionary:"")
print(d1)
new_series = pd.Series(d1)
print(""Converted series:"")
print(new_series)
"
642,Write a Python program that accepts a word from the user and reverse it. ,"word = input(""Input a word to reverse: "")
for char in range(len(word) - 1, -1, -1):
print(word[char], end="""")
print(""\n"")
"
643,Write a NumPy program to find the indices of the maximum and minimum values along the given axis of an array. ,"import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
print(""Original array: "",x)
print(""Maximum Values: "",np.argmax(x))
print(""Minimum Values: "",np.argmin(x))
"
644,Write a Python program to replace a given tag with whatever's inside a given tag. ,"from bs4 import BeautifulSoup
markup = 'Python exercises.w3resource.com'
soup = BeautifulSoup(markup, ""lxml"")
a_tag = soup.a
print(""Original markup:"")
print(a_tag)
a_tag.i.unwrap()
print(""\nAfter unwrapping:"")
print(a_tag)
"
645,Write a Python program to map two lists into a dictionary. ,"keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
"
646,Write a Python program to get the length in bytes of one array item in the internal representation. ,"from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print(""Original array: ""+str(array_num))
print(""Length in bytes of one array item: ""+str(array_num.itemsize))
"
647,Write a Pandas program to convert the first column of a DataFrame as a Series. ,"import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print(""Original DataFrame"")
print(df)
s1 = df.ix[:,0]
print(""\n1st column as a Series:"")
print(s1)
print(type(s1))
"
648,Write a NumPy program to find the number of rows and columns of a given matrix. ,"import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(""Original matrix:"")
print(m)
print(""Number of rows and columns of the said matrix:"")
print(m.shape)
"
649,Write a Python program to get all possible two digit letter combinations from a digit (1 to 9) string. ,"def letter_combinations(digits):
if digits == """":
return []
string_maps = {
""1"": ""abc"",
""2"": ""def"",
""3"": ""ghi"",
""4"": ""jkl"",
""5"": ""mno"",
""6"": ""pqrs"",
""7"": ""tuv"",
""8"": ""wxy"",
""9"": ""z""
}
result = [""""]
for num in digits:
temp = []
for an in result:
for char in string_maps[num]:
temp.append(an + char)
result = temp
return result
digit_string = ""47""
print(letter_combinations(digit_string))
digit_string = ""29""
print(letter_combinations(digit_string))
"
650,Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters. ,"def to_uppercase(str1):
num_upper = 0
for letter in str1[:4]:
if letter.upper() == letter:
num_upper += 1
if num_upper >= 2:
return str1.upper()
return str1
print(to_uppercase('Python'))
print(to_uppercase('PyThon'))
"
651,Write a Python program to split a string on the last occurrence of the delimiter. ,"str1 = ""w,3,r,e,s,o,u,r,c,e""
print(str1.rsplit(',', 1))
print(str1.rsplit(',', 2))
print(str1.rsplit(',', 5))
"
652,Write a Python program to create a flat list of all the keys in a flat dictionary. ,"def test(flat_dict):
return list(flat_dict.keys())
students = {
'Theodore': 19,
'Roxanne': 20,
'Mathew': 21,
'Betty': 20
}
print(""\nOriginal dictionary elements:"")
print(students)
print(""\nCreate a flat list of all the keys of the said flat dictionary:"")
print(test(students))
"
653,Write a NumPy program to compute the inverse of a given matrix. ,"import numpy as np
m = np.array([[1,2],[3,4]])
print(""Original matrix:"")
print(m)
result = np.linalg.inv(m)
print(""Inverse of the said matrix:"")
print(result)
"
654,Write a Python program to calculate the sum of all digits of the base to the specified power. ,"def power_base_sum(base, power):
return sum([int(i) for i in str(pow(base, power))])
print(power_base_sum(2, 100))
print(power_base_sum(8, 10))
"
655,Write a Python program to start a new process replacing the current process. ,"import os
import sys
program = ""python""
arguments = [""hello.py""]
print(os.execvp(program, (program,) + tuple(arguments)))
print(""Goodbye"")
"
656,Write a Pandas program to swap the cases of a specified character column in a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print(""Original DataFrame:"")
print(df)
print(""\nSwapp cases in comapny_code:"")
df['swapped_company_code'] = list(map(lambda x: x.swapcase(), df['company_code']))
print(df)
"
657,"Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays. ","import numpy as np
x = np.array([3, 5])
y = np.array([2, 5])
print(""Original numbers:"")
print(x)
print(y)
print(""Comparison - greater"")
print(np.greater(x, y))
print(""Comparison - greater_equal"")
print(np.greater_equal(x, y))
print(""Comparison - less"")
print(np.less(x, y))
print(""Comparison - less_equal"")
print(np.less_equal(x, y))
"
658,"Write a Python program to build a list, using an iterator function and an initial seed value. ","def unfold(fn, seed):
def fn_generator(val):
while True:
val = fn(val[1])
if val == False: break
yield val[0]
return [i for i in fn_generator([None, seed])]
f = lambda n: False if n > 40 else [-n, n + 10]
print(unfold(f, 10))
"
659,"Write a Python program to remove the K'th element from a given list, print the new list. ","def remove_kth_element(n_list, L):
return n_list[:L-1] + n_list[L:]
n_list = [1,1,2,3,4,4,5,1]
print(""Original list:"")
print(n_list)
kth_position = 3
result = remove_kth_element(n_list, kth_position)
print(""\nAfter removing an element at the kth position of the said list:"")
print(result)
"
660,Write a Python program to interleave multiple given lists of different lengths. ,"def interleave_diff_len_lists(list1, list2, list3, list4):
result = []
l1 = len(list1)
l2 = len(list2)
l3 = len(list3)
l4 = len(list4)
for i in range(max(l1, l2, l3, l4)):
if i < l1:
result.append(list1[i])
if i < l2:
result.append(list2[i])
if i < l3:
result.append(list3[i])
if i < l4:
result.append(list4[i])
return result
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [2, 5, 8]
nums3 = [0, 1]
nums4 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(nums3)
print(nums4)
print(""\nInterleave said lists of different lengths:"")
print(interleave_diff_len_lists(nums1, nums2, nums3, nums4))
"
661,Write a NumPy program to combine a one and a two dimensional array together and display their elements. ,"import numpy as np
x = np.arange(4)
print(""One dimensional array:"")
print(x)
y = np.arange(8).reshape(2,4)
print(""Two dimensional array:"")
print(y)
for a, b in np.nditer([x,y]):
print(""%d:%d"" % (a,b),)
"
662,"Write a NumPy program to calculate hyperbolic sine, hyperbolic cosine, and hyperbolic tangent for all elements in a given array. ","import numpy as np
x = np.array([-1., 0, 1.])
print(np.sinh(x))
print(np.cosh(x))
print(np.tanh(x))
"
663,Write a NumPy program to calculate the Euclidean distance. ,"from scipy.spatial import distance
p1 = (1, 2, 3)
p2 = (4, 5, 6)
d = distance.euclidean(p1, p2)
print(""Euclidean distance: "",d)
"
664,Write a Pandas program to find the Indexes of missing 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nMissing values in purch_amt column:"")
result = df['ord_no'].isnull().to_numpy().nonzero()
print(result)
"
665,Write a NumPy program to print all the values of an array. ,"import numpy as np
np.set_printoptions(threshold=np.nan)
x = np.zeros((4, 4))
print(x)
"
666,Write a Python program to skip the headers of a given CSV file. Use csv.reader,"import csv
f = open(""employees.csv"", ""r"")
reader = csv.reader(f)
next(reader)
for row in reader:
print(row)
"
667,Write a NumPy program to compute pearson product-moment correlation coefficients of two given arrays. ,"import numpy as np
x = np.array([0, 1, 3])
y = np.array([2, 4, 5])
print(""\nOriginal array1:"")
print(x)
print(""\nOriginal array1:"")
print(y)
print(""\nPearson product-moment correlation coefficients of the said arrays:\n"",np.corrcoef(x, y))
"
668,Write a Python program to get the frequency of the tuples in a given list. ,"from collections import Counter
nums = [(['1', '4'], ['4', '1'], ['3', '4'], ['2', '7'], ['6', '8'], ['5','8'], ['6','8'], ['5','7'], ['2','7'])]
print(""Original list of tuples:"")
print(nums)
result = Counter(tuple(sorted(i)) for i in nums[0])
print(""\nTuples"","" "",""frequency"")
for key,val in result.items():
print(key,"" "", val)
"
669,Write a NumPy program to make the length of each element 15 of a given array and the string centered / left-justified / right-justified with paddings of _. ,"import numpy as np
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
print(""Original Array:"")
print(x)
centered = np.char.center(x, 15, fillchar='_')
left = np.char.ljust(x, 15, fillchar='_')
right = np.char.rjust(x, 15, fillchar='_')
print(""\nCentered ="", centered)
print(""Left ="", left)
print(""Right ="", right)
"
670,"Write a NumPy program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2. ","import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print(""Array1: "",array1)
array2 = [10, 30, 40, 50, 70]
print(""Array2: "",array2)
print(""Unique values in array1 that are not in array2:"")
print(np.setdiff1d(array1, array2))
"
671,"Write a NumPy program to create a vector of size 10 with values ranging from 0 to 1, both excluded. ","import numpy as np
x = np.linspace(0,1,12,endpoint=True)[1:-1]
print(x)
"
672,Write a NumPy program to evaluate Einstein's summation convention of two given multidimensional arrays. ,"import numpy as np
a = np.array([1,2,3])
b = np.array([0,1,0])
print(""Original 1-d arrays:"")
print(a)
print(b)
result = np.einsum(""n,n"", a, b)
print(""Einstein’s summation convention of the said arrays:"")
print(result)
x = np.arange(9).reshape(3, 3)
y = np.arange(3, 12).reshape(3, 3)
print(""Original Higher dimension:"")
print(x)
print(y)
result = np.einsum(""mk,kn"", x, y)
print(""Einstein’s summation convention of the said arrays:"")
print(result)
"
673,Write a Python program to remove the contents of a tag in a given html document. ,"from bs4 import BeautifulSoup
html_content = 'Python exercisesw3resource'
soup = BeautifulSoup(html_content, ""lxml"")
print(""Original Markup:"")
print(soup.a)
tag = soup.a
tag = tag.clear()
print(""\nAfter clearing the contents in the tag:"")
print(soup.a)
"
674,Write a Python program to count the number of elements in a list within a specified range. ,"def count_range_in_list(li, min, max):
ctr = 0
for x in li:
if min <= x <= max:
ctr += 1
return ctr
list1 = [10,20,30,40,40,40,70,80,99]
print(count_range_in_list(list1, 40, 100))
list2 = ['a','b','c','d','e','f']
print(count_range_in_list(list2, 'a', 'e'))
"
675,Write a Python program to concatenate elements of a list. ,"color = ['red', 'green', 'orange']
print('-'.join(color))
print(''.join(color))
"
676,Write a Python program to access multiple elements of specified index from a given list. ,"def access_elements(nums, list_index):
result = [nums[i] for i in list_index]
return result
nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
print (""Original list:"")
print(nums)
list_index = [0,3,5,7,10]
print(""Index list:"")
print(list_index)
print(""\nItems with specified index of the said list:"")
print(access_elements(nums, list_index))
"
677,Write a Python program to Zip two given lists of lists. ,"list1 = [[1, 3], [5, 7], [9, 11]]
list2 = [[2, 4], [6, 8], [10, 12, 14]]
print(""Original lists:"")
print(list1)
print(list2)
result = list(map(list.__add__, list1, list2))
print(""\nZipped list:\n"" + str(result))
"
678,Write a Pandas program to extract unique reporting dates of unidentified flying object (UFO). ,"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(""\nUnique reporting dates of UFO:"")
print(df[""Date_time""].map(lambda t: t.date()).unique())
"
679,"Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
age = pd.cut(df['age'], [0, 20, 55])
result = df.pivot_table('survived', index=['sex', age], columns='class')
print(result)
"
680,Write a Python program to sort unsorted numbers using Pigeonhole sorting. ,"#Ref. https://bit.ly/3olnZcd
def pigeonhole_sort(a):
# size of range of values in the list (ie, number of pigeonholes we need)
min_val = min(a) # min() finds the minimum value
max_val = max(a) # max() finds the maximum value
size = max_val - min_val + 1 # size is difference of max and min values plus one
# list of pigeonholes of size equal to the variable size
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert isinstance(x, int), ""integers only please""
holes[x - min_val] += 1
# Putting the elements back into the array in an order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + min_val
i += 1
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
pigeonhole_sort(nums)
print(""Sorted order is:"", nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
pigeonhole_sort(nums)
print(""Sorted order is:"", nums)
"
681,"Write a Python program to calculate the difference between two iterables, without filtering duplicate values. ","def difference(x, y):
_y = set(y)
return [item for item in x if item not in _y]
print(difference([1, 2, 3], [1, 2, 4]))
"
682,Write a Python program to get the number of datasets currently listed on data.gov. ,"from lxml import html
import requests
response = requests.get('http://www.data.gov/')
doc_gov = html.fromstring(response.text)
link_gov = doc_gov.cssselect('small a')[0]
print(""Number of datasets currently listed on data.gov:"")
print(link_gov.text)
"
683,"Write a NumPy program to add two arrays A and B of sizes (3,3) and (,3). ","import numpy as np
A = np.ones((3,3))
B = np.arange(3)
print(""Original array:"")
print(""Array-1"")
print(A)
print(""Array-2"")
print(B)
print(""A + B:"")
new_array = A + B
print(new_array)
"
684,Write a Python program to detect the number of local variables declared in a function. ,"def abc():
x = 1
y = 2
str1= ""w3resource""
print(""Python Exercises"")
print(abc.__code__.co_nlocals)
"
685,Write a Python program to that takes any number of iterable objects or objects with a length property and returns the longest one. ,"def longest_item(*args):
return max(args, key = len)
print(longest_item('this', 'is', 'a', 'Green'))
print(longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))
print(longest_item([1, 2, 3, 4], 'Red'))
"
686,Write a Python program that multiply each number of given list with a given number using lambda function. Print the result. ,"nums = [2, 4, 6, 9 , 11]
n = 2
print(""Original list: "", nums)
print(""Given number: "", n)
filtered_numbers=list(map(lambda number:number*n,nums))
print(""Result:"")
print(' '.join(map(str,filtered_numbers)))
"
687,Write a Python program to convert list to list of dictionaries. ,"color_name = [""Black"", ""Red"", ""Maroon"", ""Yellow""]
color_code = [""#000000"", ""#FF0000"", ""#800000"", ""#FFFF00""]
print([{'color_name': f, 'color_code': c} for f, c in zip(color_name, color_code)])
"
688,"Write a Python program to round a Decimal value to the nearest multiple of 0.10, unless already an exact multiple of 0.05. Use decimal.Decimal","from decimal import Decimal
#Source: https://bit.ly/3hEyyY4
def round_to_10_cents(x):
remainder = x.remainder_near(Decimal('0.10'))
if abs(remainder) == Decimal('0.05'):
return x
else:
return x - remainder
# Test code.
for x in range(80, 120):
y = Decimal(x) / Decimal('1E2')
print(""{0} rounds to {1}"".format(y, round_to_10_cents(y)))
"
689,Write a Pandas program to split the following given dataframe into groups based on school code and cast grouping as a list. ,"import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(student_data)
print('\nCast grouping as a list:')
result = student_data.groupby(['school_code'])
print(list(result))
"
690,Write a Python program to find the missing number in a given array of numbers between 10 and 20. ,"import array as arr
def test(nums):
return sum(range(10, 21)) - sum(list(nums))
array_num = arr.array('i', [10, 11, 12, 13, 14, 16, 17, 18, 19, 20])
print(""Original array:"")
for i in range(len(array_num)):
print(array_num[i], end=' ')
print(""\nMissing number in the said array (10-20): "",test(array_num))
array_num = arr.array('i', [10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
print(""\nOriginal array:"")
for i in range(len(array_num)):
print(array_num[i], end=' ')
print(""\nMissing number in the said array (10-20): "",test(array_num))
"
691,"Write a Python program to map the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. ","def map_dictionary(itr, fn):
return dict(zip(itr, map(fn, itr)))
print(map_dictionary([1, 2, 3], lambda x: x * x))
"
692,Write a Python program to check if there are duplicate values in a given flat list. ,"def has_duplicates(lst):
return len(lst) != len(set(lst))
nums = [1, 2, 3, 4, 5, 6, 7]
print(""Original list:"")
print(nums)
print(""Check if there are duplicate values in the said given flat list:"")
print(has_duplicates(nums))
nums = [1, 2, 3, 3, 4, 5, 5, 6, 7]
print(""\nOriginal list:"")
print(nums)
print(""Check if there are duplicate values in the said given flat list:"")
print(has_duplicates(nums))
"
693,Write a Python program to combine two given sorted lists using heapq module. ,"from heapq import merge
nums1 = [1, 3, 5, 7, 9, 11]
nums2 = [0, 2, 4, 6, 8, 10]
print(""Original sorted lists:"")
print(nums1)
print(nums2)
print(""\nAfter merging the said two sorted lists:"")
print(list(merge(nums1, nums2)))
"
694,Write a Python program to find shortest list of values with the keys in a given dictionary. ,"def test(dictt):
min_value=1
result = [k for k, v in dictt.items() if len(v) == (min_value)]
return result
dictt = {
'V': [10, 12],
'VI': [10],
'VII': [10, 20, 30, 40],
'VIII': [20],
'IX': [10,30,50,70],
'X': [80]
}
print(""\nOriginal Dictionary:"")
print(dictt)
print(""\nShortest list of values with the keys of the said dictionary:"")
print(test(dictt))
"
695,"Write a Python program to check for access to a specified path. Test the existence, readability, writability and executability of the specified path. ","import os
print('Exist:', os.access('c:\\Users\\Public\\C programming library.docx', os.F_OK))
print('Readable:', os.access('c:\\Users\\Public\\C programming library.docx', os.R_OK))
print('Writable:', os.access('c:\\Users\\Public\\C programming library.docx', os.W_OK))
print('Executable:', os.access('c:\\Users\\Public\\C programming library.docx', os.X_OK))
"
696,Write a Python program to sort a list of elements using Selection sort. ,"def selection_sort(nums):
for i, n in enumerate(nums):
mn = min(range(i,len(nums)), key=nums.__getitem__)
nums[i], nums[mn] = nums[mn], n
return nums
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
print(selection_sort(nums))
"
697,Write a Pandas program to split the following datasets into groups on customer_id to summarize purch_amt and calculate percentage of purch_amt in 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': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'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)
gr_data = df.groupby(['customer_id','salesman_id']).agg({'purch_amt': 'sum'})
gr_data[""% (Purch Amt.)""] = gr_data.apply(lambda x: 100*x / x.sum())
print(""\nPercentage of purch_amt in each group of customer_id:"")
print(gr_data)
"
698,Write a Python program to extract a tag or string from a given tree of html document. ,"from bs4 import BeautifulSoup
html_content = 'Python exercisesw3resource'
soup = BeautifulSoup(html_content, ""lxml"")
print(""Original Markup:"")
print(soup.a)
i_tag = soup.i.extract()
print(""\nExtract i tag from said html Markup:"")
print(i_tag)
"
699,Write a Python program to remove consecutive duplicates of a given list. ,"from itertools import groupby
def compress(l_nums):
return [key for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print(""Original list:"")
print(n_list)
print(""\nAfter removing consecutive duplicates:"")
print(compress(n_list))
"
700,"Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise, sales man wise. ","import numpy as np
import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=[""Region"",""Manager"",""SalesMan""], values=""Sale_amt"", aggfunc=np.sum))
"
701,Write a Pandas program to find out the alcohol consumption details in the year '1986' where WHO region is 'Western Pacific' and country is 'VietNam' 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 where WHO region is Western Pacific and country is VietNam :"")
print(w_a_con[(w_a_con['Year']==1986) & (w_a_con['WHO region']=='Western Pacific') & (w_a_con['Country']=='Viet Nam')])
"
702,"Write a Python function that checks whether a passed string is palindrome or not.
","def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))
"
703,Write a Python program to count integer in a given mixed list. ,"def count_integer(list1):
ctr = 0
for i in list1:
if isinstance(i, int):
ctr = ctr + 1
return ctr
list1 = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
print(""Original list:"")
print(list1)
print(""\nNumber of integers in the said mixed list:"")
print(count_integer(list1))
"
704,Write a Python program to check if first digit/character of each element in a given list is same or not. ,"def test(lst):
result = all(str(x)[0] == str(lst[0])[0] for x in lst)
return result
nums = [1234, 122, 1984, 19372, 100]
print(""\nOriginal list:"")
print(nums)
print(""Check if first digit in each element of the said given list is same or not!"")
print(test(nums))
nums = [1234, 922, 1984, 19372, 100]
print(""\nOriginal list:"")
print(nums)
print(""Check if first digit in each element of the said given list is same or not!"")
print(test(nums))
nums = ['aabc', 'abc', 'ab', 'a']
print(""\nOriginal list:"")
print(nums)
print(""Check if first character in each element of the said given list is same or not!"")
print(test(nums))
nums = ['aabc', 'abc', 'ab', 'ha']
print(""\nOriginal list:"")
print(nums)
print(""Check if first character in each element of the said given list is same or not!"")
print(test(nums))
"
705,"Write a Python program to print four values decimal, octal, hexadecimal (capitalized), binary in a single line of a given integer. ","i = int(input(""Input an integer: ""))
o = str(oct(i))[2:]
h = str(hex(i))[2:]
h = h.upper()
b = str(bin(i))[2:]
d = str(i)
print(""Decimal Octal Hexadecimal (capitalized), Binary"")
print(d,' ',o,' ',h,' ',b)
"
706,Write a NumPy program to extract third and fourth elements of the first and second rows from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: Third and fourth elements of the first and second rows "")
print(arra_data[0:2, 2:4])
"
707,Write a NumPy program to create a record array from a (flat) list of arrays. ,"import numpy as np
a1=np.array([1,2,3,4])
a2=np.array(['Red','Green','White','Orange'])
a3=np.array([12.20,15,20,40])
result= np.core.records.fromarrays([a1, a2, a3],names='a,b,c')
print(result[0])
print(result[1])
print(result[2])
"
708,Write a Python program to find palindromes in a given list of strings using Lambda. ,"texts = [""php"", ""w3r"", ""Python"", ""abcd"", ""Java"", ""aaa""]
print(""Orginal list of strings:"")
print(texts)
result = list(filter(lambda x: (x == """".join(reversed(x))), texts))
print(""\nList of palindromes:"")
print(result)
"
709,"Write a Python program that reads a CSV file and remove initial spaces, quotes around each entry and the delimiter. ","import csv
csv.register_dialect('csv_dialect',
delimiter='|',
skipinitialspace=True,
quoting=csv.QUOTE_ALL)
with open('temp.csv', 'r') as csvfile:
reader = csv.reader(csvfile, dialect='csv_dialect')
for row in reader:
print(row)
"
710,Write a Pandas program to create a bar plot of the trading volume of Alphabet Inc. stock between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-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.set_index('Date')
plt.figure(figsize=(6,6))
plt.suptitle('Trading Volume of Alphabet Inc. stock,\n01-04-2020 to 30-04-2020', fontsize=16, color='black')
plt.xlabel(""Date"",fontsize=12, color='black')
plt.ylabel(""Trading Volume"", fontsize=12, color='black')
df2['Volume'].plot(kind='bar');
plt.show()
"
711,Write a Python program to delete all occurrences of a specified character in a given string. ,"def delete_all_occurrences(str1, ch):
result = str1.replace(ch, """")
return(result)
str_text = ""Delete all occurrences of a specified character in a given string""
print(""Original string:"")
print(str_text)
print(""\nModified string:"")
ch='a'
print(delete_all_occurrences(str_text, ch))
"
712,"Write a Pandas program to create a Pivot table and find manager wise, salesman wise total sale and also display the sum of all sale amount at the bottom. ","import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df,index=[""Manager"",""SalesMan""],values=[""Units"",""Sale_amt""],
aggfunc=[np.sum],fill_value=0,margins=True)
print(table)
"
713,"Write a Python program to create a time object with the same hour, minute, second, microsecond and timezone info. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nTime object with the same hour, minute, second, microsecond and timezone info.:"")
print(arrow.utcnow().timetz())
"
714,Write a Pandas program to get the items of a given series not present in another given series. ,"import pandas as pd
sr1 = pd.Series([1, 2, 3, 4, 5])
sr2 = pd.Series([2, 4, 6, 8, 10])
print(""Original Series:"")
print(""sr1:"")
print(sr1)
print(""sr2:"")
print(sr2)
print(""\nItems of sr1 not present in sr2:"")
result = sr1[~sr1.isin(sr2)]
print(result)
"
715,Write a Python program to create a new list dividing two given lists of numbers. ,"def dividing_two_lists(l1,l2):
result = [x/y for x, y in zip(l1,l2)]
return result
nums1 = [7,2,3,4,9,2,3]
nums2 = [9,8,2,3,3,1,2]
print(""Original list:"")
print(nums1)
print(nums1)
print(dividing_two_lists(nums1, nums2))
"
716,"Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s). ",print(abs.__doc__)
717,"Write a Python program to count the even, odd numbers in a given array of integers using Lambda. ","array_nums = [1, 2, 3, 5, 7, 8, 9, 10]
print(""Original arrays:"")
print(array_nums)
odd_ctr = len(list(filter(lambda x: (x%2 != 0) , array_nums)))
even_ctr = len(list(filter(lambda x: (x%2 == 0) , array_nums)))
print(""\nNumber of even numbers in the above array: "", even_ctr)
print(""\nNumber of odd numbers in the above array: "", odd_ctr)
"
718,Write a Python program to get a datetime or timestamp representation from current datetime. ,"import arrow
a = arrow.utcnow()
print(""Datetime representation:"")
print(a.datetime)
b = a.timestamp
print(""\nTimestamp representation:"")
print(b)
"
719,Write a Python program to check whether lowercase letters exist in a string. ,"str1 = 'A8238i823acdeOUEI'
print(any(c.islower() for c in str1))
"
720,Write a Pandas program to split the following given dataframe into groups based on single column and multiple columns. Find the size of the grouped data. ,"import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(student_data)
print('\nSplit the said data on school_code wise:')
grouped_single = student_data.groupby(['school_code'])
print(""Size of the grouped data - single column"")
print(grouped_single.size())
print('\nSplit the said data on school_code and class wise:')
grouped_mul = student_data.groupby(['school_code', 'class'])
print(""Size of the grouped data - multiple columns:"")
print(grouped_mul.size())
"
721,Write a Python program to create a new JSON file from an existing JSON file. ,"import json
with open('states.json') as f:
state_data= json.load(f)
for state in state_data['states']:
del state['area_codes']
with open('new_states.json', 'w') as f:
json.dump(state_data, f, indent=2)
"
722,Write a Python program to move spaces to the front of a given string. ,"def move_Spaces_front(str1):
noSpaces_char = [ch for ch in str1 if ch!=' ']
spaces_char = len(str1) - len(noSpaces_char)
result = ' '*spaces_char
result = '""'+result + ''.join(noSpaces_char)+'""'
return(result)
print(move_Spaces_front(""w3resource . com ""))
print(move_Spaces_front("" w3resource.com ""))
"
723,Write a Pandas program to check whether alpha numeric values present in a given column of a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'name_code': ['Company','Company a001','Company 123', '1234', 'Company 12'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
print(""\nWhether all characters in the string are alphanumeric?"")
df['name_code_is_alphanumeric'] = list(map(lambda x: x.isalnum(), df['name_code']))
print(df)
"
724,Write a Python program to split a given dictionary of lists into list of dictionaries. ,"def list_of_dicts(marks):
keys = marks.keys()
vals = zip(*[marks[k] for k in keys])
result = [dict(zip(keys, v)) for v in vals]
return result
marks = {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}
print(""Original dictionary of lists:"")
print(marks)
print(""\nSplit said dictionary of lists into list of dictionaries:"")
print(list_of_dicts(marks))
"
725,Write a Python program to read specific columns of a given CSV file and print the content of the columns. ,"import csv
with open('departments.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
print(""ID Department Name"")
print(""---------------------------------"")
for row in data:
print(row['department_id'], row['department_name'])
"
726,Write a Python program to create a list with infinite elements. ,"import itertools
c = itertools.count()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
"
727,Write a NumPy program to select indices satisfying multiple conditions in a NumPy array. ,"import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print(""Original arrays"")
print(a)
print(b)
print(""Elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110:"")
print(b[(100 < a) & (a < 110)])
"
728,Write a Python program to invert a given dictionary with non-unique hashable values. ,"from collections import defaultdict
def test(students):
obj = defaultdict(list)
for key, value in students.items():
obj[value].append(key)
return dict(obj)
students = {
'Ora Mckinney': 8,
'Theodore Hollandl': 7,
'Mae Fleming': 7,
'Mathew Gilbert': 8,
'Ivan Little': 7,
}
print(test(students))
"
729,Write a NumPy program to create an inner product of two arrays. ,"import numpy as np
x = np.arange(24).reshape((2,3,4))
print(""Array x:"")
print(x)
print(""Array y:"")
y = np.arange(4)
print(y)
print(""Inner of x and y arrays:"")
print(np.inner(x, y))
"
730,Write a Pandas program to create a Pivot table and find the maximum sale value of the items. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=np.max)
print(table)
"
731,Write a Pandas program to convert index of a given dataframe into a column. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 32, 33, 30, 31, 32]},
index = ['t1', 't2', 't3', 't4', 't5', 't6'])
print(""Original DataFrame:"")
print(df)
print(""\nConvert index of the said dataframe into a column:"")
df.reset_index(level=0, inplace=True)
print(df)
"
732,Write a Python program to sum a specific column of a list in a given list of lists. ,"def sum_column(nums, C):
result = sum(row[C] for row in nums)
return result
nums = [
[1,2,3,2],
[4,5,6,2],
[7,8,9,5],
]
print(""Original list of lists:"")
print(nums)
column = 0
print(""\nSum: 1st column of the said list of lists:"")
print(sum_column(nums, column))
column = 1
print(""\nSum: 2nd column of the said list of lists:"")
print(sum_column(nums, column))
column = 3
print(""\nSum: 4th column of the said list of lists:"")
print(sum_column(nums, column))
"
733,Write a Python program to add two given lists and find the difference between lists. Use map() function. ,"def addition_subtrction(x, y):
return x + y, x - y
nums1 = [6, 5, 3, 9]
nums2 = [0, 1, 7, 7]
print(""Original lists:"")
print(nums1)
print(nums2)
result = map(addition_subtrction, nums1, nums2)
print(""\nResult:"")
print(list(result))
"
734,Write a Pandas program to create a date range using a startpoint date and a number of periods. ,"import pandas as pd
date_range = pd.date_range('2020-01-01', periods=45)
print(""Date range of perods 45:"")
print(date_range)
"
735,"Write a NumPy program to calculate inverse sine, inverse cosine, and inverse tangent for all elements in a given array. ","import numpy as np
x = np.array([-1., 0, 1.])
print(""Inverse sine:"", np.arcsin(x))
print(""Inverse cosine:"", np.arccos(x))
print(""Inverse tangent:"", np.arctan(x))
"
736,Write a Pandas program to create the mean and standard deviation of the data of a given Series. ,"import pandas as pd
s = pd.Series(data = [1,2,3,4,5,6,7,8,9,5,3])
print(""Original Data Series:"")
print(s)
print(""Mean of the said Data Series:"")
print(s.mean())
print(""Standard deviation of the said Data Series:"")
print(s.std())
"
737,Write a Python program to remove duplicates from a list. ,"a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
"
738,Write a Python program to find the latitude and longitude of a given location using Nominatim API and GeoPy package. ,"from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent=""geoapiExercises"")
ladd1 = ""27488 Stanford Avenue, North Dakota""
print(""Location address:"",ladd1)
location = geolocator.geocode(ladd1)
print(""Latitude and Longitude of the said address:"")
print((location.latitude, location.longitude))
ladd2 = ""380 New York St, Redlands, CA 92373""
print(""\nLocation address:"",ladd2)
location = geolocator.geocode(ladd2)
print(""Latitude and Longitude of the said address:"")
print((location.latitude, location.longitude))
ladd3 = ""1600 Pennsylvania Avenue NW""
print(""\nLocation address:"",ladd3)
location = geolocator.geocode(ladd3)
print(""Latitude and Longitude of the said address:"")
print((location.latitude, location.longitude))
"
739,Write a Python program to get hourly datetime between two hours. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nString representing the date, controlled by an explicit format string:"")
print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
"
740,Write a Python program to sort an unsorted array numbers using Wiggle sort. ,"def wiggle_sort(arra_nums):
for i, _ in enumerate(arra_nums):
if (i % 2 == 1) == (arra_nums[i - 1] > arra_nums[i]):
arra_nums[i - 1], arra_nums[i] = arra_nums[i], arra_nums[i - 1]
return arra_nums
print(""Input the array elements: "")
arra_nums = list(map(int, input().split()))
print(""Original unsorted array:"")
print(arra_nums)
print(""The said array after applying Wiggle sort:"")
print(wiggle_sort(arra_nums))
"
741,Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension. ,"import numpy as np
a = np.array([1,2,5])
b = np.array([2,1,0])
print(""Original 1-d arrays:"")
print(a)
print(b)
print
result = np.inner(a, b)
print(""Inner product of the said vectors:"")
x = np.arange(9).reshape(3, 3)
y = np.arange(3, 12).reshape(3, 3)
print(""Higher dimension arrays:"")
print(x)
print(y)
result = np.inner(x, y)
print(""Inner product of the said vectors:"")
print(result)
"
742,Write a Python program to find the pairs of maximum and minimum product from a given list. Use itertools module. ,"import itertools as it
def list_max_min_pair(nums):
result_max = max(it.combinations(nums, 2), key = lambda sub: sub[0] * sub[1])
result_min = min(it.combinations(nums, 2), key = lambda sub: sub[0] * sub[1])
return result_max, result_min
nums = [2,5,8,7,4,3,1,9,10,1]
print(""The original list: "")
print(nums)
print(""\nPairs of maximum and minimum product from the said list:"")
print(list_max_min_pair(nums))
"
743,Write a python program to check whether two lists are circularly identical. ,"list1 = [10, 10, 0, 0, 10]
list2 = [10, 10, 10, 0, 0]
list3 = [1, 10, 10, 0, 0]
print('Compare list1 and list2')
print(' '.join(map(str, list2)) in ' '.join(map(str, list1 * 2)))
print('Compare list1 and list3')
print(' '.join(map(str, list3)) in ' '.join(map(str, list1 * 2)))
"
744," Write a NumPy program to create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal. ","import numpy as np
x = np.zeros((4, 4))
x[::2, 1::2] = 1
x[1::2, ::2] = 1
print(x)
"
745,Write a Python program to convert a given list of integers and a tuple of integers in a list of strings. ,"nums_list = [1,2,3,4]
nums_tuple = (0, 1, 2, 3)
print(""Original list and tuple:"")
print(nums_list)
print(nums_tuple)
result_list = list(map(str,nums_list))
result_tuple = tuple(map(str,nums_tuple))
print(""\nList of strings:"")
print(result_list)
print(""\nTuple of strings:"")
print(result_tuple)
"
746,Write a Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list. ,"from functools import reduce
from operator import getitem
def test(d, selectors):
return reduce(getitem, selectors, d)
users = {
'Carla ': {
'name': {
'first': 'Carla ',
'last': 'Russell'
},
'postIds': [1, 2, 3, 4, 5]
}
}
print(test(users, ['Carla ', 'name', 'last']))
print(test(users, ['Carla ', 'postIds', 1]))
"
747,Write a Python program to insert tags or strings immediately after specified tags or strings. ,"from bs4 import BeautifulSoup
soup = BeautifulSoup(""w3resource.com"", ""lxml"")
print(""Original Markup:"")
print(soup.b)
tag = soup.new_tag(""i"")
tag.string = ""Python""
print(""\nNew Markup, after inserting the text:"")
soup.b.string.insert_after(tag)
print(soup.b)
"
748,Write a Python program to get all values from an enum class. ,"from enum import IntEnum
class Country(IntEnum):
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
country_code_list = list(map(int, Country))
print(country_code_list)
"
749,Write a Python program to create a list of random integers and randomly select multiple items from the said list. Use random.sample(),"import random
print(""Create a list of random integers:"")
population = range(0, 100)
nums_list = random.sample(population, 10)
print(nums_list)
no_elements = 4
print(""\nRandomly select"",no_elements,""multiple items from the said list:"")
result_elements = random.sample(nums_list, no_elements)
print(result_elements)
no_elements = 8
print(""\nRandomly select"",no_elements,""multiple items from the said list:"")
result_elements = random.sample(nums_list, no_elements)
print(result_elements)
"
750,Write a Python program to find tags by CSS class in a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
This is an example HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
LacieTillie
""""""
soup = BeautifulSoup(html_doc,""lxml"")
print(""\nTags by CSS class:"")
print(soup.select("".sister""))
"
751,Write a Pandas program to create a plot to visualize daily percentage returns of Alphabet Inc. stock price between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
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)
daily_changes['Adj Close'].plot(figsize=(10,7),legend=True,linestyle='--',marker='o')
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()
"
752,Write a Python program to count the most common words in a dictionary. ,"words = [
'red', 'green', 'black', 'pink', 'black', 'white', 'black', 'eyes',
'white', 'black', 'orange', 'pink', 'pink', 'red', 'red', 'white', 'orange',
'white', ""black"", 'pink', 'green', 'green', 'pink', 'green', 'pink',
'white', 'orange', ""orange"", 'red'
]
from collections import Counter
word_counts = Counter(words)
top_four = word_counts.most_common(4)
print(top_four)
"
753,Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array. ,"import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print(""Original array: "")
print(x)
print(""Values bigger than 10 ="", x[x>10])
print(""Their indices are "", np.nonzero(x > 10))
"
754,Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.,"for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
print(""\n"")
"
755,A Python Dictionary contains List as value. Write a Python program to clear the list values in the said dictionary. ,"def test(dictionary):
for key in dictionary:
dictionary[key].clear()
return dictionary
dictionary = {
'C1' : [10,20,30],
'C2' : [20,30,40],
'C3' : [12,34]
}
print(""\nOriginal Dictionary:"")
print(dictionary)
print(""\nClear the list values in the said dictionary:"")
print(test(dictionary))
"
756,Write a Python program to find the maximum and minimum values in a given list within specified index range. ,"def reverse_list_of_lists(nums,lr,hr):
temp = []
for idx, el in enumerate(nums):
if idx >= lr and idx < hr:
temp.append(el)
result_max = max(temp)
result_min = min(temp)
return result_max, result_min
nums = [4,3,0,5,3,0,2,3,4,2,4,3,5]
print(""Original list:"")
print(nums)
print(""\nIndex range:"")
lr = 3
hr = 8
print(lr,""to"",hr)
print(""\nMaximum and minimum values of the said given list within index range:"")
print(reverse_list_of_lists(nums,lr,hr))
"
757,Write a Pandas program to get the positions of items of a given series in another given series. ,"import pandas as pd
series1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
series2 = pd.Series([1, 3, 5, 7, 10])
print(""Original Series:"")
print(series1)
print(series2)
result = [pd.Index(series1).get_loc(i) for i in series2]
print(""Positions of items of series2 in series1:"")
print(result)
"
758,Write a Python program to count the frequency in a given dictionary. ,"from collections import Counter
def test(dictt):
result = Counter(dictt.values())
return result
dictt = {
'V': 10,
'VI': 10,
'VII': 40,
'VIII': 20,
'IX': 70,
'X': 80,
'XI': 40,
'XII': 20,
}
print(""\nOriginal Dictionary:"")
print(dictt)
print(""\nCount the frequency of the said dictionary:"")
print(test(dictt))
"
759,Write a Python program to insert values to a table from user input. ,"import sqlite3
conn = sqlite3 . connect ( 'mydatabase.db' )
cursor = conn.cursor ()
#create the salesman table
cursor.execute(""CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));"")
s_id = input('Salesman ID:')
s_name = input('Name:')
s_city = input('City:')
s_commision = input('Commission:')
cursor.execute(""""""
INSERT INTO salesman(salesman_id, name, city, commission)
VALUES (?,?,?,?)
"""""", (s_id, s_name, s_city, s_commision))
conn.commit ()
print ( 'Data entered successfully.' )
conn . close ()
if (conn):
conn.close()
print(""\nThe SQLite connection is closed."")
"
760,Write a Python program to find the length of the text of the first
tag of a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
This is an example HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
""""""
soup = BeautifulSoup(html_doc, 'html.parser')
print(""Length of the text of the first
tag:"")
print(len(soup.find('h2').text))
"
761,Write a NumPy program to get the number of nonzero elements in an array. ,"import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print(""Original array:"")
print(x)
print(""Number of non zero elements in the above array:"")
print(np.count_nonzero(x))
"
762,Write a Pandas program to replace more than one value with other values in a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['A','B', 'C', 'D', 'A'],
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print(""Original DataFrame:"")
print(df)
print(""\nReplace A with c:"")
df = df.replace([""A"", ""D""], [""X"", ""Y""])
print(df)
"
763,Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array. ,"import numpy as np
m = np.mat(""3 -2;1 0"")
print(""Original matrix:"")
print(""a\n"", m)
w, v = np.linalg.eig(m)
print( ""Eigenvalues of the said matrix"",w)
print( ""Eigenvectors of the said matrix"",v)
"
764,Write a Python program to chunk a given list into n smaller lists. ,"from math import ceil
def chunk_list_into_n(nums, n):
size = ceil(len(nums) / n)
return list(
map(lambda x: nums[x * size:x * size + size],
list(range(n)))
)
print(chunk_list_into_n([1, 2, 3, 4, 5, 6, 7], 4))
"
765,Write a NumPy program to add a border (filled with 0's) around an existing array. ,"import numpy as np
x = np.ones((3,3))
print(""Original array:"")
print(x)
print(""0 on the border and 1 inside in the array"")
x = np.pad(x, pad_width=1, mode='constant', constant_values=0)
print(x)
"
766,Write a Python program to create an array contains six integers. Also print all the members of the array. ,"from array import array
my_array = array('i', [10, 20, 30, 40, 50])
for i in my_array:
print(i)
"
767,Write a Python program to check whether all dictionaries in a list are empty or not. ,"my_list = [{},{},{}]
my_list1 = [{1,2},{},{}]
print(all(not d for d in my_list))
print(all(not d for d in my_list1))
"
768,Write a NumPy program to place a specified element in specified time randomly in a specified 2D array. ,"import numpy as np
n = 4
i = 3
e = 10
array_nums1 = np.zeros((n,n))
print(""Original array:"")
print(array_nums1)
np.put(array_nums1, np.random.choice(range(n*n), i, replace=False), e)
print(""\nPlace a specified element in specified time randomly:"")
print(array_nums1)
"
769,"Write a Python program to read a matrix from console and print the sum for each column. Accept matrix rows, columns and elements for each column separated with a space(for every row) as input from the user. ","rows = int(input(""Input rows: ""))
columns = int(input(""Input columns: ""))
matrix = [[0]*columns for row in range(rows)]
print('Input number of elements in a row (1, 2, 3): ')
for row in range(rows):
lines = list(map(int, input().split()))
for column in range(columns):
matrix[row][column] = lines[column]
sum = [0]*columns
print(""sum for each column:"")
for column in range(columns):
for row in range(rows):
sum[column] += matrix[row][column]
print((sum[column]), ' ', end = '')
"
770,Write a Pandas program to select consecutive columns and also select rows with Index label 0 to 9 with some columns from 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(""\nSelect consecutive columns:"")
print(w_a_con.loc[:,""Country"":""Display Value""].head())
print(""\nAlternate command:"")
print(w_a_con.iloc[:,2:5].head())
print(""\nSelect rows with Index label 0 to 9 with specific columns:"")
print(w_a_con.loc[0:9,[""Year"",""Country"",""Display Value""]])
"
771,rite a Python class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle. ,"class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
newRectangle = Rectangle(12, 10)
print(newRectangle.rectangle_area())
"
772,Write a Pandas program to remove the html tags within the specified column of a given DataFrame. ,"import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'address': ['9910 Surrey Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.', '17 West Livingston Court']
})
print(""Original DataFrame:"")
print(df)
def remove_tags(string):
result = re.sub('<.*?>','',string)
return result
df['with_out_tags']=df['address'].apply(lambda cw : remove_tags(cw))
print(""\nSentences without tags':"")
print(df)
"
773,Write a NumPy program to add a vector to each row of a given matrix. ,"import numpy as np
m = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 1, 0])
print(""Original vector:"")
print(v)
print(""Original matrix:"")
print(m)
result = np.empty_like(m)
for i in range(4):
result[i, :] = m[i, :] + v
print(""\nAfter adding the vector v to each row of the matrix m:"")
print(result)
"
774,Write a Pandas program to find out the alcohol consumption of a given year 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 1985:"")
print(w_a_con[w_a_con['Year']==1985].head(10))
print(""\nThe world alcohol consumption details in the year 1989:"")
print(w_a_con[w_a_con['Year']==1989].head(10))
"
775,Write a Python program to compute average of two given lists. ,"def average_two_lists(nums1, nums2):
result = sum(nums1 + nums2) / len(nums1 + nums2)
return result
nums1 = [1, 1, 3, 4, 4, 5, 6, 7]
nums2 = [0, 1, 2, 3, 4, 4, 5, 7, 8]
print(""Original list:"")
print(nums1)
print(nums2)
print(""\nAverage of two lists:"")
print(average_two_lists(nums1, nums2))
"
776,"Write a NumPy program to create 24 python datetime.datetime objects (single object for every hour), and then put it in a numpy array. ","import numpy as np
import datetime
start = datetime.datetime(2000, 1, 1)
dt_array = np.array([start + datetime.timedelta(hours=i) for i in range(24)])
print(dt_array)
"
777,Write a Pandas program to import some excel data (coalpublic2013.xlsx ) skipping first twenty rows into a Pandas dataframe. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx', skiprows = 20)
df
"
778,Write a Python program to append the same value /a list multiple times to a list/list-of-lists. ,"print(""Add a value(7), 5 times, to a list:"")
nums = []
nums += 5 * ['7']
print(nums)
nums1 = [1,2,3,4]
print(""\nAdd 5, 6 times, to a list:"")
nums1 += 6 * [5]
print(nums1)
print(""\nAdd a list, 4 times, to a list of lists:"")
nums1 = []
nums1 += 4 * [[1,2,5]]
print(nums1)
print(""\nAdd a list, 4 times, to a list of lists:"")
nums1 = [[5,6,7]]
nums1 += 4 * [[1,2,5]]
print(nums1)
"
779,Write a NumPy program to replace all elements of NumPy array that are greater than specified array. ,"import numpy as np
x = np.array([[ 0.42436315, 0.48558583, 0.32924763], [ 0.7439979,0.58220701,0.38213418], [ 0.5097581,0.34528799,0.1563123 ]])
print(""Original array:"")
print(x)
print(""Replace all elements of the said array with .5 which are greater than .5"")
x[x > .5] = .5
print(x)
"
780,Write a Python program to calculate the product of the unique numbers of a given list. ,"def unique_product(list_data):
temp = list(set(list_data))
p = 1
for i in temp:
p *= i
return p
nums = [10, 20, 30, 40, 20, 50, 60, 40]
print(""Original List : "",nums)
print(""Product of the unique numbers of the said list: "",unique_product(nums))
"
781,Write a Pandas program to create a heatmap (rectangular data as a color-encoded matrix) for comparison of the top 10 years in which the UFO was sighted vs each Month. ,"import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Source: https://bit.ly/1l9yjm9
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
most_sightings_years = df['Date_time'].dt.year.value_counts().head(10)
def is_top_years(year):
if year in most_sightings_years.index:
return year
month_vs_year = df.pivot_table(columns=df['Date_time'].dt.month,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city')
month_vs_year.columns = month_vs_year.columns.astype(int)
print(""\nHeatmap for comparison of the top 10 years in which the UFO was sighted vs each month:"")
plt.figure(figsize=(10,8))
ax = sns.heatmap(month_vs_year, vmin=0, vmax=4)
ax.set_xlabel('Month').set_size(20)
ax.set_ylabel('Year').set_size(20)
"
782,Write a Python program to remove existing indentation from all of the lines in a given text. ,"import textwrap
sample_text = '''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
text_without_Indentation = textwrap.dedent(sample_text)
print()
print(text_without_Indentation )
print()
"
783,Write a Pandas program to import given excel data (employee.xlsx ) into a Pandas dataframe and sort based on multiple given columns. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\employee.xlsx')
result = df.sort_values(by=['first_name','last_name'],ascending=[0,1])
result
"
784,Write a Pandas program to start index with different value rather than 0 in a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 37, 33, 30, 31, 32]})
print(""Original DataFrame:"")
print(df)
print(""\nDefault Index Range:"")
print(df.index)
df.index += 10
print(""\nNew Index Range:"")
print(df.index)
print(""\nDataFrame with new index:"")
print(df)
"
785,"Write a Pandas program to create a bar plot of opening, closing stock prices of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-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', 'Open', 'Close']]
df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot(kind='bar');
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020 to 30-04-2020', fontsize=12, color='black')
plt.show()
"
786,Write a Pandas program to create a Pivot table and calculate how many women and men were in a particular cabin class. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index=['sex'], columns=['pclass'], values='survived', aggfunc='count')
print(result)
"
787,Write a Python program to find the maximum and minimum values in a given heterogeneous list. ,"def max_min_val(list_val):
max_val = max(i for i in list_val if isinstance(i, int))
min_val = min(i for i in list_val if isinstance(i, int))
return(max_val, min_val)
list_val = ['Python', 3, 2, 4, 5, 'version']
print(""Original list:"")
print(list_val)
print(""\nMaximum and Minimum values in the said list:"")
print(max_min_val(list_val))
"
788,Write a Pandas program to split a given dataset using group by on specified column into two labels and ranges. ,"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({
'salesman_id': [5001,5002,5003,5004,5005,5006,5007,5008,5009,5010,5011,5012],
'sale_jan':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 1760, 2983.43, 480.4, 1250.45, 75.29,1045.6]})
print(""Original Orders DataFrame:"")
print(df)
result = df.groupby(pd.cut(df['salesman_id'],
bins=[0,5006,np.inf],
labels=['S1', 'S2']))['sale_jan'].sum().reset_index()
print(""\nGroupBy with condition of two labels and ranges:"")
print(result)
"
789,Write a Python program to find common elements in a given list of lists. ,"def common_list_of_lists(lst):
temp = set(lst[0]).intersection(*lst)
return list(temp)
nums = [[7,2,3,4,7],[9,2,3,2,5],[8,2,3,4,4]]
print(""Original list:"")
print(nums)
print(""\nCommon elements of the said list of lists:"")
print(common_list_of_lists(nums))
chars = [['a','b','c'],['b','c','d'],['c','d','e']]
print(""\nOriginal list:"")
print(chars)
print(""\nCommon elements of the said list of lists:"")
print(common_list_of_lists(chars))
"
790,Write a Python program to check whether a list contains a sublist. ,"def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n = 1
while (n < len(s)) and (l[i+n] == s[n]):
n += 1
if n == len(s):
sub_set = True
return sub_set
a = [2,4,3,5,7]
b = [4,3]
c = [3,7]
print(is_Sublist(a, b))
print(is_Sublist(a, c))
"
791,Write a Python program to count the number of each character of a given text of a text file. ,"import collections
import pprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
"
792,Write a NumPy program to concatenate two 2-dimensional arrays. ,"import numpy as np
a = np.array([[0, 1, 3], [5, 7, 9]])
b = np.array([[0, 2, 4], [6, 8, 10]])
c = np.concatenate((a, b), 1)
print(c)
"
793,Write a Python program to remove None value from a given list using lambda function. ,"def remove_none(nums):
result = filter(lambda v: v is not None, nums)
return list(result)
nums = [12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]
print(""Original list:"")
print(nums)
print(""\nRemove None value from the said list:"")
print(remove_none(nums))
"
794,Write a Python program to configure the rounding to round up and round down a given decimal value. Use decimal.Decimal,"import decimal
print(""Configure the rounding to round up:"")
decimal.getcontext().prec = 1
decimal.getcontext().rounding = decimal.ROUND_UP
print(decimal.Decimal(30) / decimal.Decimal(4))
print(""\nConfigure the rounding to round down:"")
decimal.getcontext().prec = 3
decimal.getcontext().rounding = decimal.ROUND_DOWN
print(decimal.Decimal(30) / decimal.Decimal(4))
print(""\nConfigure the rounding to round up:"")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP))
print(""\nConfigure the rounding to round down:"")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN))
"
795,Write a Python program to find the highest 3 values of corresponding keys in a dictionary. ,"from heapq import nlargest
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
three_largest = nlargest(3, my_dict, key=my_dict.get)
print(three_largest)
"
796,Write a Pandas program to convert a NumPy array to a Pandas series. ,"import numpy as np
import pandas as pd
np_array = np.array([10, 20, 30, 40, 50])
print(""NumPy array:"")
print(np_array)
new_series = pd.Series(np_array)
print(""Converted Pandas series:"")
print(new_series)
"
797,"Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array. ","import numpy as np
array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(""Original array:"")
print(array_nums)
print(""\nNumber of items of the said array:"")
print(array_nums.size)
print(""\nArray dimensions:"")
print(array_nums.shape)
print(""\nNumber of array dimensions:"")
print(array_nums.ndim)
print(""\nMemory size of each element of the said array"")
print(array_nums.itemsize)
"
798,Write a Python program to drop empty Items from a given Dictionary. ,"dict1 = {'c1': 'Red', 'c2': 'Green', 'c3':None}
print(""Original Dictionary:"")
print(dict1)
print(""New Dictionary after dropping empty items:"")
dict1 = {key:value for (key, value) in dict1.items() if value is not None}
print(dict1)
"
799,Write a Pandas program to stack two given series vertically and horizontally. ,"import pandas as pd
series1 = pd.Series(range(10))
series2 = pd.Series(list('pqrstuvwxy'))
print(""Original Series:"")
print(series1)
print(series2)
series1.append(series2)
df = pd.concat([series1, series2], axis=1)
print(""\nStack two given series vertically and horizontally:"")
print(df)
"
800,Write a NumPy program to create an array which looks like below array. ,"import numpy as np
x = np.triu(np.arange(2, 14).reshape(4, 3), -1)
print(x)
"
801,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))
"
802,Write a Pandas program to extract only number 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({
'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
'address': ['7277 Surrey Ave.','920 N. Bishop Ave.','9910 Golden Star St.', '25 Dunbar St.', '17 West Livingston Court']
})
print(""Original DataFrame:"")
print(df)
def find_number(text):
num = re.findall(r'[0-9]+',text)
return "" "".join(num)
df['number']=df['address'].apply(lambda x: find_number(x))
print(""\Extracting numbers from dataframe columns:"")
print(df)
"
803,Write a Python program to download and display the content of robot.txt for en.wikipedia.org. ,"import requests
response = requests.get(""https://en.wikipedia.org/robots.txt"")
test = response.text
print(""robots.txt for http://www.wikipedia.org/"")
print(""==================================================="")
print(test)
"
804,Write a Python program to calculate the discriminant value. ,"def discriminant():
x_value = float(input('The x value: '))
y_value = float(input('The y value: '))
z_value = float(input('The z value: '))
discriminant = (y_value**2) - (4*x_value*z_value)
if discriminant > 0:
print('Two Solutions. Discriminant value is:', discriminant)
elif discriminant == 0:
print('One Solution. Discriminant value is:', discriminant)
elif discriminant < 0:
print('No Real Solutions. Discriminant value is:', discriminant)
discriminant()
"
805,Write a Python program to compute the sum of non-zero groups (separated by zeros) of a given list of numbers. ,"def test(lst):
result = []
ele_val = 0
for digit in lst:
if digit == 0:
if ele_val != 0:
result.append(ele_val)
ele_val = 0
else:
ele_val += digit
if ele_val>0:
result.append(ele_val)
return result
nums = [3,4,6,2,0,0,0,0,0,0,6,7,6,9,10,0,0,0,0,0,7,4,4,0,0,0,0,0,0,5,3,2,9,7,1,0,0,0]
print(""\nOriginal list:"")
print(nums)
print(""\nCompute the sum of non-zero groups (separated by zeros) of the said list of numbers:"")
print(test(nums))
"
806,Write a Python program to generate all permutations of a list in Python. ,"import itertools
print(list(itertools.permutations([1,2,3])))
"
807,Write a Python program to sort unsorted strings using natural sort. ,"#Ref.https://bit.ly/3a657IZ
from __future__ import annotations
import re
def natural_sort(input_list: list[str]) -> list[str]:
def alphanum_key(key):
return [int(s) if s.isdigit() else s.lower() for s in re.split(""([0-9]+)"", key)]
return sorted(input_list, key=alphanum_key)
strs = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in']
print(""\nOriginal list:"")
print(strs)
natural_sort(strs)
print(""Sorted order is:"", strs)
strs = ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in']
print(""\nOriginal list:"")
print(strs)
natural_sort(strs)
print(""Sorted order is:"", strs)
strs = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
print(""\nOriginal list:"")
print(strs)
natural_sort(strs)
print(""Sorted order is:"", strs)
strs = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
print(""\nOriginal list:"")
print(strs)
natural_sort(strs)
print(""Sorted order is:"", strs)
"
808,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the maximum value in each column. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
def highlight_max(s):
'''
highlight the maximum in a Series green.
'''
is_max = s == s.max()
return ['background-color: green' if v else '' for v in is_max]
print(""\nHighlight the maximum value in each column:"")
df.style.apply(highlight_max,subset=pd.IndexSlice[:, ['B', 'C', 'D', 'E']])
"
809,Write a Python program to find whether a given array of integers contains any duplicate element. Return true if any value appears at least twice in the said array and return false if every element is distinct. ,"def test_duplicate(array_nums):
nums_set = set(array_nums)
return len(array_nums) != len(nums_set)
print(test_duplicate([1,2,3,4,5]))
print(test_duplicate([1,2,3,4, 4]))
print(test_duplicate([1,1,2,2,3,3,4,4,5]))
"
810,Write a NumPy program to create a white image of size 512x256. ,"from PIL import Image
import numpy as np
a = np.full((512, 256, 3), 255, dtype=np.uint8)
image = Image.fromarray(a, ""RGB"")
image.save(""white.png"", ""PNG"")
"
811,Write a Python program to find the maximum and minimum values in a given list of tuples. ,"from operator import itemgetter
def max_min_list_tuples(class_students):
return_max = max(class_students,key=itemgetter(1))[1]
return_min = min(class_students,key=itemgetter(1))[1]
return return_max, return_min
class_students = [('V', 60), ('VI', 70), ('VII', 75), ('VIII', 72), ('IX', 78), ('X', 70)]
print(""Original list with tuples:"")
print(class_students)
print(""\nMaximum and minimum values of the said list of tuples:"")
print(max_min_list_tuples(class_students))
"
812,Write a Python program to find the items starts with specific character from a given list. ,"def test(lst, char):
result = [i for i in lst if i.startswith(char)]
return result
text = [""abcd"", ""abc"", ""bcd"", ""bkie"", ""cder"", ""cdsw"", ""sdfsd"", ""dagfa"", ""acjd""]
print(""\nOriginal list:"")
print(text)
char = ""a""
print(""\nItems start with"",char,""from the said list:"")
print(test(text, char))
char = ""d""
print(""\nItems start with"",char,""from the said list:"")
print(test(text, char))
char = ""w""
print(""\nItems start with"",char,""from the said list:"")
print(test(text, char))
"
813,Write a Python program to split a given list into two parts where the length of the first part of the list is given. ,"def split_two_parts(n_list, L):
return n_list[:L], n_list[L:]
n_list = [1,1,2,3,4,4,5, 1]
print(""Original list:"")
print(n_list)
first_list_length = 3
print(""\nLength of the first part of the list:"",first_list_length)
print(""\nSplited the said list into two parts:"")
print(split_two_parts(n_list, first_list_length))
"
814,Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. ,"import itertools
from functools import partial
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
T = 70
def check_sum_array(N, *nums):
if sum(x for x in nums) == N:
return (True, nums)
else:
return (False, nums)
pro = itertools.product(X,Y,Z)
func = partial(check_sum_array, T)
sums = list(itertools.starmap(func, pro))
result = set()
for s in sums:
if s[0] == True and s[1] not in result:
result.add(s[1])
print(result)
"
815,Write a Python program to construct an infinite iterator that returns evenly spaced values starting with a specified number and step. ,"import itertools as it
start = 10
step = 1
print(""The starting number is "", start, ""and step is "",step)
my_counter = it.count(start, step)
# Following loop will run for ever
print(""The said function print never-ending items:"")
for i in my_counter:
print(i)
"
816,Write a NumPy program to create an array of equal shape and data type of a given array. ,"import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 8.32, 6.99],
[1.54, 2.39, 9.29]])
print(""Original array:"")
print(nums)
print(""\nNew array of equal shape and data type of the said array filled by 0:"")
print(np.zeros_like(nums))
"
817,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in table style and border around the table and not around the rows. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
print(""\nDataframe - table style and border around the table and not around the rows:"")
df.style.set_table_styles([{'selector':'','props':[('border','4px solid #7a7')]}])
"
818,rite a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers that are divisible by 5 in a comma separated sequence. ,"items = []
num = [x for x in input().split(',')]
for p in num:
x = int(p, 2)
if not x%5:
items.append(p)
print(','.join(items))
"
819,Write a Python program to compute the sum of digits of each number of a given list. ,"def sum_of_digits(nums):
return sum(int(el) for n in nums for el in str(n) if el.isdigit())
nums = [10,2,56]
print(""Original tuple: "")
print(nums)
print(""Sum of digits of each number of the said list of integers:"")
print(sum_of_digits(nums))
nums = [10,20,4,5,'b',70,'a']
print(""\nOriginal tuple: "")
print(nums)
print(""Sum of digits of each number of the said list of integers:"")
print(sum_of_digits(nums))
nums = [10,20,-4,5,-70]
print(""\nOriginal tuple: "")
print(nums)
print(""Sum of digits of each number of the said list of integers:"")
print(sum_of_digits(nums))
"
820,Write a Pandas program to print the day after and before a specified date. Also print the days between two given dates. ,"import pandas as pd
import datetime
from datetime import datetime, date
today = datetime(2012, 10, 30)
print(""Current date:"", today)
tomorrow = today + pd.Timedelta(days=1)
print(""Tomorrow:"", tomorrow)
yesterday = today - pd.Timedelta(days=1)
print(""Yesterday:"", yesterday)
date1 = datetime(2016, 8, 2)
date2 = datetime(2016, 7, 19)
print(""\nDifference between two dates: "",(date1 - date2))
"
821,Write a Pandas program to extract date (format: mm-dd-yyyy) from a given column of a given DataFrame. ,"import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print(""Original DataFrame:"")
print(df)
def find_valid_dates(dt):
#format: mm-dd-yyyy
result = re.findall(r'\b(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/([0-9]{4})\b',dt)
return result
df['valid_dates']=df['date_of_sale'].apply(lambda dt : find_valid_dates(dt))
print(""\nValid dates (format: mm-dd-yyyy):"")
print(df)
"
822,Write a Python program to sort a list of elements using the quick sort algorithm. ,"def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
def quickSortHlp(data_list,first,last):
if first < last:
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = data_list[leftmark]
data_list[leftmark] = data_list[rightmark]
data_list[rightmark] = temp
temp = data_list[first]
data_list[first] = data_list[rightmark]
data_list[rightmark] = temp
return rightmark
data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)
print(data_list)
"
823,"Write a Python program to check if a given list is strictly increasing or not. Moreover, If removing only one element from the list results in a strictly increasing list, we still consider the list true. ","# Source: https://bit.ly/3qZqcwm
def almost_increasing_sequence(sequence):
if len(sequence) < 3:
return True
a, b, *sequence = sequence
skipped = 0
for c in sequence:
if a < b < c: # XXX
a, b = b, c
continue
elif b < c: # !XX
a, b = b, c
elif a < c: # X!X
a, b = a, c
skipped += 1
if skipped == 2:
return False
return a < b
print(almost_increasing_sequence([]))
print(almost_increasing_sequence([1]))
print(almost_increasing_sequence([1, 2]))
print(almost_increasing_sequence([1, 2, 3]))
print(almost_increasing_sequence([3, 1, 2]))
print(almost_increasing_sequence([1, 2, 3, 0, 4, 5, 6]))
print(almost_increasing_sequence([1, 2, 3, 0]))
print(almost_increasing_sequence([1, 2, 0, 3]))
print(almost_increasing_sequence([10, 1, 2, 3, 4, 5]))
print(almost_increasing_sequence([1, 2, 10, 3, 4]))
print(almost_increasing_sequence([1, 2, 3, 12, 4, 5]))
print(almost_increasing_sequence([3, 2, 1]))
print(almost_increasing_sequence([1, 2, 0, -1]))
print(almost_increasing_sequence([5, 6, 1, 2]))
print(almost_increasing_sequence([1, 2, 3, 0, -1]))
print(almost_increasing_sequence([10, 11, 12, 2, 3, 4, 5]))
"
824,"Write a Python program to generate a random color hex, a random alphabetical string, random value between two integers (inclusive) and a random multiple of 7 between 0 and 70. Use random.randint()","import random
import string
print(""Generate a random color hex:"")
print(""#{:06x}"".format(random.randint(0, 0xFFFFFF)))
print(""\nGenerate a random alphabetical string:"")
max_length = 255
s = """"
for i in range(random.randint(1, max_length)):
s += random.choice(string.ascii_letters)
print(s)
print(""Generate a random value between two integers, inclusive:"")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print(""Generate a random multiple of 7 between 0 and 70:"")
print(random.randint(0, 10) * 7)
"
825,Write a Python class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case. ,"class IOString():
def __init__(self):
self.str1 = """"
def get_String(self):
self.str1 = input()
def print_String(self):
print(self.str1.upper())
str1 = IOString()
str1.get_String()
str1.print_String()
"
826,Write a Python program to get the Fibonacci series between 0 to 50. ,"x,y=0,1
while y<50:
print(y)
x,y = y,x+y
"
827,Write a Python program to convert a given dictionary into a list of lists. ,"def test(dictt):
result = list(map(list, dictt.items()))
return result
color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'}
print(""\nOriginal Dictionary:"")
print(color_dict)
print(""Convert the said dictionary into a list of lists:"")
print(test(color_dict))
color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'}
print(""\nOriginal Dictionary:"")
print(color_dict)
print(""Convert the said dictionary into a list of lists:"")
print(test(color_dict))
"
828,"Write a NumPy program to create two arrays with shape (300,400, 5), fill values using unsigned integer (0 to 255). Insert a new axis that will appear at the beginning in the expanded array shape. Now combine the said two arrays into one. ","import numpy as np
nums1 = np.random.randint(low=0, high=256, size=(200, 300, 3), dtype=np.uint8)
nums2 = np.random.randint(low=0, high=256, size=(200, 300, 3), dtype=np.uint8)
print(""Array1:"")
print(nums1)
print(""\nArray2:"")
print(nums2)
nums1 = np.expand_dims(nums1, axis=0)
nums2 = np.expand_dims(nums2, axis=0)
nums = np.append(nums1, nums2, axis=0)
print(""\nCombined array:"")
print(nums)
"
829,Write a Pandas program to create a Pivot table and find the minimum sale value of the items. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=np.min)
print(table)
"
830,Write a Python program to print all unique values in a dictionary. ,"L = [{""V"":""S001""}, {""V"": ""S002""}, {""VI"": ""S001""}, {""VI"": ""S005""}, {""VII"":""S005""}, {""V"":""S009""},{""VIII"":""S007""}]
print(""Original List: "",L)
u_value = set( val for dic in L for val in dic.values())
print(""Unique Values: "",u_value)
"
831,Write a Python program to remove key values pairs from a list of dictionaries. ,"original_list = [{'key1':'value1', 'key2':'value2'}, {'key1':'value3', 'key2':'value4'}]
print(""Original List: "")
print(original_list)
new_list = [{k: v for k, v in d.items() if k != 'key1'} for d in original_list]
print(""New List: "")
print(new_list)
"
832,Write a NumPy program to create a 5x5 matrix with row values ranging from 0 to 4. ,"import numpy as np
x = np.zeros((5,5))
print(""Original array:"")
print(x)
print(""Row values ranging from 0 to 4."")
x += np.arange(5)
print(x)
"
833,"Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. ","def not_poor(str1):
snot = str1.find('not')
spoor = str1.find('poor')
if spoor > snot and snot>0 and spoor>0:
str1 = str1.replace(str1[snot:(spoor+4)], 'good')
return str1
else:
return str1
print(not_poor('The lyrics is not that poor!'))
print(not_poor('The lyrics is poor!'))
"
834,Write a Python program to lowercase first n characters in a string. ,"str1 = 'W3RESOURCE.COM'
print(str1[:4].lower() + str1[4:])
"
835,Write a Python program to find the first duplicate element in a given array of integers. Return -1 If there are no such elements. ,"def find_first_duplicate(nums):
num_set = set()
no_duplicate = -1
for i in range(len(nums)):
if nums[i] in num_set:
return nums[i]
else:
num_set.add(nums[i])
return no_duplicate
print(find_first_duplicate([1, 2, 3, 4, 4, 5]))
print(find_first_duplicate([1, 2, 3, 4]))
print(find_first_duplicate([1, 1, 2, 3, 3, 2, 2]))
"
836,Write a Python program to interleave two given list into another list randomly using map() function. ,"import random
def randomly_interleave(nums1, nums2):
result = list(map(next, random.sample([iter(nums1)]*len(nums1) + [iter(nums2)]*len(nums2), len(nums1)+len(nums2))))
return result
nums1 = [1,2,7,8,3,7]
nums2 = [4,3,8,9,4,3,8,9]
print(""Original lists:"")
print(nums1)
print(nums2)
print(""\nInterleave two given list into another list randomly:"")
print(randomly_interleave(nums1, nums2))
"
837,Write a Python program to remove duplicate words from a given string. ,"def unique_list(text_str):
l = text_str.split()
temp = []
for x in l:
if x not in temp:
temp.append(x)
return ' '.join(temp)
text_str = ""Python Exercises Practice Solution Exercises""
print(""Original String:"")
print(text_str)
print(""\nAfter removing duplicate words from the said string:"")
print(unique_list(text_str))
"
838,Write a Pandas program to get the index of an element of a given Series. ,"import pandas as pd
ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8])
print(""Original Series:"")
print(ds)
print(""\nIndex of 11 in the said series:"")
x = ds[ds == 11].index[0]
print(x)
"
839,"Write a Python program to check if a given string contains an element, which is present in a list. ","def test(lst,str1):
result = [el for el in lst if(el in str1)]
return bool(result)
str1 = ""https://www.w3resource.com/python-exercises/list/""
lst = ['.com', '.edu', '.tv']
print(""The original string and list: "")
print(str1)
print(lst)
print(""\nCheck if"",str1,""contains an element, which is present in the list"",lst)
print(test(lst,str1))
str1 = ""https://www.w3resource.net""
lst = ['.com', '.edu', '.tv']
print(""\nThe original string and list: "" + str1)
print(str1)
print(lst)
print(""\nCheck if"",str1,""contains an element, which is present in the list"",lst)
print(test(lst,str1))
"
840,Write a Python program to insert a list of records into a given SQLite table. ,"import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn, rows):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute(""CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));"")
sqlite_insert_query = """"""INSERT INTO salesman
(salesman_id, name, city, commission)
VALUES (?, ?, ?, ?);""""""
cursorObj.executemany(sqlite_insert_query, rows)
conn.commit()
print(""Number of records after inserting rows:"")
cursor = cursorObj.execute('select * from salesman;')
print(len(cursor.fetchall()))
# Insert records
rows = [(5001,'James Hoog', 'New York', 0.15),
(5002,'Nail Knite', 'Paris', 0.25),
(5003,'Pit Alex', 'London', 0.15),
(5004,'Mc Lyon', 'Paris', 0.35),
(5005,'Paul Adam', 'Rome', 0.45)]
sqllite_conn = sql_connection()
sql_table(sqllite_conn, rows)
if (sqllite_conn):
sqllite_conn.close()
print(""\nThe SQLite connection is closed."")
"
841,Write a Python program to sort a list of elements using Pancake sort. ,"def pancake_sort(nums):
arr_len = len(nums)
while arr_len > 1:
mi = nums.index(max(nums[0:arr_len]))
nums = nums[mi::-1] + nums[mi+1:len(nums)]
nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]
arr_len -= 1
return nums
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
print(pancake_sort(nums))
"
842,Write a Python program to shift last element to first position and first element to last position in a given list. ,"def shift_first_last(lst):
x = lst.pop(0)
y = lst.pop()
lst.insert(0, y)
lst.insert(len(lst), x)
return lst
nums = [1,2,3,4,5,6,7]
print(""Original list:"")
print(nums)
print(""Shift last element to first position and first element to last position of the said list:"")
print(shift_first_last(nums))
chars = ['s','d','f','d','s','s','d','f']
print(""\nOriginal list:"")
print(chars)
print(""Shift last element to first position and first element to last position of the said list:"")
print(shift_first_last(chars))
"
843,Write a NumPy program to create a 5x5x5 cube of 1's. ,"import numpy as np
x = np.zeros((5, 5, 5)).astype(int) + 1
print(x)
"
844,Write a NumPy program to display NumPy array elements of floating values with given precision. ,"import numpy as np
x=np.array([ 0.26153123, 0.52760141, 0.5718299, 0.5927067, 0.7831874, 0.69746349,
0.35399976, 0.99469633, 0.0694458, 0.54711478])
print(""Original array elements:"")
print(x)
print(""Print array values with precision 3:"")
np.set_printoptions(precision=3)
print(x)
"
845,"Write a Pandas program to compute the minimum, 25th percentile, median, 75th, and maximum of a given series. ","import pandas as pd
import numpy as np
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
print(""Original Series:"")
print(num_series)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
print(""\nMinimum, 25th percentile, median, 75th, and maximum of a given series:"")
print(result)
"
846,Write a Python program to find the majority element from a given array of size n using Collections module. ,"import collections
class Solution(object):
def majorityElement(self, nums):
""""""
:type nums: List[int]
:return type: int
""""""
count_ele=collections.Counter(nums)
return count_ele.most_common()[0][0]
result = Solution().majorityElement([10,10,20,30,40,10,20,10])
print(result)
"
847,Write a Python program to insert a new text within a url in a specified position. ,"from bs4 import BeautifulSoup
html_doc = 'HTMLw3resource.com'
soup = BeautifulSoup(html_doc, ""lxml"")
tag = soup.a
print(""Original Markup:"")
print(tag.contents)
tag.insert(2, ""CSS"") #2-> Position of the text (1, 2, 3…)
print(""\nNew url after inserting the text:"")
print(tag.contents)
"
848,Write a Python program to convert a given list of strings and characters to a single list of characters. ,"def l_strs_to_l_chars(lst):
result = [i for element in lst for i in element]
return result
colors = [""red"", ""white"", ""a"", ""b"", ""black"", ""f""]
print(""Original list:"")
print(colors)
print(""\nConvert the said list of strings and characters to a single list of characters:"")
print(l_strs_to_l_chars(colors))
"
849,Write a Python program to perform a deep flattens a list. ,"from collections.abc import Iterable
def deep_flatten(lst):
return ([a for i in lst for a in
deep_flatten(i)] if isinstance(lst, Iterable) else [lst])
nums = [1, [2], [[3], [4], 5], 6]
print(""Original list elements:"")
print(nums)
print()
print(""Deep flatten the said list:"")
print(deep_flatten(nums))
nums = [[[1, 2, 3], [4, 5]], 6]
print(""\nOriginal list elements:"")
print(nums)
print()
print(""Deep flatten the said list:"")
print(deep_flatten(nums))
"
850,Write a Python program to insert a given string at the beginning of all items in a list. ,"num = [1,2,3,4]
print(['emp{0}'.format(i) for i in num])
"
851,Write a Python program to get a datetime or timestamp representation from current datetime. ,"import arrow
a = arrow.utcnow()
print(""Datetime representation:"")
print(a.datetime)
b = a.timestamp
print(""\nTimestamp representation:"")
print(b)
"
852,rite a NumPy program to create a null vector of size 10 and update sixth value to 11.,"
import numpy as np
x = np.zeros(10)
print(x)
print(""Update sixth value to 11"")
x[6] = 11
print(x)
"
853,Write a Python program to concatenate the consecutive numbers in a given string. ,"import re
txt = ""Enter at 1 20 Kearny Street. The security desk can direct you to floor 1 6. Please have your identification ready.""
print(""Original string:"")
print(txt)
new_txt = re.sub(r""(?<=\d)\s(?=\d)"", '', txt)
print('\nAfter concatenating the consecutive numbers in the said string:')
print(new_txt)
"
854,Write a Python program to sort unsorted numbers using Odd Even Transposition Parallel sort. ,"#Ref.https://bit.ly/3cce7iB
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
processLock = Lock()
def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe):
global processLock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10):
if (i + position) % 2 == 0 and RSend is not None:
# send your value to your right neighbor
processLock.acquire()
RSend[1].send(value)
processLock.release()
# receive your right neighbor's value
processLock.acquire()
temp = RRcv[0].recv()
processLock.release()
# take the lower value since you are on the left
value = min(value, temp)
elif (i + position) % 2 != 0 and LSend is not None:
# send your value to your left neighbor
processLock.acquire()
LSend[1].send(value)
processLock.release()
# receive your left neighbor's value
processLock.acquire()
temp = LRcv[0].recv()
processLock.release()
# take the higher value since you are on the right
value = max(value, temp)
# after all swaps are performed, send the values back to main
resultPipe[1].send(value)
""""""
the function which creates the processes that perform the parallel swaps
arr = the list to be sorted
""""""
def OddEvenTransposition(arr):
processArray = []
resultPipe = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
resultPipe.append(Pipe())
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
tempRs = Pipe()
tempRr = Pipe()
processArray.append(
Process(
target=oeProcess,
args=(0, arr[0], None, tempRs, None, tempRr, resultPipe[0]),
)
)
tempLr = tempRs
tempLs = tempRr
for i in range(1, len(arr) - 1):
tempRs = Pipe()
tempRr = Pipe()
processArray.append(
Process(
target=oeProcess,
args=(i, arr[i], tempLs, tempRs, tempLr, tempRr, resultPipe[i]),
)
)
tempLr = tempRs
tempLs = tempRr
processArray.append(
Process(
target=oeProcess,
args=(
len(arr) - 1,
arr[len(arr) - 1],
tempLs,
None,
tempLr,
None,
resultPipe[len(arr) - 1],
),
)
)
# start the processes
for p in processArray:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0, len(resultPipe)):
arr[p] = resultPipe[p][0].recv()
processArray[p].join()
return arr
# creates a reverse sorted list and sorts it
def main():
arr = list(range(10, 0, -1))
print(""Initial List"")
print(*arr)
arr = OddEvenTransposition(arr)
print(""\nSorted List:"")
print(*arr)
if __name__ == ""__main__"":
main()
"
855,Write a NumPy program to rearrange columns of a given NumPy 2D array using given index positions. ,"import numpy as np
array1 = np.array([[11, 22, 33, 44, 55],
[66, 77, 88, 99, 100]])
print(""Original arrays:"")
print(array1)
i = [1,3,0,4,2]
result = array1[:,i]
print(""New array:"")
print(result)
"
856,Write a Python program to remove a specified dictionary from a given list. ,"def remove_dictionary(colors, r_id):
colors[:] = [d for d in colors if d.get('id') != r_id]
return colors
colors = [{""id"" : ""#FF0000"", ""color"" : ""Red""},
{""id"" : ""#800000"", ""color"" : ""Maroon""},
{""id"" : ""#FFFF00"", ""color"" : ""Yellow""},
{""id"" : ""#808000"", ""color"" : ""Olive""}]
print('Original list of dictionary:')
print(colors)
r_id = ""#FF0000""
print(""\nRemove id"",r_id,""from the said list of dictionary:"")
print(remove_dictionary(colors, r_id))
"
857,Write a Pandas program to extract only punctuations 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({
'company_code': ['c0001.','c000,2','c0003', 'c0003#', 'c0004,'],
'year': ['year 1800','year 1700','year 2300', 'year 1900', 'year 2200']
})
print(""Original DataFrame:"")
print(df)
def find_punctuations(text):
result = re.findall(r'[!""\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]*', text)
string="""".join(result)
return list(string)
df['nonalpha']=df['company_code'].apply(lambda x: find_punctuations(x))
print(""\nExtracting punctuation:"")
print(df)
"
858,Write a NumPy program to extract all the elements of the second row from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: Second row"")
print(arra_data[1,:])
"
859,Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x2 matrix representing cartesian coordinates. ,"import numpy as np
z= np.random.random((10,2))
x,y = z[:,0], z[:,1]
r = np.sqrt(x**2+y**2)
t = np.arctan2(y,x)
print(r)
print(t)
"
860,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the maximum value in last two columns. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
def highlight_max(s):
'''
highlight the maximum in a Series green.
'''
is_max = s == s.max()
return ['background-color: green' if v else '' for v in is_max]
print(""\nHighlight the maximum value in last two columns:"")
df.style.apply(highlight_max,subset=pd.IndexSlice[:, ['D', 'E']])
"
861,Write a Python program to check if all items of a given list of strings is equal to a given string. ,"color1 = [""green"", ""orange"", ""black"", ""white""]
color2 = [""green"", ""green"", ""green"", ""green""]
print(all(c == 'blue' for c in color1))
print(all(c == 'green' for c in color2))
"
862,Write a Python program to convert the values of RGB components to a hexadecimal color code. ,"def rgb_to_hex(r, g, b):
return ('{:02X}' * 3).format(r, g, b)
print(rgb_to_hex(255, 165, 1))
print(rgb_to_hex(255, 255, 255))
print(rgb_to_hex(0, 0, 0))
print(rgb_to_hex(0, 0, 128))
print(rgb_to_hex(192, 192, 192))
"
863,Write a NumPy program to compute the determinant of an array. ,"import numpy as np
a = np.array([[1,2],[3,4]])
print(""Original array:"")
print(a)
result = np.linalg.det(a)
print(""Determinant of the said array:"")
print(result)
"
864,Write a Python program to find the first occurrence of a given number in a sorted list using Binary Search (bisect). ,"from bisect import bisect_left
def Binary_Search(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
nums = [1, 2, 3, 4, 8, 8, 10, 12]
x = 8
num_position = Binary_Search(nums, x)
if num_position == -1:
print(x, ""is not present."")
else:
print(""First occurrence of"", x, ""is present at index"", num_position)
"
865,Write a Python program to get the frequency of the elements in a list. ,"import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print(""Original List : "",my_list)
ctr = collections.Counter(my_list)
print(""Frequency of the elements in the List : "",ctr)
"
866,Write a Pandas program to count the number of missing values of a specified column 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nMissing values in purch_amt column:"")
result = df['purch_amt'].value_counts(dropna=False).loc[np.nan]
print(result)
"
867,rite a Python program to display the current date and time.,"import datetime
now = datetime.datetime.now()
print (""Current date and time : "")
print (now.strftime(""%Y-%m-%d %H:%M:%S""))
"
868,"Write a NumPy program to test element-wise of a given array for finiteness (not infinity or not Not a Number), positive or negative infinity, for NaN, for NaT (not a time), for negative infinity, for positive infinity. ","import numpy as np
print(""\nTest element-wise for finiteness (not infinity or not Not a Number):"")
print(np.isfinite(1))
print(np.isfinite(0))
print(np.isfinite(np.nan))
print(""\nTest element-wise for positive or negative infinity:"")
print(np.isinf(np.inf))
print(np.isinf(np.nan))
print(np.isinf(np.NINF))
print(""Test element-wise for NaN:"")
print(np.isnan([np.log(-1.),1.,np.log(0)]))
print(""Test element-wise for NaT (not a time):"")
print(np.isnat(np.array([""NaT"", ""2016-01-01""], dtype=""datetime64[ns]"")))
print(""Test element-wise for negative infinity:"")
x = np.array([-np.inf, 0., np.inf])
y = np.array([2, 2, 2])
print(np.isneginf(x, y))
print(""Test element-wise for positive infinity:"")
x = np.array([-np.inf, 0., np.inf])
y = np.array([2, 2, 2])
print(np.isposinf(x, y))
"
869,Write a NumPy program to sum and compute the product of a NumPy array elements. ,"import numpy as np
x = np.array([10, 20, 30], float)
print(""Original array:"")
print(x)
print(""Sum of the array elements:"")
print(x.sum())
print(""Product of the array elements:"")
print(x.prod())
"
870,Write a Python program to interleave multiple given lists of different lengths using itertools module. ,"from itertools import chain, zip_longest
def interleave_diff_len_lists(list1, list2, list3, list4):
return [x for x in chain(*zip_longest(list1, list2, list3, list4)) if x is not None]
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [2, 5, 8]
nums3 = [0, 1]
nums4 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(nums3)
print(nums4)
print(""\nInterleave said lists of different lengths:"")
print(interleave_diff_len_lists(nums1, nums2, nums3, nums4))
"
871,Write a Python program to find the maximum value in a given heterogeneous list using lambda. ,"def max_val(list_val):
max_val = max(list_val, key = lambda i: (isinstance(i, int), i))
return(max_val)
list_val = ['Python', 3, 2, 4, 5, 'version']
print(""Original list:"")
print(list_val)
print(""\nMaximum values in the said list using lambda:"")
print(max_val(list_val))
"
872,"Write a NumPy program to find the set exclusive-or of two arrays. Set exclusive-or will return the sorted, unique values that are in only one (not both) of the input arrays. ","import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print(""Array1: "",array1)
array2 = [10, 30, 40, 50, 70]
print(""Array2: "",array2)
print(""Unique values that are in only one (not both) of the input arrays:"")
print(np.setxor1d(array1, array2))
"
873,Write a NumPy program to stack arrays in sequence vertically. ,"import numpy as np
print(""\nOriginal arrays:"")
x = np.arange(9).reshape(3,3)
y = x*3
print(""Array-1"")
print(x)
print(""Array-2"")
print(y)
new_array = np.vstack((x,y))
print(""\nStack arrays in sequence vertically:"")
print(new_array)
"
874,Write a Python program to get the n maximum elements from a given list of numbers. ,"def max_n_nums(nums, n = 1):
return sorted(nums, reverse = True)[:n]
nums = [1, 2, 3]
print(""Original list elements:"")
print(nums)
print(""Maximum values of the said list:"", max_n_nums(nums))
nums = [1, 2, 3]
print(""\nOriginal list elements:"")
print(nums)
print(""Two maximum values of the said list:"", max_n_nums(nums,2))
nums = [-2, -3, -1, -2, -4, 0, -5]
print(""\nOriginal list elements:"")
print(nums)
print(""Threee maximum values of the said list:"", max_n_nums(nums,3))
nums = [2.2, 2, 3.2, 4.5, 4.6, 5.2, 2.9]
print(""\nOriginal list elements:"")
print(nums)
print(""Two maximum values of the said list:"", max_n_nums(nums, 2))
"
875,Write a NumPy program to test element-wise for positive or negative infinity. ,"import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print(""Original array"")
print(a)
print(""Test element-wise for positive or negative infinity:"")
print(np.isinf(a))
"
876,"Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference. ","def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
print(difference(22))
print(difference(14))
"
877,Write a NumPy program to remove all rows in a NumPy array that contain non-numeric values. ,"import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print(""Original array:"")
print(x)
print(""Remove all non-numeric elements of the said array"")
print(x[~np.isnan(x).any(axis=1)])
"
878,Write a Pandas program to find the indexes of rows of a specified value of a given column in a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 32, 33, 30, 31, 32]},
index = [1, 2, 3, 4, 5, 6])
print(""Original DataFrame with single index:"")
print(df)
print(""\nIndex of rows where specified column matches certain value:"")
print(df.index[df['school_code']=='s001'].tolist())
"
879,Write a Python program to calculate arc length of an angle. ,"def arclength():
pi=22/7
diameter = float(input('Diameter of circle: '))
angle = float(input('angle measure: '))
if angle >= 360:
print(""Angle is not possible"")
return
arc_length = (pi*diameter) * (angle/360)
print(""Arc Length is: "", arc_length)
arclength()
"
880,Write a NumPy program to create a Cartesian product of two arrays into single array of 2D points. ,"import numpy as np
x = np.array([1,2,3])
y = np.array([4,5])
result = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
print(result)
"
881,Write a NumPy program to find the missing data in a given array. ,"import numpy as np
nums = np.array([[3, 2, np.nan, 1],
[10, 12, 10, 9],
[5, np.nan, 1, np.nan]])
print(""Original array:"")
print(nums)
print(""\nFind the missing data of the said array:"")
print(np.isnan(nums))
"
882,Write a Python program to add more number of elements to a deque object from an iterable object. ,"import collections
even_nums = (2, 4, 6, 8, 10)
even_deque = collections.deque(even_nums)
print(""Even numbers:"")
print(even_deque)
more_even_nums = (12, 14, 16, 18, 20)
even_deque.extend(more_even_nums)
print(""More even numbers:"")
print(even_deque)
"
883,Write a Python program to print content of elements that contain a specified string of a given web page. ,"import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nContent of elements that contain 'Python' string:"")
str1 = soup.find_all(string=re.compile('Python'))
for txt in str1:
print("" "".join(txt.split()))
"
884,Write a Python program to get an array buffer information. ,"from array import array
a = array(""I"", (12,25))
print(""Array buffer start address in memory and number of elements."")
print(a.buffer_info())
"
885,Write a Python program to count the number of lines in a given CSV file. Use csv.reader,"import csv
reader = csv.reader(open(""employees.csv""))
no_lines= len(list(reader))
print(no_lines)
"
886,Write a Python program to sort an odd-even sort or odd-even transposition sort. ,"def odd_even_transposition(arr: list) -> list:
arr_size = len(arr)
for _ in range(arr_size):
for i in range(_ % 2, arr_size - 1, 2):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
odd_even_transposition(nums)
print(""Sorted order is:"", nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
odd_even_transposition(nums)
print(""Sorted order is:"", nums)
"
887,"Write a Python program to display a number in left, right and center aligned of width 10. ","x = 22
print(""\nOriginal Number: "", x)
print(""Left aligned (width 10) :""+""{:< 10d}"".format(x));
print(""Right aligned (width 10) :""+""{:10d}"".format(x));
print(""Center aligned (width 10) :""+""{:^10d}"".format(x));
print()
"
888,Write a Python program to determine whether variable is defined or not. ,"try:
x = 1
except NameError:
print(""Variable is not defined....!"")
else:
print(""Variable is defined."")
try:
y
except NameError:
print(""Variable is not defined....!"")
else:
print(""Variable is defined."")
"
889,Write a NumPy program to replace the negative values in a NumPy array with 0. ,"import numpy as np
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
print(""Original array:"")
print(x)
print(""Replace the negative values of the said array with 0:"")
x[x < 0] = 0
print(x)
"
890,"Write a Pandas program to create a stacked bar plot of opening, closing stock prices of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-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', 'Open', 'Close']]
df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot.bar(stacked=True);
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020 to 30-04-2020', fontsize=12, color='black')
plt.show()
"
891,Write a Python program to find missing and additional values in two lists. ,"list1 = ['a','b','c','d','e','f']
list2 = ['d','e','f','g','h']
print('Missing values in second list: ', ','.join(set(list1).difference(list2)))
print('Additional values in second list: ', ','.join(set(list2).difference(list1)))
"
892,rite a Python program to remove spaces from a given string. ,"def remove_spaces(str1):
str1 = str1.replace(' ','')
return str1
print(remove_spaces(""w 3 res ou r ce""))
print(remove_spaces(""a b c""))
"
893,Write a Pandas program to create a Pivot table and find the region wise Television and Home Theater sold. ,"import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df,index=[""Region"", ""Item""], values=""Units"")
print(table.query('Item == [""Television"",""Home Theater""]'))
"
894,Write a Python program to update all the values of a specific column of a given SQLite table. ,"import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute(""CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));"")
# Insert records
cursorObj.executescript(""""""
INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);
INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
"""""")
cursorObj.execute(""SELECT * FROM salesman"")
rows = cursorObj.fetchall()
print(""Agent details:"")
for row in rows:
print(row)
print(""\nUpdate all commision to .55:"")
sql_update_query = """"""Update salesman set commission = .55""""""
cursorObj.execute(sql_update_query)
conn.commit()
print(""Record Updated successfully "")
cursorObj.execute(""SELECT * FROM salesman"")
rows = cursorObj.fetchall()
print(""\nAfter updating Agent details:"")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
print(""\nThe SQLite connection is closed."")
"
895,Write a Python program to swap two variables. ,"a = 30
b = 20
print(""\nBefore swap a = %d and b = %d"" %(a, b))
a, b = b, a
print(""\nAfter swaping a = %d and b = %d"" %(a, b))
print()
"
896,Write a Pandas program to join two dataframes using keys from right dataframe only. ,"import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'R': ['R0', 'R1', 'R2', 'R3'],
'S': ['S0', 'S1', 'S2', 'S3']})
print(""Original DataFrames:"")
print(data1)
print(""--------------------"")
print(data2)
print(""\nMerged Data (keys from data2):"")
merged_data = pd.merge(data1, data2, how='right', on=['key1', 'key2'])
print(merged_data)
print(""\nMerged Data (keys from data1):"")
merged_data = pd.merge(data2, data1, how='right', on=['key1', 'key2'])
print(merged_data)
"
897,Write a NumPy program to compute the inner product of two given vectors. ,"import numpy as np
x = np.array([4, 5])
y = np.array([7, 10])
print(""Original vectors:"")
print(x)
print(y)
print(""Inner product of said vectors:"")
print(np.dot(x, y))
"
898,Write a Pandas program to calculate all Thursdays between two given days. ,"import pandas as pd
thursdays = pd.date_range('2020-01-01',
'2020-12-31', freq=""W-THU"")
print(""All Thursdays between 2020-01-01 and 2020-12-31:\n"")
print(thursdays.values)
"
899,Write a Python program to print all permutations of a given string (including duplicates). ,"def permute_string(str):
if len(str) == 0:
return ['']
prev_list = permute_string(str[1:len(str)])
next_list = []
for i in range(0,len(prev_list)):
for j in range(0,len(str)):
new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]
if new_str not in next_list:
next_list.append(new_str)
return next_list
print(permute_string('ABCD'));
"
900,Write a Python program to extract values from a given dictionaries and create a list of lists from those values. ,"def test(dictt,keys):
return [list(d[k] for k in keys) for d in dictt]
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
]
print(""\nOriginal Dictionary:"")
print(students)
print(""\nExtract values from the said dictionarie and create a list of lists using those values:"")
print(""\n"",test(students,('student_id', 'name', 'class')))
print(""\n"",test(students,('student_id', 'name')))
print(""\n"",test(students,('name', 'class')))
"
901,Write a NumPy program to calculate the sum of all columns of a 2D NumPy array. ,"import numpy as np
num = np.arange(36)
arr1 = np.reshape(num, [4, 9])
print(""Original array:"")
print(arr1)
result = arr1.sum(axis=0)
print(""\nSum of all columns:"")
print(result)
"
902,Write a Python program to remove the n,"def remove_char(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
print(remove_char('Python', 0))
print(remove_char('Python', 3))
print(remove_char('Python', 5))
"
903,Write a Python program to remove duplicate characters of a given string. ,"from collections import OrderedDict
def remove_duplicate(str1):
return """".join(OrderedDict.fromkeys(str1))
print(remove_duplicate(""python exercises practice solution""))
print(remove_duplicate(""w3resource""))
"
904,Write a NumPy program to create a record array from a given regular array. ,"import numpy as np
arra1 = np.array([(""Yasemin Rayner"", 88.5, 90),
(""Ayaana Mcnamara"", 87, 99),
(""Jody Preece"", 85.5, 91)])
print(""Original arrays:"")
print(arra1)
print(""\nRecord array;"")
result = np.core.records.fromarrays(arra1.T,
names='col1, col2, col3',
formats = 'S80, f8, i8')
print(result)
"
905,Write a Python program to create a ctime formatted representation of the date and time using arrow module. ,"import arrow
print(""Ctime formatted representation of the date and time:"")
a = arrow.utcnow().ctime()
print(a)
"
906,Write a Python program to input two integers in a single line. ,"print(""Input the value of x & y"")
x, y = map(int, input().split())
print(""The value of x & y are: "",x,y)
"
907,"Write a Python program to find out, if the given number is abundant. ","def is_abundant(n):
fctr_sum = sum([fctr for fctr in range(1, n) if n % fctr == 0])
return fctr_sum > n
print(is_abundant(12))
print(is_abundant(13))
"
908,Write a NumPy program to create a random vector of size 10 and sort it. ,"import numpy as np
x = np.random.random(10)
print(""Original array:"")
print(x)
x.sort()
print(""Sorted array:"")
print(x)
"
909,"Write a NumPy program to create to concatenate two given arrays of shape (2, 2) and (2,1). ","import numpy as np
nums1 = np.array([[4.5, 3.5],
[5.1, 2.3]])
nums2 = np.array([[1],
[2]])
print(""Original arrays:"")
print(nums1)
print(nums2)
print(""\nConcatenating the said two arrays:"")
print(np.concatenate((nums1, nums2), axis=1))
"
910,Write a Python program to find the first repeated character in a given string. ,"def first_repeated_char(str1):
for index,c in enumerate(str1):
if str1[:index+1].count(c) > 1:
return c
return ""None""
print(first_repeated_char(""abcdabcd""))
print(first_repeated_char(""abcd""))
"
911,Write a python program to find the longest words. ,"def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('test.txt'))
"
912,"Write a Python program to display your details like name, age, address in three different lines. ","def personal_details():
name, age = ""Simon"", 19
address = ""Bangalore, Karnataka, India""
print(""Name: {}\nAge: {}\nAddress: {}"".format(name, age, address))
personal_details()
"
913,Write a Python program to count the frequency of consecutive duplicate elements in a given list of numbers. Use itertools module. ,"from itertools import groupby
def count_same_pair(nums):
result = [sum(1 for _ in group) for _, group in groupby(nums)]
return result
nums = [1,1,2,2,2,4,4,4,5,5,5,5]
print(""Original lists:"")
print(nums)
print(""\nFrequency of the consecutive duplicate elements:"")
print(count_same_pair(nums))
"
914,Write a Python program to get the daylight savings time adjustment using arrow module. ,"import arrow
print(""Daylight savings time adjustment:"")
a = arrow.utcnow().dst()
print(a)
"
915,Write a Pandas program to construct a series using the MultiIndex levels as the column and index. ,"import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
print(""Create a MultiIndex:"")
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print(sales_tuples)
print(""\nConstruct a series using the said MultiIndex levels: "")
s = pd.Series(np.random.randn(8), index = sales_index)
print(s)
"
916,Write a Python program to write dictionaries and a list of dictionaries to a given CSV file. Use csv.reader,"import csv
print(""Write dictionaries to a CSV file:"")
fw = open(""test.csv"", ""w"", newline='')
writer = csv.DictWriter(fw, fieldnames=[""Name"", ""Class""])
writer.writeheader()
writer.writerow({""Name"": ""Jasmine Barrett"", ""Class"": ""V""})
writer.writerow({""Name"": ""Garry Watson"", ""Class"": ""V""})
writer.writerow({""Name"": ""Courtney Caldwell"", ""Class"": ""VI""})
fw.close()
fr = open(""test.csv"", ""r"")
csv = csv.reader(fr, delimiter = "","")
for row in csv:
print(row)
fr.close()
"
917,Write a Python program to find the first non-repeating character in given string. ,"def first_non_repeating_character(str1):
char_order = []
ctr = {}
for c in str1:
if c in ctr:
ctr[c] += 1
else:
ctr[c] = 1
char_order.append(c)
for c in char_order:
if ctr[c] == 1:
return c
return None
print(first_non_repeating_character('abcdef'))
print(first_non_repeating_character('abcabcdef'))
print(first_non_repeating_character('aabbcc'))
"
918,Write a Python program to merge more than one dictionary in a single expression. ,"import collections as ct
def merge_dictionaries(color1,color2):
merged_dict = dict(ct.ChainMap({}, color1, color2))
return merged_dict
color1 = { ""R"": ""Red"", ""B"": ""Black"", ""P"": ""Pink"" }
color2 = { ""G"": ""Green"", ""W"": ""White"" }
print(""Original dictionaries:"")
print(color1,' ',color2)
print(""\nMerged dictionary:"")
print(merge_dictionaries(color1, color2))
def merge_dictionaries(color1,color2, color3):
merged_dict = dict(ct.ChainMap({}, color1, color2, color3))
return merged_dict
color1 = { ""R"": ""Red"", ""B"": ""Black"", ""P"": ""Pink"" }
color2 = { ""G"": ""Green"", ""W"": ""White"" }
color3 = { ""O"": ""Orange"", ""W"": ""White"", ""B"": ""Black"" }
print(""\nOriginal dictionaries:"")
print(color1,' ',color2, color3)
print(""\nMerged dictionary:"")
# Duplicate colours have automatically removed.
print(merge_dictionaries(color1, color2, color3))
"
919,Write a Python program to shuffle the elements of a given list. Use random.shuffle(),"import random
nums = [1, 2, 3, 4, 5]
print(""Original list:"")
print(nums)
random.shuffle(nums)
print(""Shuffle list:"")
print(nums)
words = ['red', 'black', 'green', 'blue']
print(""\nOriginal list:"")
print(words)
random.shuffle(words)
print(""Shuffle list:"")
print(words)
"
920,"Write a Pandas program to filter those records where WHO region matches with multiple values (Africa, Eastern Mediterranean, Europe) from world alcohol consumption dataset. ","import pandas as pd
# World alcohol consumption data
new_w_a_con = pd.read_csv('world_alcohol.csv')
print(""World alcohol consumption sample data:"")
print(new_w_a_con.head())
print(""\nFilter by matching multiple values in a given dataframe:"")
flt_wine = new_w_a_con[""WHO region""].isin([""Africa"", ""Eastern Mediterranean"", ""Europe""])
print(new_w_a_con[flt_wine])
"
921,Write a Python program to sort a given matrix in ascending order according to the sum of its rows. ,"def sort_matrix(M):
result = sorted(M, key=sum)
return result
matrix1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
matrix2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
print(""Original Matrix:"")
print(matrix1)
print(""\nSort the said matrix in ascending order according to the sum of its rows"")
print(sort_matrix(matrix1))
print(""\nOriginal Matrix:"")
print(matrix2)
print(""\nSort the said matrix in ascending order according to the sum of its rows"")
print(sort_matrix(matrix2))
"
922,"Write a Python code to send a request to a web page, and print the JSON value of the response. Also print each key value of the response. ","import requests
r = requests.get('https://api.github.com/')
response = r.json()
print(""JSON value of the said response:"")
print(r.json())
print(""\nEach key of the response:"")
print(""Current user url:"",response['current_user_url'])
print(""Current user authorizations html url:"",response['current_user_authorizations_html_url'])
print(""Authorizations url:"",response['authorizations_url'])
print(""code_search_url:"",response['code_search_url'])
print(""commit_search_url:"",response['commit_search_url'])
print(""Emails url:"",response['emails_url'])
print(""Emojis url:"",response['emojis_url'])
print(""Events url:"",response['events_url'])
print(""Feeds url:"",response['feeds_url'])
print(""Followers url:"",response['followers_url'])
print(""Following url:"",response['following_url'])
print(""Gists url:"",response['gists_url'])
print(""Issue search url:"",response['issue_search_url'])
print(""Issues url:"",response['issues_url'])
print(""Keys url:"",response['keys_url'])
print(""label search url:"",response['label_search_url'])
print(""Notifications url:"",response['notifications_url'])
print(""Organization url:"",response['organization_url'])
print(""Organization repositories url:"",response['organization_repositories_url'])
print(""Organization teams url:"",response['organization_teams_url'])
print(""Public gists url:"",response['public_gists_url'])
print(""Rate limit url:"",response['rate_limit_url'])
print(""Repository url:"",response['repository_url'])
print(""Repository search url:"",response['repository_search_url'])
print(""Current user repositories url:"",response['current_user_repositories_url'])
print(""Starred url:"",response['starred_url'])
print(""Starred gists url:"",response['starred_gists_url'])
print(""User url:"",response['user_url'])
print(""User organizations url:"",response['user_organizations_url'])
print(""User repositories url:"",response['user_repositories_url'])
print(""User search url:"",response['user_search_url'])
"
923,Write a Python program to insert a new item before the second element in an existing array. ,"from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print(""Original array: ""+str(array_num))
print(""Insert new value 4 before 3:"")
array_num.insert(1, 4)
print(""New array: ""+str(array_num))
"
924,Write a NumPy program to save as text a matrix which has in each row 2 float and 1 string at the end. ,"import numpy as np
matrix = [[1, 0, 'aaa'], [0, 1, 'bbb'], [0, 1, 'ccc']]
np.savetxt('test', matrix, delimiter=' ', header='string', comments='', fmt='%s')
"
925,Write a Python program to check whether multiple variables have the same value. ,"x = 20
y = 20
z = 20
if x == y == z == 20:
print(""All variables have same value!"")
"
926,"Write a Python program to write a string to a buffer and retrieve the value written, at the end discard buffer memory. ","import io
# Write a string to a buffer
output = io.StringIO()
output.write('Python Exercises, Practice, Solution')
# Retrieve the value written
print(output.getvalue())
# Discard buffer memory
output.close()
"
927,Write a Python program to copy the contents of a file to another file . ,"from shutil import copyfile
copyfile('test.py', 'abc.py')
"
928,Write a NumPy program to merge three given NumPy arrays of same shape. ,"import numpy as np
arr1 = np.random.random(size=(25, 25, 1))
arr2 = np.random.random(size=(25, 25, 1))
arr3 = np.random.random(size=(25, 25, 1))
print(""Original arrays:"")
print(arr1)
print(arr2)
print(arr3)
result = np.concatenate((arr1, arr2, arr3), axis=-1)
print(""\nAfter concatenate:"")
print(result)
"
929,Write a NumPy program to interchange two axes of an array. ,"import numpy as np
x = np.array([[1,2,3]])
print(x)
y = np.swapaxes(x,0,1)
print(y)
"
930,Write a Python program to decapitalize the first letter of a given string. ,"def decapitalize_first_letter(s, upper_rest = False):
return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])
print(decapitalize_first_letter('Java Script'))
print(decapitalize_first_letter('Python'))
"
931,"Write a Pandas program to select first 2 rows, 2 columns and specific two columns from 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(""\nSelect first 2 rows:"")
print(w_a_con.iloc[:2])
print(""\nSelect first 2 columns:"")
print(w_a_con.iloc[:,:2].head())
print(""\nSelect 2 specific columns:"")
print(w_a_con[['Display Value', 'Year']])
"
932,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)
"
933,Write a Python program to move the specified number of elements to the start of the given list. ,"def move_start(nums, offset):
return nums[-offset:] + nums[:-offset]
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 3))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -3))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 8))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -8))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 7))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -7))
"
934,Write a Python program to find and print all li tags of a given web page. ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.w3resource.com/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nFind and print all li tags:\n"")
for tag in soup.find_all(""li""):
print(""{0}: {1}"".format(tag.name, tag.text))
"
935,Write a Pandas program to add summation to a row of the given excel file. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
sum_row=df[[""Production"", ""Labor_Hours""]].sum()
df_sum=pd.DataFrame(data=sum_row).T
df_sum=df_sum.reindex(columns=df.columns)
df_sum
"
936,"Write a Python program to make a chain of function decorators (bold, italic, underline etc.) in Python. ","def make_bold(fn):
def wrapped():
return """" + fn() + """"
return wrapped
def make_italic(fn):
def wrapped():
return """" + fn() + """"
return wrapped
def make_underline(fn):
def wrapped():
return """" + fn() + """"
return wrapped
@make_bold
@make_italic
@make_underline
def hello():
return ""hello world""
print(hello()) ## returns ""hello world""
"
937,Write a Python program to remove an element from a given list. ,"student = ['Ricky Rivera', 98, 'Math', 90, 'Science']
print(""Original list:"")
print(student)
print(""\nAfter deleting an element:, using index of the element:"")
del(student[0])
print(student)
"
938,Write a Python program to count repeated characters in a string. ,"import collections
str1 = 'thequickbrownfoxjumpsoverthelazydog'
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print('%s %d' % (c, d[c]))
"
939,Write a Pandas program to check if a specified column starts with a specified string in a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print(""Original DataFrame:"")
print(df)
print(""\nIf a specified column starts with a specified string?"")
df['company_code_starts_with'] = list(
map(lambda x: x.startswith('ze'), df['company_code']))
print(df)
"
940,Write a NumPy program to replace all the nan (missing values) of a given array with the mean of another array. ,"import numpy as np
array_nums1 = np.arange(20).reshape(4,5)
array_nums2 = np.array([[1,2,np.nan],[4,5,6],[np.nan, 7, np.nan]])
print(""Original arrays:"")
print(array_nums1)
print(array_nums2)
print(""\nAll the nan of array_nums2 replaced by the mean of array_nums1:"")
array_nums2[np.isnan(array_nums2)]= np.nanmean(array_nums1)
print(array_nums2)
"
941,Write a Python program to execute a string containing Python code. ,"mycode = 'print(""hello world"")'
code = """"""
def mutiply(x,y):
return x*y
print('Multiply of 2 and 3 is: ',mutiply(2,3))
""""""
exec(mycode)
exec(code)
"
942,Write a Python program to check whether an integer fits in 64 bits. ,"int_val = 30
if int_val.bit_length() <= 63:
print((-2 ** 63).bit_length())
print((2 ** 63).bit_length())
"
943,Write a Python program to calculate the sum of the numbers in a list between the indices of a specified range. ,"def sum_Range_list(nums, m, n):
sum_range = 0
for i in range(m, n+1, 1):
sum_range += nums[i]
return sum_range
nums = [2,1,5,6,8,3,4,9,10,11,8,12]
print(""Original list:"")
print(nums)
m = 8
n = 10
print(""Range:"",m,"","",n)
print(""\nSum of the specified range:"")
print(sum_Range_list(nums, m, n))
"
944,Write a Pandas program to convert year-month string to dates adding a specified day of the month. ,"import pandas as pd
from dateutil.parser import parse
date_series = pd.Series(['Jan 2015', 'Feb 2016', 'Mar 2017', 'Apr 2018', 'May 2019'])
print(""Original Series:"")
print(date_series)
print(""\nNew dates:"")
result = date_series.map(lambda d: parse('11 ' + d))
print(result)
"
945,Write a NumPy program to convert numpy datetime64 to Timestamp. ,"import numpy as np
from datetime import datetime
dt = datetime.utcnow()
print(""Current date:"")
print(dt)
dt64 = np.datetime64(dt)
ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
print(""Timestamp:"")
print(ts)
print(""UTC from Timestamp:"")
print(datetime.utcfromtimestamp(ts))
"
946,Write a Pandas program to rename all and only some of the column names from world alcohol consumption dataset. ,"import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
new_w_a_con = pd.read_csv('world_alcohol.csv')
print(""World alcohol consumption sample data:"")
print(w_a_con.head())
print(""\nRename all the column names:"")
w_a_con.columns = ['year','who_region','country','beverage_types','display_values']
print(w_a_con.head())
print(""\nRenaming only some of the column names:"")
new_w_a_con.rename(columns = {""WHO region"":""WHO_region"",""Display Value"":""Display_Value"" },inplace = True)
print(new_w_a_con.head())
"
947,Write a Python program to get the n minimum elements from a given list of numbers. ,"def min_n_nums(nums, n = 1):
return sorted(nums, reverse = False)[:n]
nums = [1, 2, 3]
print(""Original list elements:"")
print(nums)
print(""Minimum values of the said list:"", min_n_nums(nums))
nums = [1, 2, 3]
print(""\nOriginal list elements:"")
print(nums)
print(""Two minimum values of the said list:"", min_n_nums(nums,2))
nums = [-2, -3, -1, -2, -4, 0, -5]
print(""\nOriginal list elements:"")
print(nums)
print(""Threee minimum values of the said list:"", min_n_nums(nums,3))
nums = [2.2, 2, 3.2, 4.5, 4.6, 5.2, 2.9]
print(""\nOriginal list elements:"")
print(nums)
print(""Two minimum values of the said list:"", min_n_nums(nums, 2))
"
948,Write a Pandas program to create a dataframe and set a title or name of the index column. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index = ['t1', 't2', 't3', 't4', 't5', 't6'])
print(""Original DataFrame:"")
print(df)
df.index.name = 'Index_name'
print(""\nSaid DataFrame with a title or name of the index column:"")
print(df)
"
949,Write a Pandas program to join the two dataframes with matching records from both sides where available. ,"import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],
'marks': [201, 200, 198, 219, 201]})
print(""Original DataFrames:"")
print(student_data1)
print(student_data2)
merged_data = pd.merge(student_data1, student_data2, on='student_id', how='outer')
print(""Merged data (outer join):"")
print(merged_data)
"
950,Write a Python program to create a symbolic link and read it to decide the original file pointed by the link. ,"import os
path = '/tmp/' + os.path.basename(__file__)
print('Creating link {} -> {}'.format(path, __file__))
os.symlink(__file__, path)
stat_info = os.lstat(path)
print('\nFile Permissions:', oct(stat_info.st_mode))
print('\nPoints to:', os.readlink(path))
#removes the file path
os.unlink(path)
"
951,Write a Python program to reverse strings in a given list of string values. ,"def reverse_strings_list(string_list):
result = [x[::-1] for x in string_list]
return result
colors_list = [""Red"", ""Green"", ""Blue"", ""White"", ""Black""]
print(""\nOriginal lists:"")
print(colors_list)
print(""\nReverse strings of the said given list:"")
print(reverse_strings_list(colors_list))
"
952,Write a Pandas program to convert integer or float epoch times to Timestamp and DatetimeIndex. ,"import pandas as pd
dates1 = pd.to_datetime([1329806505, 129806505, 1249892905,
1249979305, 1250065705], unit='s')
print(""Convert integer or float epoch times to Timestamp and DatetimeIndex upto second:"")
print(dates1)
print(""\nConvert integer or float epoch times to Timestamp and DatetimeIndex upto milisecond:"")
dates2 = pd.to_datetime([1249720105100, 1249720105200, 1249720105300,
1249720105400, 1249720105500], unit='ms')
print(dates2)
"
953,Write a Python program to convert more than one list to nested dictionary. ,"def nested_dictionary(l1, l2, l3):
result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)]
return result
student_id = [""S001"", ""S002"", ""S003"", ""S004""]
student_name = [""Adina Park"", ""Leyton Marsh"", ""Duncan Boyle"", ""Saim Richards""]
student_grade = [85, 98, 89, 92]
print(""Original strings:"")
print(student_id)
print(student_name)
print(student_grade)
print(""\nNested dictionary:"")
ch='a'
print(nested_dictionary(student_id, student_name, student_grade))
"
954,Write a Python program to find a first even and odd number in a given list of numbers. ,"def first_even_odd(nums):
first_even = next((el for el in nums if el%2==0),-1)
first_odd = next((el for el in nums if el%2!=0),-1)
return first_even,first_odd
nums= [1,3,5,7,4,1,6,8]
print(""Original list:"")
print(nums)
print(""\nFirst even and odd number of the said list of numbers:"")
print(first_even_odd(nums))
"
955,Write a Python program to sort a list of lists by a given index of the inner list. ,"from operator import itemgetter
def index_on_inner_list(list_data, index_no):
result = sorted(list_data, key=itemgetter(index_no))
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print (""Original list:"")
print(students)
index_no = 0
print(""\nSort the said list of lists by a given index"",""( Index = "",index_no,"") of the inner list"")
print(index_on_inner_list(students, index_no))
index_no = 2
print(""\nSort the said list of lists by a given index"",""( Index = "",index_no,"") of the inner list"")
print(index_on_inner_list(students, index_no))
"
956,Write a Python program to generate a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit. ,"def arithmetic_progression(n, x):
return list(range(n, x + 1, n))
print(arithmetic_progression(1, 15))
print(arithmetic_progression(3, 37))
print(arithmetic_progression(5, 25))
"
957,Write a NumPy program to sort an given array by the n,"import numpy as np
print(""Original array:\n"")
nums = np.random.randint(0,10,(3,3))
print(nums)
print(""\nSort the said array by the nth column: "")
print(nums[nums[:,1].argsort()])
"
958,Write a Python program to sort a list of elements using Bogosort sort. ,"import random
def bogosort(nums):
def isSorted(nums):
if len(nums) < 2:
return True
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return False
return True
while not isSorted(nums):
random.shuffle(nums)
return nums
num1 = input('Input comma separated numbers:\n').strip()
nums = [int(item) for item in num1.split(',')]
print(bogosort(nums))
"
959,"Write a Python program to create a floating-point representation of the Arrow object, in UTC time using arrow module. ","import arrow
a = arrow.utcnow()
print(""Current Datetime:"")
print(a)
print(""\nFloating-point representation of the said Arrow object:"")
f = arrow.utcnow().float_timestamp
print(f)
"
960,"Write a Python program to create a time object with the same hour, minute, second, microsecond and timezone info. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nTime object with the same hour, minute, second, microsecond and timezone info.:"")
print(arrow.utcnow().timetz())
"
961,Write a NumPy program to append values to the end of an array. ,"import numpy as np
x = [10, 20, 30]
print(""Original array:"")
print(x)
x = np.append(x, [[40, 50, 60], [70, 80, 90]])
print(""After append values to the end of the array:"")
print(x)
"
962,Write a Python program to convert a string to a list. ,"import ast
color =""['Red', 'Green', 'White']""
print(ast.literal_eval(color))
"
963,"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)
"
964,Write a Python program to convert a given string to snake case. ,"from re import sub
def snake_case(s):
return '_'.join(
sub('([A-Z][a-z]+)', r' \1',
sub('([A-Z]+)', r' \1',
s.replace('-', ' '))).split()).lower()
print(snake_case('JavaScript'))
print(snake_case('Foo-Bar'))
print(snake_case('foo_bar'))
print(snake_case('--foo.bar'))
print(snake_case('Foo-BAR'))
print(snake_case('fooBAR'))
print(snake_case('foo bar'))
"
965,Write a Python program to find common element(s) in a given nested lists. ,"def common_in_nested_lists(nested_list):
result = list(set.intersection(*map(set, nested_list)))
return result
nested_list = [[12, 18, 23, 25, 45], [7, 12, 18, 24, 28], [1, 5, 8, 12, 15, 16, 18]]
print(""\nOriginal lists:"")
print(nested_list)
print(""\nCommon element(s) in nested lists:"")
print(common_in_nested_lists(nested_list))
"
966,Write a NumPy program to remove nan values from a given array. ,"import numpy as np
x = np.array([200, 300, np.nan, np.nan, np.nan ,700])
y = np.array([[1, 2, 3], [np.nan, 0, np.nan] ,[6,7,np.nan]] )
print(""Original array:"")
print(x)
print(""After removing nan values:"")
result = x[np.logical_not(np.isnan(x))]
print(result)
print(""\nOriginal array:"")
print(y)
print(""After removing nan values:"")
result = y[np.logical_not(np.isnan(y))]
print(result)
"
967,"Write a Pandas program to create a plot of adjusted closing prices, thirty days and forty days simple moving average of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
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]
stock_data = df1.set_index('Date')
close_px = stock_data['Adj Close']
stock_data['SMA_30_days'] = stock_data.iloc[:,4].rolling(window=30).mean()
stock_data['SMA_40_days'] = stock_data.iloc[:,4].rolling(window=40).mean()
plt.figure(figsize=[10,8])
plt.grid(True)
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]\n',fontsize=18, color='black')
plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price', color='black')
plt.plot(stock_data['SMA_30_days'],label='30 days simple moving average', color='red')
plt.plot(stock_data['SMA_40_days'],label='40 days simple moving average', color='green')
plt.legend(loc=2)
plt.show()
"
968,Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21. ,"import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(m)
"
969,Write a NumPy program to extract second and third elements of the second and third rows from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: Second and third elements of the second and third rows"")
print(arra_data[1:3, 1:3])
"
970,Write a Pandas program to create a Pivot table and find survival rate by gender on various classes. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index='sex', columns='class')
print(result)
"
971,Write a NumPy program to calculate percentiles for a sequence or single-dimensional NumPy array. ,"import numpy as np
nums = np.array([1,2,3,4,5])
print(""50th percentile (median):"")
p = np.percentile(nums, 50)
print(p)
print(""40th percentile:"")
p = np.percentile(nums, 40)
print(p)
print(""90th percentile:"")
p = np.percentile(nums, 90)
print(p)
"
972,Write a Python program to break a given list of integers into sets of a given positive number. Return true or false. ,"import collections as clt
def check_break_list(nums, n):
coll_data = clt.Counter(nums)
for x in sorted(coll_data.keys()):
for index in range(1, n):
coll_data[x+index] = coll_data[x+index] - coll_data[x]
if coll_data[x+index] < 0:
return False
return True
nums = [1,2,3,4,5,6,7,8]
n = 4
print(""Original list:"",nums)
print(""Number to devide the said list:"",n)
print(check_break_list(nums, n))
nums = [1,2,3,4,5,6,7,8]
n = 3
print(""\nOriginal list:"",nums)
print(""Number to devide the said list:"",n)
print(check_break_list(nums, n))
"
973,Write a Python program to sort a list of elements using the insertion sort algorithm. ,"def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
"
974,"Write a Python program to find the numbers of a given string and store them in a list, display the numbers which are bigger than the length of the list in sorted form. Use lambda function to solve the problem. ","str1 = ""sdf 23 safs8 5 sdfsd8 sdfs 56 21sfs 20 5""
print(""Original string: "",str1)
str_num=[i for i in str1.split(' ')]
lenght=len(str_num)
numbers=sorted([int(x) for x in str_num if x.isdigit()])
print('Numbers in sorted form:')
for i in ((filter(lambda x:x>lenght,numbers))):
print(i,end=' ')
"
975,Write a Pandas program to merge two given dataframes with different columns. ,"import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'R': ['R0', 'R1', 'R2', 'R3'],
'S': ['S0', 'S1', 'S2', 'S3']})
print(""Original DataFrames:"")
print(data1)
print(""--------------------"")
print(data2)
print(""\nMerge two dataframes with different columns:"")
result = pd.concat([data1,data2], axis=0, ignore_index=True)
print(result)
"
976,Write a Pandas program to drop those rows from a given DataFrame in which specific columns have missing values. ,"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(""\nDrop those rows in which specific columns have missing values:"")
result = df.dropna(subset=['ord_no', 'customer_id'])
print(result)
"
977,Write a Python program to find the difference between elements (n+1th - nth) of a given list of numeric values. ,"def elements_difference(nums):
result = [j-i for i, j in zip(nums[:-1], nums[1:])]
return result
nums1 = [1,2,3,4,5,6,7,8,9,10]
nums2 = [2,4,6,8]
print(""Original list:"")
print(nums1)
print(""\nDfference between elements (n+1th – nth) of the said list :"")
print(elements_difference(nums1))
print(""\nOriginal list:"")
print(nums2)
print(""\nDfference between elements (n+1th – nth) of the said list :"")
print(elements_difference(nums2))
"
978,Write a Pandas program to create a time-series from a given list of dates as strings. ,"import pandas as pd
import numpy as np
import datetime
from datetime import datetime, date
dates = ['2014-08-01','2014-08-02','2014-08-03','2014-08-04']
time_series = pd.Series(np.random.randn(4), dates)
print(time_series)
"
979,Write a Pandas program to convert a series of date strings to a timeseries. ,"import pandas as pd
date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20'])
print(""Original Series:"")
print(date_series)
print(""\nSeries of date strings to a timeseries:"")
print(pd.to_datetime(date_series))
"
980,"Write a NumPy program to create a 90x30 array filled with random point numbers, increase the number of items (10 edge elements) shown by the print statement. ","import numpy as np
nums = np.random.randint(10, size=(90, 30))
print(""Original array:"")
print(nums)
print(""\nIncrease the number of items (10 edge elements) shown by the print statement:"")
np.set_printoptions(edgeitems=10)
print(nums)
"
981,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the minimum value in each column. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
def highlight_min(s):
'''
highlight the minimum in a Series red.
'''
is_max = s == s.min()
return ['background-color: red' if v else '' for v in is_max]
print(""\nHighlight the minimum value in each column:"")
df.style.apply(highlight_min,subset=pd.IndexSlice[:, ['B', 'C', 'D', 'E']])
"
982,Write a Pandas program to split the following dataframe into groups and calculate quarterly purchase amount. ,"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': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'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)
df['ord_date']= pd.to_datetime(df['ord_date'])
print(""\nQuartly purchase amount:"")
result = df.set_index('ord_date').groupby(pd.Grouper(freq='Q')).agg({'purch_amt':sum})
print(result)
"
983,Write a NumPy program to sort a given array by row and column in ascending order. ,"import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 4.38, 6.99],
[1.54, 2.39, 9.29]])
print(""Original array:"")
print(nums)
print(""\nSort the said array by row in ascending order:"")
print(np.sort(nums))
print(""\nSort the said array by column in ascending order:"")
print(np.sort(nums, axis=0))
"
984,Write a Python program that reads a given expression and evaluates it. ,"#https://bit.ly/2lxQysi
import re
print(""Input number of data sets:"")
class c(int):
def __add__(self,n):
return c(int(self)+int(n))
def __sub__(self,n):
return c(int(self)-int(n))
def __mul__(self,n):
return c(int(self)*int(n))
def __truediv__(self,n):
return c(int(int(self)/int(n)))
for _ in range(int(input())):
print(""Input an expression:"")
print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))
"
985,"Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0. ","import numpy as np
x = np.ones((10, 10))
x[1:-1, 1:-1] = 0
print(x)
"
986,Write a Python program to pack consecutive duplicates of a given list elements into sublists. ,"from itertools import groupby
def pack_consecutive_duplicates(l_nums):
return [list(group) for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print(""Original list:"")
print(n_list)
print(""\nAfter packing consecutive duplicates of the said list elements into sublists:"")
print(pack_consecutive_duplicates(n_list))
"
987,Write a Python program to remove additional spaces in a given list. ,"def test(lst):
result =[]
for i in lst:
j = i.replace(' ','')
result.append(j)
return result
text = ['abc ', ' ', ' ', 'sdfds ', ' ', ' ', 'sdfds ', 'huy']
print(""\nOriginal list:"")
print(text)
print(""Remove additional spaces from the said list:"")
print(test(text))
"
988,Write a NumPy program to compute the 80th percentile for all elements in a given array along the second axis. ,"import numpy as np
x = np.arange(12).reshape((2, 6))
print(""\nOriginal array:"")
print(x)
r1 = np.percentile(x, 80, 1)
print(""\n80th percentile for all elements of the said array along the second axis:"")
print(r1)
"
989,Write a NumPy program to multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product. ,"import numpy as np
x = np.random.random((5,3))
print(""First array:"")
print(x)
y = np.random.random((3,2))
print(""Second array:"")
print(y)
z = np.dot(x, y)
print(""Dot product of two arrays:"")
print(z)
"
990,Write a Pandas program to subtract two timestamps of same time zone or different time zone. ,"import pandas as pd
print(""Subtract two timestamps of same time zone:"")
date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern')
date2 = pd.Timestamp('2019-04-01 07:00', tz='US/Eastern')
print(""Difference: "", (date2-date1))
print(""\nSubtract two timestamps of different time zone:"")
date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern')
date2 = pd.Timestamp('2019-03-01 07:00', tz='US/Pacific')
# Remove the time zone and do the subtraction
print(""Difference: "", (date1.tz_localize(None) - date2.tz_localize(None)))
"
991,Write a Python program to get the weighted average of two or more numbers. ,"def weighted_average(nums, weights):
return sum(x * y for x, y in zip(nums, weights)) / sum(weights)
nums1 = [10, 50, 40]
nums2 = [2, 5, 3]
print(""Original list elements:"")
print(nums1)
print(nums2)
print(""\nWeighted average of the said two list of numbers:"")
print(weighted_average(nums1, nums2))
nums1 = [82, 90, 76, 83]
nums2 = [.2, .35, .45, 32]
print(""\nOriginal list elements:"")
print(nums1)
print(nums2)
print(""\nWeighted average of the said two list of numbers:"")
print(weighted_average(nums1, nums2))
"
992,Write a Python program to form Bigrams of words in a given list of strings. ,"def bigram_sequence(text_lst):
result = [a for ls in text_lst for a in zip(ls.split("" "")[:-1], ls.split("" "")[1:])]
return result
text = [""Sum all the items in a list"", ""Find the second smallest number in a list""]
print(""Original list:"")
print(text)
print(""\nBigram sequence of the said list:"")
print(bigram_sequence(text))
"
993,Write a Python program to delete the last item from a singly linked list. ,"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 delete_item(self, data):
# Delete an item from the list
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def iterate_item(self):
# Iterate the list.
current_item = self.tail
while current_item:
val = current_item.data
current_item = current_item.next
yield val
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(""Original list:"")
for val in items.iterate_item():
print(val)
print(""\nAfter removing the last item from the list:"")
items.delete_item('Java')
for val in items.iterate_item():
print(val)
"
994,Write a Pandas program to filter words from a given series that contain atleast two vowels. ,"import pandas as pd
from collections import Counter
color_series = pd.Series(['Red', 'Green', 'Orange', 'Pink', 'Yellow', 'White'])
print(""Original Series:"")
print(color_series)
print(""\nFiltered words:"")
result = mask = color_series.map(lambda c: sum([Counter(c.lower()).get(i, 0) for i in list('aeiou')]) >= 2)
print(color_series[result])
"
995,Write a Python program to add leading zeroes to a string. ,"str1='122.22'
print(""Original String: "",str1)
print(""\nAdded trailing zeros:"")
str1 = str1.ljust(8, '0')
print(str1)
str1 = str1.ljust(10, '0')
print(str1)
print(""\nAdded leading zeros:"")
str1='122.22'
str1 = str1.rjust(8, '0')
print(str1)
str1 = str1.rjust(10, '0')
print(str1)
"
996,"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()
"
997,"Write a NumPy program to calculate round, floor, ceiling, truncated and round (to the given number of decimals) of the input, element-wise of a given array. ","import numpy as np
x = np.array([3.1, 3.5, 4.5, 2.9, -3.1, -3.5, -5.9])
print(""Original array: "")
print(x)
r1 = np.around(x)
r2 = np.floor(x)
r3 = np.ceil(x)
r4 = np.trunc(x)
r5 = [round(elem) for elem in x]
print(""\naround: "", r1)
print(""floor: "",r2)
print(""ceil: "",r3)
print(""trunc: "",r4)
print(""round: "",r5)
"
998,Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50. ,"import numpy as np
v = np.linspace(10, 49, 5)
print(""Length 10 with values evenly distributed between 5 and 50:"")
print(v)
"
999,Write a Python program to check whether any word in a given sting contains duplicate characrters or not. Return True or False. ,"def duplicate_letters(text):
word_list = text.split()
for word in word_list:
if len(word) > len(set(word)):
return False
return True
text = ""Filter out the factorials of the said list.""
print(""Original text:"")
print(text)
print(""Check whether any word in the said sting contains duplicate characrters or not!"")
print(duplicate_letters(text))
text = ""Python Exercise.""
print(""\nOriginal text:"")
print(text)
print(""Check whether any word in the said sting contains duplicate characrters or not!"")
print(duplicate_letters(text))
text = ""The wait is over.""
print(""\nOriginal text:"")
print(text)
print(""Check whether any word in the said sting contains duplicate characrters or not!"")
print(duplicate_letters(text))
"
1000,Write a Python program to find the maximum and minimum value of the three given lists. ,"nums1 = [2,3,5,8,7,2,3]
nums2 = [4,3,9,0,4,3,9]
nums3 = [2,1,5,6,5,5,4]
print(""Original lists:"")
print(nums1)
print(nums2)
print(nums3)
print(""Maximum value of the said three lists:"")
print(max(nums1+nums2+nums3))
print(""Minimum value of the said three lists:"")
print(min(nums1+nums2+nums3))
"
1001,Write a Pandas program to rename names of columns and specific labels of the Main Index of the MultiIndex dataframe. ,"import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print(sales_tuples)
print(""\nConstruct a Dataframe using the said MultiIndex levels: "")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)
print(""\nRename the columns name of the said dataframe"")
df1 = df.rename(columns={0: ""col1"", 1: ""col2"", 2:""col3"", 3:""col4"", 4:""col5""})
print(df1)
print(""\nRename specific labels of the main index of the DataFrame"")
df2 = df1.rename(index={""sale2"": ""S2"", ""city2"": ""C2""})
print(df2)
"
1002,Write a Pandas program to create a line plot of the historical stock prices of Alphabet Inc. between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-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.set_index('Date')
plt.figure(figsize=(5,5))
plt.suptitle('Stock prices of Alphabet Inc.,\n01-04-2020 to 30-09-2020', \
fontsize=18, color='black')
plt.xlabel(""Date"",fontsize=16, color='black')
plt.ylabel(""$ price"", fontsize=16, color='black')
df2['Close'].plot(color='green');
plt.show()
"
1003,Write a NumPy program to join a sequence of arrays along a new axis. ,"import numpy as np
x = np.array([1, 2, 3])
y = np.array([2, 3, 4])
print(""Original arrays:"")
print(x)
print(y)
print(""Sequence of arrays along a new axis:"")
print(np.vstack((x, y)))
x = np.array([[1], [2], [3]])
y = np.array([[2], [3], [4]])
print(""\nOriginal arrays:"")
print(x)
print()
print(y)
print(""Sequence of arrays along a new axis:"")
print(np.vstack((x, y)))
"
1004,Write a Python program to rotate a given list by specified number of items to the right or left direction. ,"nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(""original List:"")
print(nums1)
print(""\nRotate the said list in left direction by 4:"")
result = nums1[3:] + nums1[:4]
print(result)
print(""\nRotate the said list in left direction by 2:"")
result = nums1[2:] + nums1[:2]
print(result)
print(""\nRotate the said list in Right direction by 4:"")
result = nums1[-3:] + nums1[:-4]
print(result)
print(""\nRotate the said list in Right direction by 2:"")
result = nums1[-2:] + nums1[:-2]
print(result)
"
1005,Write a Python program to get the last part of a string before a specified character. ,"str1 = 'https://www.w3resource.com/python-exercises/string'
print(str1.rsplit('/', 1)[0])
print(str1.rsplit('-', 1)[0])
"
1006,Write a NumPy program to create a 5x5 array with random values and find the minimum and maximum values. ,"import numpy as np
x = np.random.random((5,5))
print(""Original Array:"")
print(x)
xmin, xmax = x.min(), x.max()
print(""Minimum and Maximum Values:"")
print(xmin, xmax)
"
1007,Write a NumPy program to find the 4th element of a specified array. ,"import numpy as np
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)
print(x)
e1 = x.flat[3]
print(""Forth e1ement of the array:"")
print(e1)
"
1008,Write a Python program to find the list with maximum and minimum length. ,"def max_length_list(input_list):
max_length = max(len(x) for x in input_list )
max_list = max(input_list, key = len)
return(max_length, max_list)
def min_length_list(input_list):
min_length = min(len(x) for x in input_list )
min_list = min(input_list, key = len)
return(min_length, min_list)
list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
print(""Original list:"")
print(list1)
print(""\nList with maximum length of lists:"")
print(max_length_list(list1))
print(""\nList with minimum length of lists:"")
print(min_length_list(list1))
list1 = [[0], [1, 3], [5, 7], [9, 11], [3, 5, 7]]
print(""Original list:"")
print(list1)
print(""\nList with maximum length of lists:"")
print(max_length_list(list1))
print(""\nList with minimum length of lists:"")
print(min_length_list(list1))
list1 = [[12], [1, 3], [1, 34, 5, 7], [9, 11], [3, 5, 7]]
print(""Original list:"")
print(list1)
print(""\nList with maximum length of lists:"")
print(max_length_list(list1))
print(""\nList with minimum length of lists:"")
print(min_length_list(list1))
"
1009,Write a Python program to extract and display all the header tags from en.wikipedia.org/wiki/Main_Page. ,"from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen('https://en.wikipedia.org/wiki/Peter_Jeffrey_(RAAF_officer)')
bs = BeautifulSoup(html, 'html.parser')
images = bs.find_all('img', {'src':re.compile('.jpg')})
for image in images:
print(image['src']+'\n')
"
1010,Write a Python program to select an item randomly from a list. ,"import random
color_list = ['Red', 'Blue', 'Green', 'White', 'Black']
print(random.choice(color_list))
"
1011,Write a NumPy program to build an array of all combinations of three NumPy arrays. ,"import numpy as np
x = [1, 2, 3]
y = [4, 5]
z = [6, 7]
print(""Original arrays:"")
print(""Array-1"")
print(x)
print(""Array-2"")
print(y)
print(""Array-3"")
print(z)
new_array = np.array(np.meshgrid(x, y, z)).T.reshape(-1,3)
print(""Combine array:"")
print(new_array)
"
1012,Write a Python program to count the number of groups of non-zero numbers separated by zeros of a given list of numbers. ,"def test(lst):
previous_digit = 0
ctr = 0
for digit in lst:
if previous_digit==0 and digit!=0:
ctr+=1
previous_digit = digit
return ctr
nums = [3,4,6,2,0,0,0,0,0,0,6,7,6,9,10,0,0,0,0,0,5,9,9,7,4,4,0,0,0,0,0,0,5,3,2,9,7,1]
print(""\nOriginal list:"")
print(nums)
print(""\nNumber of groups of non-zero numbers separated by zeros of the said list:"")
print(test(nums))
"
1013,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 = '')
"
1014,"Write a Python code to send a request to a web page, and print the response text and content. Also get the raw socket response from the server. ","import requests
res = requests.get('https://www.google.com/')
print(""Response text of https://google.com/:"")
print(res.text)
print(""\n=============================================================================="")
print(""\nContent of the said url:"")
print(res.content)
print(""\n=============================================================================="")
print(""\nRaw data of the said url:"")
r = requests.get('https://api.github.com/events', stream = True)
print(r.raw)
print(r.raw.read(15))
"
1015,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)
"
1016,"Write a Pandas program to create a Pivot table and find number of adult male, adult female and children. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('sex', 'who', aggfunc = 'count')
print(result)
"
1017,Write a Python program to clone or copy a list. ,"original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)
"
1018,Write a NumPy program to calculate the absolute value element-wise. ,"import numpy as np
x = np.array([-10.2, 122.2, .20])
print(""Original array:"")
print(x)
print(""Element-wise absolute value:"")
print(np.absolute(x))
"
1019,"Write a NumPy program to check whether each element of a given array is composed of digits only, lower case letters only and upper case letters only. ","import numpy as np
x = np.array(['Python', 'PHP', 'JS', 'Examples', 'html5', '5'], dtype=np.str)
print(""\nOriginal Array:"")
print(x)
r1 = np.char.isdigit(x)
r2 = np.char.islower(x)
r3 = np.char.isupper(x)
print(""Digits only ="", r1)
print(""Lower cases only ="", r2)
print(""Upper cases only ="", r3)
"
1020,"Write a Pandas program to extract year, month, day, hour, minute, second and weekday from unidentified flying object (UFO) reporting date. ","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(""\nYear:"")
print(df.Date_time.dt.year.head())
print(""\nMonth:"")
print(df.Date_time.dt.month.head())
print(""\nDay:"")
print(df.Date_time.dt.day.head())
print(""\nHour:"")
print(df.Date_time.dt.hour.head())
print(""\nMinute:"")
print(df.Date_time.dt.minute.head())
print(""\nSecond:"")
print(df.Date_time.dt.second.head())
print(""\nWeekday:"")
print(df.Date_time.dt.weekday_name.head())
"
1021,Write a Python program to wrap an element in the specified tag and create the new wrapper. ,"from bs4 import BeautifulSoup
soup = BeautifulSoup(""
Python exercises.
"", ""lxml"")
print(""Original Markup:"")
print(soup.p.string.wrap(soup.new_tag(""i"")))
print(""\nNew Markup:"")
print(soup.p.wrap(soup.new_tag(""div"")))
"
1022,Write a NumPy program to find unique rows in a NumPy array. ,"import numpy as np
x = np.array([[20, 20, 20, 0],
[0, 20, 20, 20],
[0, 20, 20, 20],
[20, 20, 20, 0],
[10, 20, 20,20]])
print(""Original array:"")
print(x)
y = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1])))
_, idx = np.unique(y, return_index=True)
unique_result = x[idx]
print(""Unique rows of the above array:"")
print(unique_result)
"
1023,"Write a NumPy program to sort a given complex array using the real part first, then the imaginary part. ","import numpy as np
complex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j]
print(""Original array:"")
print(complex_num)
print(""\nSorted a given complex array using the real part first, then the imaginary part."")
print(np.sort_complex(complex_num))
"
1024,Write a Pandas program to get a time series with the last working days of each month of a specific year. ,"import pandas as pd
s = pd.date_range('2021-01-01', periods=12, freq='BM')
df = pd.DataFrame(s, columns=['Date'])
print('last working days of each month of a specific year:')
print(df)
"
1025,Write a Python program to check whether the n-th element exists in a given list. ,"x = [1, 2, 3, 4, 5, 6]
xlen = len(x)-1
print(x[xlen])
"
1026,"Write a Pandas program to create a plot of adjusted closing prices, 30 days simple moving average and exponential moving average of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
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]
stock_data = df1.set_index('Date')
close_px = stock_data['Adj Close']
stock_data['SMA_30_days'] = stock_data.iloc[:,4].rolling(window=30).mean()
stock_data['EMA_20_days'] = stock_data.iloc[:,4].ewm(span=20,adjust=False).mean()
plt.figure(figsize=[15,10])
plt.grid(True)
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]\n',fontsize=18, color='black')
plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price', color='black')
plt.plot(stock_data['SMA_30_days'],label='30 days Simple moving average', color='red')
plt.plot(stock_data['EMA_20_days'],label='20 days Exponential moving average', color='green')
plt.legend(loc=2)
plt.show()
"
1027,"Write a Python program to create a new Arrow object, representing the ""ceiling"" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute. ","import arrow
print(arrow.utcnow())
print(""Hour ceiling:"")
print(arrow.utcnow().ceil('hour'))
print(""\nMinute ceiling:"")
print(arrow.utcnow().ceil('minute'))
print(""\nSecond ceiling:"")
print(arrow.utcnow().ceil('second'))
"
1028,"Write a NumPy program to create a 4x4 array with random values, now create a new array from the said array swapping first and last rows. ","import numpy as np
nums = np.arange(16, dtype='int').reshape(-1, 4)
print(""Original array:"")
print(nums)
print(""\nNew array after swapping first and last rows of the said array:"")
new_nums = nums[::-1]
print(new_nums)
"
1029,"Write a Python program to create a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each HTML/XML tag and string. ","from bs4 import BeautifulSoup
str1 = ""
"", ""xml"")
print(""\nFormatted Unicode string:"")
print(soup.prettify())
"
1030,Write a Python program to find the indexes of all elements in the given list that satisfy the provided testing function. ,"def find_index_of_all(lst, fn):
return [i for i, x in enumerate(lst) if fn(x)]
print(find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1))
"
1031,Write a Pandas program to join the two given dataframes along rows and merge with another dataframe along the common column id. ,"import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],
'marks': [201, 200, 198, 219, 201]})
exam_data = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5', 'S7', 'S8', 'S9', 'S10', 'S11', 'S12', 'S13'],
'exam_id': [23, 45, 12, 67, 21, 55, 33, 14, 56, 83, 88, 12]})
print(""Original DataFrames:"")
print(student_data1)
print(student_data2)
print(exam_data)
print(""\nJoin first two said dataframes along rows:"")
result_data = pd.concat([student_data1, student_data2])
print(result_data)
print(""\nNow join the said result_data and df_exam_data along student_id:"")
final_merged_data = pd.merge(result_data, exam_data, on='student_id')
print(final_merged_data)
"
1032,Write a Pandas program to remove the duplicates from 'WHO region' column of 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(""\nAfter removing the duplicates of WHO region column:"")
print(w_a_con.drop_duplicates('WHO region'))
"
1033,Write a Pandas program to import three datasheets from a given excel data (coalpublic2013.xlsx ) and combine in to a single dataframe. ,"import pandas as pd
import numpy as np
df1 = pd.read_excel('E:\employee.xlsx',sheet_name=0)
df2 = pd.read_excel('E:\employee.xlsx',sheet_name=1)
df3 = pd.read_excel('E:\employee.xlsx',sheet_name=2)
df = pd.concat([df1, df2, df3])
print(df)
"
1034,"Write a Python program to create a string representation of the Arrow object, formatted according to a format string. ","import arrow
print(""Current datetime:"")
print(arrow.utcnow())
print(""\nYYYY-MM-DD HH:mm:ss ZZ:"")
print(arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ'))
print(""\nDD-MM-YYYY HH:mm:ss ZZ:"")
print(arrow.utcnow().format('DD-MM-YYYY HH:mm:ss ZZ'))
print(arrow.utcnow().format('\nMMMM DD, YYYY'))
print(arrow.utcnow().format())
"
1035,Write a Python program to get the daylight savings time adjustment using arrow module. ,"import arrow
print(""Daylight savings time adjustment:"")
a = arrow.utcnow().dst()
print(a)
"
1036,Write a NumPy program to compute the natural logarithm of one plus each element of a given array in floating-point accuracy. ,"import numpy as np
x = np.array([1e-99, 1e-100])
print(""Original array: "")
print(x)
print(""\nNatural logarithm of one plus each element:"")
print(np.log1p(x))
"
1037,A Python Dictionary contains List as value. Write a Python program to update the list values in the said dictionary. ,"def test(dictionary):
dictionary['Math'] = [x+1 for x in dictionary['Math']]
dictionary['Physics'] = [x-2 for x in dictionary['Physics']]
return dictionary
dictionary = {
'Math' : [88, 89, 90],
'Physics' : [92, 94, 89],
'Chemistry' : [90, 87, 93]
}
print(""\nOriginal Dictionary:"")
print(dictionary)
print(""\nUpdate the list values of the said dictionary:"")
print(test(dictionary))
"
1038,Write a NumPy program to calculate averages without NaNs along a given array. ,"import numpy as np
arr1 = np.array([[10, 20 ,30], [40, 50, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]])
print(""Original array:"")
print(arr1)
temp = np.ma.masked_array(arr1,np.isnan(arr1))
result = np.mean(temp, axis=1)
print(""Averages without NaNs along the said array:"")
print(result.filled(np.nan))
"
1039,Write a Python program to create a dictionary with the unique values of a given list as keys and their frequencies as the values. ,"from collections import defaultdict
def frequencies(lst):
freq = defaultdict(int)
for val in lst:
freq[val] += 1
return dict(freq)
print(frequencies(['a', 'b', 'f', 'a', 'c', 'e', 'a', 'a', 'b', 'e', 'f']))
print(frequencies([3,4,7,5,9,3,4,5,0,3,2,3]))
"
1040,Write a Python program to find the most common element of a given list. ,"from collections import Counter
language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python','PHP', 'Python']
print(""Original list:"")
print(language)
cnt = Counter(language)
print(""\nMost common element of the said list:"")
print(cnt.most_common(1)[0][0])
"
1041,Write a python program to access environment variables and value of the environment variable. ,"import os
print(""Access all environment variables:"")
print('*----------------------------------*')
print(os.environ)
print('*----------------------------------*')
print(""Access a particular environment variable:"")
print(os.environ['HOME'])
print('*----------------------------------*')
print(os.environ['PATH'])
print('*----------------------------------*')
print('Value of the environment variable key:')
print(os.getenv('JAVA_HOME'))
print(os.getenv('PYTHONPATH'))
"
1042,Write a Python program to round every number of a given list of numbers and print the total sum multiplied by the length of the list. ,"nums = [22.4, 4.0, -16.22, -9.10, 11.00, -12.22, 14.20, -5.20, 17.50]
print(""Original list: "", nums)
print(""Result:"")
lenght=len(nums)
print(sum(list(map(round,nums))* lenght))
"
1043,Write a Python program to retrieve all descendants of the body tag from a given web page. ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nDescendants of the body tag (https://www.python.org):\n"")
root = soup.html
root_childs = [e.name for e in root.descendants if e.name is not None]
print(root_childs)
"
1044,Write a Pandas program to capitalize all the string values of specified columns of a given DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'name': ['alberto','gino','ryan', 'Eesha', 'syed'],
'date_of_birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
print(""\nAfter capitalizing name column:"")
df['name'] = list(map(lambda x: x.capitalize(), df['name']))
print(df)
"
1045,Write a Python program to check whether a given datetime is between two dates and times using arrow module. ,"import arrow
print(""Test whether a given datetime is between two dates and times:"")
start = arrow.get(datetime(2017, 6, 5, 12, 30, 10))
end = arrow.get(datetime(2017, 6, 5, 12, 30, 36))
print(arrow.get(datetime(2017, 6, 5, 12, 30, 27)).is_between(start, end))
start = arrow.get(datetime(2017, 5, 5))
end = arrow.get(datetime(2017, 5, 8))
print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[]'))
start = arrow.get(datetime(2017, 5, 5))
end = arrow.get(datetime(2017, 5, 8))
print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[)'))
"
1046,Write a Python program to get variable unique identification number or string. ,"x = 100
print(format(id(x), 'x'))
s = 'w3resource'
print(format(id(s), 'x'))
"
1047,Write a Python program to calculate number of days between two dates.,"from datetime import date
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)
"
1048,Write a Python program to create a string from two given strings concatenating uncommon characters of the said strings. ,"def uncommon_chars_concat(s1, s2):
set1 = set(s1)
set2 = set(s2)
common_chars = list(set1 & set2)
result = [ch for ch in s1 if ch not in common_chars] + [ch for ch in s2 if ch not in common_chars]
return(''.join(result))
s1 = 'abcdpqr'
s2 = 'xyzabcd'
print(""Original Substrings:\n"",s1+""\n"",s2)
print(""\nAfter concatenating uncommon characters:"")
print(uncommon_chars_concat(s1, s2))
"
1049,Write a Pandas program to create a Pivot table and find the item wise unit sold. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=[""Item""], values=""Units"", aggfunc=np.sum))
"
1050,Write a NumPy program to test whether all elements in an array evaluate to True. ,"import numpy as np
print(np.all([[True,False],[True,True]]))
print(np.all([[True,True],[True,True]]))
print(np.all([10, 20, 0, -50]))
print(np.all([10, 20, -50]))
"
1051,Write a Python program to remove leading zeros from an IP address. ,"def remove_zeros_from_ip(ip_add):
new_ip_add = ""."".join([str(int(i)) for i in ip_add.split(""."")])
return new_ip_add ;
print(remove_zeros_from_ip(""255.024.01.01""))
print(remove_zeros_from_ip(""127.0.0.01 ""))
"
1052,Write a NumPy program to convert specified inputs to arrays with at least one dimension. ,"import numpy as np
x= 12.0
print(np.atleast_1d(x))
x = np.arange(6.0).reshape(2, 3)
print(np.atleast_1d(x))
print(np.atleast_1d(1, [3, 4]))
"
1053,Write a Python program to split a given list into specified sized chunks using itertools module. ,"from itertools import islice
def split_list(lst, n):
lst = iter(lst)
result = iter(lambda: tuple(islice(lst, n)), ())
return list(result)
nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83]
print(""Original list:"")
print(nums)
n = 3
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
n = 4
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
n = 5
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
"
1054,Write a Python program to find all the link tags and list the first ten from the webpage python.org. ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""First four h2 tags from the webpage python.org.:"")
print(soup.find_all('a')[0:10])
"
1055,Write a Pandas program to check inequality over the index axis of a given dataframe and a given series. ,"import pandas as pd
df_data = pd.DataFrame({'W':[68,75,86,80,None],'X':[78,75,None,80,86], 'Y':[84,94,89,86,86],'Z':[86,97,96,72,83]});
sr_data = pd.Series([68, 75, 86, 80, None])
print(""Original DataFrame:"")
print(df_data)
print(""\nOriginal Series:"")
print(sr_data)
print(""\nCheck for inequality of the said series & dataframe:"")
print(df_data.ne(sr_data, axis = 0))
"
1056,Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2). ,"def insert_end(str):
sub_str = str[-2:]
return sub_str * 4
print(insert_end('Python'))
print(insert_end('Exercises'))
"
1057,"Write a Python program to display vertically each element of a given list, list of lists. ","text = [""a"", ""b"", ""c"", ""d"",""e"", ""f""]
print(""Original list:"")
print(text)
print(""\nDisplay each element vertically of the said list:"")
for i in text:
print(i)
nums = [[1, 2, 5], [4, 5, 8], [7, 3, 6]]
print(""Original list:"")
print(nums)
print(""\nDisplay each element vertically of the said list of lists:"")
for a,b,c in zip(*nums):
print(a, b, c)
"
1058,Write a Python program to check if the elements of a given list are unique or not. ,"def all_unique(test_list):
if len(test_list) > len(set(test_list)):
return False
return True
nums1 = [1,2,4,6,8,2,1,4,10,12,14,12,16,17]
print (""Original list:"")
print(nums1)
print(""\nIs the said list contains all unique elements!"")
print(all_unique(nums1))
nums2 = [2,4,6,8,10,12,14]
print (""\nOriginal list:"")
print(nums2)
print(""\nIs the said list contains all unique elements!"")
print(all_unique(nums2))
"
1059,Write a Python program to check if a nested list is a subset of another nested list. ,"def checkSubset(input_list1, input_list2):
return all(map(input_list1.__contains__, input_list2))
list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]]
list2 = [[1, 3],[13,15,17]]
print(""Original list:"")
print(list1)
print(list2)
print(""\nIf the one of the said list is a subset of another.:"")
print(checkSubset(list1, list2))
list1 = [
[
[1,2],[2,3]
],
[
[3,4],[5,6]
]
]
list2 = [
[
[3,4], [5, 6]
]
]
print(""Original list:"")
print(list1)
print(list2)
print(""\nIf the one of the said list is a subset of another.:"")
print(checkSubset(list1, list2))
list1 = [
[
[1,2],[2,3]
],
[
[3,4],[5,7]
]
]
list2 = [
[
[3,4], [5, 6]
]
]
print(""Original list:"")
print(list1)
print(list2)
print(""\nIf the one of the said list is a subset of another.:"")
print(checkSubset(list1, list2))
"
1060,"Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot comparing year, MSHA ID, Production and Labor_hours of first ten records. ","import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.head(10).plot(kind='bar', figsize=(20,8))
plt.show()
"
1061,"Write a NumPy program to add elements in a matrix. If an element in the matrix is 0, we will not add the element below this element. ","import numpy as np
def sum_matrix_Elements(m):
arra = np.array(m)
element_sum = 0
for p in range(len(arra)):
for q in range(len(arra[p])):
if arra[p][q] == 0 and p < len(arra)-1:
arra[p+1][q] = 0
element_sum += arra[p][q]
return element_sum
m = [[1, 1, 0, 2],
[0, 3, 0, 3],
[1, 0, 4, 4]]
print(""Original matrix:"")
print(m)
print(""Sum:"")
print(sum_matrix_Elements(m))
"
1062,"Write a Python program to get the minimum value of a list, after mapping each element to a value using a given function. ","def min_by(lst, fn):
return min(map(fn, lst))
print(min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
"
1063,"Write a NumPy program to find the number of elements of an array, length of one array element in bytes and total bytes consumed by the elements. ","import numpy as np
x = np.array([1,2,3], dtype=np.float64)
print(""Size of the array: "", x.size)
print(""Length of one array element in bytes: "", x.itemsize)
print(""Total bytes consumed by the elements of the array: "", x.nbytes)
"
1064,Create two arrays of six elements. Write a NumPy program to count the number of instances of a value occurring in one array on the condition of another array. ,"import numpy as np
x = np.array([10,-10,10,-10,-10,10])
y = np.array([.85,.45,.9,.8,.12,.6])
print(""Original arrays:"")
print(x)
print(y)
result = np.sum((x == 10) & (y > .5))
print(""\nNumber of instances of a value occurring in one array on the condition of another array:"")
print(result)
"
1065,Write a Python program to count the number 4 in a given list. ,"def list_count_4(nums):
count = 0
for num in nums:
if num == 4:
count = count + 1
return count
print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))"
1066,Write a Python script to merge two Python dictionaries. ,"d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)
print(d)
"
1067,Write a Pandas program to convert unix/epoch time to a regular time stamp in UTC. Also convert the said timestamp in to a given time zone. ,"import pandas as pd
epoch_t = 1621132355
time_stamp = pd.to_datetime(epoch_t, unit='s')
# UTC (Coordinated Universal Time) is one of the well-known names of UTC+0 time zone which is 0h.
# By default, time series objects of pandas do not have an assigned time zone.
print(""Regular time stamp in UTC:"")
print(time_stamp)
print(""\nConvert the said timestamp in to US/Pacific:"")
print(time_stamp.tz_localize('UTC').tz_convert('US/Pacific'))
print(""\nConvert the said timestamp in to Europe/Berlin:"")
print(time_stamp.tz_localize('UTC').tz_convert('Europe/Berlin'))
"
1068,Write a NumPy program to create random vector of size 15 and replace the maximum value by -1. ,"import numpy as np
x = np.random.random(15)
print(""Original array:"")
print(x)
x[x.argmax()] = -1
print(""Maximum value replaced by -1:"")
print(x)
"
1069,"Write a Python program to generate a random integer between 0 and 6 - excluding 6, random integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and random date between two dates. Use random.randrange()","import random
import datetime
print(""Generate a random integer between 0 and 6:"")
print(random.randrange(5))
print(""Generate random integer between 5 and 10, excluding 10:"")
print(random.randrange(start=5, stop=10))
print(""Generate random integer between 0 and 10, with a step of 3:"")
print(random.randrange(start=0, stop=10, step=3))
print(""\nRandom date between two dates:"")
start_dt = datetime.date(2019, 2, 1)
end_dt = datetime.date(2019, 3, 1)
time_between_dates = end_dt - start_dt
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_dt + datetime.timedelta(days=random_number_of_days)
print(random_date)
"
1070,Write a Pandas program to create a conversion between strings and datetime. ,"from datetime import datetime
from dateutil.parser import parse
print(""Convert datatime to strings:"")
stamp=datetime(2019,7,1)
print(stamp.strftime('%Y-%m-%d'))
print(stamp.strftime('%d/%b/%y'))
print(""\nConvert strings to datatime:"")
print(parse('Sept 17th 2019'))
print(parse('1/11/2019'))
print(parse('1/11/2019', dayfirst=True))
"
1071,Write a Python program to solve (x + y) * (x + y). ,"x, y = 4, 3
result = x * x + 2 * x * y + y * y
print(""({} + {}) ^ 2) = {}"".format(x, y, result))
"
1072,Write a Python program to get 90 days of visits broken down by browser for all sites on data.gov. ,"from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen(""https://en.wikipedia.org/wiki/Python"")
bsObj = BeautifulSoup(html)
for link in bsObj.findAll(""a""):
if 'href' in link.attrs:
print(link.attrs['href'])
"
1073,Write a Pandas program to extract only phone number 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({
'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
'company_phone_no': ['Company1-Phone no. 4695168357','Company2-Phone no. 8088729013','Company3-Phone no. 6204658086', 'Company4-Phone no. 5159530096', 'Company5-Phone no. 9037952371']
})
print(""Original DataFrame:"")
print(df)
def find_phone_number(text):
ph_no = re.findall(r""\b\d{10}\b"",text)
return """".join(ph_no)
df['number']=df['company_phone_no'].apply(lambda x: find_phone_number(x))
print(""\Extracting numbers from dataframe columns:"")
print(df)
"
1074,Write a Pandas program to split a given dataframe into groups and display target column as a list of unique values. ,"import pandas as pd
df = pd.DataFrame( {'id' : ['A','A','A','A','A','A','B','B','B','B','B'],
'type' : [1,1,1,1,2,2,1,1,1,2,2],
'book' : ['Math','Math','English','Physics','Math','English','Physics','English','Physics','English','English']})
print(""Original DataFrame:"")
print(df)
new_df = df[['id', 'type', 'book']].drop_duplicates()\
.groupby(['id','type'])['book']\
.apply(list)\
.reset_index()
new_df['book'] = new_df.apply(lambda x: (','.join([str(s) for s in x['book']])), axis = 1)
print(""\nList all unique values in a group:"")
print(new_df)
"
1075,Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda. ,"def sort_matrix(M):
result = sorted(M, key=lambda matrix_row: sum(matrix_row))
return result
matrix1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
matrix2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
print(""Original Matrix:"")
print(matrix1)
print(""\nSort the said matrix in ascending order according to the sum of its rows"")
print(sort_matrix(matrix1))
print(""\nOriginal Matrix:"")
print(matrix2)
print(""\nSort the said matrix in ascending order according to the sum of its rows"")
print(sort_matrix(matrix2))
"
1076,Write a Python program to group a sequence of key-value pairs into a dictionary of lists. ,"from collections import defaultdict
class_roll = [('v', 1), ('vi', 2), ('v', 3), ('vi', 4), ('vii', 1)]
d = defaultdict(list)
for k, v in class_roll:
d[k].append(v)
print(sorted(d.items()))
"
1077,Write a Pandas program to drop the columns where at least one element is missing 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,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',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nDrop the columns where at least one element is missing:"")
result = df.dropna(axis='columns')
print(result)
"
1078,Write a Python program to get the maximum and minimum value in a dictionary. ,"my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
"
1079,Write a NumPy program to split of an array of shape 4x4 it into two arrays along the second axis. ,"import numpy as np
x = np.arange(16).reshape((4, 4))
print(""Original array:"",x)
print(""After splitting horizontally:"")
print(np.hsplit(x, [2, 6]))
"
1080,Write a Pandas program to split a given dataframe into groups and create a new column with count from GroupBy. ,"import pandas as pd
pd.set_option('display.max_rows', None)
df = pd.DataFrame({
'book_name':['Book1','Book2','Book3','Book4','Book1','Book2','Book3','Book5'],
'book_type':['Math','Physics','Computer','Science','Math','Physics','Computer','English'],
'book_id':[1,2,3,4,1,2,3,5]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nNew column with count from groupby:"")
result = df.groupby([""book_name"", ""book_type""])[""book_type""].count().reset_index(name=""count"")
print(result)
"
1081,"Write a Pandas program to create a Pivot table and find the probability of survival by class, gender, solo boarding and port of embarkation. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', ['sex' , 'alone' ], [ 'embark_town', 'class' ])
print(result)
"
1082,"Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself. ","def change_char(str1):
char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
"
1083,Write a NumPy program to create two arrays of size bigger and smaller than a given array. ,"import numpy as np
x = np.arange(16).reshape(4,4)
print(""Original arrays:"")
print(x)
print(""\nArray with size 2x2 from the said array:"")
new_array1 = np.resize(x,(2,2))
print(new_array1)
print(""\nArray with size 6x6 from the said array:"")
new_array2 = np.resize(x,(6,6))
print(new_array2)
"
1084,"Write a Pandas program to find out the records where consumption of beverages per person average >=4 and Beverage Types is Beer, Wine, Spirits from 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: average consumption of \nbeverages per person >=4 and Beverage Types is Beer:"")
print(w_a_con[(w_a_con['Display Value'] >= 4) & ((w_a_con['Beverage Types'] == 'Beer') | (w_a_con['Beverage Types'] == 'Wine')| (w_a_con['Beverage Types'] == 'Spirits'))].head(10))
"
1085,"Write a NumPy program to create a three-dimension array with shape (300,400,5) and set to a variable. Fill the array elements with values using unsigned integer (0 to 255). ","import numpy as np
np.random.seed(32)
nums = np.random.randint(low=0, high=256, size=(300, 400, 5), dtype=np.uint8)
print(nums)
"
1086,Write a Python program to check a dictionary is empty or not. ,"my_dict = {}
if not bool(my_dict):
print(""Dictionary is empty"")
"
1087,"Write a NumPy program to count the number of ""P"" in a given array, element-wise. ","import numpy as np
x1 = np.array(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str)
print(""\nOriginal Array:"")
print(x1)
print(""Number of ‘P’:"")
r = np.char.count(x1, ""P"")
print(r)
"
1088,"Write a Python program to calculate the sum of a list, after mapping each element to a value using the provided function. ","def sum_by(lst, fn):
return sum(map(fn, lst))
print(sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
"
1089,Write a Pandas program to create a comparison of the top 10 years in which the UFO was sighted vs each Month. ,"import pandas as pd
#Source: https://bit.ly/1l9yjm9
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
most_sightings_years = df['Date_time'].dt.year.value_counts().head(10)
def is_top_years(year):
if year in most_sightings_years.index:
return year
month_vs_year = df.pivot_table(columns=df['Date_time'].dt.month,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city')
month_vs_year.index = month_vs_year.index.astype(int)
month_vs_year.columns = month_vs_year.columns.astype(int)
print(""\nComparison of the top 10 years in which the UFO was sighted vs each month:"")
print(month_vs_year.head(10))
"
1090,Write a NumPy program to remove single-dimensional entries from a specified shape. ,"import numpy as np
x = np.zeros((3, 1, 4))
print(np.squeeze(x).shape)
"
1091,Write a Python code to send cookies to a given server and access cookies from the response of a server. ,"import requests
url = 'http://httpbin.org/cookies'
# A dictionary (my_cookies) of cookies to send to the specified url.
my_cookies = dict(cookies_are='Cookies parameter use to send cookies to the server')
r = requests.get(url, cookies = my_cookies)
print(r.text)
# Accessing cookies with Requests
# url = 'http://WebsiteName/cookie/setting/url'
# res = requests.get(url)
# Value of cookies
# print(res.cookies['cookie_name'])
"
1092,"Write a Pandas program to split a dataset, group by one column and get mean, min, and max values by group. Using the following dataset find the mean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id). ","import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
orders_data = 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':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print(""Original Orders DataFrame:"")
print(orders_data)
result = orders_data.groupby('customer_id').agg({'purch_amt': ['mean', 'min', 'max']})
print(""\nMean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id)."")
print(result)
"
1093,Write a Python program to sort a tuple by its float element. ,"price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
print( sorted(price, key=lambda x: float(x[1]), reverse=True))
"
1094,Write a NumPy program to get the element-wise remainder of an array of division. ,"import numpy as np
x = np.arange(7)
print(""Original array:"")
print(x)
print(""Element-wise remainder of division:"")
print(np.remainder(x, 5))
"
1095,"Write a Python program to get string representing the date, controlled by an explicit format string. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nString representing the date, controlled by an explicit format string:"")
print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
"
1096,Write a Python program to remove a specified column from a given nested list. ,"def remove_column(nums, n):
for i in nums:
del i[n]
return nums
list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
n = 0
print(""Original Nested list:"")
print(list1)
print(""After removing 1st column:"")
print(remove_column(list1, n))
list2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
n = 2
print(""\nOriginal Nested list:"")
print(list2)
print(""After removing 3rd column:"")
print(remove_column(list2, n))
"
1097,Write a Python program to count the frequency of words in a file. ,"from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print(""Number of words in the file :"",word_count(""test.txt""))
"
1098,Write a Python program to chunk a given list into smaller lists of a specified size. ,"from math import ceil
def chunk_list(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(ceil(len(lst) / size)))))
print(chunk_list([1, 2, 3, 4, 5, 6, 7, 8], 3))
"
1099,"Write a NumPy program to create a 4x4 array, now create a new array from the said array swapping first and last, second and third columns. ","import numpy as np
nums = np.arange(16, dtype='int').reshape(-1, 4)
print(""Original array:"")
print(nums)
print(""\nNew array after swapping first and last columns of the said array:"")
new_nums = nums[:, ::-1]
print(new_nums)
"
1100,"Write a Python program to create a time object with the same hour, minute, second, microsecond and a timestamp representation of the Arrow object, in UTC time. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nTime object with the same hour, minute, second, microsecond:"")
print(arrow.utcnow().time())
print(""\nTimestamp representation of the Arrow object, in UTC time:"")
print(arrow.utcnow().timestamp)
"
1101,Write a Python program to get the proleptic Gregorian ordinal of a given date. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\nProleptic Gregorian ordinal of the date:"")
print(arrow.utcnow().toordinal())
"
1102,Write a Python program to capitalize first and last letters of each word of a given string. ,"def capitalize_first_last_letters(str1):
str1 = result = str1.title()
result = """"
for word in str1.split():
result += word[:-1] + word[-1].upper() + "" ""
return result[:-1]
print(capitalize_first_last_letters(""python exercises practice solution""))
print(capitalize_first_last_letters(""w3resource""))
"
1103,Write a Python program to find if a given string starts with a given character using Lambda. ,"starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Python'))
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Java'))
"
1104,Write a Python program to read a given string character by character and compress repeated character by storing the length of those character(s). ,"from itertools import groupby
def encode_str(input_str):
return [(len(list(n)), m) for m,n in groupby(input_str)]
str1 = ""AAASSSSKKIOOOORRRREEETTTTAAAABBBBBBDDDDD""
print(""Original string:"")
print(str1)
print(""Result:"")
print(encode_str(str1))
str1 = ""jjjjiiiiooooosssnssiiiiwwwweeeaaaabbbddddkkkklll""
print(""\nOriginal string:"")
print(str1)
print(""Result:"")
print(encode_str(str1))
"
1105,Write a NumPy program to create a 3x3x3 array filled with arbitrary values. ,"import numpy as np
x = np.random.random((3, 3, 3))
print(x)
"
1106,Write a Python program to print a variable without spaces between values. ,"x = 30
print('Value of x is ""{}""'.format(x))
"
1107,Write a Python function to reverses a string if it's length is a multiple of 4. ,"def reverse_string(str1):
if len(str1) % 4 == 0:
return ''.join(reversed(str1))
return str1
print(reverse_string('abcd'))
print(reverse_string('python'))
"
1108,Write a NumPy program to convert angles from radians to degrees for all elements in a given array. ,"import numpy as np
x = np.array([-np.pi, -np.pi/2, np.pi/2, np.pi])
r1 = np.degrees(x)
r2 = np.rad2deg(x)
assert np.array_equiv(r1, r2)
print(r1)
"
1109,Write a NumPy program to extract all the contiguous 4x4 blocks from a given random 12x12 matrix. ,"import numpy as np
arra1 = np.random.randint(0,5,(12,12))
print(""Original arrays:"")
print(arra1)
n = 4
i = 1 + (arra1.shape[0]-4)
j = 1 + (arra1.shape[1]-4)
result = np.lib.stride_tricks.as_strided(arra1, shape=(i, j, n, n), strides = arra1.strides + arra1.strides)
print(""\nContiguous 4x4 blocks:"")
print(result)
"
1110,Write a Python program to compute the greatest common divisor (GCD) of two positive integers. ,"def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print(""GCD of 12 & 17 ="",gcd(12, 17))
print(""GCD of 4 & 6 ="",gcd(4, 6))
print(""GCD of 336 & 360 ="",gcd(336, 360))
"
1111,"Write a NumPy program to change the sign of a given array to that of a given array, element-wise. ","import numpy as np
x1 = np.array([-1, 0, 1, 2])
print(""Original array: "")
print(x1)
x2 = -2.1
print(""\nSign of x1 to that of x2, element-wise:"")
print(np.copysign(x1, x2))
"
1112,Write a Python program to sort a given list of lists by length and value. ,"def sort_sublists(input_list):
input_list.sort() # sort by sublist contents
input_list.sort(key=len)
return input_list
list1 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]
print(""Original list:"")
print(list1)
print(""\nSort the list of lists by length and value:"")
print(sort_sublists(list1))
"
1113,Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda. ,"def average_tuple(nums):
result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
return result
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print (""Original Tuple: "")
print(nums)
print(""\nAverage value of the numbers of the said tuple of tuples:\n"",average_tuple(nums))
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
print (""\nOriginal Tuple: "")
print(nums)
print(""\nAverage value of the numbers of the said tuple of tuples:\n"",average_tuple(nums))
"
1114,Write a NumPy program to change the dimension of an array. ,"import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
print(""6 rows and 0 columns"")
print(x.shape)
y = np.array([[1, 2, 3],[4, 5, 6],[7,8,9]])
print(""(3, 3) -> 3 rows and 3 columns "")
print(y)
x = np.array([1,2,3,4,5,6,7,8,9])
print(""Change array shape to (3, 3) -> 3 rows and 3 columns "")
x.shape = (3, 3)
print(x)
"
1115,Write a Pandas program to replace missing white spaces in a given string with the least frequent character. ,"import pandas as pd
str1 = 'abc def abcdef icd'
print(""Original series:"")
print(str1)
ser = pd.Series(list(str1))
element_freq = ser.value_counts()
print(element_freq)
current_freq = element_freq.dropna().index[-1]
result = """".join(ser.replace(' ', current_freq))
print(result)
"
1116,Write a Pandas program to remove the time zone information from a Time series data. ,"import pandas as pd
date1 = pd.Timestamp('2019-01-01', tz='Europe/Berlin')
date2 = pd.Timestamp('2019-01-01', tz='US/Pacific')
date3 = pd.Timestamp('2019-01-01', tz='US/Eastern')
print(""Time series data with time zone:"")
print(date1)
print(date2)
print(date3)
print(""\nTime series data without time zone:"")
print(date1.tz_localize(None))
print(date2.tz_localize(None))
print(date3.tz_localize(None))
"
1117,Write a Python program to print the calendar of a given month and year.,"import calendar
y = int(input(""Input the year : ""))
m = int(input(""Input the month : ""))
print(calendar.month(y, m))"
1118,Write a Python program to count the number of lines in a text file. ,"def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(""Number of lines in the file: "",file_lengthy(""test.txt""))
"
1119,Write a NumPy program to check element-wise True/False of a given array where signbit is set. ,"import numpy as np
x = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
print(""Original array: "")
print(x)
r1 = np.signbit(x)
r2 = x < 0
assert np.array_equiv(r1, r2)
print(r1)
"
1120,"Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum. ","def sum_thrice(x, y, z):
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
"
1121,Write a Python program to sort unsorted numbers using Patience sorting. ,"#Ref.https://bit.ly/2YiegZB
from bisect import bisect_left
from functools import total_ordering
from heapq import merge
@total_ordering
class Stack(list):
def __lt__(self, other):
return self[-1] < other[-1]
def __eq__(self, other):
return self[-1] == other[-1]
def patience_sort(collection: list) -> list:
stacks = []
# sort into stacks
for element in collection:
new_stacks = Stack([element])
i = bisect_left(stacks, new_stacks)
if i != len(stacks):
stacks[i].append(element)
else:
stacks.append(new_stacks)
# use a heap-based merge to merge stack efficiently
collection[:] = merge(*[reversed(stack) for stack in stacks])
return collection
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
patience_sort(nums)
print(""Sorted order is:"", nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
patience_sort(nums)
print(""Sorted order is:"", nums)
"
1122,Write a Pandas program to filter those records which not appears in a given list from world alcohol consumption dataset. ,"import pandas as pd
# World alcohol consumption data
new_w_a_con = pd.read_csv('world_alcohol.csv')
print(""World alcohol consumption sample data:"")
print(new_w_a_con.head())
print(""\nSelect all rows which not appears in a given list:"")
who_region = [""Africa"", ""Eastern Mediterranean"", ""Europe""]
flt_wine = ~new_w_a_con[""WHO region""].isin(who_region)
print(new_w_a_con[flt_wine])
"
1123,"Write a Pandas program to create a Pivot table and count survival by gender, categories wise age of various classes. ","import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
age = pd.cut(df['age'], [0, 10, 30, 60, 80])
result = df.pivot_table('survived', index=['sex',age], columns='pclass', aggfunc='count')
print(result)
"
1124,Write a NumPy program to round elements of the array to the nearest integer. ,"import numpy as np
x = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0])
print(""Original array:"")
print(x)
x = np.rint(x)
print(""Round elements of the array to the nearest integer:"")
print(x)
"
1125,Write a Pandas program to count the missing 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nTotal missing values in a dataframe:"")
tot_missing_vals = df.isnull().sum().sum()
print(tot_missing_vals)
"
1126,Write a Python program to remove all the values except integer values from a given array of mixed values. ,"def test(lst):
return [lst for lst in lst if isinstance(lst, int)]
mixed_list = [34.67, 12, -94.89, ""Python"", 0, ""C#""]
print(""Original list:"", mixed_list)
print(""After removing all the values except integer values from the said array of mixed values:"")
print(test(mixed_list))
"
1127,Write a Python program to calculate the sum of two lowest negative numbers of a given array of integers. ,"def test(nums):
result = sorted([item for item in nums if item < 0])
return result[0]+result[1]
nums = [-14, 15, -10, -11, -12, -13, 16, 17, 18, 19, 20]
print(""Original list elements:"")
print(nums)
print(""Sum of two lowest negative numbers of the said array of integers: "",test(nums))
nums = [-4, 5, -2, 0, 3, -1, 4 , 9]
print(""\nOriginal list elements:"")
print(nums)
print(""Sum of two lowest negative numbers of the said array of integers: "",test(nums))
"
1128,Write a Python program to convert a given list of lists to a dictionary. ,"def test(lst):
result = {item[0]: item[1:] for item in lst}
return result
students = [[1, 'Jean Castro', 'V'], [2, 'Lula Powell', 'V'], [3, 'Brian Howell', 'VI'], [4, 'Lynne Foster', 'VI'], [5, 'Zachary Simon', 'VII']]
print(""\nOriginal list of lists:"")
print(students)
print(""\nConvert the said list of lists to a dictionary:"")
print(test(students))
"
1129,Write a Python program to extract a given number of randomly selected elements from a given list. ,"import random
def random_select_nums(n_list, n):
return random.sample(n_list, n)
n_list = [1,1,2,3,4,4,5,1]
print(""Original list:"")
print(n_list)
selec_nums = 3
result = random_select_nums(n_list, selec_nums)
print(""\nSelected 3 random numbers of the above list:"")
print(result)
"
1130," Write a Python program to that retrieves an arbitary Wikipedia page of ""Python"" and creates a list of links on that page. ","from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html.read(), ""lxml"")
title = bsObj.body.h1
except AttributeError as e:
return None
return title
title = getTitle(url)
if title == None:
return ""Title could not be found""
else:
return title
print(getTitle(""https://www.w3resource.com/""))
print(getTitle(""http://www.example.com/""))
"
1131,Write a Python program to alter the owner and the group id of a specified file. ,"import os
fd = os.open( ""/tmp"", os.O_RDONLY )
os.fchown( fd, 100, -1)
os.fchown( fd, -1, 50)
print(""Changed ownership successfully.."")
os.close( fd )
"
1132,"Write a NumPy program to create a two-dimensional array with shape (8,5) of random numbers. Select random numbers from a normal distribution (200,7). ","import numpy as np
np.random.seed(20)
cbrt = np.cbrt(7)
nd1 = 200
print(cbrt * np.random.randn(10, 4) + nd1)
"
1133,Write a Python program to multiply two integers without using the * operator in python. ,"def multiply(x, y):
if y < 0:
return -multiply(x, -y)
elif y == 0:
return 0
elif y == 1:
return x
else:
return x + multiply(x, y - 1)
print(multiply(3, 5));
"
1134,Write a Pandas program to extract email from a specified column of string type of a given DataFrame. ,"import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'name_email': ['Alberto Franco [email protected]','Gino Mcneill [email protected]','Ryan Parkes [email protected]', 'Eesha Hinton', 'Gino Mcneill [email protected]']
})
print(""Original DataFrame:"")
print(df)
def find_email(text):
email = re.findall(r'[\w\.-][email protected][\w\.-]+',str(text))
return "","".join(email)
df['email']=df['name_email'].apply(lambda x: find_email(x))
print(""\Extracting email from dataframe columns:"")
print(df)
"
1135,Write a Python program to read a given CSV files with initial spaces after a delimiter and remove those initial spaces. ,"import csv
print(""\nWith initial spaces after a delimiter:\n"")
with open('departments.csv', 'r') as csvfile:
data = csv.reader(csvfile, skipinitialspace=False)
for row in data:
print(', '.join(row))
print(""\n\nWithout initial spaces after a delimiter:\n"")
with open('departments.csv', 'r') as csvfile:
data = csv.reader(csvfile, skipinitialspace=True)
for row in data:
print(', '.join(row))
"
1136,"Write a Pandas program to split a given dataset, group by one column and remove those groups if all the values of a specific columns are not available. ","import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'weight': [173, 192, 186, 167, 151, 159],
'height': [35, None, 33, 30, None, 32]},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(df)
print(""\nGroup by one column and remove those groups if all the values of a specific columns are not available:"")
result = df[(~df['height'].isna()).groupby(df['school_code']).transform('any')]
print(result)
"
1137,Write a Python program to check whether a string starts with specified characters.,"string = ""w3resource.com""
print(string.startswith(""w3r""))
"
1138,Write a NumPy program to get the largest integer smaller or equal to the division of the inputs. ,"import numpy as np
x = [1., 2., 3., 4.]
print(""Original array:"")
print(x)
print(""Largest integer smaller or equal to the division of the inputs:"")
print(np.floor_divide(x, 1.5))
"
1139,Write a Python program to calculate the maximum aggregate from the list of tuples (pairs). ,"from collections import defaultdict
def max_aggregate(st_data):
temp = defaultdict(int)
for name, marks in st_data:
temp[name] += marks
return max(temp.items(), key=lambda x: x[1])
students = [('Juan Whelan',90),('Sabah Colley',88),('Peter Nichols',7),('Juan Whelan',122),('Sabah Colley',84)]
print(""Original list:"")
print(students)
print(""\nMaximum aggregate value of the said list of tuple pair:"")
print(max_aggregate(students))
"
1140,"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)
"
1141,Write a NumPy program to split array into multiple sub-arrays along the 3rd axis. ,"import numpy as np
print(""\nOriginal arrays:"")
x = np.arange(16.0).reshape(2, 2, 4)
print(x)
new_array1 = np.dsplit(x, 2)
print(""\nsplit array into multiple sub-arrays along the 3rd axis:"")
print(new_array1)
"
1142,Write a NumPy program to change the data type of an array. ,"import numpy as np
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)
print(x)
print(""Data type of the array x is:"",x.dtype)
# Change the data type of x
y = x.astype(float)
print(""New Type: "",y.dtype)
print(y)
"
1143,"Write a NumPy program to Create a 1-D array of 30 evenly spaced elements between 2.5. and 6.5, inclusive. ","import numpy as np
x = np.linspace(2.5, 6.5, 30)
print(x)
"
1144,Write a Pandas program to drop the rows where all elements are missing 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,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[np.nan,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': [np.nan,'2012-09-10',np.nan,'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':[np.nan,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nDrop the rows where all elements are missing:"")
result = df.dropna(how='all')
print(result)
"
1145,Write a Pandas program to remove repetitive characters 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({
'text_code': ['t0001.','t0002','t0003', 't0004'],
'text_lang': ['She livedd a long life.', 'How oold is your father?', 'What is tthe problem?','TThhis desk is used by Tom.']
})
print(""Original DataFrame:"")
print(df)
def rep_char(str1):
tchr = str1.group(0)
if len(tchr) > 1:
return tchr[0:1] # can change the value here on repetition
def unique_char(rep, sent_text):
convert = re.sub(r'(\w)\1+', rep, sent_text)
return convert
df['normal_text']=df['text_lang'].apply(lambda x : unique_char(rep_char,x))
print(""\nRemove repetitive characters:"")
print(df)
"
1146,Write a Python program to remove the specific item from a given list of lists. ,"import copy
def remove_list_of_lists(color, N):
for x in color:
del x[N]
return color
nums = [
[""Red"",""Maroon"",""Yellow"",""Olive""],
[""#FF0000"", ""#800000"", ""#FFFF00"", ""#808000""],
[""rgb(255,0,0)"",""rgb(128,0,0)"",""rgb(255,255,0)"",""rgb(128,128,0)""]
]
nums1 = copy.deepcopy(nums)
nums2 = copy.deepcopy(nums)
nums3 = copy.deepcopy(nums)
print(""Original list of lists:"")
print(nums)
N = 0
print(""\nRemove 1st item from the said list of lists:"")
print(remove_list_of_lists(nums1, N))
N = 1
print(""\nRemove 2nd item from the said list of lists:"")
print(remove_list_of_lists(nums2, N))
N = 3
print(""\nRemove 4th item from the said list of lists:"")
print(remove_list_of_lists(nums3, N))
"
1147,Write a Pandas program to convert a given Series to an array. ,"import pandas as pd
import numpy as np
s1 = pd.Series(['100', '200', 'python', '300.12', '400'])
print(""Original Data Series:"")
print(s1)
print(""Series to an array"")
a = np.array(s1.values.tolist())
print (a)
"
1148,Write a NumPy program to split the element of a given array with spaces. ,"import numpy as np
x = np.array(['Python PHP Java C++'], dtype=np.str)
print(""Original Array:"")
print(x)
r = np.char.split(x)
print(""\nSplit the element of the said array with spaces: "")
print(r)
"
1149,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))
"
1150,Write a Python program to check if a given element occurs at least n times in a list. ,"def check_element_in_list(lst, x, n):
t = 0
try:
for _ in range(n):
t = lst.index(x, t) + 1
return True
except ValueError:
return False
nums = [0,1,3,5,0,3,4,5,0,8,0,3,6,0,3,1,1,0]
print(""Original list:"")
print(nums)
x = 3
n = 4
print(""\nCheck if"",x,""occurs at least"",n,""times in a list:"")
print(check_element_in_list(nums,x,n))
x = 0
n = 5
print(""\nCheck if"",x,""occurs at least"",n,""times in a list:"")
print(check_element_in_list(nums,x,n))
x = 8
n = 3
print(""\nCheck if"",x,""occurs at least"",n,""times in a list:"")
print(check_element_in_list(nums,x,n))
"
1151,Write a Python program to find maximum length of consecutive 0's in a given binary string. ,"def max_consecutive_0(input_str):
return max(map(len,input_str.split('1')))
str1 = '111000010000110'
print(""Original string:"" + str1)
print(""Maximum length of consecutive 0’s:"")
print(max_consecutive_0(str1))
str1 = '111000111'
print(""Original string:"" + str1)
print(""Maximum length of consecutive 0’s:"")
print(max_consecutive_0(str1))
"
1152,Write a python program to find the next smallest palindrome of a specified number. ,"import sys
def Next_smallest_Palindrome(num):
numstr = str(num)
for i in range(num+1,sys.maxsize):
if str(i) == str(i)[::-1]:
return i
print(Next_smallest_Palindrome(99));
print(Next_smallest_Palindrome(1221));
"
1153,Write a Python program to generate an infinite cycle of elements from an iterable. ,"import itertools as it
def cycle_data(iter):
return it.cycle(iter)
# Following loops will run for ever
#List
result = cycle_data(['A','B','C','D'])
print(""The said function print never-ending items:"")
for i in result:
print(i)
#String
result = cycle_data('Python itertools')
print(""The said function print never-ending items:"")
for i in result:
print(i)
"
1154,Write a NumPy program to test whether any of the elements of a given array is non-zero. ,"import numpy as np
x = np.array([1, 0, 0, 0])
print(""Original array:"")
print(x)
print(""Test whether any of the elements of a given array is non-zero:"")
print(np.any(x))
x = np.array([0, 0, 0, 0])
print(""Original array:"")
print(x)
print(""Test whether any of the elements of a given array is non-zero:"")
print(np.any(x))
"
1155,Write a Python program to get the array size of types unsigned integer and float. ,"from array import array
a = array(""I"", (12,25))
print(a.itemsize)
a = array(""f"", (12.236,36.36))
print(a.itemsize)
"
1156,Write a Python program to print the index of the character in a string. ,"str1 = ""w3resource""
for index, char in enumerate(str1):
print(""Current character"", char, ""position at"", index )
"
1157,Write a Python program to parse a given CSV string and get the list of lists of string values. Use csv.reader,"import csv
csv_string = """"""1,2,3
4,5,6
7,8,9
""""""
print(""Original string:"")
print(csv_string)
lines = csv_string.splitlines()
print(""List of CSV formatted strings:"")
print(lines)
reader = csv.reader(lines)
parsed_csv = list(reader)
print(""\nList representation of the CSV file:"")
print(parsed_csv)
"
1158,"Write a Pandas program to filter all records starting from the 'Year' column, access every other column from 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(""\nFrom the 'Year' column, access every other column:"")
print(w_a_con.loc[:,'Year'::2].head(10))
print(""\nAlternate solution:"")
print(w_a_con.iloc[:,0::2].head(10))
"
1159,"Write a Pandas program to get the current date, oldest date and number of days between Current date and oldest date of Ufo dataset. ","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(""\nCurrent date of Ufo dataset:"")
print(df.Date_time.max())
print(""\nOldest date of Ufo dataset:"")
print(df.Date_time.min())
print(""\nNumber of days between Current date and oldest date of Ufo dataset:"")
print((df.Date_time.max() - df.Date_time.min()).days)
"
1160,Write a Python program to filter even numbers from a given dictionary values. ,"def test(dictt):
result = {key: [idx for idx in val if not idx % 2]
for key, val in dictt.items()}
return result
students = {'V' : [1, 4, 6, 10], 'VI' : [1, 4, 12], 'VII' : [1, 3, 8]}
print(""\nOriginal Dictionary:"")
print(students)
print(""Filter even numbers from said dictionary values:"")
print(test(students))
students = {'V' : [1, 3, 5], 'VI' : [1, 5], 'VII' : [2, 7, 9]}
print(""\nOriginal Dictionary:"")
print(students)
print(""Filter even numbers from said dictionary values:"")
print(test(students))
"
1161,Write a Pandas program to split the following dataset using group by on first column and aggregate over multiple lists on second column. ,"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({
'student_id': ['S001','S001','S002','S002','S003','S003'],
'marks': [[88,89,90],[78,81,60],[84,83,91],[84,88,91],[90,89,92],[88,59,90]]})
print(""Original DataFrame:"")
print(df)
print(""\nGroupby and aggregate over multiple lists:"")
result = df.set_index('student_id')['marks'].groupby('student_id').apply(list).apply(lambda x: np.mean(x,0))
print(result)
"
1162,Write a NumPy program to calculate the arithmetic means of corresponding elements of two given arrays of same size. ,"import numpy as np
nums1 = np.array([[2, 5, 2],
[1, 5, 5]])
nums2 = np.array([[5, 3, 4],
[3, 2, 5]])
print(""Array1:"")
print(nums1)
print(""Array2:"")
print(nums2)
print(""\nArithmetic means of corresponding elements of said two arrays:"")
print(np.divide(np.add(nums1, nums2), 2))
"
1163,Write a Python program to count the number of sublists contain a particular element. ,"def count_element_in_list(input_list, x):
ctr = 0
for i in range(len(input_list)):
if x in input_list[i]:
ctr+= 1
return ctr
list1 = [[1, 3], [5, 7], [1, 11], [1, 15, 7]]
print(""Original list:"")
print(list1)
print(""\nCount 1 in the said list:"")
print(count_element_in_list(list1, 1))
print(""\nCount 7 in the said list:"")
print(count_element_in_list(list1, 7))
list1 = [['A', 'B'], ['A', 'C'], ['A', 'D', 'E'], ['B', 'C', 'D']]
print(""\nOriginal list:"")
print(list1)
print(""\nCount 'A' in the said list:"")
print(count_element_in_list(list1, 'A'))
print(""\nCount 'E' in the said list:"")
print(count_element_in_list(list1, 'E'))
"
1164,"Write a NumPy program to create a three-dimension array with shape (3,5,4) and set to a variable. ","import numpy as np
nums = np.array([[[1, 5, 2, 1],
[4, 3, 5, 6],
[6, 3, 0, 6],
[7, 3, 5, 0],
[2, 3, 3, 5]],
[[2, 2, 3, 1],
[4, 0, 0, 5],
[6, 3, 2, 1],
[5, 1, 0, 0],
[0, 1, 9, 1]],
[[3, 1, 4, 2],
[4, 1, 6, 0],
[1, 2, 0, 6],
[8, 3, 4, 0],
[2, 0, 2, 8]]])
print(""Array:"")
print(nums)
"
1165,Write a NumPy program to create random set of rows from 2D array. ,"import numpy as np
new_array = np.random.randint(5, size=(5,3))
print(""Random set of rows from 2D array array:"")
print(new_array)
"
1166,"Write a Python program to get the difference between two given lists, after applying the provided function to each list element of both. ","def difference_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) not in _b]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor))
print(difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']))
"
1167,Write a Pandas program to create a Pivot table and calculate number of women and men were in a particular cabin class. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index=['sex'], columns=['pclass'], aggfunc='count')
print(result)
"
1168,"Write a Python program to get a new string from a given string where ""Is"" has been added to the front. If the given string already begins with ""Is"" then return the string unchanged. ","def new_string(str):
if len(str) >= 2 and str[:2] == ""Is"":
return str
return ""Is"" + str
print(new_string(""Array""))
print(new_string(""IsEmpty""))
"
1169,Write a Python program to remove all elements from a given list present in another list. ,"def index_on_inner_list(list1, list2):
result = [x for x in list1 if x not in list2]
return result
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [2,4,6,8]
print(""Original lists:"")
print(""list1:"", list1)
print(""list2:"", list2)
print(""\nRemove all elements from 'list1' present in 'list2:"")
print(index_on_inner_list(list1, list2))
"
1170,Write a Python program to concatenate all elements in a list into a string and return it. ,"def concatenate_list_data(list):
result= ''
for element in list:
result += str(element)
return result
print(concatenate_list_data([1, 5, 12, 2]))
"
1171,Write a Pandas program to select a specific row of given series/dataframe by integer index. ,"import pandas as pd
ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8])
print(""Original Series:"")
print(ds)
print(""\nPrint specified row from the said series using location based indexing:"")
print(""\nThird row:"")
print(ds.iloc[[2]])
print(""\nFifth row:"")
print(ds.iloc[[4]])
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 32, 33, 30, 31, 32]})
print(""Original DataFrame with single index:"")
print(df)
print(""\nPrint specified row from the said DataFrame using location based indexing:"")
print(""\nThird row:"")
print(df.iloc[[2]])
print(""\nFifth row:"")
print(df.iloc[[4]])
"
1172,"Write a Python program to check if a function is a user-defined function or not. Use types.FunctionType, types.LambdaType()","import types
def func():
return 1
print(isinstance(func, types.FunctionType))
print(isinstance(func, types.LambdaType))
print(isinstance(lambda x: x, types.FunctionType))
print(isinstance(lambda x: x, types.LambdaType))
print(isinstance(max, types.FunctionType))
print(isinstance(max, types.LambdaType))
print(isinstance(abs, types.FunctionType))
print(isinstance(abs, types.LambdaType))
"
1173,Write a Python program to match key values in two dictionaries. ,"x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
"
1174,Write a Python program to add a prefix text to all of the lines in a string. ,"import textwrap
sample_text ='''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
text_without_Indentation = textwrap.dedent(sample_text)
wrapped = textwrap.fill(text_without_Indentation, width=50)
#wrapped += '\n\nSecond paragraph after a blank line.'
final_result = textwrap.indent(wrapped, '> ')
print()
print(final_result)
print()
"
1175,Write a Python program to move a specified element in a given list. ,"def group_similar_items(seq,el):
seq.append(seq.pop(seq.index(el)))
return seq
colors = ['red','green','white','black','orange']
print(""Original list:"")
print(colors)
el = ""white""
print(""Move"",el,""at the end of the said list:"")
print(group_similar_items(colors, el))
colors = ['red','green','white','black','orange']
print(""\nOriginal list:"")
print(colors)
el = ""red""
print(""Move"",el,""at the end of the said list:"")
print(group_similar_items(colors, el))
colors = ['red','green','white','black','orange']
print(""\nOriginal list:"")
print(colors)
el = ""black""
print(""Move"",el,""at the end of the said list:"")
print(group_similar_items(colors, el))
"
1176,"Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere. ","import numpy as np
x = np.diagflat([4, 5, 6, 8])
print(x)
"
1177,Write a Python program to computing square roots using the Babylonian method. ,"def BabylonianAlgorithm(number):
if(number == 0):
return 0;
g = number/2.0;
g2 = g + 1;
while(g != g2):
n = number/ g;
g2 = g;
g = (g + n)/2;
return g;
print('The Square root of 0.3 =', BabylonianAlgorithm(0.3));
"
1178,Write a Python program to find the greatest common divisor (gcd) of two integers. ,"def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))
"
1179,Write a Pandas program to create a DataFrame using intervals as an index. ,"import pandas as pd
print(""Create an Interval Index using IntervalIndex.from_breaks:"")
df_interval = pd.DataFrame({""X"":[1, 2, 3, 4, 5, 6, 7]},
index = pd.IntervalIndex.from_breaks(
[0, 0.5, 1.0, 1.5, 2.0, 2.5, 3, 3.5]))
print(df_interval)
print(df_interval.index)
print(""\nCreate an Interval Index using IntervalIndex.from_tuples:"")
df_interval = pd.DataFrame({""X"":[1, 2, 3, 4, 5, 6, 7]},
index = pd.IntervalIndex.from_tuples(
[(0, .5), (.5, 1), (1, 1.5), (1.5, 2), (2, 2.5), (2.5, 3), (3, 3.5)]))
print(df_interval)
print(df_interval.index)
print(""\nCreate an Interval Index using IntervalIndex.from_arrays:"")
df_interval = pd.DataFrame({""X"":[1, 2, 3, 4, 5, 6, 7]},
index = pd.IntervalIndex.from_arrays(
[0, .5, 1, 1.5, 2, 2.5, 3], [.5, 1, 1.5, 2, 2.5, 3, 3.5]))
print(df_interval)
print(df_interval.index)
"
1180,Write a NumPy program to divide each row by a vector element. ,"import numpy as np
x = np.array([[20,20,20],[30,30,30],[40,40,40]])
print(""Original array:"")
print(x)
v = np.array([20,30,40])
print(""Vector:"")
print(v)
print(x / v[:,None])
"
1181,Write a Python program to print the following 'here document'. ,"print(""""""
a string that you ""don't"" have to escape
This
is a ....... multi-line
heredoc string --------> example
"""""")
"
1182,Write a Python program to print the element(s) that has a specified id of a given web page. ,"import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nelement(s) that has #python-network id:\n"")
print(soup.select_one(""#python-network""))
"
1183,Write a Python program to get a string which is n (non-negative integer) copies of a given string. ,"def larger_string(str, n):
result = """"
for i in range(n):
result = result + str
return result
print(larger_string('abc', 2))
print(larger_string('.py', 3))
"
1184,Write a Python program to split a list based on first character of word. ,"from itertools import groupby
from operator import itemgetter
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
for letter, words in groupby(sorted(word_list), key=itemgetter(0)):
print(letter)
for word in words:
print(word)
"
1185,Write a NumPy program to extract all the elements of the third column from a given (4x4) array. ,"import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print(""Original array:"")
print(arra_data)
print(""\nExtracted data: Third column"")
print(arra_data[:,2])
"
1186,Write a Python program to format a specified string limiting the length of a string. ,"str_num = ""1234567890""
print(""Original string:"",str_num)
print('%.6s' % str_num)
print('%.9s' % str_num)
print('%.10s' % str_num)
"
1187,Write a Python program to check whether a given string is number or not using Lambda. ,"is_num = lambda q: q.replace('.','',1).isdigit()
print(is_num('26587'))
print(is_num('4.2365'))
print(is_num('-12547'))
print(is_num('00'))
print(is_num('A001'))
print(is_num('001'))
print(""\nPrint checking numbers:"")
is_num1 = lambda r: is_num(r[1:]) if r[0]=='-' else is_num(r)
print(is_num1('-16.4'))
print(is_num1('-24587.11'))
"
1188,Write a Python program to count the number occurrence of a specific character in a string. ,"s = ""The quick brown fox jumps over the lazy dog.""
print(""Original string:"")
print(s)
print(""Number of occurrence of 'o' in the said string:"")
print(s.count(""o""))
"
1189,"Write a NumPy program to create a 1-D array of 20 element spaced evenly on a log scale between 2. and 5., exclusive. ","import numpy as np
x = np.logspace(2., 5., 20, endpoint=False)
print(x)
"
1190,"Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3). ","import numpy as np
p = np.array([[0], [10], [20]])
q= np.array([10, 11, 12])
print(""Original arrays:"")
print(""Array-1"")
print(p)
print(""Array-2"")
print(q)
print(""\nNew Array:"")
new_array1 = p + q
print(new_array1)
"
1191,"Write a Python program to configure the rounding to round to the floor, ceiling. Use decimal.ROUND_FLOOR, decimal.ROUND_CEILING","import decimal
print(""Configure the rounding to round to the floor:"")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_FLOOR
print(decimal.Decimal(20) / decimal.Decimal(6))
print(""\nConfigure the rounding to round to the ceiling:"")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_CEILING
print(decimal.Decimal(20) / decimal.Decimal(6))
"
1192,Write a Python program to read and display the content of a given CSV file. Use csv.reader,"import csv
reader = csv.reader(open(""employees.csv""))
for row in reader:
print(row)
"
1193,Write a Python program that will accept the base and height of a triangle and compute the area. ,"b = int(input(""Input the base : ""))
h = int(input(""Input the height : ""))
area = b*h/2
print(""area = "", area)
"
1194,Write a NumPy program to compute the sum of the diagonal element of a given array. ,"import numpy as np
m = np.arange(6).reshape(2,3)
print(""Original matrix:"")
print(m)
result = np.trace(m)
print(""Condition number of the said matrix:"")
print(result)
"
1195,Write a Python program to find three integers which gives the sum of zero in a given array of integers using Binary Search (bisect). ,"from bisect import bisect, bisect_left
from collections import Counter
class Solution:
def three_Sum(self, nums):
""""""
:type nums: List[int]
:rtype: List[List[int]]
""""""
triplets = []
if len(nums) < 3:
return triplets
num_freq = Counter(nums)
nums = sorted(num_freq) # Sorted unique numbers
max_num = nums[-1]
for i, v in enumerate(nums):
if num_freq[v] >= 2:
complement = -2 * v
if complement in num_freq:
if complement != v or num_freq[v] >= 3:
triplets.append([v] * 2 + [complement])
# When all 3 numbers are different.
if v < 0: # Only when v is the smallest
two_sum = -v
# Lower/upper bound of the smaller of remainingtwo.
lb = bisect_left(nums, two_sum - max_num, i + 1)
ub = bisect(nums, two_sum // 2, lb)
for u in nums[lb : ub]:
complement = two_sum - u
if complement in num_freq and u != complement:
triplets.append([v, u, complement])
return triplets
nums = [-20, 0, 20, 40, -20, -40, 80]
s = Solution()
result = s.three_Sum(nums)
print(result)
nums = [1, 2, 3, 4, 5, -6]
result = s.three_Sum(nums)
print(result)
"
1196,Write a Python program to find the items that are parity outliers in a given list. ,"from collections import Counter
def find_parity_outliers(nums):
return [
x for x in nums
if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0]
]
print(find_parity_outliers([1, 2, 3, 4, 6]))
print(find_parity_outliers([1, 2, 3, 4, 5, 6, 7]))
"
1197,Write a Python program to convert an array to an array of machine values and return the bytes representation. ,"from array import *
print(""Bytes to String: "")
x = array('b', [119, 51, 114, 101, 115, 111, 117, 114, 99, 101])
s = x.tobytes()
print(s)
"
1198,Write a Python program to retrieve children of the html tag from a given web page. ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nChildren of the html tag (https://www.python.org):\n"")
root = soup.html
root_childs = [e.name for e in root.children if e.name is not None]
print(root_childs)
"
1199,Write a Pandas program to append a list of dictioneries or series to a existing DataFrame and display the combined data. ,"import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
s6 = pd.Series(['S6', 'Scarlette Fisher', 205], index=['student_id', 'name', 'marks'])
dicts = [{'student_id': 'S6', 'name': 'Scarlette Fisher', 'marks': 203},
{'student_id': 'S7', 'name': 'Bryce Jensen', 'marks': 207}]
print(""Original DataFrames:"")
print(student_data1)
print(""\nDictionary:"")
print(s6)
combined_data = student_data1.append(dicts, ignore_index=True, sort=False)
print(""\nCombined Data:"")
print(combined_data)
"
1200,Write a Python program to sort a list of elements using shell sort algorithm. ,"def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for start_position in range(sublistcount):
gap_InsertionSort(alist, start_position, sublistcount)
print(""After increments of size"",sublistcount, ""The list is"",nlist)
sublistcount = sublistcount // 2
def gap_InsertionSort(nlist,start,gap):
for i in range(start+gap,len(nlist),gap):
current_value = nlist[i]
position = i
while position>=gap and nlist[position-gap]>current_value:
nlist[position]=nlist[position-gap]
position = position-gap
nlist[position]=current_value
nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist)
"
1201,Write a Python NumPy program to compute the weighted average along the specified axis of a given flattened array. ,"import numpy as np
a = np.arange(9).reshape((3,3))
print(""Original flattened array:"")
print(a)
print(""Weighted average along the specified axis of the above flattened array:"")
print(np.average(a, axis=1, weights=[1./4, 2./4, 2./4]))
"
1202,Write a Python program to multiply all the items in a dictionary. ,"my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
result=result * my_dict[key]
print(result)
"
1203,Write a Python program to count number of substrings with same first and last characters of a given string. ,"def no_of_substring_with_equalEnds(str1):
result = 0;
n = len(str1);
for i in range(n):
for j in range(i, n):
if (str1[i] == str1[j]):
result = result + 1
return result
str1 = input(""Input a string: "")
print(no_of_substring_with_equalEnds(str1))
"
1204,Write a Python program to create a list of empty dictionaries. ,"n = 5
l = [{} for _ in range(n)]
print(l)
"
1205,Write a Python program to test whether a number is within 100 of 1000 or 2000. ,"def near_thousand(n):
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
"
1206,Write a Python program to sort unsorted numbers using Random Pivot Quick Sort. Picks the random index as the pivot. ,"#Ref.https://bit.ly/3pl5kyn
import random
def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[left_index], A[i - 1] = A[i - 1], A[left_index]
return i - 1
def quick_sort_random(A, left, right):
if left < right:
pivot = random.randint(left, right - 1)
A[pivot], A[left] = (
A[left],
A[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(A, left, right)
quick_sort_random(
A, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
A, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 0, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 0, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 0, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 1, len(nums))
print(nums)
nums = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 0, len(nums))
print(nums)
nums = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_random(nums, 2, len(nums))
print(nums)
"
1207,"Write a NumPy program to compute natural, base 10, and base 2 logarithms for all elements in a given array. ","import numpy as np
x = np.array([1, np.e, np.e**2])
print(""Original array: "")
print(x)
print(""\nNatural log ="", np.log(x))
print(""Common log ="", np.log10(x))
print(""Base 2 log ="", np.log2(x))
"
1208,Write a NumPy program to find the roots of the following polynomials. ,"import numpy as np
print(""Roots of the first polynomial:"")
print(np.roots([1, -2, 1]))
print(""Roots of the second polynomial:"")
print(np.roots([1, -12, 10, 7, -10]))
"
1209,"Write a Python program to generate a float between 0 and 1, inclusive and generate a random float within a specific range. Use random.uniform()","import random
print(""Generate a float between 0 and 1, inclusive:"")
print(random.uniform(0, 1))
print(""\nGenerate a random float within a range:"")
random_float = random.uniform(1.0, 3.0)
print(random_float)
"
1210,Write a Python program to print number with commas as thousands separators(from right side). ,"print(""{:,}"".format(1000000))
print(""{:,}"".format(10000))
"
1211,Write a NumPy program to create a 10x4 array filled with random floating point number values with and set the array values with specified precision. ,"import numpy as np
nums = np.random.randn(10, 4)
print(""Original arrays:"")
print(nums)
print(""Set the array values with specified precision:"")
np.set_printoptions(precision=4)
print(nums)
"
1212,Write a Python program to generate all sublists of a list. ,"from itertools import combinations
def sub_lists(my_list):
subs = []
for i in range(0, len(my_list)+1):
temp = [list(x) for x in combinations(my_list, i)]
if len(temp)>0:
subs.extend(temp)
return subs
l1 = [10, 20, 30, 40]
l2 = ['X', 'Y', 'Z']
print(""Original list:"")
print(l1)
print(""S"")
print(sub_lists(l1))
print(""Sublists of the said list:"")
print(sub_lists(l1))
print(""\nOriginal list:"")
print(l2)
print(""Sublists of the said list:"")
print(sub_lists(l2))
"
1213,Write a Python program to split a given list into specified sized chunks. ,"def split_list(lst, n):
result = list((lst[i:i+n] for i in range(0, len(lst), n)))
return result
nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83]
print(""Original list:"")
print(nums)
n = 3
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
n = 4
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
n = 5
print(""\nSplit the said list into equal size"",n)
print(split_list(nums,n))
"
1214,Write a Python program to strip a set of characters from a string. ,"def strip_chars(str, chars):
return """".join(c for c in str if c not in chars)
print(""\nOriginal String: "")
print(""The quick brown fox jumps over the lazy dog."")
print(""After stripping a,e,i,o,u"")
print(strip_chars(""The quick brown fox jumps over the lazy dog."", ""aeiou""))
print()
"
1215,Write a Python program to find the nested lists elements which are present in another list. ,"def intersection_nested_lists(l1, l2):
result = [[n for n in lst if n in l1] for lst in l2]
return result
nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums2 = [[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""\nIntersection of said nested lists:"")
print(intersection_nested_lists(nums1, nums2))
"
1216,Write a NumPy program to take values from a source array and put them at specified indices of another array. ,"import numpy as np
x = np.array([10, 10, 20, 30, 30], float)
print(x)
print(""Put 0 and 40 in first and fifth position of the above array"")
y = np.array([0, 40, 60], float)
x.put([0, 4], y)
print(""Array x, after putting two values:"")
print(x)
"
1217,Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. ,"def grouping_dictionary(l):
result = {}
for k, v in l:
result.setdefault(k, []).append(v)
return result
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
print(""Original list:"")
print(colors)
print(""\nGrouping a sequence of key-value pairs into a dictionary of lists:"")
print(grouping_dictionary(colors))
"
1218,Write a Python program to find files and skip directories of a given directory. ,"import os
print([f for f in os.listdir('/home/students') if os.path.isfile(os.path.join('/home/students', f))])
"
1219,Write a NumPy program to check two random arrays are equal or not. ,"import numpy as np
x = np.random.randint(0,2,6)
print(""First array:"")
print(x)
y = np.random.randint(0,2,6)
print(""Second array:"")
print(y)
print(""Test above two arrays are equal or not!"")
array_equal = np.allclose(x, y)
print(array_equal)
"
1220,Write a Python program to find the minimum window in a given string which will contain all the characters of another given string. ,"import collections
def min_window(str1, str2):
result_char, missing_char = collections.Counter(str2), len(str2)
i = p = q = 0
for j, c in enumerate(str1, 1):
missing_char -= result_char[c] > 0
result_char[c] -= 1
if not missing_char:
while i < q and result_char[str1[i]] < 0:
result_char[str1[i]] += 1
i += 1
if not q or j - i <= q - p:
p, q = i, j
return str1[p:q]
str1 = ""PRWSOERIUSFK""
str2 = ""OSU""
print(""Original Strings:\n"",str1,""\n"",str2)
print(""Minimum window:"")
print(min_window(str1,str2))
"
1221,Write a Pandas program to get all the sighting days of the unidentified flying object (ufo) which are less than or equal to 40 years (365*40 days). ,"import pandas as pd
import datetime
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
now = pd.to_datetime('today')
duration = datetime.timedelta(days=365*40)
print(""Original Dataframe:"")
print(df.head())
print(""\nCurrent date:"")
print(now)
print(""\nSighting days of the unidentified flying object (ufo) which are less than or equal to 40 years (365*40 days):"")
df = df[now - df['Date_time'] <= duration]
print(df.head())
"
1222,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())
"
1223,Write a Python program to convert a list of characters into a string. ,"s = ['a', 'b', 'c', 'd']
str1 = ''.join(s)
print(str1)
"
1224,"Write a Python program to map the values of a given list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. ","def test(itr, fn):
return dict(zip(itr, map(fn, itr)))
print(test([1, 2, 3, 4], lambda x: x * x))
"
1225,Write a NumPy program to remove specific elements in a NumPy array. ,"import numpy as np
x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
index = [0, 3, 4]
print(""Original array:"")
print(x)
print(""Delete first, fourth and fifth elements:"")
new_x = np.delete(x, index)
print(new_x)
"
1226,Write a Pandas program to get the difference (in days) between documented date and reporting date of unidentified flying object (UFO). ,"import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
df['date_documented'] = df['date_documented'].astype('datetime64[ns]')
print(""Original Dataframe:"")
print(df.head())
print(""\nDifference (in days) between documented date and reporting date of UFO:"")
df['Difference'] = (df['date_documented'] - df['Date_time']).dt.days
print(df)
"
1227,Write a Pandas program to check whether alphabetic values present in a given column of a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Company','Company a001','Company 123', 'abcd', 'Company 12'],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]})
print(""Original DataFrame:"")
print(df)
print(""\nWhether Alphabetic values present in company_code column?"")
df['company_code_is_alpha'] = list(map(lambda x: x.isalpha(), df['company_code']))
print(df)
"
1228,Write a Python program to convert a given unicode list to a list contains strings. ,"def unicode_to_str(lst):
result = [str(x) for x in lst]
return result
students = [u'S001', u'S002', u'S003', u'S004']
print(""Original lists:"")
print(students)
print("" Convert the said unicode list to a list contains strings:"")
print(unicode_to_str(students))
"
1229,"Write a Python program to round the numbers of a given list, print the minimum and maximum numbers and multiply the numbers by 5. Print the unique numbers in ascending order separated by space. ","nums = [22.4, 4.0, 16.22, 9.10, 11.00, 12.22, 14.20, 5.20, 17.50]
print(""Original list:"", nums)
numbers=list(map(round,nums))
print(""Minimum value: "",min(numbers))
print(""Maximum value: "",max(numbers))
numbers=list(set(numbers))
numbers=(sorted(map(lambda n:n*5,numbers)))
print(""Result:"")
for numb in numbers:
print(numb,end=' ')
"
1230,Write a Python program to get a dictionary from an object's fields. ,"class dictObj(object):
def __init__(self):
self.x = 'red'
self.y = 'Yellow'
self.z = 'Green'
def do_nothing(self):
pass
test = dictObj()
print(test.__dict__)
"
1231,Write a Python program to find the longest common sub-string from two given strings. ,"from difflib import SequenceMatcher
def longest_Substring(s1,s2):
seq_match = SequenceMatcher(None,s1,s2)
match = seq_match.find_longest_match(0, len(s1), 0, len(s2))
# return the longest substring
if (match.size!=0):
return (s1[match.a: match.a + match.size])
else:
return ('Longest common sub-string not present')
s1 = 'abcdefgh'
s2 = 'xswerabcdwd'
print(""Original Substrings:\n"",s1+""\n"",s2)
print(""\nCommon longest sub_string:"")
print(longest_Substring(s1,s2))
"
1232,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)
"
1233,Write a Python program to calculate the value of 'a' to the power 'b'. ,"def power(a,b):
if b==0:
return 1
elif a==0:
return 0
elif b==1:
return a
else:
return a*power(a,b-1)
print(power(3,4))
"
1234,Write a Python program to find the factorial of a number using itertools module. ,"import itertools as it
import operator as op
def factorials_nums(n):
result = list(it.accumulate(it.chain([1], range(1, 1 + n)), op.mul))
return result;
print(""Factorials of 5 :"", factorials_nums(5))
print(""Factorials of 9 :"", factorials_nums(9))
"
1235,"Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. ","def add_string(str1):
length = len(str1)
if length > 2:
if str1[-3:] == 'ing':
str1 += 'ly'
else:
str1 += 'ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
"
1236,"Write a Python program to compute the square of first N Fibonacci numbers, using map function and generate a list of the numbers. ","import itertools
n = 10
def fibonacci_nums(x=0, y=1):
yield x
while True:
yield y
x, y = y, x + y
print(""First 10 Fibonacci numbers:"")
result = list(itertools.islice(fibonacci_nums(), n))
print(result)
square = lambda x: x * x
print(""\nAfter squaring said numbers of the list:"")
print(list(map(square, result)))
"
1237,Write a NumPy program to compute an element-wise indication of the sign for all elements in a given array. ,"import numpy as np
x = np.array([1, 3, 5, 0, -1, -7, 0, 5])
print(""Original array;"")
print(x)
r1 = np.sign(x)
r2 = np.copy(x)
r2[r2 > 0] = 1
r2[r2 < 0] = -1
assert np.array_equal(r1, r2)
print(""Element-wise indication of the sign for all elements of the said array:"")
print(r1)
"
1238,Write a Python program to create a naïve (without time zone) datetime representation of the Arrow object. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
r = arrow.now('US/Mountain')
print(""\nNaive datetime representation:"")
print(r.naive)
"
1239,Write a Python program to extract a list of values from a given list of dictionaries. ,"def test(lst, marks):
result = [d[marks] for d in lst if marks in d]
return result
marks = [{'Math': 90, 'Science': 92},
{'Math': 89, 'Science': 94},
{'Math': 92, 'Science': 88}]
print(""\nOriginal Dictionary:"")
print(marks)
subj = ""Science""
print(""\nExtract a list of values from said list of dictionaries where subject ="",subj)
print(test(marks, subj))
print(""\nOriginal Dictionary:"")
print(marks)
subj = ""Math""
print(""\nExtract a list of values from said list of dictionaries where subject ="",subj)
print(test(marks, subj))
"
1240,"a href=""#EDITOR"">Go to the editor","def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
"
1241,Write a Python function that takes two lists and returns True if they have at least one common member. ,"def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))
"
1242,"Write a Pandas program to create a stacked histograms plot of opening, closing, high, low stock prices of Alphabet Inc. between two specific dates with more bins. ","import pandas as pd
import matplotlib.pyplot as plt
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[['Open','Close','High','Low']]
plt.figure(figsize=(25,25))
df2.plot.hist(stacked=True, bins=200)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()
"
1243,"Write a Python program to combine two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values. The values of the first list need to be unique and hashable. ","def test(keys, values):
return dict(zip(keys, values))
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [1, 2, 3, 4, 5]
print(""Original lists:"")
print(l1)
print(l2)
print(""\nCombine the values of the said two lists into a dictionary:"")
print(test(l1, l2))
"
1244,Write a Python program to replace the last element in a list with another list. ,"num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
"
1245,Write a Python program to sort a list of elements using Topological sort. ,"# License https://bit.ly/2InTS3W
# a
# / \
# b c
# / \
# d e
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
vertices = ['a', 'b', 'c', 'd', 'e']
def topological_sort(start, visited, sort):
""""""Perform topolical sort on a directed acyclic graph.""""""
current = start
# add current to visited
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
# if all neighbors visited add current to sort
sort.append(current)
# if all vertices haven't been visited select a new one to visit
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)
# return sort
return sort
sort = topological_sort('a', [], [])
print(sort)
"
1246,Write a Pandas program to change the data type of given a column or a Series. ,"import pandas as pd
s1 = pd.Series(['100', '200', 'python', '300.12', '400'])
print(""Original Data Series:"")
print(s1)
print(""Change the said data type to numeric:"")
s2 = pd.to_numeric(s1, errors='coerce')
print(s2)
"
1247,Write a NumPy program to convert a Python dictionary to a NumPy ndarray. ,"import numpy as np
from ast import literal_eval
udict = """"""{""column0"":{""a"":1,""b"":0.0,""c"":0.0,""d"":2.0},
""column1"":{""a"":3.0,""b"":1,""c"":0.0,""d"":-1.0},
""column2"":{""a"":4,""b"":1,""c"":5.0,""d"":-1.0},
""column3"":{""a"":3.0,""b"":-1.0,""c"":-1.0,""d"":-1.0}
}""""""
t = literal_eval(udict)
print(""\nOriginal dictionary:"")
print(t)
print(""Type: "",type(t))
result_nparra = np.array([[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()])
print(""\nndarray:"")
print(result_nparra)
print(""Type: "",type(result_nparra))
"
1248,"Write a Python program to get the maximum value of a list, after mapping each element to a value using a given function. ","def max_by(lst, fn):
return max(map(fn, lst))
print(max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
"
1249,"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('*','/'))
"
1250,Write a Python program to wrap a given string into a paragraph of given width. ,"import textwrap
s = input(""Input a string: "")
w = int(input(""Input the width of the paragraph: "").strip())
print(""Result:"")
print(textwrap.fill(s,w))
"
1251,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)
"
1252,"Write a Python program to get every element that exists in any of the two given lists once, after applying the provided function to each element of both. ","def union_by_el(x, y, fn):
_x = set(map(fn, x))
return list(set(x + [item for item in y if fn(item) not in _x]))
from math import floor
print(union_by_el([4.1], [2.2, 4.3], floor))
"
1253,Write a Python program to generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. ,"from operator import itemgetter
DEBUG = False # like the built-in __debug__
def spermutations(n):
""""""permutations by swapping. Yields: perm, sign""""""
sign = 1
p = [[i, 0 if i == 0 else -1] # [num, direction]
for i in range(n)]
if DEBUG: print(' #', p)
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p): # moving
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
key=itemgetter(1))
sign *= -1
if d1 == -1:
# Swap down
i2 = i1 - 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the First or last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == 0 or p[i2 - 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
elif d1 == 1:
# Swap up
i2 = i1 + 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the first or Last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == n - 1 or p[i2 + 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
if DEBUG: print(' #', p)
yield tuple(pp[0] for pp in p), sign
for i3, pp in enumerate(p):
n3, d3 = pp
if n3 > n1:
pp[1] = 1 if i3 < i2 else -1
if DEBUG: print(' # Set Moving')
if __name__ == '__main__':
from itertools import permutations
for n in (3, 4):
print('\nPermutations and sign of %i items' % n)
sp = set()
for i in spermutations(n):
sp.add(i[0])
print('Permutation: %r Sign: %2i' % i)
#if DEBUG: raw_input('?')
# Test
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree'
"
1254,Write a Python program to get the number of occurrences of a specified element in an array. ,"from array import *
array_num = array('i', [1, 3, 5, 3, 7, 9, 3])
print(""Original array: ""+str(array_num))
print(""Number of occurrences of the number 3 in the said array: ""+str(array_num.count(3)))
"
1255,Write a Python program to check if a substring presents in a given list of string values. ,"def find_substring(str1, sub_str):
if any(sub_str in s for s in str1):
return True
return False
colors = [""red"", ""black"", ""white"", ""green"", ""orange""]
print(""Original list:"")
print(colors)
sub_str = ""ack""
print(""Substring to search:"")
print(sub_str)
print(""Check if a substring presents in the said list of string values:"")
print(find_substring(colors, sub_str))
sub_str = ""abc""
print(""Substring to search:"")
print(sub_str)
print(""Check if a substring presents in the said list of string values:"")
print(find_substring(colors, sub_str))
"
1256,Write a Python program to print a dictionary line by line. ,"students = {'Aex':{'class':'V',
'rolld_id':2},
'Puja':{'class':'V',
'roll_id':3}}
for a in students:
print(a)
for b in students[a]:
print (b,':',students[a][b])
"
1257,Write a Python program to create a shallow copy of a given list. Use copy.copy,"import copy
nums_x = [1, [2, 3, 4]]
print(""Original list: "", nums_x)
nums_y = copy.copy(nums_x)
print(""\nCopy of the said list:"")
print(nums_y)
print(""\nChange the value of an element of the original list:"")
nums_x[1][1] = 10
print(nums_x)
print(""\nSecond list:"")
print(nums_y)
nums = [[1], [2]]
nums_copy = copy.copy(nums)
print(""\nOriginal list:"")
print(nums)
print(""\nCopy of the said list:"")
print(nums_copy)
print(""\nChange the value of an element of the original list:"")
nums[0][0] = 0
print(""\nFirst list:"")
print(nums)
print(""\nSecond list:"")
print(nums_copy)
"
1258,Write a Python program to extend a list without append. ,"x = [10, 20, 30]
y = [40, 50, 60]
x[:0] =y
print(x)
"
1259,Write a Python program to create a naïve (without time zone) datetime representation of the Arrow object. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
r = arrow.now('US/Mountain')
print(""\nNaive datetime representation:"")
print(r.naive)
"
1260,"Write a NumPy program to count the lowest index of ""P"" in a given array, element-wise. ","import numpy as np
x1 = np.array(['Python', 'PHP', 'JS', 'EXAMPLES', 'HTML'], dtype=np.str)
print(""\nOriginal Array:"")
print(x1)
print(""count the lowest index of ‘P’:"")
r = np.char.find(x1, ""P"")
print(r)
"
1261,Write a Pandas program to display most frequent value in a given series and replace everything else as 'Other' in the series. ,"import pandas as pd
import numpy as np
np.random.RandomState(100)
num_series = pd.Series(np.random.randint(1, 5, [15]))
print(""Original Series:"")
print(num_series)
print(""Top 2 Freq:"", num_series.value_counts())
result = num_series[~num_series.isin(num_series.value_counts().index[:1])] = 'Other'
print(num_series)
"
1262,Write a Python program find the common values that appear in two given strings. ,"def intersection_of_two_string(str1, str2):
result = """"
for ch in str1:
if ch in str2 and not ch in result:
result += ch
return result
str1 = 'Python3'
str2 = 'Python2.7'
print(""Original strings:"")
print(str1)
print(str2)
print(""\nIntersection of two said String:"")
print(intersection_of_two_string(str1, str2))
"
1263,"Write a Python program to create a 3-tuple ISO year, ISO week number, ISO weekday and an ISO 8601 formatted representation of the date and time. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\n3-tuple - ISO year, ISO week number, ISO weekday:"")
print(arrow.utcnow().isocalendar())
print(""\nISO 8601 formatted representation of the date and time:"")
print(arrow.utcnow().isoformat())
"
1264,Write a Python program to count number of occurrences of each value in a given array of non-negative integers. ,"import numpy as np
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7]
print(""Original array:"")
print(array1)
print(""Number of occurrences of each value in array: "")
print(np.bincount(array1))
"
1265,Write a Python program to get a list of locally installed Python modules. ,"import pkg_resources
installed_packages = pkg_resources.working_set
installed_packages_list = sorted([""%s==%s"" % (i.key, i.version)
for i in installed_packages])
for m in installed_packages_list:
print(m)
"
1266,Write a Python program to find intersection of two given arrays using Lambda. ,"array_nums1 = [1, 2, 3, 5, 7, 8, 9, 10]
array_nums2 = [1, 2, 4, 8, 9]
print(""Original arrays:"")
print(array_nums1)
print(array_nums2)
result = list(filter(lambda x: x in array_nums1, array_nums2))
print (""\nIntersection of the said arrays: "",result)
"
1267,Write a Python program to combine values in python list of dictionaries. ,"from collections import Counter
item_list = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
result = Counter()
for d in item_list:
result[d['item']] += d['amount']
print(result)
"
1268,"Write a NumPy program to create a new array of 3*5, filled with 2. ","import numpy as np
#using no.full
x = np.full((3, 5), 2, dtype=np.uint)
print(x)
#using no.ones
y = np.ones([3, 5], dtype=np.uint) *2
print(y)
"
1269,"Write a Pandas program to filter all records starting from the 2nd row, access every 5th row from 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(""\nStarting from the 2nd row, access every 5th row:"")
print(w_a_con.iloc[1::5].head(10))
"
1270,Write a NumPy program to check whether the dimensions of two given arrays are same or not. ,"import numpy as np
def test_array_dimensions(ar1,ar2):
try:
ar1 + ar2
except ValueError:
return ""Different dimensions""
else:
return ""Same dimensions""
ar1 = np.arange(20).reshape(4,5)
ar2 = np.arange(20).reshape(4,5)
print(test_array_dimensions(ar1, ar2))
ar1 = np.arange(20).reshape(5,4)
ar2 = np.arange(20).reshape(4,5)
print(test_array_dimensions(ar1, ar2))
"
1271,Write a Pandas program to create a time-series with two index labels and random values. Also print the type of the index. ,"import pandas as pd
import numpy as np
import datetime
from datetime import datetime, date
dates = [datetime(2011, 9, 1), datetime(2011, 9, 2)]
print(""Time-series with two index labels:"")
time_series = pd.Series(np.random.randn(2), dates)
print(time_series)
print(""\nType of the index:"")
print(type(time_series.index))
"
1272,Write a NumPy program to compute the condition number of a given matrix. ,"import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
print(""Original matrix:"")
print(a)
print(""The condition number of the said matrix:"")
print(LA.cond(a))
"
1273,"Write a NumPy program to view inputs as arrays with at least two dimensions, three dimensions. ","import numpy as np
x = 10
print(""View inputs as arrays with at least two dimensions:"")
print(np.atleast_1d(x))
x = np.arange(4.0).reshape(2, 2)
print(np.atleast_1d(x))
print(""View inputs as arrays with at least three dimensions:"")
x =15
print(np.atleast_3d(x))
x = np.arange(3.0)
print(np.atleast_3d(x))
"
1274,Write a Pandas program to create the todays date. ,"import pandas as pd
from datetime import date
now = pd.to_datetime(str(date.today()), format='%Y-%m-%d')
print(""Today's date:"")
print(now)
"
1275,"Write a NumPy program to create a new array of given shape (5,6) and type, filled with zeros. ","import numpy as np
nums = np.zeros(shape=(5, 6), dtype='int')
print(""Original array:"")
print(nums)
nums[::2, ::2] = 3
nums[1::2, ::2] = 7
print(""\nNew array:"")
print(nums)
"
1276,Write a NumPy program to save a given array to a binary file . ,"import numpy as np
import os
a = np.arange(20)
np.save('temp_arra.npy', a)
print(""Check if 'temp_arra.npy' exists or not?"")
if os.path.exists('temp_arra.npy'):
x2 = np.load('temp_arra.npy')
print(np.array_equal(a, x2))
"
1277,Write a Python program to extract the nth element from a given list of tuples. ,"def extract_nth_element(test_list, n):
result = [x[n] for x in test_list]
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print (""Original list:"")
print(students)
n = 0
print(""\nExtract nth element ( n ="",n,"") from the said list of tuples:"")
print(extract_nth_element(students, n))
n = 2
print(""\nExtract nth element ( n ="",n,"") from the said list of tuples:"")
print(extract_nth_element(students, n))
"
1278,Write a NumPy program to create a contiguous flattened array. ,"import numpy as np
x = np.array([[10, 20, 30], [20, 40, 50]])
print(""Original array:"")
print(x)
y = np.ravel(x)
print(""New flattened array:"")
print(y)
"
1279,Write a Python program to print the first n Lucky Numbers. ,"n=int(input(""Input a Number: ""))
List=range(-1,n*n+9,2)
i=2
while List[i:]:List=sorted(set(List)-set(List[List[i]::List[i]]));i+=1
print(List[1:n+1])
"
1280,Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. ,"def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input(""Input a number to compute the factiorial : ""))
print(factorial(n))
"
1281,Write a Python program to convert a list into a nested dictionary of keys. ,"num_list = [1, 2, 3, 4]
new_dict = current = {}
for name in num_list:
current[name] = {}
current = current[name]
print(new_dict)
"
1282,"Write a Python program to find the second lowest grade of any student(s) from the given names and grades of each student using lists and lambda. Input number of students, names and grades of each student. ","students = []
sec_name = []
second_low = 0
n = int(input(""Input number of students: ""))
for _ in range(n):
s_name = input(""Name: "")
score = float(input(""Grade: ""))
students.append([s_name,score])
print(""\nNames and Grades of all students:"")
print(students)
order =sorted(students, key = lambda x: int(x[1]))
for i in range(n):
if order[i][1] != order[0][1]:
second_low = order[i][1]
break
print(""\nSecond lowest grade: "",second_low)
sec_student_name = [x[0] for x in order if x[1] == second_low]
sec_student_name.sort()
print(""\nNames:"")
for s_name in sec_student_name:
print(s_name)
"
1283,Write a Python program to check whether a given datetime is between two dates and times using arrow module. ,"import arrow
print(""Test whether a given datetime is between two dates and times:"")
start = arrow.get(datetime(2017, 6, 5, 12, 30, 10))
end = arrow.get(datetime(2017, 6, 5, 12, 30, 36))
print(arrow.get(datetime(2017, 6, 5, 12, 30, 27)).is_between(start, end))
start = arrow.get(datetime(2017, 5, 5))
end = arrow.get(datetime(2017, 5, 8))
print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[]'))
start = arrow.get(datetime(2017, 5, 5))
end = arrow.get(datetime(2017, 5, 8))
print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[)'))
"
1284,Write a Python program to convert string element to integer inside a given tuple using lambda. ,"def tuple_int_str(tuple_str):
result = tuple(map(lambda x: (int(x[0]), int(x[2])), tuple_str))
return result
tuple_str = (('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34'))
print(""Original tuple values:"")
print(tuple_str)
print(""\nNew tuple values:"")
print(tuple_int_str(tuple_str))
"
1285,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)
"
1286,"Write a Python program to get the index of the first element, which is greater than a specified element using itertools module. ","from itertools import takewhile
def first_index(l1, n):
return len(list(takewhile(lambda x: x[1] <= n, enumerate(l1))))
nums = [12,45,23,67,78,90,100,76,38,62,73,29,83]
print(""Original list:"")
print(nums)
n = 73
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 21
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 80
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 55
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
"
1287,Write a Python program to sort unsorted numbers using Timsort. ,"#Ref:https://bit.ly/3qNYxh9
def binary_search(lst, item, start, end):
if start == end:
return start if lst[start] > item else start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def tim_sort(lst):
length = len(lst)
runs, sorted_runs = [], []
new_run = [lst[0]]
sorted_array = []
i = 1
while i < length:
if lst[i] < lst[i - 1]:
runs.append(new_run)
new_run = [lst[i]]
else:
new_run.append(lst[i])
i += 1
runs.append(new_run)
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(lst)
print(""After applying Timsort the said list becomes:"")
sorted_lst = tim_sort(lst)
print(sorted_lst)
lst = ""Python""
print(""\nOriginal list:"")
print(lst)
print(""After applying Timsort the said list becomes:"")
sorted_lst = tim_sort(lst)
print(sorted_lst)
lst = (1.1, 1, 0, -1, -1.1)
print(""\nOriginal list:"")
print(lst)
print(""After applying Timsort the said list becomes:"")
sorted_lst = tim_sort(lst)
print(sorted_lst)
"
1288,Write a Python program to check if a given function returns True for at least one element in the list. ,"def test(lst, fn = lambda x: x):
return all(not fn(x) for x in lst)
print(test([1, 0, 2, 3], lambda x: x >= 3 ))
print(test([1, 0, 2, 3], lambda x: x < 0 ))
print(test([2, 2, 4, 4]))
"
1289,Write a Python program to initialize a list containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1. ,"from math import floor, log
def geometric_progression(end, start=1, step=2):
return [start * step ** i for i in range(floor(log(end / start)
/ log(step)) + 1)]
print(geometric_progression(256))
print(geometric_progression(256, 3))
print(geometric_progression(256, 1, 4))
"
1290,"Write a Pandas program to create a whole month of dates in daily frequencies. Also find the maximum, minimum timestamp and indexs. ","import pandas as pd
dates = pd.Series(pd.date_range('2020-12-01',periods=31, freq='D'))
print(""Month of December 2020:"")
print(dates)
dates = pd.Series(pd.date_range('2020-12-01',periods=31, freq='D'))
print(""\nMaximum date: "", dates.max())
print(""Minimum date: "", dates.min())
print(""Maximum index: "", dates.idxmax())
print(""Minimum index: "", dates.idxmin())
"
1291,Write a Python program to sort a list of elements using Radix sort. ,"def radix_sort(nums):
RADIX = 10
placement = 1
max_digit = max(nums)
while placement < max_digit:
buckets = [list() for _ in range( RADIX )]
for i in nums:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
a = 0
for b in range( RADIX ):
buck = buckets[b]
for i in buck:
nums[a] = i
a += 1
placement *= RADIX
return nums
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
print(radix_sort(nums))
"
1292,Write a Pandas program to add some data to an existing Series. ,"import pandas as pd
s = pd.Series(['100', '200', 'python', '300.12', '400'])
print(""Original Data Series:"")
print(s)
print(""\nData Series after adding some data:"")
new_s = s.append(pd.Series(['500', 'php']))
print(new_s)
"
1293,"Write a Python program to create a datetime object, converted to the specified timezone using arrow module. ","import arrow
utc = arrow.utcnow()
pacific=arrow.now('US/Pacific')
nyc=arrow.now('America/Chicago').tzinfo
print(pacific.astimezone(nyc))
"
1294,Write a Python program to create a dictionary from two lists without losing duplicate values. ,"from collections import defaultdict
class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII']
id_list = [1, 2, 2, 3]
temp = defaultdict(set)
for c, i in zip(class_list, id_list):
temp[c].add(i)
print(temp)
"
1295,Write a Python program to create a dictionary with the same keys as the given dictionary and values generated by running the given function for each value. ,"def test(obj, fn):
return dict((k, fn(v)) for k, v in obj.items())
users = {
'Theodore': { 'user': 'Theodore', 'age': 45 },
'Roxanne': { 'user': 'Roxanne', 'age': 15 },
'Mathew': { 'user': 'Mathew', 'age': 21 },
}
print(""\nOriginal dictionary elements:"")
print(users)
print(""\nDictionary with the same keys:"")
print(test(users, lambda u : u['age']))
"
1296,Write a Pandas program to create a plot of stock price and trading volume of Alphabet Inc. between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
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]
stock_data = df1.set_index('Date')
top_plt = plt.subplot2grid((5,4), (0, 0), rowspan=3, colspan=4)
top_plt.plot(stock_data.index, stock_data[""Close""])
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]')
bottom_plt = plt.subplot2grid((5,4), (3,0), rowspan=1, colspan=4)
bottom_plt.bar(stock_data.index, stock_data['Volume'])
plt.title('\nAlphabet Inc. Trading Volume', y=-0.60)
plt.gcf().set_size_inches(12,8)
"
1297,Write a Python program to square and cube every number in a given list of integers using Lambda. ,"nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(""Original list of integers:"")
print(nums)
print(""\nSquare every number of the said list:"")
square_nums = list(map(lambda x: x ** 2, nums))
print(square_nums)
print(""\nCube every number of the said list:"")
cube_nums = list(map(lambda x: x ** 3, nums))
print(cube_nums)
"
1298,"Write a NumPy program to generate a uniform, non-uniform random sample from a given 1-D array with and without replacement. ","import numpy as np
print(""Generate a uniform random sample with replacement:"")
print(np.random.choice(7, 5))
print(""\nGenerate a uniform random sample without replacement:"")
print(np.random.choice(7, 5, replace=False))
print(""\nGenerate a non-uniform random sample with replacement:"")
print(np.random.choice(7, 5, p=[0.1, 0.2, 0, 0.2, 0.4, 0, 0.1]))
print(""\nGenerate a uniform random sample without replacement:"")
print(np.random.choice(7, 5, replace=False, p=[0.1, 0.2, 0, 0.2, 0.4, 0, 0.1]))
"
1299,Write a Python program to use double quotes to display strings. ,"import json
print(json.dumps({'Alex': 1, 'Suresh': 2, 'Agnessa': 3}))
"
1300,Write a Python program to get the current memory address and the length in elements of the buffer used to hold an array's contents and also find the size of the memory buffer in bytes. ,"from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print(""Original array: ""+str(array_num))
print(""Current memory address and the length in elements of the buffer: ""+str(array_num.buffer_info()))
print(""The size of the memory buffer in bytes: ""+str(array_num.buffer_info()[1] * array_num.itemsize))
"
1301,Write a NumPy program to compute the determinant of a given square array. ,"import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0], [1, 2]])
print(""Original 2-d array"")
print(a)
print(""Determinant of the said 2-D array:"")
print(np.linalg.det(a))
"
1302,"Write a Pandas program to split the following dataframe into groups by school code and get mean, min, and max value of age with customized column name for each school. ","import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
' height ': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(student_data)
print('\nMean, min, and max value of age for each school with customized column names:')
grouped_single = student_data.groupby('school_code').agg(Age_Mean = ('age','mean'),Age_Max=('age',max),Age_Min=('age',min))
print(grouped_single)
"
1303,"Write a Python program to filter the height and width of students, which are stored in a dictionary using lambda. ","def filter_data(students):
result = dict(filter(lambda x: (x[1][0], x[1][1]) > (6.0, 70), students.items()))
return result
students = {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), 'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)}
print(""Original Dictionary:"")
print(students)
print(""\nHeight> 6ft and Weight> 70kg:"")
print(filter_data(students))
"
1304,"Write a NumPy program to remove the first dimension from a given array of shape (1,3,4). ","import numpy as np
nums = np.array([[[1, 2, 3, 4],
[0, 1, 3, 4],
[5, 0, 3, 2]]])
print('Shape of the said array:')
print(nums.shape)
print(""\nAfter removing the first dimension of the shape of the said array:"")
"
1305,Write a NumPy program to compute the following polynomial values. ,"import numpy as np
print(""Polynomial value when x = 2:"")
print(np.polyval([1, -2, 1], 2))
print(""Polynomial value when x = 3:"")
print(np.polyval([1, -12, 10, 7, -10], 3))
"
1306,Write a Python program to get the file size of a plain file. ,"def file_size(fname):
import os
statinfo = os.stat(fname)
return statinfo.st_size
print(""File size in bytes of a plain file: "",file_size(""test.txt""))
"
1307,Write a Python program to remove all consecutive duplicates of a given string. ,"from itertools import groupby
def remove_all_consecutive(str1):
result_str = []
for (key,group) in groupby(str1):
result_str.append(key)
return ''.join(result_str)
str1 = 'xxxxxyyyyy'
print(""Original string:"" + str1)
print(""After removing consecutive duplicates: "" + str1)
print(remove_all_consecutive(str1))
"
1308,Write a Python program that accept some words and count the number of distinct words. Print the number of distinct words and number of occurrences for each distinct word according to their appearance. ,"from collections import Counter, OrderedDict
class OrderedCounter(Counter,OrderedDict):
pass
word_array = []
n = int(input(""Input number of words: ""))
print(""Input the words: "")
for i in range(n):
word_array.append(input().strip())
word_ctr = OrderedCounter(word_array)
print(len(word_ctr))
for word in word_ctr:
print(word_ctr[word],end=' ')
"
1309,Write a Pandas program to get the average mean of the UFO (unidentified flying object) sighting was reported. ,"import pandas as pd
#Source: https://bit.ly/32kGinQ
df = pd.read_csv(r'ufo.csv')
df['date_documented'] = df['date_documented'].astype('datetime64[ns]')
print(""Original Dataframe:"")
print(df.head())
# Add a new column instance, this adds a value to each instance of ufo sighting
df['instance'] = 1
# set index to time, this makes df a time series df and then you can apply pandas time series functions.
df.set_index(df['date_documented'], drop=True, inplace=True)
# create another df by resampling the original df and counting the instance column by Month ('M' is resample by month)
ufo2 = pd.DataFrame(df['instance'].resample('M').count())
# just to find month of resampled observation
ufo2['date_documented'] = pd.to_datetime(ufo2.index.values)
ufo2['month'] = ufo2['date_documented'].apply(lambda x: x.month)
print(""Average mean of the UFO (unidentified flying object) sighting was reported:"")
print(ufo2.groupby(by='month').mean())
"
1310,Write a Python program to reverse a given list of lists. ,"def reverse_list_of_lists(list1):
return list1[::-1]
colors = [['orange', 'red'], ['green', 'blue'], ['white', 'black', 'pink']]
print(""Original list:"")
print(colors)
print(""\nReverse said list of lists:"")
print(reverse_list_of_lists(colors))
nums = [[1,2,3,4], [0,2,4,5], [2,3,4,2,4]]
print(""\nOriginal list:"")
print(nums)
print(""\nReverse said list of lists:"")
print(reverse_list_of_lists(nums))
"
1311,Write a Python program to iterate over two lists simultaneously. ,"num = [1, 2, 3]
color = ['red', 'white', 'black']
for (a,b) in zip(num, color):
print(a, b)
"
1312,Write a Python program to split a given dictionary of lists into list of dictionaries using map function. ,"def list_of_dicts(marks):
result = map(dict, zip(*[[(key, val) for val in value] for key, value in marks.items()]))
return list(result)
marks = {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}
print(""Original dictionary of lists:"")
print(marks)
print(""\nSplit said dictionary of lists into list of dictionaries:"")
print(list_of_dicts(marks))
"
1313,Write a Python program to find the second largest number in a list. ,"def second_largest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] == numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[-2]
print(second_largest([1,2,3,4,4]))
print(second_largest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_largest([2,2]))
print(second_largest([1]))
"
1314,Write a Pandas program to split the following dataframe into groups based on all columns and calculate Groupby value counts on the dataframe. ,"import pandas as pd
df = pd.DataFrame( {'id' : [1, 2, 1, 1, 2, 1, 2],
'type' : [10, 15, 11, 20, 21, 12, 14],
'book' : ['Math','English','Physics','Math','English','Physics','English']})
print(""Original DataFrame:"")
print(df)
result = df.groupby(['id', 'type', 'book']).size().unstack(fill_value=0)
print(""\nResult:"")
print(result)
"
1315,Write a Python program to sort a list of lists by a given index of the inner list using lambda. ,"def index_on_inner_list(list_data, index_no):
result = sorted(list_data, key=lambda x: x[index_no])
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print (""Original list:"")
print(students)
index_no = 0
print(""\nSort the said list of lists by a given index"",""( Index = "",index_no,"") of the inner list"")
print(index_on_inner_list(students, index_no))
index_no = 2
print(""\nSort the said list of lists by a given index"",""( Index = "",index_no,"") of the inner list"")
print(index_on_inner_list(students, index_no))
"
1316,Write a Python program to get all combinations of key-value pairs in a given dictionary. ,"import itertools
def test(dictt):
result = list(map(dict, itertools.combinations(dictt.items(), 2)))
return result
students = {'V' : [1, 4, 6, 10], 'VI' : [1, 4, 12], 'VII' : [1, 3, 8]}
print(""\nOriginal Dictionary:"")
print(students)
print(""\nCombinations of key-value pairs of the said dictionary:"")
print(test(students))
students = {'V' : [1, 3, 5], 'VI' : [1, 5]}
print(""\nOriginal Dictionary:"")
print(students)
print(""\nCombinations of key-value pairs of the said dictionary:"")
print(test(students))
"
1317,Write a Pandas program to create a Pivot table and find the region wise total sale. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df,index=""Region"",values=""Sale_amt"", aggfunc = np.sum)
print(table)
"
1318,Write a Python program to sort a list alphabetically in a dictionary. ,"num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}
sorted_dict = {x: sorted(y) for x, y in num.items()}
print(sorted_dict)
"
1319,Write a Python program to sort unsorted numbers using Merge-insertion sort. ,"#Ref.https://bit.ly/3r32ezJ
from __future__ import annotations
def merge_insertion_sort(collection: list[int]) -> list[int]:
""""""Pure implementation of merge-insertion sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> merge_insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_insertion_sort([99])
[99]
>>> merge_insertion_sort([-2, -5, -45])
[-45, -5, -2]
""""""
def binary_search_insertion(sorted_list, item):
left = 0
right = len(sorted_list) - 1
while left <= right:
middle = (left + right) // 2
if left == right:
if sorted_list[middle] < item:
left = middle + 1
break
elif sorted_list[middle] < item:
left = middle + 1
else:
right = middle - 1
sorted_list.insert(left, item)
return sorted_list
def sortlist_2d(list_2d):
def merge(left, right):
result = []
while left and right:
if left[0][0] < right[0][0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result + left + right
length = len(list_2d)
if length <= 1:
return list_2d
middle = length // 2
return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:]))
if len(collection) <= 1:
return collection
""""""
Group the items into two pairs, and leave one element if there is a last odd item.
Example: [999, 100, 75, 40, 10000]
-> [999, 100], [75, 40]. Leave 10000.
""""""
two_paired_list = []
has_last_odd_item = False
for i in range(0, len(collection), 2):
if i == len(collection) - 1:
has_last_odd_item = True
else:
""""""
Sort two-pairs in each groups.
Example: [999, 100], [75, 40]
-> [100, 999], [40, 75]
""""""
if collection[i] < collection[i + 1]:
two_paired_list.append([collection[i], collection[i + 1]])
else:
two_paired_list.append([collection[i + 1], collection[i]])
""""""
Sort two_paired_list.
Example: [100, 999], [40, 75]
-> [40, 75], [100, 999]
""""""
sorted_list_2d = sortlist_2d(two_paired_list)
""""""
40 < 100 is sure because it has already been sorted.
Generate the sorted_list of them so that you can avoid unnecessary comparison.
Example:
group0 group1
40 100
75 999
->
group0 group1
[40, 100]
75 999
""""""
result = [i[0] for i in sorted_list_2d]
""""""
100 < 999 is sure because it has already been sorted.
Put 999 in last of the sorted_list so that you can avoid unnecessary comparison.
Example:
group0 group1
[40, 100]
75 999
->
group0 group1
[40, 100, 999]
75
""""""
result.append(sorted_list_2d[-1][1])
""""""
Insert the last odd item left if there is.
Example:
group0 group1
[40, 100, 999]
75
->
group0 group1
[40, 100, 999, 10000]
75
""""""
if has_last_odd_item:
pivot = collection[-1]
result = binary_search_insertion(result, pivot)
""""""
Insert the remaining items.
In this case, 40 < 75 is sure because it has already been sorted.
Therefore, you only need to insert 75 into [100, 999, 10000],
so that you can avoid unnecessary comparison.
Example:
group0 group1
[40, 100, 999, 10000]
^ You don't need to compare with this as 40 < 75 is already sure.
75
->
[40, 75, 100, 999, 10000]
""""""
is_last_odd_item_inserted_before_this_index = False
for i in range(len(sorted_list_2d) - 1):
if result[i] == collection[-i]:
is_last_odd_item_inserted_before_this_index = True
pivot = sorted_list_2d[i][1]
# If last_odd_item is inserted before the item's index,
# you should forward index one more.
if is_last_odd_item_inserted_before_this_index:
result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot)
else:
result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot)
return result
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Merge-insertion Sort the said list becomes:"")
print(merge_insertion_sort(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Merge-insertion Sort the said list becomes:"")
print(merge_insertion_sort(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Merge-insertion Sort the said list becomes:"")
print(merge_insertion_sort(nums))
chars = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(chars)
print(""After applying Merge-insertion Sort the said list becomes:"")
print(merge_insertion_sort(chars))
"
1320,Write a NumPy program to save a given array to a text file and load it. ,"import numpy as np
import os
x = np.arange(12).reshape(4, 3)
print(""Original array:"")
print(x)
header = 'col1 col2 col3'
np.savetxt('temp.txt', x, fmt=""%d"", header=header)
print(""After loading, content of the text file:"")
result = np.loadtxt('temp.txt')
print(result)
"
1321,"Write a Python program to sum two or more lists, the lengths of the lists may be different. ","def sum_lists_diff_length(test_list):
result = [sum(x) for x in zip(*map(lambda x:x+[0]*max(map(len, test_list)) if len(x)%s%s>"" % (tag, word, tag)
print(add_tags('i', 'Python'))
print(add_tags('b', 'Python Tutorial'))
"
1325,Write a Python program to get the least common multiple (LCM) of two positive integers. ,"def lcm(x, y):
if x > y:
z = x
else:
z = y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
"
1326,"Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string. ","def count_chars(str):
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1
elif str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1
elif str[i] >= '0' and str[i] <= '9': number_ctr += 1
else: special_ctr += 1
return upper_ctr, lower_ctr, number_ctr, special_ctr
str = ""@W3Resource.Com""
print(""Original Substrings:"",str)
u, l, n, s = count_chars(str)
print('\nUpper case characters: ',u)
print('Lower case characters: ',l)
print('Number case: ',n)
print('Special case characters: ',s)
"
1327,Write a Python program to find all the values in a list are greater than a specified number. ,"list1 = [220, 330, 500]
list2 = [12, 17, 21]
print(all(x >= 200 for x in list1))
print(all(x >= 25 for x in list2))
"
1328,"Write a Python program to join two given list of lists of same length, element wise. ","def elementswise_join(l1, l2):
result = [x + y for x, y in zip(l1, l2)]
return result
nums1 = [[10,20], [30,40], [50,60], [30,20,80]]
nums2 = [[61], [12,14,15], [12,13,19,20], [12]]
print(""Original lists:"")
print(nums1)
print(nums2)
print(""\nJoin the said two lists element wise:"")
print(elementswise_join(nums1, nums2))
list1 = [['a','b'], ['b','c','d'], ['e', 'f']]
list2 = [['p','q'], ['p','s','t'], ['u','v','w']]
print(""\nOriginal lists:"")
print(list1)
print(list2)
print(""\nJoin the said two lists element wise:"")
print(elementswise_join(list1, list2))
"
1329,Write a NumPy program to find indices of elements equal to zero in a NumPy array. ,"import numpy as np
nums = np.array([1,0,2,0,3,0,4,5,6,7,8])
print(""Original array:"")
print(nums)
print(""Indices of elements equal to zero of the said array:"")
result = np.where(nums == 0)[0]
print(result)
"
1330,Write a Python program to search a date from a given string using arrow module. ,"import arrow
print(""\nSearch a date from a string:"")
d1 = arrow.get('David was born in 11 June 2003', 'DD MMMM YYYY')
print(d1)
"
1331,Write a Pandas program to join (left join) the two dataframes using keys from left dataframe only. ,"import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'R': ['R0', 'R1', 'R2', 'R3'],
'S': ['S0', 'S1', 'S2', 'S3']})
print(""Original DataFrames:"")
print(data1)
print(""--------------------"")
print(data2)
print(""\nMerged Data (keys from data1):"")
merged_data = pd.merge(data1, data2, how='left', on=['key1', 'key2'])
print(merged_data)
print(""\nMerged Data (keys from data2):"")
merged_data = pd.merge(data2, data1, how='left', on=['key1', 'key2'])
print(merged_data)
"
1332,Write a Python program to sort a list of elements using Heap sort. ,"def heap_data(nums, index, heap_size):
largest_num = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and nums[left_index] > nums[largest_num]:
largest_num = left_index
if right_index < heap_size and nums[right_index] > nums[largest_num]:
largest_num = right_index
if largest_num != index:
nums[largest_num], nums[index] = nums[index], nums[largest_num]
heap_data(nums, largest_num, heap_size)
def heap_sort(nums):
n = len(nums)
for i in range(n // 2 - 1, -1, -1):
heap_data(nums, i, n)
for i in range(n - 1, 0, -1):
nums[0], nums[i] = nums[i], nums[0]
heap_data(nums, 0, i)
return nums
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
heap_sort(nums)
print(nums)
"
1333,"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])
"
1334,Write a Pandas program to split the following dataset using group by on 'salesman_id' and find the first 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':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5004,5003,5002,5004,5001]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nGroupby to find first order date for each group(salesman_id):"")
result = df.groupby('salesman_id')['ord_date'].min()
print(result)
"
1335,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))
"
1336,Write a NumPy program to get the index of a maximum element in a NumPy array along one axis. ,"import numpy as np
a = np.array([[1,2,3],[4,3,1]])
print(""Original array:"")
print(a)
i,j = np.unravel_index(a.argmax(), a.shape)
print(""Index of a maximum element in a numpy array along one axis:"")
print(a[i,j])
"
1337,"Write a Python program to create a localized, humanized representation of a relative difference in time using arrow module. ","import arrow
print(""Current datetime:"")
print(arrow.utcnow())
earlier = arrow.utcnow().shift(hours=-4)
print(earlier.humanize())
later = earlier.shift(hours=3)
print(later.humanize(earlier))
"
1338,Write a Python program to get the difference between the two lists. ,"list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))
total_diff = diff_list1_list2 + diff_list2_list1
print(total_diff)
"
1339,"Write a NumPy program to create an array of 10 zeros,10 ones, 10 fives. ","import numpy as np
array=np.zeros(10)
print(""An array of 10 zeros:"")
print(array)
array=np.ones(10)
print(""An array of 10 ones:"")
print(array)
array=np.ones(10)*5
print(""An array of 10 fives:"")
print(array)
"
1340,Write a Python program to calculate the difference between the squared sum of first n natural numbers and the sum of squared first n natural numbers.(default value of number=2). ,"def sum_difference(n=2):
sum_of_squares = 0
square_of_sum = 0
for num in range(1, n+1):
sum_of_squares += num * num
square_of_sum += num
square_of_sum = square_of_sum ** 2
return square_of_sum - sum_of_squares
print(sum_difference(12))
"
1341,"Write a Pandas program to create a stacked histograms plot with more bins of opening, closing, high, low stock prices of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
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[['Open','Close','High','Low']]
plt.figure(figsize=(30,30))
df2.hist();
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc., From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()
"
1342,Write a Python program to read a string and interpreting the string as an array of machine values. ,"from array import array
import binascii
array1 = array('i', [7, 8, 9, 10])
print('array1:', array1)
as_bytes = array1.tobytes()
print('Bytes:', binascii.hexlify(as_bytes))
array2 = array('i')
array2.frombytes(as_bytes)
print('array2:', array2)
"
1343,"Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements. Write a NumPy program to find the number of occurrences of a sequence in the said array. ","import numpy as np
np_array = np.array([[1, 2, 3], [2, 1, 2]], np.int32)
print(""Original Numpy array:"")
print(np_array)
print(""Type: "",type(np_array))
print(""Sequence: 1,2"",)
result = repr(np_array).count(""1, 2"")
print(""Number of occurrences of the said sequence:"",result)
"
1344,Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and find a specific MSHA ID. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df[df[""MSHA ID""]==102901].head()
"
1345,Write a Python program to sort a list of elements using the bubble sort algorithm. ,"def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(nlist)
"
1346,"Write a NumPy program to get the floor, ceiling and truncated values of the elements of a numpy array. ","import numpy as np
x = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0])
print(""Original array:"")
print(x)
print(""Floor values of the above array elements:"")
print(np.floor(x))
print(""Ceil values of the above array elements:"")
print(np.ceil(x))
print(""Truncated values of the above array elements:"")
print(np.trunc(x))
"
1347,Write a Python program to check whether a JSON string contains complex object or not. ,"import json
def is_complex_num(objct):
if '__complex__' in objct:
return complex(objct['real'], objct['img'])
return objct
complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num)
simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num)
print(""Complex_object: "",complex_object)
print(""Without complex object: "",simple_object)
"
1348,Write a Python program to remove the characters which have odd index values of a given string. ,"def odd_values_string(str):
result = """"
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))
"
1349,"Write a Python program to configure the rounding to round to the nearest, with ties going to the nearest even integer. Use decimal.ROUND_HALF_EVEN","import decimal
print(""Configure the rounding to round to the nearest, with ties going to the nearest even integer:"")
decimal.getcontext().prec = 1
decimal.getcontext().rounding = decimal.ROUND_HALF_EVEN
print(decimal.Decimal(10) / decimal.Decimal(4))
"
1350,Write a NumPy program to generate a generic 2D Gaussian-like array. ,"import numpy as np
x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
d = np.sqrt(x*x+y*y)
sigma, mu = 1.0, 0.0
g = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(""2D Gaussian-like array:"")
print(g)
"
1351,Write a Python program to calculate the distance between London and New York city. ,"from geopy import distance
london = (""51.5074° N, 0.1278° W"")
newyork = (""40.7128° N, 74.0060° W"")
print(""Distance between London and New York city (in km):"")
print(distance.distance(london, newyork).km,"" kms"")
"
1352,Write a NumPy program to create a function cube which cubes all the elements of an array. ,"import numpy as np
def cube(e):
it = np.nditer([e, None])
for a, b in it:
b[...] = a*a*a
return it.operands[1]
print(cube([1,2,3]))
"
1353,Write a Python program to reverse words in a string. ,"def reverse_string_words(text):
for line in text.split('\n'):
return(' '.join(line.split()[::-1]))
print(reverse_string_words(""The quick brown fox jumps over the lazy dog.""))
print(reverse_string_words(""Python Exercises.""))
"
1354,Write a Python program to find the specified number of maximum values in a given dictionary. ,"def test(dictt, N):
result = sorted(dictt, key=dictt.get, reverse=True)[:N]
return result
dictt = {'a':5, 'b':14, 'c': 32, 'd':35, 'e':24, 'f': 100, 'g':57, 'h':8, 'i': 100}
print(""\nOriginal Dictionary:"")
print(dictt)
N = 1
print(""\n"",N,""maximum value(s) in the said dictionary:"")
print(test(dictt, N))
N = 2
print(""\n"",N,""maximum value(s) in the said dictionary:"")
print(test(dictt, N))
N = 5
print(""\n"",N,""maximum value(s) in the said dictionary:"")
print(test(dictt, N))
"
1355,"Write a Python program to iterate over a root level path and print all its sub-directories and files, also loop over specified dirs and files. ","import os
print('Iterate over a root level path:')
path = '/tmp/'
for root, dirs, files in os.walk(path):
print(root)
"
1356,Write a Python code to remove all characters except a specified character in a given string. ,"def remove_characters(str1,c):
return ''.join([el for el in str1 if el == c])
text = ""Python Exercises""
print(""Original string"")
print(text)
except_char = ""P""
print(""Remove all characters except"",except_char,""in the said string:"")
print(remove_characters(text,except_char))
text = ""google""
print(""\nOriginal string"")
print(text)
except_char = ""g""
print(""Remove all characters except"",except_char,""in the said string:"")
print(remove_characters(text,except_char))
text = ""exercises""
print(""\nOriginal string"")
print(text)
except_char = ""e""
print(""Remove all characters except"",except_char,""in the said string:"")
print(remove_characters(text,except_char))
"
1357,Write a Pandas program to create a Pivot table and find number of survivors and average rate grouped by gender and class. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index='sex', columns='class', aggfunc={'survived':sum, 'fare':'mean'})
print(result)
"
1358,Write a Python program to find all keys in the provided dictionary that have the given value. ,"def test(dict, val):
return list(key for key, value in dict.items() if value == val)
students = {
'Theodore': 19,
'Roxanne': 20,
'Mathew': 21,
'Betty': 20
}
print(""\nOriginal dictionary elements:"")
print(students)
print(""\nFind all keys in the said dictionary that have the specified value:"")
print(test(students, 20))
"
1359,Write a NumPy program to find the closest value (to a given scalar) in an array. ,"import numpy as np
x = np.arange(100)
print(""Original array:"")
print(x)
a = np.random.uniform(0,100)
print(""Value to compare:"")
print(a)
index = (np.abs(x-a)).argmin()
print(x[index])
"
1360,Write a Pandas program to split a string of a column of a given DataFrame into multiple columns. ,"import pandas as pd
df = pd.DataFrame({
'name': ['Alberto Franco','Gino Ann Mcneill','Ryan Parkes', 'Eesha Artur Hinton', 'Syed Wharton'],
'date_of_birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
df[[""first"", ""middle"", ""last""]] = df[""name""].str.split("" "", expand = True)
print(""\nNew DataFrame:"")
print(df)
"
1361,Write a Pandas program to create a Pivot table with multiple indexes from a given excel sheet (Salesdata.xlsx). ,"import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(df)
pd.pivot_table(df,index=[""Region"",""SalesMan""])
"
1362,"Write a Python program which iterates the integers from 1 to a given number and print ""Fizz"" for multiples of three, print ""Buzz"" for multiples of five, print ""FizzBuzz"" for multiples of both three and five using itertools module. ","#Source:https://bit.ly/30PS62m
import itertools as it
def fizz_buzz(n):
fizzes = it.cycle([""""] * 2 + [""Fizz""])
buzzes = it.cycle([""""] * 4 + [""Buzz""])
fizzes_buzzes = (fizz + buzz for fizz, buzz in zip(fizzes, buzzes))
result = (word or n for word, n in zip(fizzes_buzzes, it.count(1)))
for i in it.islice(result, 100):
print(i)
n = 50
fizz_buzz(n)
"
1363,Write a Python program to create a shallow copy of a given dictionary. Use copy.copy,"import copy
nums_x = {""a"":1, ""b"":2, 'cc':{""c"":3}}
print(""Original dictionary: "", nums_x)
nums_y = copy.copy(nums_x)
print(""\nCopy of the said list:"")
print(nums_y)
print(""\nChange the value of an element of the original dictionary:"")
nums_x[""cc""][""c""] = 10
print(nums_x)
print(""\nSecond dictionary:"")
print(nums_y)
nums = {""x"":1, ""y"":2, 'zz':{""z"":3}}
nums_copy = copy.copy(nums)
print(""\nOriginal dictionary :"")
print(nums)
print(""\nCopy of the said list:"")
print(nums_copy)
print(""\nChange the value of an element of the original dictionary:"")
nums[""zz""][""z""] = 10
print(""\nFirst dictionary:"")
print(nums)
print(""\nSecond dictionary (copy):"")
print(nums_copy)
"
1364,Write a Python program access the index of a list. ,"nums = [5, 15, 35, 8, 98]
for num_index, num_val in enumerate(nums):
print(num_index, num_val)
"
1365,"Write a Python program to remove sublists from a given list of lists, which contains an element outside a given range. ","#Source bit.ly/33MAeHe
def remove_list_range(input_list, left_range, rigth_range):
result = [i for i in input_list if (min(i)>=left_range and max(i)<=rigth_range)]
return result
list1 = [[2], [0], [1, 2, 3], [0, 1, 2, 3, 6, 7], [9, 11], [13, 14, 15, 17]]
left_range = 13
rigth_range = 17
print(""Original list:"")
print(list1)
print(""\nAfter removing sublists from a given list of lists, which contains an element outside the given range:"")
print(remove_list_range(list1, left_range, rigth_range))
"
1366,"Write a Python program to create a string representation of the Arrow object, formatted according to a format string. ","import arrow
print(""Current datetime:"")
print(arrow.utcnow())
print(""\nYYYY-MM-DD HH:mm:ss ZZ:"")
print(arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ'))
print(""\nDD-MM-YYYY HH:mm:ss ZZ:"")
print(arrow.utcnow().format('DD-MM-YYYY HH:mm:ss ZZ'))
print(arrow.utcnow().format('\nMMMM DD, YYYY'))
print(arrow.utcnow().format())
"
1367,Write a Pandas program to create a Pivot table and find survival rate by gender. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result=df.groupby('sex')[['survived']].mean()
print(result)
"
1368,Write a Python program to calculate surface volume and area of a sphere. ,"pi=22/7
radian = float(input('Radius of sphere: '))
sur_area = 4 * pi * radian **2
volume = (4/3) * (pi * radian ** 3)
print(""Surface Area is: "", sur_area)
print(""Volume is: "", volume)
"
1369,Write a Python program to convert all the characters in uppercase and lowercase and eliminate duplicate letters from a given sequence. Use map() function. ,"def change_cases(s):
return str(s).upper(), str(s).lower()
chrars = {'a', 'b', 'E', 'f', 'a', 'i', 'o', 'U', 'a'}
print(""Original Characters:\n"",chrars)
result = map(change_cases, chrars)
print(""\nAfter converting above characters in upper and lower cases\nand eliminating duplicate letters:"")
print(set(result))
"
1370,Write a Python program to create a deque from an existing iterable object. ,"import collections
even_nums = (2, 4, 6)
print(""Original tuple:"")
print(even_nums)
print(type(even_nums))
even_nums_deque = collections.deque(even_nums)
print(""\nOriginal deque:"")
print(even_nums_deque)
even_nums_deque.append(8)
even_nums_deque.append(10)
even_nums_deque.append(12)
even_nums_deque.appendleft(2)
print(""New deque from an existing iterable object:"")
print(even_nums_deque)
print(type(even_nums_deque))
"
1371,Write a Pandas program to find the index of a substring of DataFrame with beginning and end position. ,"import pandas as pd
df = pd.DataFrame({
'name_code': ['c0001','1000c','b00c2', 'b2c02', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
print(""\nIndex of a substring in a specified column of a dataframe:"")
df['Index'] = list(map(lambda x: x.find('c', 0, 5), df['name_code']))
print(df)
"
1372,Write a Pandas program to check whether only space is present in a given column of a DataFrame. ,"import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF ', ' ', 'abcd', ' '],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]})
print(""Original DataFrame:"")
print(df)
print(""\nIs space is present?"")
df['company_code_is_title'] = list(map(lambda x: x.isspace(), df['company_code']))
print(df)
"
1373,"Write a NumPy program to calculate the difference between neighboring elements, element-wise of a given array. ","import numpy as np
x = np.array([1, 3, 5, 7, 0])
print(""Original array: "")
print(x)
print(""Difference between neighboring elements, element-wise of the said array."")
print(np.diff(x))
"
1374,Write a Python program to count characters at same position in a given string (lower and uppercase characters) as in English alphabet. ,"def count_char_position(str1):
count_chars = 0
for i in range(len(str1)):
if ((i == ord(str1[i]) - ord('A')) or
(i == ord(str1[i]) - ord('a'))):
count_chars += 1
return count_chars
str1 = input(""Input a string: "")
print(""Number of characters of the said string at same position as in English alphabet:"")
print(count_char_position(str1))
"
1375,Write a NumPy program to multiply the values of two given vectors. ,"import numpy as np
x = np.array([1, 8, 3, 5])
print(""Vector-1"")
print(x)
y= np.random.randint(0, 11, 4)
print(""Vector-2"")
print(y)
result = x * y
print(""Multiply the values of two said vectors:"")
print(result)
"
1376,Write a Python program to remove duplicate words from a given string use collections module. ,"from collections import OrderedDict
text_str = ""Python Exercises Practice Solution Exercises""
print(""Original String:"")
print(text_str)
print(""\nAfter removing duplicate words from the said string:"")
result = ' '.join(OrderedDict((w,w) for w in text_str.split()).keys())
print(result)
"
1377,Write a NumPy program to test a given array element-wise for finiteness (not infinity or not a Number). ,"import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print(""Original array"")
print(a)
print(""Test a given array element-wise for finiteness :"")
print(np.isfinite(a))
"
1378,Write a NumPy program to convert a NumPy array of float values to a NumPy array of integer values. ,"import numpy as np
x= np.array([[12.0, 12.51], [2.34, 7.98], [25.23, 36.50]])
print(""Original array elements:"")
print(x)
print(""Convert float values to integer values:"")
print(x.astype(int))
"
1379,Write a Python program to find the second most repeated word in a given string. ,"def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
counts_x = sorted(counts.items(), key=lambda kv: kv[1])
#print(counts_x)
return counts_x[-2]
print(word_count(""Both of these issues are fixed by postponing the evaluation of annotations. Instead of compiling code which executes expressions in annotations at their definition time, the compiler stores the annotation in a string form equivalent to the AST of the expression in question. If needed, annotations can be resolved at runtime using typing.get_type_hints(). In the common case where this is not required, the annotations are cheaper to store (since short strings are interned by the interpreter) and make startup time faster.""))
"
1380,"Write a Python program to find the specified number of largest products from two given list, multiplying an element from each list. ","def top_product(nums1, nums2, N):
result = sorted([x*y for x in nums1 for y in nums2], reverse=True)[:N]
return result
nums1 = [1, 2, 3, 4, 5, 6]
nums2 = [3, 6, 8, 9, 10, 6]
print(""Original lists:"")
print(nums1)
print(nums2,""\n"")
N = 3
print(N,""Number of largest products from the said two lists:"")
print(top_product(nums1, nums2, N))
N = 4
print(N,""Number of largest products from the said two lists:"")
print(top_product(nums1, nums2, N))
"
1381,Write a Pandas program to extract only non alphanumeric characters 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({
'company_code': ['c0001#','[email protected]^2','$c0003', 'c0003', '&c0004'],
'year': ['year 1800','year 1700','year 2300', 'year 1900', 'year 2200']
})
print(""Original DataFrame:"")
print(df)
def find_nonalpha(text):
result = re.findall(""[^A-Za-z0-9 ]"",text)
return result
df['nonalpha']=df['company_code'].apply(lambda x: find_nonalpha(x))
print(""\Extracting only non alphanumeric characters from company_code:"")
print(df)
"
1382,Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot where each bar will represent one of the top 10 production. ,"import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('E:\coalpublic2013.xlsx')
sorted_by_production = df.sort_values(['Production'], ascending=False).head(10)
sorted_by_production['Production'].head(10).plot(kind=""barh"")
plt.show()
"
1383,Write a Python program to chose specified number of colours from three different colours and generate all the combinations with repetitions. ,"from itertools import combinations_with_replacement
def combinations_colors(l, n):
return combinations_with_replacement(l,n)
l = [""Red"",""Green"",""Blue""]
print(""Original List: "",l)
n=1
print(""\nn = 1"")
print(list(combinations_colors(l, n)))
n=2
print(""\nn = 2"")
print(list(combinations_colors(l, n)))
n=3
print(""\nn = 3"")
print(list(combinations_colors(l, n)))
"
1384,"Write a Python program to add two given lists of different lengths, start from left. ","def elementswise_left_join(l1, l2):
f_len = len(l1)-(len(l2) - 1)
for i in range(0, len(l2), 1):
if f_len - i >= len(l1):
break
else:
l1[i] = l1[i] + l2[i]
return l1
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""\nAdd said two lists from left:"")
print(elementswise_left_join(nums1,nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print(""\nOriginal lists:"")
print(nums3)
print(nums4)
print(""\nAdd said two lists from left:"")
print(elementswise_left_join(nums3,nums4))
"
1385,Write a Pandas program to draw a horizontal and cumulative histograms plot of opening stock prices of Alphabet Inc. between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-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[['Open']]
plt.figure(figsize=(15,15))
df2.plot.hist(orientation='horizontal', cumulative=True)
plt.suptitle('Opening stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-04-2020', fontsize=12, color='black')
plt.show()
"
1386,Write a Python program to generate a 3*4*6 3D array whose each element is *. ,"array = [[ ['*' for col in range(6)] for col in range(4)] for row in range(3)]
print(array)
"
1387,Write a Python program to group the elements of a given list based on the given function. ,"from collections import defaultdict
from math import floor
def test(lst, fn):
d = defaultdict(list)
for el in lst:
d[fn(el)].append(el)
return dict(d)
nums = [7,23, 3.2, 3.3, 8.4]
print(""Original list & function:"")
print(nums,"" Function name: floor:"")
print(""Group the elements of the said list based on the given function:"")
print(test(nums, floor))
print(""\n"")
print(""Original list & function:"")
colors = ['Red', 'Green', 'Black', 'White', 'Pink']
print(colors,"" Function name: len:"")
print(""Group the elements of the said list based on the given function:"")
print(test(colors, len))
"
1388,Write a Python program to get unique values from a list. ,"my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print(""Original List : "",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print(""List of unique numbers : "",my_new_list)
"
1389,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])
"
1390,"Write a Pandas program to select random number of rows, fraction of random rows from 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(""\nSelect random number of rows:"")
print(w_a_con.sample(5))
print(""\nSelect fraction of randome rows:"")
print(w_a_con.sample(frac=0.02))
"
1391,"Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5. ","import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)
"
1392,"Write a NumPy program to compute the trigonometric sine, cosine and tangent array of angles given in degrees. ","import numpy as np
print(""sine: array of angles given in degrees"")
print(np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
print(""cosine: array of angles given in degrees"")
print(np.cos(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
print(""tangent: array of angles given in degrees"")
print(np.tan(np.array((0., 30., 45., 60., 90.)) * np.pi / 180.))
"
1393,Write a Python program to print the names of all HTML tags of a given web page going through the document tree. ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""\nNames of all HTML tags (https://www.python.org):\n"")
for child in soup.recursiveChildGenerator():
if child.name:
print(child.name)
"
1394,Write a Python program to create a backup of a SQLite database. ,"import sqlite3
import io
conn = sqlite3.connect('mydatabase.db')
with io.open('clientes_dump.sql', 'w') as f:
for linha in conn.iterdump():
f.write('%s\n' % linha)
print('Backup performed successfully.')
print('Saved as mydatabase_dump.sql')
conn.close()
"
1395,Write a Python program to find the dimension of a given matrix. ,"def matrix_dimensions(test_list):
row = len(test_list)
column = len(test_list[0])
return row,column
lst = [[1,2],[2,4]]
print(""\nOriginal list:"")
print(lst)
print(""Dimension of the said matrix:"")
print(matrix_dimensions(lst))
lst = [[0,1,2],[2,4,5]]
print(""\nOriginal list:"")
print(lst)
print(""Dimension of the said matrix:"")
print(matrix_dimensions(lst))
lst = [[0,1,2],[2,4,5],[2,3,4]]
print(""\nOriginal list:"")
print(lst)
print(""Dimension of the said matrix:"")
print(matrix_dimensions(lst))
"
1396,Write a Python program to find the index position of the last occurrence of a given number in a sorted list using Binary Search (bisect). ,"from bisect import bisect_right
def BinarySearch(a, x):
i = bisect_right(a, x)
if i != len(a)+1 and a[i-1] == x:
return (i-1)
else:
return -1
nums = [1, 2, 3, 4, 8, 8, 10, 12]
x = 8
num_position = BinarySearch(nums, x)
if num_position == -1:
print(""not presetn!"")
else:
print(""Last occurrence of"", x, ""is present at"", num_position)
"
1397,Write a Python program to list home directory without absolute path. ,"import os.path
print(os.path.expanduser('~'))
"
1398,Write a Python program to check if two given lists contain the same elements regardless of order. ,"def check_same_contents(nums1, nums2):
for x in set(nums1 + nums2):
if nums1.count(x) != nums2.count(x):
return False
return True
nums1 = [1, 2, 4]
nums2 = [2, 4, 1]
print(""Original list elements:"")
print(nums1)
print(nums2)
print(""\nCheck two said lists contain the same elements regardless of order!"")
print(check_same_contents(nums1, nums2))
nums1 = [1, 2, 3]
nums2 = [1, 2, 3]
print(""\nOriginal list elements:"")
print(nums1)
print(nums2)
print(""\nCheck two said lists contain the same elements regardless of order!"")
print(check_same_contents(nums1, nums2))
nums1 = [1, 2, 3]
nums2 = [1, 2, 4]
print(""\nOriginal list elements:"")
print(nums1)
print(nums2)
print(""\nCheck two said lists contain the same elements regardless of order!"")
print(check_same_contents(nums1, nums2))
"
1399,Write a NumPy program to insert a new axis within a 2-D array. ,"import numpy as np
x = np.zeros((3, 4))
y = np.expand_dims(x, axis=1).shape
print(y)
"
1400,Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. ,"color_list_1 = set([""White"", ""Black"", ""Red""])
color_list_2 = set([""Red"", ""Green""])
print(""Original set elements:"")
print(color_list_1)
print(color_list_2)
print(""\nDifferenct of color_list_1 and color_list_2:"")
print(color_list_1.difference(color_list_2))
print(""\nDifferenct of color_list_2 and color_list_1:"")
print(color_list_2.difference(color_list_1))
"
1401,Write a Python program to read last n lines of a file. ,"import sys
import os
def file_read_from_tail(fname,lines):
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open(fname) as f:
if bufsize > fsize:
bufsize = fsize-1
data = []
while True:
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
if len(data) >= lines or f.tell() == 0:
print(''.join(data[-lines:]))
break
file_read_from_tail('test.txt',2)
"
1402,"Write a Pandas program to find the sum, mean, max, min value of 'Production (short tons)' column of coalpublic2013.xlsx file. ","import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
print(""Sum: "",df[""Production""].sum())
print(""Mean: "",df[""Production""].mean())
print(""Maximum: "",df[""Production""].max())
print(""Minimum: "",df[""Production""].min())
"
1403,"Write a Pandas program to filter rows based on row numbers ended with 0, like 0, 10, 20, 30 from 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(""\nFilter rows based on row numbers ended with 0, like 0, 10, 20, 30:"")
print(w_a_con.filter(regex='0$', axis=0))
"
1404,Write a Pandas program to split a given dataframe into groups with bin counts. ,"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],
'customer_id':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'sales_id':[5002,5003,5004,5003,5002,5001,5005,5007,5008,5004,5005,5001]})
print(""Original DataFrame:"")
print(df)
groups = df.groupby(['customer_id', pd.cut(df.sales_id, 3)])
result = groups.size().unstack()
print(result)
"
1405,Write a Pandas program to keep the valid entries of 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 said DataFrame with valid entries:"")
result = df.dropna(inplace=False)
print(result)
"
1406,Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) Sightings year. ,"import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
df[""ufo_yr""] = df.Date_time.dt.year
years_data = df.ufo_yr.value_counts()
years_index = years_data.index # x ticks
years_values = years_data.get_values()
plt.figure(figsize=(15,8))
plt.xticks(rotation = 60)
plt.title('UFO Sightings by Year')
plt.xlabel(""Year"")
plt.ylabel(""Number of reports"")
years_plot = sns.barplot(x=years_index[:60],y=years_values[:60], palette = ""Reds"")
"
1407,Write a NumPy program to remove the trailing whitespaces of all the elements of a given array. ,"import numpy as np
x = np.array([' python exercises ', ' PHP ', ' java ', ' C++'], dtype=np.str)
print(""Original Array:"")
print(x)
rstripped_char = np.char.rstrip(x)
print(""\nRemove the trailing whitespaces : "", rstripped_char)
"
1408,"Write a Python program to calculate the sum of all items of a container (tuple, list, set, dictionary). ","s = sum([10,20,30])
print(""\nSum of the container: "", s)
print()
"
1409,Write a NumPy program to test element-wise for NaN of a given array. ,"import numpy as np
a = np.array([1, 0, np.nan, np.inf])
print(""Original array"")
print(a)
print(""Test element-wise for NaN:"")
print(np.isnan(a))
"
1410,Write a NumPy program to find the index of the sliced elements as follows from a given 4x4 array. ,"import numpy as np
x = np.reshape(np.arange(16),(4,4))
print(""Original arrays:"")
print(x)
print(""Sliced elements:"")
result = x[[0,1,2],[0,1,3]]
print(result)
"
1411,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight dataframe's specific columns with different colors. ","import pandas as pd
import numpy as np
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)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print(""Original array:"")
print(df)
print(""\nDifferent background color:"")
coldict = {'B':'red', 'D':'yellow'}
def highlight_cols(x):
#copy df to new - original data are not changed
df = x.copy()
#select all values to default value - red color
df.loc[:,:] = 'background-color: red'
#overwrite values grey color
df[['B','C', 'E']] = 'background-color: grey'
#return color df
return df
df.style.apply(highlight_cols, axis=None)
"
1412,Write a NumPy program to calculate exp(x) - 1 for all elements in a given array. ,"import numpy as np
x = np.array([1., 2., 3., 4.], np.float32)
print(""Original array: "")
print(x)
print(""\nexp(x)-1 for all elements of the said array:"")
r1 = np.expm1(x)
r2 = np.exp(x) - 1.
assert np.allclose(r1, r2)
print(r1)
"
1413,Write a Pandas program to count of occurrence of a specified substring in a DataFrame column. ,"import pandas as pd
df = pd.DataFrame({
'name_code': ['c001','c002','c022', 'c2002', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
print(""\nCount occurrence of 2 in date_of_birth column:"")
df['count'] = list(map(lambda x: x.count(""2""), df['name_code']))
print(df)
"
1414,Write a Python program to create a file where all letters of English alphabet are listed by specified number of letters on each line. ,"import string
def letters_file_line(n):
with open(""words1.txt"", ""w"") as f:
alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + ""\n"" for i in range(0, len(alphabet), n)]
f.writelines(letters)
letters_file_line(3)
"
1415,Write a Python program to convert a given heterogeneous list of scalars into a string. ,"def heterogeneous_list_to_str(lst):
result = ','.join(str(x) for x in lst)
return result
h_data = [""Red"", 100, -50, ""green"", ""w,3,r"", 12.12, False]
print(""Original list:"")
print(h_data)
print(""\nConvert the heterogeneous list of scalars into a string:"")
print(heterogeneous_list_to_str(h_data))
"
1416,Write a Python program to get all possible combinations of the elements of a given list. ,"def combinations_list(colors):
if len(colors) == 0:
return [[]]
result = []
for el in combinations_list(colors[1:]):
result += [el, el+[colors[0]]]
return result
colors = ['orange', 'red', 'green', 'blue']
print(""Original list:"")
print(colors)
print(""\nAll possible combinations of the said list’s elements:"")
print(combinations_list(colors))
"
1417,Write a NumPy program to combine last element with first element of two given ndarray with different shapes. ,"import numpy as np
array1 = ['PHP','JS','C++']
array2 = ['Python','C#', 'NumPy']
print(""Original arrays:"")
print(array1)
print(array2)
result = np.r_[array1[:-1], [array1[-1]+array2[0]], array2[1:]]
print(""\nAfter Combining:"")
print(result)
"
1418,Write a Python program to count most and least common characters in a given string. ,"from collections import Counter
def max_least_char(str1):
temp = Counter(str1)
max_char = max(temp, key = temp.get)
min_char = min(temp, key = temp.get)
return (max_char, min_char)
str1 = ""hello world""
print (""Original string: "")
print(str1)
result = max_least_char(str1)
print(""\nMost common character of the said string:"",result[0])
print(""Least common character of the said string:"",result[1])
"
1419,Write a Python program using Sieve of Eratosthenes method for computing primes upto a specified number. ,"def prime_eratosthenes(n):
prime_list = []
for i in range(2, n+1):
if i not in prime_list:
print (i)
for j in range(i*i, n+1, i):
prime_list.append(j)
print(prime_eratosthenes(100));
"
1420,Write a NumPy program to convert the raw data in an array to a binary string and then create an array. ,"import numpy as np
x = np.array([10, 20, 30], float)
print(""Original array:"")
print(x)
s = x.tostring()
print(""Binary string array:"")
print(s)
print(""Array using fromstring():"")
y = np.fromstring(s)
print(y)
"
1421,Write a Python program to remove spaces from dictionary keys. ,"student_list = {'S 001': ['Math', 'Science'], 'S 002': ['Math', 'English']}
print(""Original dictionary: "",student_list)
student_dict = {x.translate({32: None}): y for x, y in student_list.items()}
print(""New dictionary: "",student_dict)
"
1422,Write a Python program to sort unsorted numbers using Multi-key quicksort. ,"#Ref.https://bit.ly/36fvcEw
def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
if right <= left:
return
a = i = left
b = right
pivot = sorting[left]
while i <= b:
if sorting[i] < pivot:
sorting[a], sorting[i] = sorting[i], sorting[a]
a += 1
i += 1
elif sorting[i] > pivot:
sorting[b], sorting[i] = sorting[i], sorting[b]
b -= 1
else:
i += 1
quick_sort_3partition(sorting, left, a - 1)
quick_sort_3partition(sorting, b + 1, right)
def three_way_radix_quicksort(sorting: list) -> list:
if len(sorting) <= 1:
return sorting
return (
three_way_radix_quicksort([i for i in sorting if i < sorting[0]])
+ [i for i in sorting if i == sorting[0]]
+ three_way_radix_quicksort([i for i in sorting if i > sorting[0]])
)
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Random Pivot Quick Sort the said list becomes:"")
quick_sort_3partition(nums, 0, len(nums)-1)
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Multi-key quicksort the said list becomes:"")
quick_sort_3partition(nums, 0, len(nums)-1)
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Multi-key quicksort the said list becomes:"")
quick_sort_3partition(nums, 0, len(nums)-1)
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Multi-key quicksort the said list becomes:"")
quick_sort_3partition(nums, 1, len(nums)-1)
print(nums)
nums = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(nums)
print(""After applying Multi-key quicksort the said list becomes:"")
quick_sort_3partition(nums, 0, len(nums)-1)
print(nums)
nums = ['z','a','y','b','x','c']
print(""\nOriginal list:"")
print(nums)
print(""After applying Multi-key quicksort the said list becomes:"")
quick_sort_3partition(nums, 2, len(nums)-1)
print(nums)
"
1423,Write a Python program to returns sum of all divisors of a number. ,"def sum_div(number):
divisors = [1]
for i in range(2, number):
if (number % i)==0:
divisors.append(i)
return sum(divisors)
print(sum_div(8))
print(sum_div(12))
"
1424,Write a Pandas program to plot the volatility over a period of time of Alphabet Inc. stock price between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
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', 'Close']]
df3 = df2.set_index('Date')
data_filled = df3.asfreq('D', method='ffill')
data_returns = data_filled.pct_change()
data_std = data_returns.rolling(window=30, min_periods=30).std()
plt.figure(figsize=(20,20))
data_std.plot();
plt.suptitle('Volatility over a period of time of Alphabet Inc. stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()
"
1425,Write a Python program to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters. ,"from itertools import groupby
def modified_encode(alist):
def ctr_ele(el):
if len(el)>1: return [len(el), el[0]]
else: return el[0]
return [ctr_ele(list(group)) for key, group in groupby(alist)]
n_list = [1,1,2,3,4,4,5, 1]
print(""Original list:"")
print(n_list)
print(""\nList reflecting the modified run-length encoding from the said list:"")
print(modified_encode(n_list))
n_list = 'aabcddddadnss'
print(""\nOriginal String:"")
print(n_list)
print(""\nList reflecting the modified run-length encoding from the said string:"")
print(modified_encode(n_list))
"
1426,Write a NumPy program to create a vector with values ranging from 15 to 55 and print all values except the first and last. ,"import numpy as np
v = np.arange(15,55)
print(""Original vector:"")
print(v)
print(""All values except the first and last of the said vector:"")
print(v[1:-1])
"
1427,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)
"
1428,Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5. ,"def test_number5(x, y):
if x == y or abs(x-y) == 5 or (x+y) == 5:
return True
else:
return False
print(test_number5(7, 2))
print(test_number5(3, 2))
print(test_number5(2, 2))
print(test_number5(7, 3))
print(test_number5(27, 53))
"
1429,Write a Python program to find the common tuples between two given lists. ,"def test(list1, list2):
result = set(list1).intersection(list2)
return list(result)
list1 = [('red', 'green'), ('black', 'white'), ('orange', 'pink')]
list2 = [('red', 'green'), ('orange', 'pink')]
print(""\nOriginal lists:"")
print(list1)
print(list2)
print(""\nCommon tuples between two said lists"")
print(test(list1,list2))
list1 = [('red', 'green'), ('orange', 'pink')]
list2 = [('red', 'green'), ('black', 'white'), ('orange', 'pink')]
print(""\nOriginal lists:"")
print(list1)
print(list2)
print(""\nCommon tuples between two said lists"")
print(test(list1,list2))
"
1430,Write a Python program to change a given string to a new string where the first and last chars have been exchanged. ,"def change_sring(str1):
return str1[-1:] + str1[1:-1] + str1[:1]
print(change_sring('abcd'))
print(change_sring('12345'))
"
1431,Write a Python program to convert a given list of dictionaries into a list of values corresponding to the specified key. ,"def pluck(lst, key):
return [x.get(key) for x in lst]
simpsons = [
{ 'name': 'Areeba', 'age': 8 },
{ 'name': 'Zachariah', 'age': 36 },
{ 'name': 'Caspar', 'age': 34 },
{ 'name': 'Presley', 'age': 10 }
]
print(pluck(simpsons, 'age'))
"
1432,Write a Pandas program to create a time series combining hour and minute. ,"import pandas as pd
result = pd.timedelta_range(0, periods=30, freq=""1H20T"")
print(""For a frequency of 1 hours 20 minutes, here we have combined the hour (H) and minute (T):\n"")
print(result)
"
1433,Write a Python program to format a number with a percentage. ,"x = 0.25
y = -0.25
print(""\nOriginal Number: "", x)
print(""Formatted Number with percentage: ""+""{:.2%}"".format(x));
print(""Original Number: "", y)
print(""Formatted Number with percentage: ""+""{:.2%}"".format(y));
print()
"
1434,Write a Python program to generate combinations of a given length of given iterable. ,"import itertools as it
def combinations_data(iter, length):
return it.combinations(iter, length)
#List
result = combinations_data(['A','B','C','D'], 1)
print(""\nCombinations of an given iterable of length 1:"")
for i in result:
print(i)
#String
result = combinations_data(""Python"", 1)
print(""\nCombinations of an given iterable of length 1:"")
for i in result:
print(i)
#List
result = combinations_data(['A','B','C','D'], 2)
print(""\nCombinations of an given iterable of length 2:"")
for i in result:
print(i)
#String
result = combinations_data(""Python"", 2)
print(""\nCombinations of an given iterable of length 2:"")
for i in result:
print(i)
"
1435,Write a Pandas program to find the index of a given substring of a DataFrame column. ,"import pandas as pd
df = pd.DataFrame({
'name_code': ['c001','c002','c022', 'c2002', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print(""Original DataFrame:"")
print(df)
print(""\nCount occurrence of 22 in date_of_birth column:"")
df['Index'] = list(map(lambda x: x.find('22'), df['name_code']))
print(df)
"
1436,Write a NumPy program to get the block-sum (block size is 5x5) from a given array of shape 25x25. ,"import numpy as np
arra1 = np.ones((25,25))
k = 5
print(""Original arrays:"")
print(arra1)
result = np.add.reduceat(np.add.reduceat(arra1, np.arange(0, arra1.shape[0], k), axis=0),
np.arange(0, arra1.shape[1], k), axis=1)
print(""\nBlock-sum (5x5) of the said array:"")
print(result)
"
1437,Write a Python program to get the length of an array. ,"from array import array
num_array = array('i', [10,20,30,40,50])
print(""Length of the array is:"")
print(len(num_array))
"
1438,Write a NumPy program to get the magnitude of a vector in NumPy. ,"import numpy as np
x = np.array([1,2,3,4,5])
print(""Original array:"")
print(x)
print(""Magnitude of the vector:"")
print(np.linalg.norm(x))
"
1439,Write a Python program to remove words from a given list of strings containing a character or string. ,"def remove_words(in_list, char_list):
new_list = []
for line in in_list:
new_words = ' '.join([word for word in line.split() if not any([phrase in word for phrase in char_list])])
new_list.append(new_words)
return new_list
str_list = ['Red color', 'Orange#', 'Green', 'Orange @', ""White""]
print(""Original list:"")
print(""list1:"",str_list)
char_list = ['#', 'color', '@']
print(""\nCharacter list:"")
print(char_list)
print(""\nNew list:"")
print(remove_words(str_list, char_list))
"
1440,"Write a Pandas program to split a dataset, group by one column and get mean, min, and max values by group, also change the column name of the aggregated metric. Using the following dataset find the mean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id). ","import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(df)
print('\nChange the name of an aggregated metric:')
grouped_single = df.groupby('school_code').agg({'age': [(""mean_age"",""mean""), (""min_age"", ""min""), (""max_age"",""max"")]})
print(grouped_single)
"
1441,Write a Python program to check a list is empty or not. ,"l = []
if not l:
print(""List is empty"")
"
1442,Write a Pandas program to create a scatter plot of the trading volume/stock prices of Alphabet Inc. stock between two specific dates. ,"import pandas as pd
import matplotlib.pyplot as plt
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.set_index('Date')
x= ['Close']; y = ['Volume']
plt.figure(figsize=[15,10])
df2.plot.scatter(x, y, s=50);
plt.grid(True)
plt.title('Trading Volume/Price of Alphabet Inc. stock,\n01-04-2020 to 30-09-2020', fontsize=14, color='black')
plt.xlabel(""Stock Price"",fontsize=12, color='black')
plt.ylabel(""Trading Volume"", fontsize=12, color='black')
plt.show()
"
1443,Write a Python program to calculate magic square. ,"def magic_square_test(my_matrix):
iSize = len(my_matrix[0])
sum_list = []
#Horizontal Part:
sum_list.extend([sum (lines) for lines in my_matrix])
#Vertical Part:
for col in range(iSize):
sum_list.append(sum(row[col] for row in my_matrix))
#Diagonals Part
result1 = 0
for i in range(0,iSize):
result1 +=my_matrix[i][i]
sum_list.append(result1)
result2 = 0
for i in range(iSize-1,-1,-1):
result2 +=my_matrix[i][i]
sum_list.append(result2)
if len(set(sum_list))>1:
return False
return True
m=[[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]]
print(magic_square_test(m));
m=[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
print(magic_square_test(m));
m=[[2, 7, 6], [9, 5, 1], [4, 3, 7]]
print(magic_square_test(m));
"
1444,Write a Python program to append a list to the second list. ,"list1 = [1, 2, 3, 0]
list2 = ['Red', 'Green', 'Black']
final_list = list1 + list2
print(final_list)
"
1445,Write a NumPy program to find the real and imaginary parts of an array of complex numbers. ,"import numpy as np
x = np.sqrt([1+0j])
y = np.sqrt([0+1j])
print(""Original array:x "",x)
print(""Original array:y "",y)
print(""Real part of the array:"")
print(x.real)
print(y.real)
print(""Imaginary part of the array:"")
print(x.imag)
print(y.imag)
"
1446,Write a Python program to parse a string representing a time according to a format. ,"import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\ntime.struct_time, in the current timezone:"")
print(arrow.utcnow().timetuple())
"
1447,Write a NumPy program to create a new shape to an array without changing its data. ,"import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
y = np.reshape(x,(3,2))
print(""Reshape 3x2:"")
print(y)
z = np.reshape(x,(2,3))
print(""Reshape 2x3:"")
print(z)
"
1448,Write a Python program to find the location address of a specified latitude and longitude using Nominatim API and Geopy package. ,"from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent=""geoapiExercises"")
lald = ""47.470706, -99.704723""
print(""Latitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
lald = ""34.05728435, -117.194132331602""
print(""\nLatitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
lald = ""38.8976998, -77.0365534886228""
print(""\nLatitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
lald = ""55.7558° N, 37.6173° E""
print(""\nLatitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
lald = ""35.6762° N, 139.6503° E""
print(""\nLatitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
lald = ""41.9185° N, 45.4777° E""
print(""\nLatitude and Longitude:"",lald)
location = geolocator.geocode(lald)
print(""Location address of the said Latitude and Longitude:"")
print(location)
"
1449,Write a Python program to flatten a given nested list structure. ,"def flatten_list(n_list):
result_list = []
if not n_list: return result_list
stack = [list(n_list)]
while stack:
c_num = stack.pop()
next = c_num.pop()
if c_num: stack.append(c_num)
if isinstance(next, list):
if next: stack.append(list(next))
else: result_list.append(next)
result_list.reverse()
return result_list
n_list = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
print(""Original list:"")
print(n_list)
print(""\nFlatten list:"")
print(flatten_list(n_list))
"
1450,Write a Python program to extract the text in the first paragraph tag of a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
This is an example HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
""""""
soup = BeautifulSoup(html_doc, 'html.parser')
print(""The text in the first paragraph tag:"")
print(soup.find_all('p')[0].text)
"
1451,Write a Python program to get the index of the first element which is greater than a specified element. ,"def first_index(l1, n):
return next(a[0] for a in enumerate(l1) if a[1] > n)
nums = [12,45,23,67,78,90,100,76,38,62,73,29,83]
print(""Original list:"")
print(nums)
n = 73
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 21
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 80
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
n = 55
print(""\nIndex of the first element which is greater than"",n,""in the said list:"")
print(first_index(nums,n))
"
1452,rite a Python program that accepts a string and calculate the number of digits and letters. ,"s = input(""Input a string"")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print(""Letters"", l)
print(""Digits"", d)
"
1453,"Write a NumPy program to create an array of (3, 4) shape, multiply every element value by 3 and display the new array. ","import numpy as np
x= np.arange(12).reshape(3, 4)
print(""Original array elements:"")
print(x)
for a in np.nditer(x, op_flags=['readwrite']):
a[...] = 3 * a
print(""New array elements:"")
print(x)
"
1454,Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array. ,"import numpy as np
fvalues = [0, 12, 45.21, 34, 99.91]
F = np.array(fvalues)
print(""Values in Fahrenheit degrees:"")
print(F)
print(""Values in Centigrade degrees:"")
print(5*F/9 - 5*32/9)
"
1455,Write a NumPy program to compute the weighted of a given array. ,"import numpy as np
x = np.arange(5)
print(""\nOriginal array:"")
print(x)
weights = np.arange(1, 6)
r1 = np.average(x, weights=weights)
r2 = (x*(weights/weights.sum())).sum()
assert np.allclose(r1, r2)
print(""\nWeighted average of the said array:"")
print(r1)
"
1456,Write a NumPy program to compute the Kronecker product of two given mulitdimension arrays. ,"import numpy as np
a = np.array([1,2,3])
b = np.array([0,1,0])
print(""Original 1-d arrays:"")
print(a)
print(b)
result = np.kron(a, b)
print(""Kronecker product of the said arrays:"")
print(result)
x = np.arange(9).reshape(3, 3)
y = np.arange(3, 12).reshape(3, 3)
print(""Original Higher dimension:"")
print(x)
print(y)
result = np.kron(x, y)
print(""Kronecker product of the said arrays:"")
print(result)
"
1457,Write a Python program to sort a given list of strings(numbers) numerically. ,"def sort_numeric_strings(nums_str):
result = [int(x) for x in nums_str]
result.sort()
return result
nums_str = ['4','12','45','7','0','100','200','-12','-500']
print(""Original list:"")
print(nums_str)
print(""\nSort the said list of strings(numbers) numerically:"")
print(sort_numeric_strings(nums_str))
"
1458,Write a Python program to compute the difference between two lists. ,"from collections import Counter
color1 = [""red"", ""orange"", ""green"", ""blue"", ""white""]
color2 = [""black"", ""yellow"", ""green"", ""blue""]
counter1 = Counter(color1)
counter2 = Counter(color2)
print(""Color1-Color2: "",list(counter1 - counter2))
print(""Color2-Color1: "",list(counter2 - counter1))
"
1459,"Write a NumPy program to replace all numbers in a given array which is equal, less and greater to a given number. ","import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 8.32, 6.99],
[1.54, 2.39, 9.29]])
print(""Original array:"")
print(nums)
n = 8.32
r = 18.32
print(""\nReplace elements of the said array which are equal to "",n,""with"",r)
print(np.where(nums == n, r, nums))
print(""\nReplace elements with of the said array which are less than"",n,""with"",r)
print(np.where(nums < n, r, nums))
print(""\nReplace elements with of the said array which are greater than"",n,""with"",r)
print(np.where(nums > n, r, nums))
"
1460,"Write a Python program to split values into two groups, based on the result of the given filtering function. ","def bifurcate_by(lst, fn):
return [
[x for x in lst if fn(x)],
[x for x in lst if not fn(x)]
]
print(bifurcate_by(['red', 'green', 'black', 'white'], lambda x: x[0] == 'w'))
"
1461,Write a Pandas program to create a Pivot table and check missing values of children. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.loc[df['who']=='child'].isnull().sum()
print(result)
"
1462,Write a Python program to sort a list of nested dictionaries. ,"my_list = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
print(""Original List: "")
print(my_list)
my_list.sort(key=lambda e: e['key']['subkey'], reverse=True)
print(""Sorted List: "")
print(my_list)
"
1463,Write a NumPy program to get the unique elements of an array. ,"import numpy as np
x = np.array([10, 10, 20, 20, 30, 30])
print(""Original array:"")
print(x)
print(""Unique elements of the above array:"")
print(np.unique(x))
x = np.array([[1, 1], [2, 3]])
print(""Original array:"")
print(x)
print(""Unique elements of the above array:"")
print(np.unique(x))
"
1464,Write a Python program to extract a specified column from a given nested list. ,"def remove_column(nums, n):
result = [i.pop(n) for i in nums]
return result
list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
n = 0
print(""Original Nested list:"")
print(list1)
print(""Extract 1st column:"")
print(remove_column(list1, n))
list2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
n = 2
print(""\nOriginal Nested list:"")
print(list2)
print(""Extract 3rd column:"")
print(remove_column(list2, n))
"
1465,Write a Python program to print the following floating numbers with no decimal places. ,"x = 3.1415926
y = -12.9999
print(""\nOriginal Number: "", x)
print(""Formatted Number with no decimal places: ""+""{:.0f}"".format(x));
print(""Original Number: "", y)
print(""Formatted Number with no decimal places: ""+""{:.0f}"".format(y));
print()
"
1466,"Write a Python program to get the key, value and item in a dictionary. ","dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
print(""key value count"")
for count, (key, value) in enumerate(dict_num.items(), 1):
print(key,' ',value,' ', count)
"
1467,Write a NumPy program to create an array with values ranging from 12 to 38.,"import numpy as np
x = np.arange(12, 38)
print(x)
"
1468,Write a Pandas program to create a Pivot table and separate the gender according to whether they traveled alone or not to get the probability of survival. ,"import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table( 'survived' , [ 'sex' , 'alone' ] , 'class' )
print(result)
"
1469,Write a Python program to convert a given list of strings into list of lists using map function. ,"def strings_to_listOflists(str):
result = map(list, str)
return list(result)
colors = [""Red"", ""Green"", ""Black"", ""Orange""]
print('Original list of strings:')
print(colors)
print(""\nConvert the said list of strings into list of lists:"")
print(strings_to_listOflists(colors))
"
1470,"Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. ","def chars_mix_up(a, b):
new_a = b[:2] + a[2:]
new_b = a[:2] + b[2:]
return new_a + ' ' + new_b
print(chars_mix_up('abc', 'xyz'))
"
1471,"Write a Pandas program to get the day of month, day of year, week number and day of week from a given series of date strings. ","import pandas as pd
from dateutil.parser import parse
date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20'])
print(""Original Series:"")
print(date_series)
date_series = date_series.map(lambda x: parse(x))
print(""Day of month:"")
print(date_series.dt.day.tolist())
print(""Day of year:"")
print(date_series.dt.dayofyear.tolist())
print(""Week number:"")
print(date_series.dt.weekofyear.tolist())
print(""Day of week:"")
print(date_series.dt.weekday_name.tolist())
"
1472,Write a Python program to sort a given collection of numbers and its length in ascending order using Recursive Insertion Sort. ,"#Ref.https://bit.ly/3iJWk3w
from __future__ import annotations
def rec_insertion_sort(collection: list, n: int):
# Checks if the entire collection has been sorted
if len(collection) <= 1 or n <= 1:
return
insert_next(collection, n - 1)
rec_insertion_sort(collection, n - 1)
def insert_next(collection: list, index: int):
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
collection[index - 1], collection[index] = (
collection[index],
collection[index - 1],
)
insert_next(collection, index + 1)
nums = [4, 3, 5, 1, 2]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Insertion Sort the said list becomes:"")
rec_insertion_sort(nums, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Insertion Sort the said list becomes:"")
rec_insertion_sort(nums, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print(""\nOriginal list:"")
print(nums)
print(""After applying Recursive Insertion Sort the said list becomes:"")
rec_insertion_sort(nums, len(nums))
print(nums)
"
1473,"Write a NumPy program to create a 11x3 array filled with student information (id, class and name) and shuffle the said array rows starting from 3","import numpy as np
np.random.seed(42)
student = np.array([['stident_id', 'Class', 'Name'],
['01', 'V', 'Debby Pramod'],
['02', 'V', 'Artemiy Ellie'],
['03', 'V', 'Baptist Kamal'],
['04', 'V', 'Lavanya Davide'],
['05', 'V', 'Fulton Antwan'],
['06', 'V', 'Euanthe Sandeep'],
['07', 'V', 'Endzela Sanda'],
['08', 'V', 'Victoire Waman'],
['09', 'V', 'Briar Nur'],
['10', 'V', 'Rose Lykos']])
print(""Original array:"")
print(student)
np.random.shuffle(student[2:8])
print(""Shuffle the said array rows starting from 3rd to 9th"")
print(student)
"
1474,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))
"
1475,Write a Python program to remove a key from a dictionary. ,"myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
"
1476,Write a Python program to find the occurrences of 10 most common words in a given text. ,"from collections import Counter
import re
text = """"""The Python Software Foundation (PSF) is a 501(c)(3) non-profit
corporation that holds the intellectual property rights behind
the Python programming language. We manage the open source licensing
for Python version 2.1 and later and own and protect the trademarks
associated with Python. We also run the North American PyCon conference
annually, support other Python conferences around the world, and
fund Python related development with our grants program and by funding
special projects.""""""
words = re.findall('\w+',text)
print(Counter(words).most_common(10))
"
1477,"Write a Python function to get the city, state and country name of a specified latitude and longitude using Nominatim API and Geopy package. ","from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent=""geoapiExercises"")
def city_state_country(coord):
location = geolocator.reverse(coord, exactly_one=True)
address = location.raw['address']
city = address.get('city', '')
state = address.get('state', '')
country = address.get('country', '')
return city, state, country
print(city_state_country(""47.470706, -99.704723""))
"
1478,Write a Pandas program to create a period index represent all monthly boundaries of a given year. Also print start and end time for each period object in the said index. ,"import pandas as pd
import datetime
from datetime import datetime, date
sdt = datetime(2020, 1, 1)
edt = datetime(2020, 12, 31)
dateset = pd.period_range(sdt, edt, freq='M')
print(""All monthly boundaries of a given year:"")
print(dateset)
print(""\nStart and end time for each period object in the said index:"")
for d in dateset:
print (""{0} {1}"".format(d.start_time, d.end_time))
"
1479,Write a Python program to create a new list taking specific elements from a tuple and convert a string value to integer. ,"student_data = [('Alberto Franco','15/05/2002','35kg'), ('Gino Mcneill','17/05/2002','37kg'), ('Ryan Parkes','16/02/1999', '39kg'), ('Eesha Hinton','25/09/1998', '35kg')]
print(""Original data:"")
print(student_data)
students_data_name = list(map(lambda x:x[0], student_data))
students_data_dob = list(map(lambda x:x[1], student_data))
students_data_weight = list(map(lambda x:int(x[2][:-2]), student_data))
print(""\nStudent name:"")
print(students_data_name)
print(""Student name:"")
print(students_data_dob)
print(""Student weight:"")
print(students_data_weight)
"
1480,"Write a Python program to create a floating-point representation of the Arrow object, in UTC time using arrow module. ","import arrow
a = arrow.utcnow()
print(""Current Datetime:"")
print(a)
print(""\nFloating-point representation of the said Arrow object:"")
f = arrow.utcnow().float_timestamp
print(f)
"
1481,Write a NumPy program to compute the line graph of a set of data. ,"import numpy as np
import matplotlib.pyplot as plt
arr = np.random.randint(1, 50, 10)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
"
1482,Write a Python program to remove lowercase substrings from a given string. ,"import re
str1 = 'KDeoALOklOOHserfLoAJSIskdsf'
print(""Original string:"")
print(str1)
print(""After removing lowercase letters, above string becomes:"")
remove_lower = lambda text: re.sub('[a-z]', '', text)
result = remove_lower(str1)
print(result)
"
1483,Write a Python program to count occurrences of a substring in a string. ,"str1 = 'The quick brown fox jumps over the lazy dog.'
print()
print(str1.count(""fox""))
print()
"
1484,Write a Python program that reads each row of a given csv file and skip the header of the file. Also print the number of rows and the field names. ,"import csv
fields = []
rows = []
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar=',')
# Following command skips the first row of the CSV file.
fields = next(data)
for row in data:
print(', '.join(row))
print(""\nTotal no. of rows: %d""%(data.line_num))
print('Field names are:')
print(', '.join(field for field in fields))
"
1485,Write a Pandas program to set value in a specific cell in a given dataframe using index. ,"import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, 32, 33, 30, 31, 32]},
index = ['t1', 't2', 't3', 't4', 't5', 't6'])
print(""Original DataFrame:"")
print(df)
print(""\nSet school code 's004' to 's005':"")
df.at['t6', 'school_code'] = 's005'
print(df)
print(""\nSet date_of_birth of 'Alberto Franco' to '16/05/2002':"")
df.at['t1', 'date_of_birth'] = '16/05/2002'
print(df)
"
1486, Write a Python program to check whether a page contains a title or not. ,"from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://www.wikipedia.org/')
bs = BeautifulSoup(html, ""html.parser"")
nameList = bs.findAll('a', {'class' : 'link-box'})
for name in nameList:
print(name.get_text())
"
1487,Write a Pandas program to generate sequences of fixed-frequency dates and time spans. ,"import pandas as pd
dtr = pd.date_range('2018-01-01', periods=12, freq='H')
print(""Hourly frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='min')
print(""\nMinutely frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='S')
print(""\nSecondly frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='2H')
print(""nMultiple Hourly frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='5min')
print(""\nMultiple Minutely frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='BQ')
print(""\nMultiple Secondly frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='w')
print(""\nWeekly frequency:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='2h20min')
print(""\nCombine together day and intraday offsets-1:"")
print(dtr)
dtr = pd.date_range('2018-01-01', periods=12, freq='1D10U')
print(""\nCombine together day and intraday offsets-2:"")
print(dtr)
"
1488,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()))
"
1489,Write a Python program to find the index of a given string at which a given substring starts. If the substring is not found in the given string return 'Not found'. ,"def find_Index(str1, pos):
if len(pos) > len(str1):
return 'Not found'
for i in range(len(str1)):
for j in range(len(pos)):
if str1[i + j] == pos[j] and j == len(pos) - 1:
return i
elif str1[i + j] != pos[j]:
break
return 'Not found'
print(find_Index(""Python Exercises"", ""Ex""))
print(find_Index(""Python Exercises"", ""yt""))
print(find_Index(""Python Exercises"", ""PY""))
"
1490,Write a Pandas program to import three datasheets from a given excel data (employee.xlsx ) into a single dataframe and export the result into new Excel file. ,"import pandas as pd
import numpy as np
df1 = pd.read_excel('E:\employee.xlsx',sheet_name=0)
df2 = pd.read_excel('E:\employee.xlsx',sheet_name=1)
df3 = pd.read_excel('E:\employee.xlsx',sheet_name=2)
df = pd.concat([df1, df2, df3])
df.to_excel('e:\output.xlsx', index=False)
"
1491,"Write a Python program that accept name of given subject and marks. Input number of subjects in first line and subject name,marks separated by a space in next line. Print subject name and marks in order of its first occurrence. ","import collections, re
n = int(input(""Number of subjects: ""))
item_order = collections.OrderedDict()
for i in range(n):
sub_marks_list = re.split(r'(\d+)$',input(""Input Subject name and marks: "").strip())
subject_name = sub_marks_list[0]
item_price = int(sub_marks_list[1])
if subject_name not in item_order:
item_order[subject_name]=item_price
else:
item_order[subject_name]=item_order[subject_name]+item_price
for i in item_order:
print(i+str(item_order[i]))
"
1492,Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. ,"def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
"
1493,Write a Pandas program to find the positions of the values neighboured by smaller values on both sides in a given series. ,"import pandas as pd
import numpy as np
nums = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1])
print(""Original series:"")
print(nums)
print(""\nPositions of the values surrounded by smaller values on both sides:"")
temp = np.diff(np.sign(np.diff(nums)))
result = np.where(temp == -2)[0] + 1
print(result)
"
1494,Write a Python program to print the following integers with '*' on the right of specified width. ,"x = 3
y = 123
print(""\nOriginal Number: "", x)
print(""Formatted Number(right padding, width 2): ""+""{:*< 3d}"".format(x));
print(""Original Number: "", y)
print(""Formatted Number(right padding, width 6): ""+""{:*< 7d}"".format(y));
print()
"
1495,Write a NumPy program to convert an array to a float type. ,"import numpy as np
import numpy as np
a = [1, 2, 3, 4]
print(""Original array"")
print(a)
x = np.asfarray(a)
print(""Array converted to a float type:"")
print(x)
"
1496,Write a Python program to count the same pair in two given lists. use map() function. ,"from operator import eq
def count_same_pair(nums1, nums2):
result = sum(map(eq, nums1, nums2))
return result
nums1 = [1,2,3,4,5,6,7,8]
nums2 = [2,2,3,1,2,6,7,9]
print(""Original lists:"")
print(nums1)
print(nums2)
print(""\nNumber of same pair of the said two given lists:"")
print(count_same_pair(nums1, nums2))
"
1497,Write a Python program to find unique triplets whose three elements gives the sum of zero from an array of n integers. ,"def three_sum(nums):
result = []
nums.sort()
for i in range(len(nums)-2):
if i> 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s > 0:
r -= 1
elif s < 0:
l += 1
else:
# found three sum
result.append((nums[i], nums[l], nums[r]))
# remove duplicates
while l < r and nums[l] == nums[l+1]:
l+=1
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1
r -= 1
return result
x = [1, -6, 4, 2, -1, 2, 0, -2, 0 ]
print(three_sum(x))
"
1498,Write a Python program to write (without writing separate lines between rows) and read a CSV file with specified delimiter. Use csv.reader,"import csv
fw = open(""test.csv"", ""w"", newline='')
writer = csv.writer(fw, delimiter = "","")
writer.writerow([""a"",""b"",""c""])
writer.writerow([""d"",""e"",""f""])
writer.writerow([""g"",""h"",""i""])
fw.close()
fr = open(""test.csv"", ""r"")
csv = csv.reader(fr, delimiter = "","")
for row in csv:
print(row)
fr.close()
"
1499,"Write a Python program to make an iterator that drops elements from the iterable as long as the elements are negative; afterwards, returns every element. ","import itertools as it
def drop_while(nums):
return it.takewhile(lambda x : x < 0, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print(""Original list: "",nums)
result = drop_while(nums)
print(""Drop elements from the said list as long as the elements are negative\n"",list(result))
#Alternate solution
def negative_num(x):
return x < 0
def drop_while(nums):
return it.dropwhile(negative_num, nums)
nums = [-1,-2,-3,4,-10,2,0,5,12]
print(""Original list: "",nums)
result = drop_while(nums)
print(""Drop elements from the said list as long as the elements are negative\n"",list(result))
"
1500,Write a Pandas program to create a hitmap for more information about the distribution of missing values in a given DataFrame. ,"import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
plt.figure(figsize=(16,10))
sns.heatmap(df.isnull(), cbar=False, cmap=""YlGnBu"")
plt.show()
"
1501,Write a Pandas program to create a combination from two dataframes where a column id combination appears more than once in both dataframes.,"import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'R': ['R0', 'R1', 'R2', 'R3'],
'S': ['S0', 'S1', 'S2', 'S3']})
print(""Original DataFrames:"")
print(data1)
print(""--------------------"")
print(data2)
print(""\nMerged Data (many-to-many join case):"")
result = pd.merge(data1, data2, on='key1')
print(result)
"
1502,"Write a Python program to create a new Arrow object, representing the ""ceiling"" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute. ","import arrow
print(arrow.utcnow())
print(""Hour ceiling:"")
print(arrow.utcnow().ceil('hour'))
print(""\nMinute ceiling:"")
print(arrow.utcnow().ceil('minute'))
print(""\nSecond ceiling:"")
print(arrow.utcnow().ceil('second'))
"
1503,Write a Python program to move all spaces to the front of a given string in single traversal. ,"def moveSpaces(str1):
no_spaces = [char for char in str1 if char!=' ']
space= len(str1) - len(no_spaces)
# Create string with spaces
result = ' '*space
return result + ''.join(no_spaces)
s1 = ""Python Exercises""
print(""Original String:\n"",s1)
print(""\nAfter moving all spaces to the front:"")
print(moveSpaces(s1))
"
1504,Write a Python program to check if all the elements of a list are included in another given list. ,"def test_includes_all(nums, lsts):
for x in lsts:
if x not in nums:
return False
return True
print(test_includes_all([10, 20, 30, 40, 50, 60], [20, 40]))
print(test_includes_all([10, 20, 30, 40, 50, 60], [20, 80]))
"
1505,"Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0. ","import numpy as np
x = np.eye(3)
print(x)
"
1506,Write a Python program to create a 3X3 grid with numbers. ,"nums = []
for i in range(3):
nums.append([])
for j in range(1, 4):
nums[i].append(j)
print(""3X3 grid with numbers:"")
print(nums)
"
1507,Write a Python program that sum the length of the names of a given list of names after removing the names that starts with an lowercase letter. Use lambda function. ,"sample_names = ['sally', 'Dylan', 'rebecca', 'Diana', 'Joanne', 'keith']
sample_names=list(filter(lambda el:el[0].isupper() and el[1:].islower(),sample_names))
print(""Result:"")
print(len(''.join(sample_names)))
"
1508,"Write a Python program to extract year, month and date value from current datetime using arrow module. ","import arrow
a = arrow.utcnow()
print(""Year:"")
print(a.year)
print(""\nMonth:"")
print(a.month)
print(""\nDate:"")
print(a.day)
"
1509,"Write a Pandas program to create a histograms plot of opening, closing, high, low stock prices of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
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[['Open','Close','High','Low']]
#df3 = df2.set_index('Date')
plt.figure(figsize=(25,25))
df2.plot.hist(alpha=0.5)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='blue')
plt.show()
"
1510, Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org. ,"#https://bit.ly/2lVhlLX
# via: https://analytics.usa.gov/
import requests
url = 'https://analytics.usa.gov/data/live/realtime.json'
j = requests.get(url).json()
print(""Number of people visiting a U.S. government website-"")
print(""Active Users Right Now:"")
print(j['data'][0]['active_visitors'])
"
1511,"Write a NumPy program to count the number of dimensions, number of elements and number of bytes for each element in a given array. ","import numpy as np
print(""\nOriginal arrays:"")
x = np.array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
print(x)
print(""\nNumber of dimensions:"")
print(x.ndim)
print(""Number of elements:"")
print(x.size)
print(""Number of bytes for each element in the said array:"")
print(x.itemsize)
"
1512,Write a Pandas program to find the all the business quarterly begin and end dates of a specified year. ,"import pandas as pd
q_start_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQS-JUN')
q_end_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQ-JUN')
print(""All the business quarterly begin dates of 2020:"")
print(q_start_dates.values)
print(""\nAll the business quarterly end dates of 2020:"")
print(q_end_dates.values)
"
1513,Write a Python program to replace dictionary values with their average. ,"def sum_math_v_vi_average(list_of_dicts):
for d in list_of_dicts:
n1 = d.pop('V')
n2 = d.pop('VI')
d['V+VI'] = (n1 + n2)/2
return list_of_dicts
student_details= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82},
{'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74},
{'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86}
]
print(sum_math_v_vi_average(student_details))
"
1514,"Write a Python program to convert string values of a given dictionary, into integer/float datatypes. ","def convert_to_int(lst):
result = [dict([a, int(x)] for a, x in b.items()) for b in lst]
return result
def convert_to_float(lst):
result = [dict([a, float(x)] for a, x in b.items()) for b in lst]
return result
nums =[{ 'x':'10' , 'y':'20' , 'z':'30' }, { 'p':'40', 'q':'50', 'r':'60'}]
print(""Original list:"")
print(nums)
print(""\nString values of a given dictionary, into integer types:"")
print(convert_to_int(nums))
nums =[{ 'x':'10.12', 'y':'20.23', 'z':'30'}, { 'p':'40.00', 'q':'50.19', 'r':'60.99'}]
print(""\nOriginal list:"")
print(nums)
print(""\nString values of a given dictionary, into float types:"")
print(convert_to_float(nums))
"
1515,Write a Python program to remove specific words from a given list. ,"def remove_words(list1, remove_words):
for word in list(list1):
if word in remove_words:
list1.remove(word)
return list1
colors = ['red', 'green', 'blue', 'white', 'black', 'orange']
remove_colors = ['white', 'orange']
print(""Original list:"")
print(colors)
print(""\nRemove words:"")
print(remove_colors)
print(""\nAfter removing the specified words from the said list:"")
print(remove_words(colors, remove_colors))
"
1516,"Write a NumPy program to test equal, not equal, greater equal, greater and less test of all the elements of two given arrays. ","import numpy as np
x1 = np.array(['Hello', 'PHP', 'JS', 'examples', 'html'], dtype=np.str)
x2 = np.array(['Hello', 'php', 'Java', 'examples', 'html'], dtype=np.str)
print(""\nArray1:"")
print(x1)
print(""Array2:"")
print(x2)
print(""\nEqual test:"")
r = np.char.equal(x1, x2)
print(r)
print(""\nNot equal test:"")
r = np.char.not_equal(x1, x2)
print(r)
print(""\nLess equal test:"")
r = np.char.less_equal(x1, x2)
print(r)
print(""\nGreater equal test:"")
r = np.char.greater_equal(x1, x2)
print(r)
print(""\nLess test:"")
r = np.char.less(x1, x2)
print(r)
"
1517,Write a Python program to reverse each list in a given list of lists. ,"def reverse_list_lists(nums):
for l in nums:
l.sort(reverse = True)
return nums
nums = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
print(""Original list of lists:"")
print(nums)
print(""\nReverse each list in the said list of lists:"")
print(reverse_list_lists(nums))
"
1518,Write a Pandas program to compute the autocorrelations of a given numeric series. ,"import pandas as pd
import numpy as np
num_series = pd.Series(np.arange(15) + np.random.normal(1, 10, 15))
print(""Original series:"")
print(num_series)
autocorrelations = [num_series.autocorr(i).round(2) for i in range(11)]
print(""\nAutocorrelations of the said series:"")
print(autocorrelations[1:])
"
1519,Write a NumPy program to split the element of a given array to multiple lines. ,"import numpy as np
x = np.array(['Python\Exercises, Practice, Solution'], dtype=np.str)
print(""Original Array:"")
print(x)
r = np.char.splitlines(x)
print(r)
"
1520,Write a Python program to find the text of the first tag of a given html text. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
""""""
soup = BeautifulSoup(html_doc,""lxml"")
print(""\nBeneath directly head tag:"")
print(soup.select(""head > title""))
print()
print(""\nBeneath directly p tag:"")
print(soup.select(""p > a""))
"
1564,"Write a Python program generate permutations of specified elements, drawn from specified values. ","from itertools import product
def permutations_colors(inp, n):
for x in product(inp, repeat=n):
c = ''.join(x)
print(c,end=', ')
str1 = ""Red""
print(""Original String: "",str1)
print(""Permutations of specified elements, drawn from specified values:"")
n=1
print(""\nn = 1"")
permutations_colors(str1,n)
n=2
print(""\nn = 2"")
permutations_colors(str1,n)
n=3
print(""\nn = 3"")
permutations_colors(str1,n)
lst1 = [""Red"",""Green"",""Black""]
print(""\n\nOriginal list: "",lst1)
print(""Permutations of specified elements, drawn from specified values:"")
n=1
print(""\nn = 1"")
permutations_colors(lst1,n)
n=2
print(""\nn = 2"")
permutations_colors(lst1,n)
n=3
print(""\nn = 3"")
permutations_colors(lst1,n)
"
1565,Write a Python program to remove all elements from a given list present in another list using lambda. ,"def index_on_inner_list(list1, list2):
result = list(filter(lambda x: x not in list2, list1))
return result
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [2,4,6,8]
print(""Original lists:"")
print(""list1:"", list1)
print(""list2:"", list2)
print(""\nRemove all elements from 'list1' present in 'list2:"")
print(index_on_inner_list(list1, list2))
"
1566,Write a NumPy program to shuffle numbers between 0 and 10 (inclusive). ,"import numpy as np
x = np.arange(10)
np.random.shuffle(x)
print(x)
print(""Same result using permutation():"")
print(np.random.permutation(10))
"
1567,Write a Pandas program to compute difference of differences between consecutive numbers of a given series. ,"import pandas as pd
series1 = pd.Series([1, 3, 5, 8, 10, 11, 15])
print(""Original Series:"")
print(series1)
print(""\nDifference of differences between consecutive numbers of the said series:"")
print(series1.diff().tolist())
print(series1.diff().diff().tolist())
"
1568,Write a Pandas program to extract the sentences where a specific word is present in a given column of a given DataFrame. ,"import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'address': ['9910 Surrey Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.', '17 West Livingston Court']
})
print(""Original DataFrame:"")
print(df)
def pick_only_key_sentence(str1, word):
result = re.findall(r'([^.]*'+word+'[^.]*)', str1)
return result
df['filter_sentence']=df['address'].apply(lambda x : pick_only_key_sentence(x,'Avenue'))
print(""\nText with the word 'Avenue':"")
print(df)
"
1569,"Write a Python program to get the size, permissions, owner, device, created, last modified and last accessed date time of a specified path. ","import os
import sys
import time
path = 'g:\\testpath\\'
print('Path Name ({}):'.format(path))
print('Size:', stat_info.st_size)
print('Permissions:', oct(stat_info.st_mode))
print('Owner:', stat_info.st_uid)
print('Device:', stat_info.st_dev)
print('Created :', time.ctime(stat_info.st_ctime))
print('Last modified:', time.ctime(stat_info.st_mtime))
print('Last accessed:', time.ctime(stat_info.st_atime))
"
1570,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]))
"
1571,Write a NumPy program to convert 1-D arrays as columns into a 2-D array. ,"import numpy as np
a = np.array((10,20,30))
b = np.array((40,50,60))
c = np.column_stack((a, b))
print(c)
"
1572,Write a NumPy program to convert a NumPy array into a csv file. ,"import numpy
data = numpy.asarray([ [10,20,30], [40,50,60], [70,80,90] ])
numpy.savetxt(""test.csv"", data, delimiter="","")
"
1573,Write a Python function to insert a string in the middle of a string. ,"def insert_sting_middle(str, word):
return str[:2] + word + str[2:]
print(insert_sting_middle('[[]]', 'Python'))
print(insert_sting_middle('{{}}', 'PHP'))
print(insert_sting_middle('<<>>', 'HTML'))
"
1574,"Write a Python program to calculate the average of a given list, after mapping each element to a value using the provided function. ","def average_by(lst, fn = lambda x: x):
return sum(map(fn, lst), 0.0) / len(lst)
print(average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']))
print(average_by([{ 'n': 10 }, { 'n': 20 }, { 'n': -30 }, { 'n': 60 }], lambda x: x['n']))
"
1575,"Write a Pandas program to create a line plot of the opening, closing stock prices of Alphabet Inc. between two specific dates. ","import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(""alphabet_stock_data.csv"")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df2 = df.loc[new_df]
plt.figure(figsize=(10,10))
df2.plot(x='Date', y=['Open', 'Close']);
plt.suptitle('Opening/Closing stock prices of Alphabet Inc.,\n 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.xlabel(""Date"",fontsize=12, color='black')
plt.ylabel(""$ price"", fontsize=12, color='black')
plt.show()
"
1576,Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and find all records that include two specific MSHA ID. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df[df[""MSHA ID""].isin([102976,103380])].head()
"
1577,Write a Python function that takes a number as a parameter and check the number is prime or not. ,"def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))
"
1578,Write a Python program to print a dictionary in table format. ,"my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}
for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
print(*row)
"
1579,"Write a Python code to send a request to a web page, and print the information of headers. Also parse these values and print key-value pairs holding various information. ","import requests
r = requests.get('https://api.github.com/')
response = r.headers
print(""Headers information of the said response:"")
print(response)
print(""\nVarious Key-value pairs information of the said resource and request:"")
print(""Date: "",r.headers['date'])
print(""server: "",r.headers['server'])
print(""status: "",r.headers['status'])
print(""cache-control: "",r.headers['cache-control'])
print(""vary: "",r.headers['vary'])
print(""x-github-media-type: "",r.headers['x-github-media-type'])
print(""access-control-expose-headers: "",r.headers['access-control-expose-headers'])
print(""strict-transport-security: "",r.headers['strict-transport-security'])
print(""x-content-type-options: "",r.headers['x-content-type-options'])
print(""x-xss-protection: "",r.headers['x-xss-protection'])
print(""referrer-policy: "",r.headers['referrer-policy'])
print(""content-security-policy: "",r.headers['content-security-policy'])
print(""content-encoding: "",r.headers['content-encoding'])
print(""X-Ratelimit-Remaining: "",r.headers['X-Ratelimit-Remaining'])
print(""X-Ratelimit-Reset: "",r.headers['X-Ratelimit-Reset'])
print(""X-Ratelimit-Used: "",r.headers['X-Ratelimit-Used'])
print(""Accept-Ranges:"",r.headers['Accept-Ranges'])
print(""X-GitHub-Request-Id:"",r.headers['X-GitHub-Request-Id'])
"
1580,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)
"
1581,Write a Python program to define a string containing special characters in various forms. ,"print()
print(""\#{'}${\""}@/"")
print(""\#{'}${""'""'""}@/"")
print(r""""""\#{'}${""}@/"""""")
print('\#{\'}${""}@/')
print('\#{'""'""'}${""}@/')
print(r'''\#{'}${""}@/''')
print()
"
1582,Write a Python program to create a list taking alternate elements from a given list. ,"def alternate_elements(list_data):
result=[]
for item in list_data[::2]:
result.append(item)
return result
colors = [""red"", ""black"", ""white"", ""green"", ""orange""]
print(""Original list:"")
print(colors)
print(""List with alternate elements from the said list:"")
print(alternate_elements(colors))
nums = [2,0,3,4,0,2,8,3,4,2]
print(""\nOriginal list:"")
print(nums)
print(""List with alternate elements from the said list:"")
print(alternate_elements(nums))
"
1583,Write a Python program to convert a given list of tuples to a list of strings. ,"def tuples_to_list_str(lst):
result = [(""%s ""*len(el)%el).strip() for el in lst]
return result
colors = [('red', 'green'), ('black', 'white'), ('orange', 'pink')]
print(""Original list of tuples:"")
print(colors)
print(""\nConvert the said list of tuples to a list of strings:"")
print(tuples_to_list_str(colors))
names = [('Laiba','Delacruz'), ('Mali','Stacey','Drummond'), ('Raja','Welch'), ('Saarah','Stone')]
print(""\nOriginal list of tuples:"")
print(names)
print(""\nConvert the said list of tuples to a list of strings:"")
print(tuples_to_list_str(names))
"
1584,"Write a Python program to make two given strings (lower case, may or may not be of the same length) anagrams removing any characters from any of the strings. ","def make_map(s):
temp_map = {}
for char in s:
if char not in temp_map:
temp_map[char] = 1
else:
temp_map[char] +=1
return temp_map
def make_anagram(str1, str2):
str1_map1 = make_map(str1)
str2_map2 = make_map(str2)
ctr = 0
for key in str2_map2.keys():
if key not in str1_map1:
ctr += str2_map2[key]
else:
ctr += max(0, str2_map2[key]-str1_map1[key])
for key in str1_map1.keys():
if key not in str2_map2:
ctr += str1_map1[key]
else:
ctr += max(0, str1_map1[key]-str2_map2[key])
return ctr
str1 = input(""Input string1: "")
str2 = input(""Input string2: "")
print(make_anagram(str1, str2))
"
1585,Write a Python program to convert JSON encoded data into Python objects. ,"import json
jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}'
jobj_list = '[""Red"", ""Green"", ""Black""]'
jobj_string = '""Python Json""'
jobj_int = '1234'
jobj_float = '21.34'
python_dict = json.loads(jobj_dict)
python_list = json.loads(jobj_list)
python_str = json.loads(jobj_string)
python_int = json.loads(jobj_int)
python_float = json.loads(jobj_float)
print(""Python dictionary: "", python_dict)
print(""Python list: "", python_list)
print(""Python string: "", python_str)
print(""Python integer: "", python_int)
print(""Python float: "", python_float)
"
1586,Write a Python program to extract all the URLs from the webpage python.org that are nested within
tags from . ,"import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
urls = []
for h in soup.find_all('li'):
a = h.find('a')
urls.append(a.attrs['href'])
print(urls)
"
1587,Write a Python program for counting sort. ,"def counting_sort(array1, max_val):
m = max_val + 1
count = [0] * m
for a in array1:
# count occurences
count[a] += 1
i = 0
for a in range(m):
for c in range(count[a]):
array1[i] = a
i += 1
return array1
print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))
"
1588,Write a NumPy program to create a NumPy array of 10 integers from a generator. ,"import numpy as np
iterable = (x for x in range(10))
print(np.fromiter(iterable, np.int))
"
1589,"Write a Python program to create a 3-tuple ISO year, ISO week number, ISO weekday and an ISO 8601 formatted representation of the date and time. ","import arrow
a = arrow.utcnow()
print(""Current datetime:"")
print(a)
print(""\n3-tuple - ISO year, ISO week number, ISO weekday:"")
print(arrow.utcnow().isocalendar())
print(""\nISO 8601 formatted representation of the date and time:"")
print(arrow.utcnow().isoformat())
"
1590,Write a Python program to get the frequency of the elements in a given list of lists. Use collections module. ,"from collections import Counter
from itertools import chain
nums = [
[1,2,3,2],
[4,5,6,2],
[7,1,9,5],
]
print(""Original list of lists:"")
print(nums)
print(""\nFrequency of the elements in the said list of lists:"")
result = Counter(chain.from_iterable(nums))
print(result)
"
1591,Write a Python program to concatenate N strings. ,"list_of_colors = ['Red', 'White', 'Black']
colors = '-'.join(list_of_colors)
print()
print(""All Colors: ""+colors)
print()
"
1592,Write a Python program to calculate the harmonic sum of n-1. ,"def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))
print(harmonic_sum(7))
print(harmonic_sum(4))
"
1593,Write a Python program to create a given flat list of all the keys in a flat dictionary. ,"def keys_only(students):
return list(students.keys())
students = {
'Laura': 10,
'Spencer': 11,
'Bridget': 9,
'Howard ': 10,
}
print(""Original directory elements:"")
print(students)
print(""\nFlat list of all the keys of the said dictionary:"")
print(keys_only(students))
"
1594,"Write a NumPy program to create an array of (3, 4) shape and convert the array elements in smaller chunks. ","import numpy as np
x= np.arange(12).reshape(3, 4)
print(""Original array elements:"")
print(x)
print(""Above array in small chuncks:"")
for a in np.nditer(x, flags=['external_loop'], order='F'):
print(a)
"
1595,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))
"
1596,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())
"
1597,Write a Pandas program to create a time series using three months frequency. ,"import pandas as pd
time_series = pd.date_range('1/1/2021', periods = 36, freq='3M')
print(""Time series using three months frequency:"")
print(time_series)
"
1598,Write a Pandas program to create a comparison of the top 10 years in which the UFO was sighted vs the hours of the day. ,"import pandas as pd
#Source: https://bit.ly/1l9yjm9
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
most_sightings_years = df['Date_time'].dt.year.value_counts().head(10)
def is_top_years(year):
if year in most_sightings_years.index:
return year
hour_v_year = df.pivot_table(columns=df['Date_time'].dt.hour,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city')
hour_v_year.columns = hour_v_year.columns.astype(int)
hour_v_year.columns = hour_v_year.columns.astype(str) + "":00""
hour_v_year.index = hour_v_year.index.astype(int)
print(""\nComparison of the top 10 years in which the UFO was sighted vs the hours of the day:"")
print(hour_v_year.head(10))
"
1599,Write a NumPy program to create a 3X4 array using and iterate over it. ,"import numpy as np
a = np.arange(10,22).reshape((3, 4))
print(""Original array:"")
print(a)
print(""Each element of the array is:"")
for x in np.nditer(a):
print(x,end="" "")
"
1600,Write a NumPy program to calculate average values of two given NumPy arrays. ,"import numpy as np
array1 = [[0, 1], [2, 3]]
array2 = [[4, 5], [0, 3]]
print(""Original arrays:"")
print(array1)
print(array2)
print(""Average values of two said numpy arrays:"")
result = (np.array(array1) + np.array(array2)) / 2
print(result)
"
1601,Write a NumPy program to search the index of a given array in another given array. ,"import numpy as np
np_array = np.array([[1,2,3], [4,5,6] , [7,8,9], [10, 11, 12]])
test_array = np.array([4,5,6])
print(""Original Numpy array:"")
print(np_array)
print(""Searched array:"")
print(test_array)
print(""Index of the searched array in the original array:"")
print(np.where((np_array == test_array).all(1))[0])
"
1602,Write a Python program to get the frequency of the elements in a given list of lists. ,"def count_elements_lists(nums):
nums = [item for sublist in nums for item in sublist]
dic_data = {}
for num in nums:
if num in dic_data.keys():
dic_data[num] += 1
else:
key = num
value = 1
dic_data[key] = value
return dic_data
nums = [
[1,2,3,2],
[4,5,6,2],
[7,8,9,5],
]
print(""Original list of lists:"")
print(nums)
print(""\nFrequency of the elements in the said list of lists:"")
print(count_elements_lists(nums))
"
1603,Write a Python program to perform Counter arithmetic and set operations for aggregating results. ,"import collections
c1 = collections.Counter([1, 2, 3, 4, 5])
c2 = collections.Counter([4, 5, 6, 7, 8])
print('C1:', c1)
print('C2:', c2)
print('\nCombined counts:')
print(c1 + c2)
print('\nSubtraction:')
print(c1 - c2)
print('\nIntersection (taking positive minimums):')
print(c1 & c2)
print('\nUnion (taking maximums):')
print(c1 | c2)
"
1604,Write a Python program to create group of similar items of a given list. ,"import itertools as it
def group_similar_items(seq):
result = [list(el) for _, el in it.groupby(seq, lambda x: x.split('_')[0])]
return result
colors = ['red_1', 'red_2', 'green_1', 'green_2', 'green_3', 'orange_1', 'orange_2']
print(""Original list:"")
print(colors)
print(""\nGroup similar items of the said list:"")
print(group_similar_items(colors))
colors = ['red_1', 'green-1', 'green_2', 'green_3', 'orange-1', 'orange_2']
print(""\nOriginal list:"")
print(colors)
print(""\nGroup similar items of the said list:"")
print(group_similar_items(colors))
"
1605,Write a Python program to count and display the vowels of a given text. ,"def vowel(text):
vowels = ""aeiuoAEIOU""
print(len([letter for letter in text if letter in vowels]))
print([letter for letter in text if letter in vowels])
vowel('w3resource');
"
1606,Write a Python program to calculate surface volume and area of a cylinder. ,"pi=22/7
height = float(input('Height of cylinder: '))
radian = float(input('Radius of cylinder: '))
volume = pi * radian * radian * height
sur_area = ((2*pi*radian) * height) + ((pi*radian**2)*2)
print(""Volume is: "", volume)
print(""Surface Area is: "", sur_area)
"
1607,"Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise. ","import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index = [""Region"",""Manager""], values = [""Sale_amt""],aggfunc=np.sum))
"
1608,Write a Python program to sort a list of elements using Gnome sort. ,"def gnome_sort(nums):
if len(nums) <= 1:
return nums
i = 1
while i < len(nums):
if nums[i-1] <= nums[i]:
i += 1
else:
nums[i-1], nums[i] = nums[i], nums[i-1]
i -= 1
if (i == 0):
i = 1
user_input = input(""Input numbers separated by a comma:\n"").strip()
nums = [int(item) for item in user_input.split(',')]
gnome_sort(nums)
print(nums)
"
1609,Write a Pandas program to split a given dataframe into groups and list all the keys from the GroupBy object. ,"import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print(""Original DataFrame:"")
print(df)
print(""\nSplit the data on school_code:"");
gp = df.groupby('school_code')
print(""\nList of all the keys:"")
print(gp.groups.keys())
"
1610,Write a Pandas program to join the two dataframes using the common column of both dataframes. ,"import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],
'marks': [201, 200, 198, 219, 201]})
print(""Original DataFrames:"")
print(student_data1)
print(student_data2)
merged_data = pd.merge(student_data1, student_data2, on='student_id', how='inner')
print(""Merged data (inner join):"")
print(merged_data)
"
1611,Write a NumPy program to count a given word in each row of a given array of string values. ,"import numpy as np
str1 = np.array([['Python','NumPy','Exercises'],
['Python','Pandas','Exercises'],
['Python','Machine learning','Python']])
print(""Original array of string values:"")
print(str1)
print(""\nCount 'Python' row wise in the above array of string values:"")
print(np.char.count(str1, 'Python'))
"
1612,Write a NumPy program to create an array of 10's with the same shape and type of a given array. ,"import numpy as np
x = np.arange(4, dtype=np.int64)
y = np.full_like(x, 10)
print(y)
"
1613,Write a NumPy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix. ,"import numpy as np
arra = np.array([[ 1, 1, 0],
[ 0, 0, 0],
[ 0, 2, 3],
[ 0, 0, 0],
[ 0, -1, 1],
[ 0, 0, 0]])
print(""Original array:"")
print(arra)
temp = {(0, 0, 0)}
result = []
for idx, row in enumerate(map(tuple, arra)):
if row not in temp:
result.append(idx)
print(""\nNon-zero unique rows:"")
print(arra[result])
"
1614,Write a Python program to print a list of space-separated elements. ,"num = [1, 2, 3, 4, 5]
print(*num)
"
1615,Write a Python program to get the top three items in a shop. ,"from heapq import nlargest
from operator import itemgetter
items = {'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}
for name, value in nlargest(3, items.items(), key=itemgetter(1)):
print(name, value)
"
1616,Write a Python program to insert an element at a specified position into a given list. ,"def insert_spec_position(x, n_list, pos):
return n_list[:pos-1]+[x]+n_list[pos-1:]
n_list = [1,1,2,3,4,4,5,1]
print(""Original list:"")
print(n_list)
kth_position = 3
x = 12
result = insert_spec_position(x, n_list, kth_position)
print(""\nAfter inserting an element at kth position in the said list:"")
print(result)
"
1617,Write a Python program to check if a given function returns True for every element in a list. ,"def every(lst, fn = lambda x: x):
return all(map(fn, lst))
print(every([4, 2, 3], lambda x: x > 1))
print(every([4, 2, 3], lambda x: x < 1))
print(every([4, 2, 3], lambda x: x == 1))
"
1618,Write a Pandas program to calculate the frequency counts of each unique value of a given series. ,"import pandas as pd
import numpy as np
num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40)))
print(""Original Series:"")
print(num_series)
print(""Frequency of each unique value of the said series."")
result = num_series.value_counts()
print(result)
"
1619,"Write a NumPy program to sort pairs of first name and last name return their indices. (first by last name, then by first name). ","import numpy as np
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
x = np.lexsort((first_names, last_names))
print(x)
"
1620,"Write a Pandas program to split the following datasets into groups on customer id and calculate the number of customers starting with 'C', the list of all products and the difference of maximum purchase amount and minimum purchase amount. ","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': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'customer_id':['C3001','C3001','D3005','D3001','C3005','D3001','C3005','D3001','D3005','C3001','D3005','D3005'],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print(""Original Orders DataFrame:"")
print(df)
def customer_id_C(x):
return (x.str[0] == 'C').sum()
result = df.groupby(['salesman_id'])\
.agg(customer_id_start_C = ('customer_id', customer_id_C),
customer_id_list = ('customer_id', lambda x: ', '.join(x)),
purchase_amt_gap = ('purch_amt', lambda x: x.max()-x.min())
)
print(""\nNumber of customers starting with ‘C’, the list of all products and the difference of maximum purchase amount and minimum purchase amount:"")
print(result)
"
1621,Write a Python program to read a given CSV file as a dictionary. ,"import csv
data = csv.DictReader(open(""departments.csv""))
print(""CSV file as a dictionary:\n"")
for row in data:
print(row)
"
1622,Write a Pandas program create a series with a PeriodIndex which represents all the calendar month periods in 2029 and 2031. Also print the values for all periods in 2030. ,"import pandas as pd
import numpy as np
pi = pd.Series(np.random.randn(36),
pd.period_range('1/1/2029',
'12/31/2031', freq='M'))
print(""PeriodIndex which represents all the calendar month periods in 2029 and 2030:"")
print(pi)
print(""\nValues for all periods in 2030:"")
print(pi['2030'])
"
1623,Write a Python program to sort a given list of strings(numbers) numerically using lambda. ,"def sort_numeric_strings(nums_str):
result = sorted(nums_str, key=lambda el: int(el))
return result
nums_str = ['4','12','45','7','0','100','200','-12','-500']
print(""Original list:"")
print(nums_str)
print(""\nSort the said list of strings(numbers) numerically:"")
print(sort_numeric_strings(nums_str))
"
1624,Write a Python program to count number of lists in a given list of lists. ,"def count_list(input_list):
return len(input_list)
list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]]
list2 = [[2, 4], [[6,8], [4,5,8]], [10, 12, 14]]
print(""Original list:"")
print(list1)
print(""\nNumber of lists in said list of lists:"")
print(count_list(list1))
print(""\nOriginal list:"")
print(list2)
print(""\nNumber of lists in said list of lists:"")
print(count_list(list2))
"
1625,"Write a Python program to create a datetime object, converted to the specified timezone using arrow module. ","import arrow
utc = arrow.utcnow()
pacific=arrow.now('US/Pacific')
nyc=arrow.now('America/Chicago').tzinfo
print(pacific.astimezone(nyc))
"
1626,Write a Python program to sort each sublist of strings in a given list of lists. ,"def sort_sublists(input_list):
result = list(map(sorted, input_list))
return result
color1 = [[""green"", ""orange""], [""black"", ""white""], [""white"", ""black"", ""orange""]]
print(""\nOriginal list:"")
print(color1)
print(""\nAfter sorting each sublist of the said list of lists:"")
print(sort_sublists(color1))
"
1627,"Write a Pandas program to create a Pivot table and find the region wise, item wise unit sold. ","import numpy as np
import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=[""Region"", ""Item""], values=""Units"", aggfunc=np.sum))
"
1628,Write a Python program to group the elements of a list based on the given function and returns the count of elements in each group. ,"from collections import defaultdict
def count_by(lst, fn = lambda x: x):
count = defaultdict(int)
for val in map(fn, lst):
count[val] += 1
return dict(count)
from math import floor
print(count_by([6.1, 4.2, 6.3], floor))
print(count_by(['one', 'two', 'three'], len))
"
1629,Write a Python program to find tag(s) beneath other tag(s) in a given html document. ,"from bs4 import BeautifulSoup
html_doc = """"""
An example of HTML page
This is an example HTML page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.
""""""
soup = BeautifulSoup(html_doc,""lxml"")
print(""\na tag(s) Beneath body tag:"")
print(soup.select(""body a""))
print(""\nBeneath html head:"")
print(soup.select(""html head title""))
"
1630,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))
"
1631,Write a Python program to decode a run-length encoded given list. ,"def decode(alist):
def aux(g):
if isinstance(g, list):
return [(g[1], range(g[0]))]
else:
return [(g, [0])]
return [x for g in alist for x, R in aux(g) for i in R]
n_list = [[2, 1], 2, 3, [2, 4], 5, 1]
print(""Original encoded list:"")
print(n_list)
print(""\nDecode a run-length encoded said list:"")
print(decode(n_list))
"
1632,Write a Pandas program to convert given datetime to timestamp. ,"import pandas as pd
import datetime as dt
import numpy as np
df = pd.DataFrame(index=pd.DatetimeIndex(start=dt.datetime(2019,1,1,0,0,1),
end=dt.datetime(2019,1,1,10,0,1), freq='H'))\
.reset_index().rename(columns={'index':'datetime'})
print(""Sample datetime data:"")
print(df.head(10))
df['ts'] = df.datetime.values.astype(np.int64) // 10 ** 9
print(""\nConvert datetime to timestamp:"")
print (df)
"
1633,"Write a NumPy program to compute the mean, standard deviation, and variance of a given array along the second axis. ","import numpy as np
x = np.arange(6)
print(""\nOriginal array:"")
print(x)
r1 = np.mean(x)
r2 = np.average(x)
assert np.allclose(r1, r2)
print(""\nMean: "", r1)
r1 = np.std(x)
r2 = np.sqrt(np.mean((x - np.mean(x)) ** 2 ))
assert np.allclose(r1, r2)
print(""\nstd: "", 1)
r1= np.var(x)
r2 = np.mean((x - np.mean(x)) ** 2 )
assert np.allclose(r1, r2)
print(""\nvariance: "", r1)
"
1634,Write a Pandas program to drop the rows where at least one element is missing 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,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',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""\nDrop the rows where at least one element is missing:"")
result = df.dropna()
print(result)
"
1635,Write a NumPy program to find the position of the index of a specified value greater than existing value in NumPy array. ,"import numpy as np
n= 4
nums = np.arange(-6, 6)
print(""\nOriginal array:"")
print(nums)
print(""\nPosition of the index:"")
print(np.argmax(nums>n/2))
"
1636,"Write a Python program to get a list of elements that exist in both lists, after applying the provided function to each list element of both. ","def intersection_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) in _b]
from math import floor
print(intersection_by([2.1, 1.2], [2.3, 3.4], floor))
"
1637,"Write a Python program to create datetime from integers, floats and strings timestamps using arrow module. ","import arrow
i = arrow.get(1857900545)
print(""Date from integers: "")
print(i)
f = arrow.get(1857900545.234323)
print(""\nDate from floats: "")
print(f)
s = arrow.get('1857900545')
print(""\nDate from Strings: "")
print(s)
"
1638,Write a Python program to insert an item in front of a given doubly linked list. ,"class Node(object):
# Singly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
def print_foward(self):
for node in self.iter():
print(node)
def insert_start(self, data):
if self.head is not None:
new_node = Node(data, None, None)
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
self.count += 1
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
items.append_item('SQL')
print(""Original list:"")
items.print_foward()
print(""\nAppend item in front of the list:"")
items.insert_start(""Perl"")
items.print_foward()
"
1639,Write a Python program to select the odd items of a list. ,"x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[::2])
"
1640,Write a NumPy program to create an array that represents the rank of each item of a given array. ,"import numpy as numpy
array = numpy.array([24, 27, 30, 29, 18, 14])
print(""Original array:"")
print(array)
argsort_array = array.argsort()
ranks_array = numpy.empty_like(argsort_array)
ranks_array[argsort_array] = numpy.arange(len(array))
print(""\nRank of each item of the said array:"")
print(ranks_array)
"
1641,Write a Pandas program to split a dataset to group by two columns and count by each row. ,"import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
orders_data = 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':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print(""Original Orders DataFrame:"")
print(orders_data)
print(""\nGroup by two columns and count by each row:"")
result = orders_data.groupby(['salesman_id','customer_id']).size().reset_index().groupby(['salesman_id','customer_id'])[[0]].max()
print(result)
"
1642,Write a NumPy program to encode all the elements of a given array in cp500 and decode it again. ,"import numpy as np
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
print(""Original Array:"")
print(x)
encoded_char = np.char.encode(x, 'cp500')
decoded_char = np.char.decode(encoded_char,'cp500')
print(""\nencoded ="", encoded_char)
print(""decoded ="", decoded_char)
"
1643,"Write a Python program to find the parent's process id, real user ID of the current process and change real user ID. ","import os
print(""Parent’s process id:"",os.getppid())
uid = os.getuid()
print(""\nUser ID of the current process:"", uid)
uid = 1400
os.setuid(uid)
print(""\nUser ID changed"")
print(""User ID of the current process:"", os.getuid())
"
1644,Write a Python program to valid a IP address. ,"import socket
addr = '127.0.0.2561'
try:
socket.inet_aton(addr)
print(""Valid IP"")
except socket.error:
print(""Invalid IP"")
"
1645,Write a Python program to split a list every Nth element. ,"C = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
def list_slice(S, step):
return [S[i::step] for i in range(step)]
print(list_slice(C,3))
"
1646,"Write a Python program to add two given lists of different lengths, start from left , using itertools module. ","from itertools import zip_longest
def elementswise_left_join(l1, l2):
result = [a + b for a,b in zip_longest(l1, l2, fillvalue=0)][::1]
return result
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""\nAdd said two lists from left:"")
print(elementswise_left_join(nums1, nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print(""\nOriginal lists:"")
print(nums3)
print(nums4)
print(""\nAdd said two lists from left:"")
print(elementswise_left_join(nums3, nums4))
"
1647,Write a Python program to write a list to a file. ,"color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
with open('abc.txt', ""w"") as myfile:
for c in color:
myfile.write(""%s\n"" % c)
content = open('abc.txt')
print(content.read())
"
1648,Write a Python program to find the item with maximum occurrences in a given list. ,"def max_occurrences(nums):
max_val = 0
result = nums[0]
for i in nums:
occu = nums.count(i)
if occu > max_val:
max_val = occu
result = i
return result
nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
print (""Original list:"")
print(nums)
print(""\nItem with maximum occurrences of the said list:"")
print(max_occurrences(nums))
"
1649,Write a NumPy program to compute the covariance matrix of two given arrays. ,"import numpy as np
x = np.array([0, 1, 2])
y = np.array([2, 1, 0])
print(""\nOriginal array1:"")
print(x)
print(""\nOriginal array1:"")
print(y)
print(""\nCovariance matrix of the said arrays:\n"",np.cov(x, y))
"
1650,Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and display the last ten rows. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.tail(n=10)
"
1651,Write a NumPy program to save a NumPy array to a text file. ,"import numpy as np
a = np.arange(1.0, 2.0, 36.2)
np.savetxt('file.out', a, delimiter=',')
"
1652,Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and convert the data to use the hire_date as the index. ,"import pandas as pd
import numpy as np
df = pd.read_excel('E:\employee.xlsx')
result = df.set_index(['hire_date'])
result
"
1653,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)
"
1654,Write a NumPy program to extract all the rows to compute the student weight from a given array (student information) where a specific column starts with a given character. ,"import numpy as np
np.set_printoptions(linewidth=100)
student = np.array([['01', 'V', 'Debby Pramod', 30.21],
['02', 'V', 'Artemiy Ellie', 29.32],
['03', 'V', 'Baptist Kamal', 31.00],
['04', 'V', 'Lavanya Davide', 30.22],
['05', 'V', 'Fulton Antwan', 30.21],
['06', 'V', 'Euanthe Sandeep', 31.00],
['07', 'V', 'Endzela Sanda', 32.00],
['08', 'V', 'Victoire Waman', 29.21],
['09', 'V', 'Briar Nur', 30.00],
['10', 'V', 'Rose Lykos', 32.00]])
print(""Original array:"")
print(student)
char='E'
result = student[np.char.startswith(student[:,2], char)]
print(""\nTotal weight, where student name starting with"",char)
print(np.round(result[:, 3].astype(float).sum(), 2))
char='D'
result = student[np.char.startswith(student[:,2], char)]
print(""\nTotal weight, where student name starting with"",char)
print(np.round(result[:, 3].astype(float).sum(), 2))
"
1655,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))
"
1656,Write a Python program to check whether an instance is complex or not. ,"import json
def encode_complex(object):
# check using isinstance method
if isinstance(object, complex):
return [object.real, object.imag]
# raised error if object is not complex
raise TypeError(repr(object) + "" is not JSON serialized"")
complex_obj = json.dumps(2 + 3j, default=encode_complex)
print(complex_obj)
"
1657,Write a Python program to print the numbers of a specified list after removing even numbers from it. ,"num = [7,8, 120, 25, 44, 20, 27]
num = [x for x in num if x%2!=0]
print(num)
"
1658,Write a Python program to insert tags or strings immediately before specified tags or strings. ,"from bs4 import BeautifulSoup
soup = BeautifulSoup(""w3resource.com"", ""lxml"")
print(""Original Markup:"")
print(soup.b)
tag = soup.new_tag(""i"")
tag.string = ""Python""
print(""\nNew Markup, before inserting the text:"")
soup.b.string.insert_before(tag)
print(soup.b)
"
1659,Write a Python program to convert an array to an ordinary list with the same items. ,"from array import *
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
print(""Original array: ""+str(array_num))
num_list = array_num.tolist()
print(""Convert the said array to an ordinary list with the same items:"")
print(num_list)
"
1660,Write a Python function to check whether a string is a pangram or not. ,"import string, sys
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
print ( ispangram('The quick brown fox jumps over the lazy dog'))
"
1661,Write a Python program to create a new deque with three items and iterate over the deque's elements. ,"from collections import deque
dq = deque('aeiou')
for element in dq:
print(element)
"
1662,Write a NumPy program to convert a PIL Image into a NumPy array. ,"import numpy as np
import PIL
img_data = PIL.Image.open('w3resource-logo.png' )
img_arr = np.array(img_data)
print(img_arr)
"
1663,Write a Pandas program to create a Timewheel of Hour Vs Year comparison of the top 10 years in which the UFO was sighted. ,"import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cm as cm
#Source: https://bit.ly/2XDY2XN
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
most_sightings_years = df['Date_time'].dt.year.value_counts().head(10)
def is_top_years(year):
if year in most_sightings_years.index:
return year
month_vs_year = df.pivot_table(columns=df['Date_time'].dt.month,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city')
month_vs_year.index = month_vs_year.index.astype(int)
month_vs_year.columns = month_vs_year.columns.astype(int)
print(""\nComparison of the top 10 years in which the UFO was sighted vs each month:"")
def pie_heatmap(table, cmap='coolwarm_r', vmin=None, vmax=None,inner_r=0.25, pie_args={}):
n, m = table.shape
vmin= table.min().min() if vmin is None else vmin
vmax= table.max().max() if vmax is None else vmax
centre_circle = plt.Circle((0,0),inner_r,edgecolor='black',facecolor='white',fill=True,linewidth=0.25)
plt.gcf().gca().add_artist(centre_circle)
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
cmapper = cm.ScalarMappable(norm=norm, cmap=cmap)
for i, (row_name, row) in enumerate(table.iterrows()):
labels = None if i > 0 else table.columns
wedges = plt.pie([1] * m,radius=inner_r+float(n-i)/n, colors=[cmapper.to_rgba(x) for x in row.values],
labels=labels, startangle=90, counterclock=False, wedgeprops={'linewidth':-1}, **pie_args)
plt.setp(wedges[0], edgecolor='grey',linewidth=1.5)
wedges = plt.pie([1], radius=inner_r+float(n-i-1)/n, colors=['w'], labels=[row_name], startangle=-90, wedgeprops={'linewidth':0})
plt.setp(wedges[0], edgecolor='grey',linewidth=1.5)
plt.figure(figsize=(8,8))
plt.title(""Timewheel of Hour Vs Year"",y=1.08,fontsize=30)
pie_heatmap(month_vs_year, vmin=-20,vmax=80,inner_r=0.2)
"
1664,Write a NumPy program to check whether two arrays are equal (element wise) or not. ,"import numpy as np
nums1 = np.array([0.5, 1.5, 0.2])
nums2 = np.array([0.4999999999, 1.500000000, 0.2])
np.set_printoptions(precision=15)
print(""Original arrays:"")
print(nums1)
print(nums2)
print(""\nTest said two arrays are equal (element wise) or not:?"")
print(nums1 == nums2)
nums1 = np.array([0.5, 1.5, 0.23])
nums2 = np.array([0.4999999999, 1.5000000001, 0.23])
print(""\nOriginal arrays:"")
np.set_printoptions(precision=15)
print(nums1)
print(nums2)
print(""\nTest said two arrays are equal (element wise) or not:?"")
print(np.equal(nums1, nums2))
"
1665,"Write a Python program to add two given lists of different lengths, start from right. ","def elementswise_right_join(l1, l2):
f_len = len(l1)-(len(l2) - 1)
for i in range(len(l1), 0, -1):
if i-f_len < 0:
break
else:
l1[i-1] = l1[i-1] + l2[i-f_len]
return l1
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""\nAdd said two lists from left:"")
print(elementswise_right_join(nums1, nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print(""\nOriginal lists:"")
print(nums3)
print(nums4)
print(""\nAdd said two lists from left:"")
print(elementswise_right_join(nums3, nums4))
"
1666,Write a Python program find the sorted sequence from a set of permutations of a given input. ,"from itertools import permutations
from more_itertools import windowed
def is_seq_sorted(lst):
print(lst)
return all(
x <= y
for x, y in windowed(lst, 2)
)
def permutation_sort(lst):
return next(
permutation_seq
for permutation_seq in permutations(lst)
if is_seq_sorted(permutation_seq)
)
print(""All the sequences:"")
print(""\nSorted sequence: "",permutation_sort([12, 10, 9]))
print(""\n\nAll the sequences:"")
print(""\nSorted sequence: "",permutation_sort([2, 3, 1, 0]))
"
1667,Write a Pandas program to calculate all the sighting days of the unidentified flying object (ufo) from current date. ,"import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
now = pd.to_datetime('today')
print(""Original Dataframe:"")
print(df.head())
print(""\nCurrent date:"")
print(now)
"
1668,"Write a Python program to add two given lists of different lengths, start from right , using itertools module. ","from itertools import zip_longest
def elementswise_right_join(l1, l2):
result = [a + b for a,b in zip_longest(reversed(l1), reversed(l2), fillvalue=0)][::-1]
return result
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print(""\nOriginal lists:"")
print(nums1)
print(nums2)
print(""\nAdd said two lists from right:"")
print(elementswise_right_join(nums1, nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print(""\nOriginal lists:"")
print(nums3)
print(nums4)
print(""\nAdd said two lists from right:"")
print(elementswise_right_join(nums3, nums4))
"
1669,Write a Pandas program to replace NaNs with median or mean of the specified columns 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print(""Original Orders DataFrame:"")
print(df)
print(""Using median in purch_amt to replace NaN:"")
df['purch_amt'].fillna(df['purch_amt'].median(), inplace=True)
print(df)
print(""Using mean to replace NaN:"")
df['sale_amt'].fillna(int(df['sale_amt'].mean()), inplace=True)
print(df)
"
1670,Write a Python program to change the tag's contents and replace with the given string. ,"from bs4 import BeautifulSoup
html_doc = 'HTMLexample.com'
soup = BeautifulSoup(html_doc, ""lxml"")
tag = soup.a
print(""\nOriginal Markup:"")
print(tag)
print(""\nOriginal Markup with new text:"")
tag.string = ""CSS""
print(tag)
"
1671,"Write a Python program to get the symmetric difference between two lists, after applying the provided function to each list element of both. ","def symmetric_difference_by(a, b, fn):
(_a, _b) = (set(map(fn, a)), set(map(fn, b)))
return [item for item in a if fn(item) not in _b] + [item
for item in b if fn(item) not in _a]
from math import floor
print(symmetric_difference_by([2.1, 1.2], [2.3, 3.4], floor))
"
1672,Write a NumPy program to collapse a 3-D array into one dimension array. ,"import numpy as np
x = np.eye(3)
print(""3-D array:"")
print(x)
f = np.ravel(x, order='F')
print(""One dimension array:"")
print(f)
"
1673,"Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). ","n=int(input(""Input a number ""))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
"
1674,Write a Pandas program to find out the records where consumption of beverages per person average >=5 and Beverage Types is Beer from 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: average consumption of \nbeverages per person >=5 and Beverage Types is Beer:"")
print(w_a_con[(w_a_con['Display Value'] >= 5) & (w_a_con['Beverage Types'] == 'Beer')].head(10))
"
1675,"Write a Python program to a list of all the h1, h2, h3 tags from the webpage python.org. ","import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print(""List of all the h1, h2, h3 :"")
for heading in soup.find_all([""h1"", ""h2"", ""h3""]):
print(heading.name + ' ' + heading.text.strip())
"
1676,Write a Python program to print a given doubly linked list in reverse order. ,"class Node(object):
# Singly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
def print_foward(self):
for node in self.iter():
print(node)
def reverse(self):
"""""" Reverse linked list. """"""
current = self.head
while current:
temp = current.next
current.next = current.prev
current.prev = temp
current = current.prev
temp = self.head
self.head = self.tail
self.tail = temp
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
items.append_item('SQL')
print(""Reverse list "")
items.reverse()
items.print_foward()
"
1677,"Write a NumPy program to replace ""PHP"" with ""Python"" in the element of a given array. ","import numpy as np
x = np.array(['PHP Exercises, Practice, Solution'], dtype=np.str)
print(""\nOriginal Array:"")
print(x)
r = np.char.replace(x, ""PHP"", ""Python"")
print(""\nNew array:"")
print(r)
"
1678,Write a Python program to create multiple lists. ,"obj = {}
for i in range(1, 21):
obj[str(i)] = []
print(obj)
"
1679,Write a Python program to remove duplicate words from a given list of strings. ,"def unique_list(l):
temp = []
for x in l:
if x not in temp:
temp.append(x)
return temp
text_str = [""Python"", ""Exercises"", ""Practice"", ""Solution"", ""Exercises""]
print(""Original String:"")
print(text_str)
print(""\nAfter removing duplicate words from the said list of strings:"")
print(unique_list(text_str))
"
1680,Write a Python program to split a variable length string into variables. ,"var_list = ['a', 'b', 'c']
x, y, z = (var_list + [None] * 3)[:3]
print(x, y, z)
var_list = [100, 20.25]
x, y = (var_list + [None] * 2)[:2]
print(x, y)
"
1681,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)
"
1682,Difference between List comprehension and Lambda in Python,"lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
print(lst)"
1683,Write a Python program to Convert Snake case to Pascal case,"# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using title() + replace()
# initializing string
test_str = 'geeksforgeeks_is_best'
# printing original string
print(""The original string is : "" + test_str)
# Convert Snake case to Pascal case
# Using title() + replace()
res = test_str.replace(""_"", "" "").title().replace("" "", """")
# printing result
print(""The String after changing case : "" + str(res)) "
1684,Check whether a Numpy array contains a specified row in Python,"# importing package
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]
])
# view array
print(arr)
# check for some lists
print([1, 2, 3, 4, 5] in arr.tolist())
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())
print([11, 12, 13, 14, 15] in arr.tolist())"
1685,Write a Python program to convert Set into Tuple and Tuple into Set,"# program to convert set to tuple
# create set
s = {'a', 'b', 'c', 'd', 'e'}
# print set
print(type(s), "" "", s)
# call tuple() method
# this method convert set to tuple
t = tuple(s)
# print tuple
print(type(t), "" "", t)"
1686,Write a Python datetime to integer timestamp,"from datetime import datetime
curr_dt = datetime.now()
print(""Current datetime: "", curr_dt)
timestamp = int(round(curr_dt.timestamp()))
print(""Integer timestamp of current datetime: "",
timestamp)"
1687,Different ways to iterate over rows in Pandas Dataframe in Python,"# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'],
'Age': [21, 19, 20, 18],
'Stream': ['Math', 'Commerce', 'Arts', 'Biology'],
'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print(""Given Dataframe :\n"", df)
print(""\nIterating over rows using index attribute :\n"")
# iterate through each row and select
# 'Name' and 'Stream' column respectively.
for ind in df.index:
print(df['Name'][ind], df['Stream'][ind])"
1688,Write a Python program to Sort Nested keys by Value,"# Python3 code to demonstrate working of
# Sort Nested keys by Value
# Using sorted() + generator expression + lamda
# initializing dictionary
test_dict = {'Nikhil' : {'English' : 5, 'Maths' : 2, 'Science' : 14},
'Akash' : {'English' : 15, 'Maths' : 7, 'Science' : 2},
'Akshat' : {'English' : 5, 'Maths' : 50, 'Science' : 20}}
# printing original dictionary
print(""The original dictionary : "" + str(test_dict))
# Sort Nested keys by Value
# Using sorted() + generator expression + lamda
res = {key : dict(sorted(val.items(), key = lambda ele: ele[1]))
for key, val in test_dict.items()}
# printing result
print(""The sorted dictionary : "" + str(res)) "
1689,Download Google Image Using Python and Selenium,"from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# What you enter here will be searched for in
# Google Images
query = ""dogs""
# Creating a webdriver instance
driver = webdriver.Chrome('Enter-Location-Of-Your-Webdriver')
# Maximize the screen
driver.maximize_window()
# Open Google Images in the browser
driver.get('https://images.google.com/')
# Finding the search box
box = driver.find_element_by_xpath('//*[@id=""sbtc""]/div/div[2]/input')
# Type the search query in the search box
box.send_keys(query)
# Pressing enter
box.send_keys(Keys.ENTER)
# Fumction for scrolling to the bottom of Google
# Images results
def scroll_to_bottom():
last_height = driver.execute_script('\
return document.body.scrollHeight')
while True:
driver.execute_script('\
window.scrollTo(0,document.body.scrollHeight)')
# waiting for the results to load
# Increase the sleep time if your internet is slow
time.sleep(3)
new_height = driver.execute_script('\
return document.body.scrollHeight')
# click on ""Show more results"" (if exists)
try:
driver.find_element_by_css_selector("".YstHxe input"").click()
# waiting for the results to load
# Increase the sleep time if your internet is slow
time.sleep(3)
except:
pass
# checking if we have reached the bottom of the page
if new_height == last_height:
break
last_height = new_height
# Calling the function
# NOTE: If you only want to capture a few images,
# there is no need to use the scroll_to_bottom() function.
scroll_to_bottom()
# Loop to capture and save each image
for i in range(1, 50):
# range(1, 50) will capture images 1 to 49 of the search results
# You can change the range as per your need.
try:
# XPath of each image
img = driver.find_element_by_xpath(
'//*[@id=""islrg""]/div[1]/div[' +
str(i) + ']/a[1]/div[1]/img')
# Enter the location of folder in which
# the images will be saved
img.screenshot('Download-Location' +
query + ' (' + str(i) + ').png')
# Each new screenshot will automatically
# have its name updated
# Just to avoid unwanted errors
time.sleep(0.2)
except:
# if we can't find the XPath of an image,
# we skip to the next image
continue
# Finally, we close the driver
driver.close()"
1690,How to compare two NumPy arrays in Python,"import numpy as np
an_array = np.array([[1, 2], [3, 4]])
another_array = np.array([[1, 2], [3, 4]])
comparison = an_array == another_array
equal_arrays = comparison.all()
print(equal_arrays)"
1691,Write a Python program to Avoid Last occurrence of delimitter,"# Python3 code to demonstrate working of
# Avoid Last occurrence of delimitter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing delim
delim = ""$""
# appending delim to join
# will leave stray ""$"" at end
res = ''
for ele in test_list:
res += str(ele) + ""$""
# removing last using slicing
res = res[:len(res) - 1]
# printing result
print(""The joined string : "" + str(res))"
1692,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()"
1693,GUI to generate and store passwords in SQLite using Python,"import random
import webbrowser
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import back
import csv
from ttkbootstrap import *
class window:
# these are lists of initialized characters
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
sym = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|',
'~', '>', '*', '<']
def __init__(self, root, geo, title) -> None:
self.root = root
self.root.title(title)
self.root.geometry(geo)
self.root.resizable(width=False, height=False)
Label(self.root, text='Your Password').grid(
row=0, column=0, padx=10, pady=10)
Label(self.root, text='Corresponding User_id').grid(
row=1, column=0, padx=10, pady=10)
Label(self.root, text='Of').grid(row=2, column=0, padx=10, pady=10)
self.pa = StringVar()
self.user_id = StringVar()
self.site = StringVar()
ttk.Entry(self.root, width=30, textvariable=self.pa
).grid(row=0, column=1, padx=10, pady=10)
ttk.Entry(self.root, width=30, textvariable=self.user_id
).grid(row=1, column=1, padx=10, pady=10)
ttk.Entry(self.root, width=30, textvariable=self.site
).grid(row=2, column=1, padx=10, pady=10)
self.length = StringVar()
e = ttk.Combobox(self.root, values=['4', '8', '12', '16', '20', '24'],
textvariable=self.length)
e.grid(row=0, column=2)
e['state'] = 'readonly'
self.length.set('Set password length')
ttk.Button(self.root, text='Generate', padding=5,
style='success.Outline.TButton', width=20,
command=self.generate).grid(row=1, column=2)
ttk.Button(self.root, text='Save to Database', style='success.TButton',
width=20, padding=5, command=self.save).grid(row=3, column=2)
ttk.Button(self.root, text='Delete', width=20, style='danger.TButton',
padding=5, command=self.erase).grid(row=2, column=2)
ttk.Button(self.root, text='Show All', width=20, padding=5,
command=self.view).grid(row=3, column=0)
ttk.Button(self.root, text='Update', width=20, padding=5,
command=self.update).grid(row=3, column=1)
# ========self.tree view=============
self.tree = ttk.Treeview(self.root, height=5)
self.tree['columns'] = ('site', 'user', 'pas')
self.tree.column('#0', width=0, stretch=NO)
self.tree.column('site', width=160, anchor=W)
self.tree.column('user', width=140, anchor=W)
self.tree.column('pas', width=180, anchor=W)
self.tree.heading('#0', text='')
self.tree.heading('site', text='Site name')
self.tree.heading('user', text='User Id')
self.tree.heading('pas', text='Password')
self.tree.grid(row=4, column=0, columnspan=3, pady=10)
self.tree.bind("""", self.catch)
# this command will call the catch function
# this is right click pop-up menu
self.menu = Menu(self.root, tearoff=False)
self.menu.add_command(label='Refresh', command=self.refresh)
self.menu.add_command(label='Insert', command=self.save)
self.menu.add_command(label='Update', command=self.update)
self.menu.add_separator()
self.menu.add_command(label='Show All', command=self.view)
self.menu.add_command(label='Clear Fields', command=self.clear)
self.menu.add_command(label='Clear Table', command=self.table)
self.menu.add_command(label='Export', command=self.export)
self.menu.add_separator()
self.menu.add_command(label='Delete', command=self.erase)
self.menu.add_command(label='Help', command=self.help)
self.menu.add_separator()
self.menu.add_command(label='Exit', command=self.root.quit)
# this binds the button 3 of the mouse with
self.root.bind("""", self.poppin)
# poppin function
def help(self):
# this function will open the help.txt in
# notepad when called
webbrowser.open('help.txt')
def refresh(self):
# this function basically refreshes the table
# or tree view
self.table()
self.view()
def table(self):
# this function will clear all the values
# displayed in the table
for r in self.tree.get_children():
self.tree.delete(r)
def clear(self):
# this function will clear all the entry
# fields
self.pa.set('')
self.user_id.set('')
self.site.set('')
def poppin(self, e):
# it triggers the right click pop-up menu
self.menu.tk_popup(e.x_root, e.y_root)
def catch(self, event):
# this function will take all the selected data
# from the table/ tree view and will fill up the
# respective entry fields
self.pa.set('')
self.user_id.set('')
self.site.set('')
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
self.site.set(value[0])
self.user_id.set(value[1])
self.pa.set(value[2])
def update(self):
# this function will update database with new
# values given by the user
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
back.edit(self.site.get(), self.user_id.get(), self.pa.get())
self.refresh()
def view(self):
# this will show all the data from the database
# this is similar to ""SELECT * FROM TABLE"" sql
# command
if back.check() is False:
messagebox.showerror('Attention Amigo!', 'Database is EMPTY!')
else:
for row in back.show():
self.tree.insert(parent='', text='', index='end',
values=(row[0], row[1], row[2]))
def erase(self):
# this will delete or remove the selected tuple or
# row from the database
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
back.Del(value[2])
self.refresh()
def save(self):
# this function will insert all the data into the
# database
back.enter(self.site.get(), self.user_id.get(), self.pa.get())
self.tree.insert(parent='', index='end', text='',
values=(self.site.get(), self.user_id.get(), self.pa.get()))
def generate(self):
# this function will produce a random string which
# will be used as password
if self.length.get() == 'Set password length':
messagebox.showerror('Attention!', ""You forgot to SELECT"")
else:
a = ''
for x in range(int(int(self.length.get())/4)):
a0 = random.choice(self.uc)
a1 = random.choice(self.lc)
a2 = random.choice(self.sym)
a3 = random.choice(self.digits)
a = a0+a1+a2+a3+a
self.pa.set(a)
def export(self):
# this function will save all the data from the
# database in a csv format which can be opened
# in excel
pop = Toplevel(self.root)
pop.geometry('300x100')
self.v = StringVar()
Label(pop, text='Save File Name as').pack()
ttk.Entry(pop, textvariable=self.v).pack()
ttk.Button(pop, text='Save', width=18,
command=lambda: exp(self.v.get())).pack(pady=5)
def exp(x):
with open(x + '.csv', 'w', newline='') as f:
chompa = csv.writer(f, dialect='excel')
for r in back.show():
chompa.writerow(r)
messagebox.showinfo(""File Saved"", ""Saved as "" + x + "".csv"")
if __name__ == '__main__':
win = Style(theme='darkly').master
name = 'Password Generator'
dimension = '565x320'
app = window(win, dimension, name)
win.mainloop()"
1694,Write a Python program to How to Concatenate tuples to nested tuples,"# Python3 code to demonstrate working of
# Concatenating tuples to nested tuples
# using + operator + "", "" operator during initialization
# initialize tuples
test_tup1 = (3, 4),
test_tup2 = (5, 6),
# printing original tuples
print(""The original tuple 1 : "" + str(test_tup1))
print(""The original tuple 2 : "" + str(test_tup2))
# Concatenating tuples to nested tuples
# using + operator + "", "" operator during initialization
res = test_tup1 + test_tup2
# printing result
print(""Tuples after Concatenating : "" + str(res))"
1695,How to change background color of Tkinter OptionMenu widget in Python,"# Python program to change menu background
# color of Tkinter's Option Menu
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title(""Vinayak App"")
# Construct the label in your app
l1 = Label(app, text=""Choose the the week day here"")
# Display the label l1
l1.grid()
# Construct the Options Menu widget in your app
text1 = StringVar()
# Set the value you wish to see by default
text1.set(""Choose here"")
# Create options from the Option Menu
w = OptionMenu(app, text1, ""Sunday"", ""Monday"", ""Tuesday"",
""Wednesday"", ""Thursday"", ""Friday"", ""Saturday"")
# Se the background color of Options Menu to green
w.config(bg=""GREEN"", fg=""WHITE"")
# Set the background color of Displayed Options to Red
w[""menu""].config(bg=""RED"")
# Display the Options Menu
w.grid(pady=20)
# Make the loop for displaying app
app.mainloop()"
1696,Write a Python program to find common elements in three lists using sets,"# Python3 program to find common elements
# in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
# Converting the arrays into sets
s1 = set(arr1)
s2 = set(arr2)
s3 = set(arr3)
# Calculates intersection of
# sets on s1 and s2
set1 = s1.intersection(s2) #[80, 20, 100]
# Calculates intersection of sets
# on set1 and s3
result_set = set1.intersection(s3)
# Converts resulting set to list
final_list = list(result_set)
print(final_list)
# Driver Code
if __name__ == '__main__' :
# Elements in Array1
arr1 = [1, 5, 10, 20, 40, 80, 100]
# Elements in Array2
arr2 = [6, 7, 20, 80, 100]
# Elements in Array3
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
# Calling Function
IntersecOfSets(arr1, arr2, arr3)"
1697,Write a Python program to Dictionary with maximum count of pairs,"# Python3 code to demonstrate working of
# Dictionary with maximum keys
# Using loop + len()
# initializing list
test_list = [{""gfg"": 2, ""best"" : 4},
{""gfg"": 2, ""is"" : 3, ""best"" : 4},
{""gfg"": 2}]
# printing original list
print(""The original list is : "" + str(test_list))
res = {}
max_len = 0
for ele in test_list:
# checking for lengths
if len(ele) > max_len:
res = ele
max_len = len(ele)
# printing results
print(""Maximum keys Dictionary : "" + str(res))"
1698,Write a Python program to print the Inverted heart pattern,"# determining the size of the heart
size = 15
# printing the inverted triangle
for a in range(0, size):
for b in range(a, size):
print("" "", end = """")
for b in range(1, (a * 2)):
print(""*"", end = """")
print("""")
# printing rest of the heart
for a in range(size, int(size / 2) - 1 , -2):
# printing the white space right-triangle
for b in range(1, size - a, 2):
print("" "", end = """")
# printing the first trapezium
for b in range(1, a + 1):
print(""*"", end = """")
# printing the white space triangle
for b in range(1, (size - a) + 1):
print("" "", end = """")
# printing the second trapezium
for b in range(1, a):
print(""*"", end = """")
# new line
print("""")"
1699,K’th Non-repeating Character in Python using List Comprehension and OrderedDict,"# Function to find k'th non repeating character
# in string
from collections import OrderedDict
def kthRepeating(input,k):
# OrderedDict returns a dictionary data
# structure having characters of input
# string as keys in the same order they
# were inserted and 0 as their default value
dict=OrderedDict.fromkeys(input,0)
# now traverse input string to calculate
# frequency of each character
for ch in input:
dict[ch]+=1
# now extract list of all keys whose value
# is 1 from dict Ordered Dictionary
nonRepeatDict = [key for (key,value) in dict.items() if value==1]
# now return (k-1)th character from above list
if len(nonRepeatDict) < k:
return 'Less than k non-repeating characters in input.'
else:
return nonRepeatDict[k-1]
# Driver function
if __name__ == ""__main__"":
input = ""geeksforgeeks""
k = 3
print (kthRepeating(input, k)) "
1700,Write a Python Set difference to find lost element from a duplicated array,"# Function to find lost element from a duplicate
# array
def lostElement(A,B):
# convert lists into set
A = set(A)
B = set(B)
# take difference of greater set with smaller
if len(A) > len(B):
print (list(A-B))
else:
print (list(B-A))
# Driver program
if __name__ == ""__main__"":
A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
lostElement(A,B)"
1701,Split a String into columns using regex in pandas DataFrame in Python,"# import the regex library
import pandas as pd
import re
# Create a list with all the strings
movie_data = [""Name: The_Godfather Year: 1972 Rating: 9.2"",
""Name: Bird_Box Year: 2018 Rating: 6.8"",
""Name: Fight_Club Year: 1999 Rating: 8.8""]
# Create a dictionary with the required columns
# Used later to convert to DataFrame
movies = {""Name"":[], ""Year"":[], ""Rating"":[]}
for item in movie_data:
# For Name field
name_field = re.search(""Name: .*"",item)
if name_field is not None:
name = re.search('\w*\s\w*',name_field.group())
else:
name = None
movies[""Name""].append(name.group())
# For Year field
year_field = re.search(""Year: .*"",item)
if year_field is not None:
year = re.search('\s\d\d\d\d',year_field.group())
else:
year = None
movies[""Year""].append(year.group().strip())
# For rating field
rating_field = re.search(""Rating: .*"",item)
if rating_field is not None:
rating = re.search('\s\d.\d',rating_field.group())
else:
rating - None
movies[""Rating""].append(rating.group().strip())
# Creating DataFrame
df = pd.DataFrame(movies)
print(df)"
1702,Program to check if a string contains any special character in Python,"// C++ program to check if a string
// contains any special character
// import required packages
#include
#include
using namespace std;
// Function checks if the string
// contains any special character
void run(string str)
{
// Make own character set
regex regx(""[@_!#$%^&*()<>?/|}{~:]"");
// Pass the string in regex_search
// method
if(regex_search(str, regx) == 0)
cout << ""String is accepted"";
else
cout << ""String is not accepted."";
}
// Driver Code
int main()
{
// Enter the string
string str = ""Geeks$For$Geeks"";
// Calling run function
run(str);
return 0;
}
// This code is contributed by Yash_R"
1703,Write a Python program to Tuple XOR operation,"# Python3 code to demonstrate working of
# Tuple XOR operation
# using zip() + generator expression
# initialize tuples
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
# printing original tuples
print(""The original tuple 1 : "" + str(test_tup1))
print(""The original tuple 2 : "" + str(test_tup2))
# Tuple XOR operation
# using zip() + generator expression
res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
# printing result
print(""The XOR tuple : "" + str(res)) "
1704,Calculate the mean across dimension in a 2D NumPy array in Python,"# Importing Library
import numpy as np
# creating 2d array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Calculating mean across Rows
row_mean = np.mean(arr, axis=1)
row1_mean = row_mean[0]
print(""Mean of Row 1 is"", row1_mean)
row2_mean = row_mean[1]
print(""Mean of Row 2 is"", row2_mean)
row3_mean = row_mean[2]
print(""Mean of Row 3 is"", row3_mean)
# Calculating mean across Columns
column_mean = np.mean(arr, axis=0)
column1_mean = column_mean[0]
print(""Mean of column 1 is"", column1_mean)
column2_mean = column_mean[1]
print(""Mean of column 2 is"", column2_mean)
column3_mean = column_mean[2]
print(""Mean of column 3 is"", column3_mean)"
1705,How to Build Web scraping bot in Python,"# These are the imports to be made
import time
from selenium import webdriver
from datetime import datetime"
1706,Sorting rows in pandas DataFrame in Python,"# import modules
import pandas as pd
# create dataframe
data = {'name': ['Simon', 'Marsh', 'Gaurav', 'Alex', 'Selena'],
'Maths': [8, 5, 6, 9, 7],
'Science': [7, 9, 5, 4, 7],
'English': [7, 4, 7, 6, 8]}
df = pd.DataFrame(data)
# Sort the dataframe’s rows by Science,
# in descending order
a = df.sort_values(by ='Science', ascending = 0)
print(""Sorting rows by Science:\n \n"", a)"
1707,How to get the indices of the sorted array using NumPy in Python,"import numpy as np
# Original array
array = np.array([10, 52, 62, 16, 16, 54, 453])
print(array)
# Indices of the sorted elements of a
# given array
indices = np.argsort(array)
print(indices)"
1708,Write a Python program to Get file id of windows file,"# importing popen from the os library
from os import popen
# Path to the file whose id we would
# be obtaining (relative / absolute)
file = r""C:\Users\Grandmaster\Desktop\testing.py""
# Running the command for obtaining the fileid,
# and saving the output of the command
output = popen(fr""fsutil file queryfileid {file}"").read()
# printing the output of the previous command
print(output)"
1709,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))"
1710,Write a Python program to Convert a set into dictionary,"# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print (""initial string"", ini_set)
print (type(ini_set))
# Converting set to dictionary
res = dict.fromkeys(ini_set, 0)
# printing final result and its type
print (""final list"", res)
print (type(res))"
1711,Write a Python program to Pair elements with Rear element in Matrix Row,"# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
# printing original list
print(""The original list is : "" + str(test_list))
# Pair elements with Rear element in Matrix Row
# using list comprehension
res = []
for sub in test_list:
res.append([[ele, sub[-1]] for ele in sub[:-1]])
# printing result
print (""The list after pairing is : "" + str(res))"
1712,Write a Python program to Uppercase Half String,"# Python3 code to demonstrate working of
# Uppercase Half String
# Using upper() + loop + len()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print(""The original string is : "" + str(test_str))
# computing half index
hlf_idx = len(test_str) // 2
res = ''
for idx in range(len(test_str)):
# uppercasing later half
if idx >= hlf_idx:
res += test_str[idx].upper()
else :
res += test_str[idx]
# printing result
print(""The resultant string : "" + str(res)) "
1713,"Reshape a pandas DataFrame using stack,unstack and melt method in Python","# import pandas module
import pandas as pd
# making dataframe
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
# it was print the first 5-rows
print(df.head()) "
1714,Write a Python program to Remove keys with Values Greater than K ( Including mixed values ),"# Python3 code to demonstrate working of
# Remove keys with Values Greater than K ( Including mixed values )
# Using loop + isinstance()
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# initializing K
K = 6
# using loop to iterate keys of dictionary
res = {}
for key in test_dict:
# testing for data type and then condition, order is imp.
if not (isinstance(test_dict[key], int) and test_dict[key] > K):
res[key] = test_dict[key]
# printing result
print(""The constructed dictionary : "" + str(res)) "
1715,Write a Python program to Replace duplicate Occurrence in String,"# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
Classes help understand better . '
# printing original string
print(""The original string is : "" + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print(""The string after replacing : "" + str(res)) "
1716,Write a Python program to find all the Combinations in the list with the given condition,"# Python3 code to demonstrate working of
# Optional Elements Combinations
# Using loop
# initializing list
test_list = [""geekforgeeks"", [5, 4, 3, 4], ""is"",
[""best"", ""good"", ""better"", ""average""]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing size of inner Optional list
K = 4
res = []
cnt = 0
while cnt <= K - 1:
temp = []
# inner elements selections
for idx in test_list:
# checks for type of Elements
if not isinstance(idx, list):
temp.append(idx)
else:
temp.append(idx[cnt])
cnt += 1
res.append(temp)
# printing result
print(""All index Combinations : "" + str(res))"
1717,numpy.inner() in python,"# Python Program illustrating
# numpy.inner() method
import numpy as geek
# Scalars
product = geek.inner(5, 4)
print(""inner Product of scalar values : "", product)
# 1D array
vector_a = 2 + 3j
vector_b = 4 + 5j
product = geek.inner(vector_a, vector_b)
print(""inner Product : "", product) "
1718,How to set the tab size in Text widget in Tkinter in Python,"# Import Module
from tkinter import *
# Create Object
root = Tk()
# Set Geometry
root.geometry(""400x400"")
# Execute Tkinter
root.mainloop()"
1719,Write a Python Program for Comb Sort,"# Python program for implementation of CombSort
# To find next gap from current
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10)/13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
n = len(arr)
# Initialize gap
gap = n
# Initialize swapped as true to make sure that
# loop runs
swapped = True
# Keep running while gap is more than 1 and last
# iteration caused a swap
while gap !=1 or swapped == 1:
# Find next gap
gap = getNextGap(gap)
# Initialize swapped as false so that we can
# check if swap happened or not
swapped = False
# Compare all elements with current gap
for i in range(0, n-gap):
if arr[i] > arr[i + gap]:
arr[i], arr[i + gap]=arr[i + gap], arr[i]
swapped = True
# Driver code to test above
arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]
combSort(arr)
print (""Sorted array:"")
for i in range(len(arr)):
print (arr[i]),
# This code is contributed by Mohit Kumra"
1720,Mapping external values to dataframe values in Pandas in Python,"# Creating new dataframe
import pandas as pd
initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'],
'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'],
'Age': [42, 52, 36, 21, 23],
'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']}
df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name',
'Age', 'City'])
# Create new column using dictionary
new_data = { ""Ram"":""B.Com"",
""Mohan"":""IAS"",
""Tina"":""LLB"",
""Jeetu"":""B.Tech"",
""Meera"":""MBBS"" }
# combine this new data with existing DataFrame
df[""Qualification""] = df[""First_name""].map(new_data)
print(df)"
1721,Write a Python program to Filter dictionary values in heterogeneous dictionary,"# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print(""The original dictionary : "" + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if type(val) != int or val > K}
# printing result
print(""Values greater than K : "" + str(res)) "
1722,Write a Python program to Split Strings on Prefix Occurrence,"# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + startswith()
# initializing list
test_list = [""geeksforgeeks"", ""best"", ""geeks"", ""and"", ""geeks"", ""love"", ""CS""]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing prefix
pref = ""geek""
res = []
for val in test_list:
# checking for prefix
if val.startswith(pref):
# if pref found, start new list
res.append([val])
else:
# else append in current list
res[-1].append(val)
# printing result
print(""Prefix Split List : "" + str(res))"
1723,Write a Python program to Group dates in K ranges,"# Python3 code to demonstrate working of
# Group dates in K ranges
# Using groupby() + sort()
from itertools import groupby
from datetime import datetime
# initializing list
test_list = [datetime(2020, 1, 4),
datetime(2019, 12, 30),
datetime(2020, 1, 7),
datetime(2019, 12, 27),
datetime(2020, 1, 20),
datetime(2020, 1, 10)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 7
# initializing start date
min_date = min(test_list)
# utility fnc to form groupings
def group_util(date):
return (date-min_date).days // K
# sorting before grouping
test_list.sort()
temp = []
# grouping by utility function to group by K days
for key, val in groupby(test_list , key = lambda date : group_util(date)):
temp.append((key, list(val)))
# using strftime to convert to userfriendly
# format
res = []
for sub in temp:
intr = []
for ele in sub[1]:
intr.append(ele.strftime(""%Y/%m/%d""))
res.append((sub[0], intr))
# printing result
print(""Grouped Digits : "" + str(res))"
1724,Write a Python program to Combinations of sum with tuples in tuple list,"# Python3 code to demonstrate working of
# Summation combination in tuple lists
# Using list comprehension + combinations
from itertools import combinations
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]
# printing original list
print(""The original list : "" + str(test_list))
# Summation combination in tuple lists
# Using list comprehension + combinations
res = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)]
# printing result
print(""The Summation combinations are : "" + str(res))"
1725,Plot line graph from NumPy array in Python,"# importing the modules
import numpy as np
import matplotlib.pyplot as plt
# data to be plotted
x = np.arrange(1, 11)
y = x * x
# plotting
plt.title(""Line graph"")
plt.xlabel(""X axis"")
plt.ylabel(""Y axis"")
plt.plot(x, y, color =""red"")
plt.show()"
1726,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()"
1727,Write a Python program to Extract digits from Tuple list,"# Python3 code to demonstrate working of
# Extract digits from Tuple list
# Using map() + chain.from_iterable() + set() + loop
from itertools import chain
# initializing list
test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]
# printing original list
print(""The original list is : "" + str(test_list))
# Extract digits from Tuple list
# Using map() + chain.from_iterable() + set() + loop
temp = map(lambda ele: str(ele), chain.from_iterable(test_list))
res = set()
for sub in temp:
for ele in sub:
res.add(ele)
# printing result
print(""The extracted digits : "" + str(res))"
1728,Write a Python program to Count tuples occurrence in list of tuples,"# Python code to count unique
# tuples in list of list
import collections
Output = collections.defaultdict(int)
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
[('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
# Using iteration
for elem in Input:
Output[elem[0]] += 1
# Printing output
print(Output)"
1729,Change data type of given numpy array in Python,"# importing the numpy library as np
import numpy as np
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
# Print the array
print(arr)"
1730,Write a Python program to Sort Tuples by their Maximum element,"# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using max() + sort()
# helper function
def get_max(sub):
return max(sub)
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
# printing original list
print(""The original list is : "" + str(test_list))
# sort() is used to get sorted result
# reverse for sorting by max - first element's tuples
test_list.sort(key = get_max, reverse = True)
# printing result
print(""Sorted Tuples : "" + str(test_list))"
1731,Binary Search (bisect) in Python,"# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
a = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, ""is absent"")
else:
print(""First occurrence of"", x, ""is present at"", res)"
1732,Student management system in Python,"# This is simplest Student data management program in python
# Create class ""Student""
class Student:
# Constructor
def __init__(self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
# Function to create and append new student
def accept(self, Name, Rollno, marks1, marks2 ):
# use ' int(input()) ' method to take input from user
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
# Function to display student details
def display(self, ob):
print(""Name : "", ob.name)
print(""RollNo : "", ob.rollno)
print(""Marks1 : "", ob.m1)
print(""Marks2 : "", ob.m2)
print(""\n"")
# Search Function
def search(self, rn):
for i in range(ls.__len__()):
if(ls[i].rollno == rn):
return i
# Delete Function
def delete(self, rn):
i = obj.search(rn)
del ls[i]
# Update Function
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
# Create a list to add Students
ls =[]
# an object of Student class
obj = Student('', 0, 0, 0)
print(""\nOperations used, "")
print(""\n1.Accept Student details\n2.Display Student Details\n"" /
/ ""3.Search Details of a Student\n4.Delete Details of Student"" /
/ ""\n5.Update Student Details\n6.Exit"")
# ch = int(input(""Enter choice:""))
# if(ch == 1):
obj.accept(""A"", 1, 100, 100)
obj.accept(""B"", 2, 90, 90)
obj.accept(""C"", 3, 80, 80)
# elif(ch == 2):
print(""\n"")
print(""\nList of Students\n"")
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 3):
print(""\n Student Found, "")
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
print(ls.__len__())
print(""List after deletion"")
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
print(ls.__len__())
print(""List after updation"")
for i in range(ls.__len__()):
obj.display(ls[i])
# else:
print(""Thank You !"")
"
1733,Priority Queue using Queue and Heapdict module in Python,"from queue import PriorityQueue
q = PriorityQueue()
# insert into queue
q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))
# remove and return
# lowest priority item
print(q.get())
print(q.get())
# check queue size
print('Items in queue :', q.qsize())
# check if queue is empty
print('Is queue empty :', q.empty())
# check if queue is full
print('Is queue full :', q.full())"
1734,How To Convert Python Dictionary To JSON,"import json
# Data to be written
dictionary ={
""id"": ""04"",
""name"": ""sunil"",
""department"": ""HR""
}
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
print(json_object)"
1735,Write a Python program to find Indices of Overlapping Substrings,"# Import required module
import re
# Function to depict use of finditer() method
def CntSubstr(pattern, string):
# Array storing the indices
a = [m.start() for m in re.finditer(pattern, string)]
return a
# Driver Code
string = 'geeksforgeeksforgeeks'
pattern = 'geeksforgeeks'
# Printing index values of non-overlapping pattern
print(CntSubstr(pattern, string))"
1736,Find the most frequent value in a NumPy array in Python,"import numpy as np
# create array
x = np.array([1,2,3,4,5,1,2,1,1,1])
print(""Original array:"")
print(x)
print(""Most frequent value in the above array:"")
print(np.bincount(x).argmax())"
1737,How to add a border color to a button in Tkinter in Python,"import tkinter as tk
root = tk.Tk()
root.geometry('250x150')
root.title(""Button Border"")
# Label
l = tk.Label(root, text = ""Enter your Roll No. :"",
font = ((""Times New Roman""), 15))
l.pack()
# Entry Widget
tk.Entry(root).pack()
# for space between widgets
tk.Label(root, text="" "").pack()
# Frame for button border with black border color
button_border = tk.Frame(root, highlightbackground = ""black"",
highlightthickness = 2, bd=0)
bttn = tk.Button(button_border, text = 'Submit', fg = 'black',
bg = 'yellow',font = ((""Times New Roman""),15))
bttn.pack()
button_border.pack()
root.mainloop()"
1738,Write a Python program to Convert Key-Value list Dictionary to List of Lists,"# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using loop + items()
# initializing Dictionary
test_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Convert Key-Value list Dictionary to Lists of List
# Using loop + items()
res = []
for key, val in test_dict.items():
res.append([key] + val)
# printing result
print(""The converted list is : "" + str(res)) "
1739,How to move Files and Directories in Python,"# Python program to move
# files and directories
import shutil
# Source path
source = ""D:\Pycharm projects\gfg\Test\B""
# Destination path
destination = ""D:\Pycharm projects\gfg\Test\A""
# Move the content of
# source to destination
dest = shutil.move(source, destination)
# print(dest) prints the
# Destination of moved directory"
1740,How to get file creation and modification date or time in Python,"import os
import time
# Path to the file/directory
path = r""C:\Program Files (x86)\Google\pivpT.png""
# Both the variables would contain time
# elapsed since EPOCH in float
ti_c = os.path.getctime(path)
ti_m = os.path.getmtime(path)
# Converting the time in seconds to a timestamp
c_ti = time.ctime(ti_c)
m_ti = time.ctime(ti_m)
print(
f""The file located at the path {path}
was created at {c_ti} and was last modified at {m_ti}"")"
1741,Write a Python program to convert unix timestamp string to readable date,"# Python program to illustrate the
# convertion of unix timestamp string
# to its readable date
# Importing datetime module
import datetime
# Calling the fromtimestamp() function to
# extract datetime from the given timestamp
# Calling the strftime() function to convert
# the extracted datetime into its string format
print(datetime.datetime.fromtimestamp(int(""1294113662""))
.strftime('%Y-%m-%d %H:%M:%S'))"
1742,Write a Python program to Keys associated with Values in Dictionary,"# Python3 code to demonstrate working of
# Values Associated Keys
# Using defaultdict() + loop
from collections import defaultdict
# initializing dictionary
test_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Values Associated Keys
# Using defaultdict() + loop
res = defaultdict(list)
for key, val in test_dict.items():
for ele in val:
res[ele].append(key)
# printing result
print(""The values associated dictionary : "" + str(dict(res))) "
1743,Controlling the Web Browser with Python,"# Import the required modules
from selenium import webdriver
import time
# Main Function
if __name__ == '__main__':
# Provide the email and password
email = 'example@example.com'
password = 'password'
options = webdriver.ChromeOptions()
options.add_argument(""--start-maximized"")
options.add_argument('--log-level=3')
# Provide the path of chromedriver present on your system.
driver = webdriver.Chrome(executable_path=""C:/chromedriver/chromedriver.exe"",
chrome_options=options)
driver.set_window_size(1920,1080)
# Send a get request to the url
driver.get('https://auth.geeksforgeeks.org/')
time.sleep(5)
# Finds the input box by name in DOM tree to send both
# the provided email and password in it.
driver.find_element_by_name('user').send_keys(email)
driver.find_element_by_name('pass').send_keys(password)
# Find the signin button and click on it.
driver.find_element_by_css_selector(
'button.btn.btn-green.signin-button').click()
time.sleep(5)
# Returns the list of elements
# having the following css selector.
container = driver.find_elements_by_css_selector(
'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold')
# Extracts the text from name,
# institution, email_id css selector.
name = container[0].text
try:
institution = container[1].find_element_by_css_selector('a').text
except:
institution = container[1].text
email_id = container[2].text
# Output Example 1
print(""Basic Info"")
print({""Name"": name,
""Institution"": institution,
""Email ID"": email})
# Clicks on Practice Tab
driver.find_elements_by_css_selector(
'a.mdl-navigation__link')[1].click()
time.sleep(5)
# Selected the Container containing information
container = driver.find_element_by_css_selector(
'div.mdl-cell.mdl-cell--7-col.mdl-cell--12-col-phone.\
whiteBgColor.mdl-shadow--2dp.userMainDiv')
# Selected the tags from the container
grids = container.find_elements_by_css_selector(
'div.mdl-grid')
# Iterate each tag and append the text extracted from it.
res = set()
for grid in grids:
res.add(grid.text.replace('\n',':'))
# Output Example 2
print(""Practice Info"")
print(res)
# Quits the driver
driver.close()
driver.quit()"
1744,Write a Python program to All pair combinations of 2 tuples,"# Python3 code to demonstrate working of
# All pair combinations of 2 tuples
# Using list comprehension
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
# printing original tuples
print(""The original tuple 1 : "" + str(test_tuple1))
print(""The original tuple 2 : "" + str(test_tuple2))
# All pair combinations of 2 tuples
# Using list comprehension
res = [(a, b) for a in test_tuple1 for b in test_tuple2]
res = res + [(a, b) for a in test_tuple2 for b in test_tuple1]
# printing result
print(""The filtered tuple : "" + str(res))"
1745,Write a Python program to Avoid Spaces in string length,"# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()
# initializing string
test_str = 'geeksforgeeks 33 is best'
# printing original string
print(""The original string is : "" + str(test_str))
# isspace() checks for space
# sum checks count
res = sum(not chr.isspace() for chr in test_str)
# printing result
print(""The Characters Frequency avoiding spaces : "" + str(res)) "
1746,How to create an empty class in Python,"# Incorrect empty class in
# Python
class Geeks:"
1747,Write a Python program to Generate k random dates between two other dates,"# Python3 code to demonstrate working of
# Random K dates in Range
# Using choices() + timedelta() + loop
from datetime import date, timedelta
from random import choices
# initializing dates ranges
test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1)
# printing dates
print(""The original range : "" + str(test_date1) + "" "" + str(test_date2))
# initializing K
K = 7
res_dates = [test_date1]
# loop to get each date till end date
while test_date1 != test_date2:
test_date1 += timedelta(days=1)
res_dates.append(test_date1)
# random K dates from pack
res = choices(res_dates, k=K)
# printing
print(""K random dates in range : "" + str(res))"
1748,Write a Python program to Convert List to List of dictionaries,"# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using dictionary comprehension + loop
# initializing lists
test_list = [""Gfg"", 3, ""is"", 8, ""Best"", 10, ""for"", 18, ""Geeks"", 33]
# printing original list
print(""The original list : "" + str(test_list))
# initializing key list
key_list = [""name"", ""number""]
# loop to iterate through elements
# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
# printing result
print(""The constructed dictionary list : "" + str(res))"
1749,Building an undirected graph and finding shortest path using Dictionaries in Python,"# Python3 implementation to build a
# graph using Dictonaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
[""A"", ""B""], [""A"", ""E""],
[""A"", ""C""], [""B"", ""D""],
[""B"", ""E""], [""C"", ""F""],
[""C"", ""G""], [""D"", ""E""]
]
graph = defaultdict(list)
# Loop to iterate over every
# edge of the graph
for edge in edges:
a, b = edge[0], edge[1]
# Creating the graph
# as adjacency list
graph[a].append(b)
graph[b].append(a)
return graph
if __name__ == ""__main__"":
graph = build_graph()
print(graph)"
1750,Write a Python program to Prefix frequency in string List,"# Python3 code to demonstrate
# Prefix frequency in List
# using loop + startswith()
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
# printing original list
print(""The original list is : "" + str(test_list))
# Initializing substring
test_sub = 'gfg'
# Prefix frequency in List
# using loop + startswith()
res = 0
for ele in test_list:
if ele.startswith(test_sub):
res = res + 1
# printing result
print (""Strings count with matching frequency : "" + str(res))"
1751,Write a Python program to Update each element in tuple list,"# Python3 code to demonstrate working of
# Update each element in tuple list
# Using list comprehension
# initialize list
test_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
# printing original list
print(""The original list : "" + str(test_list))
# initialize add element
add_ele = 4
# Update each element in tuple list
# Using list comprehension
res = [tuple(j + add_ele for j in sub ) for sub in test_list]
# printing result
print(""List after bulk update : "" + str(res))"
1752,How to Scrape Multiple Pages of a Website Using Python,"import requests
from bs4 import BeautifulSoup as bs
URL = 'https://www.geeksforgeeks.org/page/1/'
req = requests.get(URL)
soup = bs(req.text, 'html.parser')
titles = soup.find_all('div',attrs = {'class','head'})
print(titles[4].text)"
1753,Test the given page is found or not on the server Using Python,"# import module
from urllib.request import urlopen
from urllib.error import *
# try block to read URL
try:
html = urlopen(""https://www.geeksforgeeks.org/"")
# except block to catch
# exception
# and identify error
except HTTPError as e:
print(""HTTP error"", e)
except URLError as e:
print(""Opps ! Page not found!"", e)
else:
print('Yeah ! found ')"
1754,Write a Python program to Convert List of Lists to Tuple of Tuples,"# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# Using tuple + list comprehension
# initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# printing original list
print(""The original list is : "" + str(test_list))
# Convert List of Lists to Tuple of Tuples
# Using tuple + list comprehension
res = tuple(tuple(sub) for sub in test_list)
# printing result
print(""The converted data : "" + str(res)) "
1755,Write a Python program to Numpy dstack() method,"# import numpy
import numpy as np
gfg1 = np.array([1, 2, 3])
gfg2 = np.array([4, 5, 6])
# using numpy.dstack() method
print(np.dstack((gfg1, gfg2)))"
1756,Compute the covariance matrix of two given NumPy arrays in Python,"import numpy as np
array1 = np.array([0, 1, 1])
array2 = np.array([2, 2, 1])
# Original array1
print(array1)
# Original array2
print(array2)
# Covariance matrix
print(""\nCovariance matrix of the said arrays:\n"",
np.cov(array1, array2))"
1757,Extract punctuation from the specified column of Dataframe using Regex in Python,"# import required libraries
import pandas as pd
import re
# creating Dataframe with
# name and their comments
df = pd.DataFrame({
'Name' : ['Akash', 'Ashish', 'Ayush',
'Diksha' , 'Radhika'],
'Comments': ['Hey! Akash how r u' ,
'Why are you asking this to me?' ,
'Today, what we are going to do.' ,
'No plans for today why?' ,
'Wedding plans, what are you saying?']},
columns = ['Name', 'Comments']
)
# show the Dataframe
df"
1758,How to add timestamp to excel file in Python,"# Import the required modules
import datetime
from openpyxl import Workbook
import time
# Main Function
if __name__ == '__main__':
# Create a worbook object
wb = Workbook()
# Select the active sheet
ws = wb.active
# Heading of Cell A1
ws.cell(row=1, column=1).value = ""Current Date and Time""
# Cell A2 containing the Current Date and Time
ws.cell(row=2, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Sleep of 2 seconds
time.sleep(2)
# Cell A3 containing the Current Date and Time
ws.cell(row=3, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
time.sleep(2)
# Cell A4 containing the Current Date and Time
ws.cell(row=4, column=1).value = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Save the workbook with a
# filename and close the object
wb.save('gfg.xlsx')
wb.close()"
1759,Defining a Python function at runtime,"# importing the module
from types import FunctionType
# functttion during run-time
f_code = compile('def gfg(): return ""GEEKSFORGEEKS""', """", ""exec"")
f_func = FunctionType(f_code.co_consts[0], globals(), ""gfg"")
# calling the function
print(f_func())"
1760,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)"
1761,Getting all CSV files from a directory using Python,"# importing the required modules
import glob
import pandas as pd
# specifying the path to csv files
path = ""csvfoldergfg""
# csv files in the path
files = glob.glob(path + ""/*.csv"")
# defining an empty list to store
# content
data_frame = pd.DataFrame()
content = []
# checking all the csv files in the
# specified path
for filename in files:
# reading content of csv file
# content.append(filename)
df = pd.read_csv(filename, index_col=None)
content.append(df)
# converting content to data frame
data_frame = pd.concat(content)
print(data_frame)"
1762,numpy.where() in Python,"# Python program explaining
# where() function
import numpy as np
np.where([[True, False], [True, True]],
[[1, 2], [3, 4]], [[5, 6], [7, 8]])"
1763,Write a Python program to Multiple indices Replace in String,"# Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using loop + join()
# initializing string
test_str = 'geeksforgeeks is best'
# printing original string
print(""The original string is : "" + test_str)
# initializing list
test_list = [2, 4, 7, 10]
# initializing repl char
repl_char = '*'
# Multiple indices Replace in String
# Using loop + join()
temp = list(test_str)
for idx in test_list:
temp[idx] = repl_char
res = ''.join(temp)
# printing result
print(""The String after performing replace : "" + str(res)) "
1764,Automate Youtube with Python,"from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import speech_recognition as sr
import pyttsx3
import time
def automateYoutube(searchtext):
# giving the path of chromedriver to selenium websriver
path = ""C:\\Users\\hp\\Downloads\\chromedriver""
url = ""https://www.youtube.com/""
# opening the youtube in chromedriver
driver = webdriver.Chrome(path)
driver.get(url)
# find the search bar using selenium find_element function
driver.find_element_by_name(""search_query"").send_keys(searchtext)
# clicking on the search button
driver.find_element_by_css_selector(
""#search-icon-legacy.ytd-searchbox"").click()
# For findding the right match search
WebDriverWait(driver, 0).until(expected_conditions.title_contains(MyText))
# clicking on the match search having same as in searched query
WebDriverWait(driver, 30).until(
expected_conditions.element_to_be_clickable((By.ID, ""img""))).click()
# while(True):
# pass
speak = sr.Recognizer()
try:
with sr.Microphone() as speaky:
# adjust the energy threshold based on
# the surrounding noise level
speak.adjust_for_ambient_noise(speaky, duration=0.2)
print(""listening..."")
# listens for the user's input
searchquery = speak.listen(speaky)
# Using ggogle to recognize audio
MyText = speak.recognize_google(searchquery)
MyText = MyText.lower()
except sr.RequestError as e:
print(""Could not request results; {0}"".format(e))
except sr.UnknownValueError:
print(""unknown error occured"")
# Calling thr function
automateYoutube(MyText)"
1765,Write a Python program to Intersection in Tuple Records Data,"# Python3 code to demonstrate working of
# Intersection in Tuple Records Data
# Using list comprehension
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# Intersection in Tuple Records Data
# Using list comprehension
res = [ele1 for ele1 in test_list1
for ele2 in test_list2 if ele1 == ele2]
# printing result
print(""The Intersection of data records is : "" + str(res))"
1766,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)"
1767,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 "
1768,How to keep old content when Writing to Files in Python,"# Python program to keep the old content of the file
# when using write.
# Opening the file with append mode
file = open(""gfg input file.txt"", ""a"")
# Content to be added
content = ""\n\n# This Content is added through the program #""
# Writing the file
file.write(content)
# Closing the opened file
file.close()"
1769,Convert String to Set in Python,"# create a string str
string = ""geeks""
print(""Initially"")
print(""The datatype of string : "" + str(type(string)))
print(""Contents of string : "" + string)
# convert String to Set
string = set(string)
print(""\nAfter the conversion"")
print(""The datatype of string : "" + str(type(string)))
print(""Contents of string : "", string)"
1770,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) "
1771,Write a Python program to Replace words from Dictionary,"# Python3 code to demonstrate working of
# Replace words from Dictionary
# Using split() + join() + get()
# initializing string
test_str = 'geekforgeeks best for geeks'
# printing original string
print(""The original string is : "" + str(test_str))
# lookup Dictionary
lookp_dict = {""best"" : ""good and better"", ""geeks"" : ""all CS aspirants""}
# performing split()
temp = test_str.split()
res = []
for wrd in temp:
# searching from lookp_dict
res.append(lookp_dict.get(wrd, wrd))
res = ' '.join(res)
# printing result
print(""Replaced Strings : "" + str(res)) "
1772,Write a Python program to print negative numbers in a list,"# Python program to print negative Numbers in a List
# list of numbers
list1 = [11, -21, 0, 45, 66, -93]
# iterating each number in list
for num in list1:
# checking condition
if num < 0:
print(num, end = "" "")"
1773,Write a Python program to Find all duplicate characters in string,"from collections import Counter
def find_dup_char(input):
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
WC = Counter(input)
j = -1
# Finding no. of occurrence of a character
# and get the index of it.
for i in WC.values():
j = j + 1
if( i > 1 ):
print WC.keys()[j],
# Driver program
if __name__ == ""__main__"":
input = 'geeksforgeeks'
find_dup_char(input)"
1774,Write a Python program to Records with Value at K index,"# Python3 code to demonstrate working of
# Records with Value at K index
# Using loop
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print(""The original list is : "" + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
# Records with Value at K index
# Using loop
# using y for K = 1
res = []
for x, y, z in test_list:
if y == ele:
res.append((x, y, z))
# printing result
print(""The tuples of element at Kth position : "" + str(res))"
1775,Write a Python program to convert tuple into list by adding the given string after every element,"# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using list comprehension
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
# printing original tuple
print(""The original tuple is : "", test_tup)
# initializing K
K = ""Gfg""
# list comprehension for nested loop for flatten
res = [ele for sub in test_tup for ele in (sub, K)]
# printing result
print(""Converted Tuple with K : "", res)"
1776,numpy matrix operations | randn() function in Python,"# Python program explaining
# numpy.matlib.randn() function
# importing matrix library from numpy
import numpy as geek
import numpy.matlib
# desired 3 x 4 random output matrix
out_mat = geek.matlib.randn((3, 4))
print (""Output matrix : "", out_mat) "
1777,How to scroll down followers popup in Instagram in Python,"import selenium
print(selenium.__version__)"
1778,Write a Python program to Tuple List intersection (Order irrespective),"# Python3 code to demonstrate working of
# Tuple List intersection [ Order irrespective ]
# Using sorted() + set() + & operator + list comprehension
# initializing lists
test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)]
test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)]
# printing original list
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# Using sorted() + set() + & operator + list comprehension
# Using & operator to intersect, sorting before performing intersection
res = set([tuple(sorted(ele)) for ele in test_list1]) & set([tuple(sorted(ele)) for ele in test_list2])
# printing result
print(""List after intersection : "" + str(res)) "
1779,Write a Python Library for Linked List,"# importing module
import collections
# initialising a deque() of arbitary length
linked_lst = collections.deque()
# filling deque() with elements
linked_lst.append('first')
linked_lst.append('second')
linked_lst.append('third')
print(""elements in the linked_list:"")
print(linked_lst)
# adding element at an arbitary position
linked_lst.insert(1, 'fourth')
print(""elements in the linked_list:"")
print(linked_lst)
# deleting the last element
linked_lst.pop()
print(""elements in the linked_list:"")
print(linked_lst)
# removing a specific element
linked_lst.remove('fourth')
print(""elements in the linked_list:"")
print(linked_lst)"
1780,Write a Python program to convert any base to decimal by using int() method,"# Python program to convert any base
# number to its corresponding decimal
# number
# Function to convert any base number
# to its corresponding decimal number
def any_base_to_decimal(number, base):
# calling the builtin function
# int(number, base) by passing
# two arguments in it number in
# string form and base and store
# the output value in temp
temp = int(number, base)
# printing the corresponding decimal
# number
print(temp)
# Driver's Code
if __name__ == '__main__' :
hexadecimal_number = '1A'
base = 16
any_base_to_decimal(hexadecimal_number, base)"
1781,How to create filename containing date or time in Python,"# import module
from datetime import datetime
# get current date and time
current_datetime = datetime.now()
print(""Current date & time : "", current_datetime)
# convert datetime obj to string
str_current_datetime = str(current_datetime)
# create a file object along with extension
file_name = str_current_datetime+"".txt""
file = open(file_name, 'w')
print(""File created : "", file.name)
file.close()"
1782,Write a Python program to Replace NaN values with average of columns,"# Python code to demonstrate
# to replace nan values
# with an average of columns
import numpy as np
# Initialising numpy array
ini_array = np.array([[1.3, 2.5, 3.6, np.nan],
[2.6, 3.3, np.nan, 5.5],
[2.1, 3.2, 5.4, 6.5]])
# printing initial array
print (""initial array"", ini_array)
# column mean
col_mean = np.nanmean(ini_array, axis = 0)
# printing column mean
print (""columns mean"", str(col_mean))
# find indices where nan value is present
inds = np.where(np.isnan(ini_array))
# replace inds with avg of column
ini_array[inds] = np.take(col_mean, inds[1])
# printing final array
print (""final array"", ini_array)"
1783,Write a Python program to String till Substring,"# Python3 code to demonstrate
# String till Substring
# using partition()
# initializing string
test_string = ""GeeksforGeeks is best for geeks""
# initializing split word
spl_word = 'best'
# printing original string
print(""The original string : "" + str(test_string))
# printing split string
print(""The split string : "" + str(spl_word))
# using partition()
# String till Substring
res = test_string.partition(spl_word)[0]
# print result
print(""String before the substring occurrence : "" + res)"
1784,Find the number of occurrences of a sequence in a NumPy array in Python,"# importing package
import numpy
# create numpy array
arr = numpy.array([[2, 8, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
# Counting sequence
output = repr(arr).count(""9, 4"")
# view output
print(output)"
1785,Write a Python program to Remove substring list from String,"# Python3 code to demonstrate working of
# Remove substring list from String
# Using loop + replace()
# initializing string
test_str = ""gfg is best for all geeks""
# printing original string
print(""The original string is : "" + test_str)
# initializing sub list
sub_list = [""best"", ""all""]
# Remove substring list from String
# Using loop + replace()
for sub in sub_list:
test_str = test_str.replace(' ' + sub + ' ', ' ')
# printing result
print(""The string after substring removal : "" + test_str) "
1786,numpy.random.geometric() in Python,"# import numpy and geometric
import numpy as np
import matplotlib.pyplot as plt
# Using geometric() method
gfg = np.random.geometric(0.65, 1000)
count, bins, ignored = plt.hist(gfg, 40, density = True)
plt.show()"
1787,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)"
1788,Write a Python program to Numpy matrix.take(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1, 12, 3, 4, 6, 7]')
# applying matrix.take() method
geek = gfg.take(2)
print(geek)"
1789,"What is a clean, Pythonic way to have multiple constructors in Python","class example:
def __init__(self):
print(""One"")
def __init__(self):
print(""Two"")
def __init__(self):
print(""Three"")
e = example()"
1790,Implementation of XOR Linked List in Python,"# import required module
import ctypes
# create node class
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
self.head = None
self.tail = None
self.__nodes = []
# method to insert node at beginning
def InsertAtStart(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.head.npx = id(node) ^ self.head.npx
node.npx = id(self.head)
self.head = node
self.__nodes.append(node)
# method to insert node at end
def InsertAtEnd(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.tail.npx = id(node) ^ self.tail.npx
node.npx = id(self.tail)
self.tail = node
self.__nodes.append(node)
# method to remove node at beginning
def DeleteAtStart(self):
if self.isEmpty(): # If list is empty
return ""List is empty !""
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif (0 ^ self.head.npx) == id(self.tail): # If list has 2 nodes
self.head = self.tail
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
res = self.head.value
x = self.__type_cast(0 ^ self.head.npx) # Address of next node
y = (id(self.head) ^ x.npx) # Address of next of next node
self.head = x
self.head.npx = 0 ^ y
return res
# method to remove node at end
def DeleteAtEnd(self):
if self.isEmpty(): # If list is empty
return ""List is empty !""
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif self.__type_cast(0 ^ self.head.npx) == (self.tail): # If list has 2 nodes
self.tail = self.head
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
prev_id = 0
node = self.head
next_id = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
res = node.value
x = self.__type_cast(prev_id).npx ^ id(node)
y = self.__type_cast(prev_id)
y.npx = x ^ 0
self.tail = y
return res
# method to traverse linked list
def Print(self):
""""""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list.""""""
if self.head != None:
prev_id = 0
node = self.head
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print(""List is empty !"")
# method to traverse linked list in reverse order
def ReversePrint(self):
# Print Values is reverse order.
""""""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list.""""""
if self.head != None:
prev_id = 0
node = self.tail
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print(""List is empty !"")
# method to get length of linked list
def Length(self):
if not self.isEmpty():
prev_id = 0
node = self.head
next_id = 1
count = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
count += 1
else:
return count
else:
return 0
# method to get node data value by index
def PrintByIndex(self, index):
prev_id = 0
node = self.head
for i in range(index):
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
else:
return ""Value dosn't found index out of range.""
return node.value
# method to check if the liked list is empty or not
def isEmpty(self):
if self.head is None:
return True
return False
# method to return a new instance of type
def __type_cast(self, id):
return ctypes.cast(id, ctypes.py_object).value
# Driver Code
# create object
obj = XorLinkedList()
# insert nodes
obj.InsertAtEnd(2)
obj.InsertAtEnd(3)
obj.InsertAtEnd(4)
obj.InsertAtStart(0)
obj.InsertAtStart(6)
obj.InsertAtEnd(55)
# display length
print(""\nLength:"", obj.Length())
# traverse
print(""\nTraverse linked list:"")
obj.Print()
print(""\nTraverse in reverse order:"")
obj.ReversePrint()
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print(""Data value at index"", i, 'is', obj.PrintByIndex(i))
# removing nodes
print(""\nDelete Last Node: "", obj.DeleteAtEnd())
print(""\nDelete First Node: "", obj.DeleteAtStart())
# new length
print(""\nUpdated length:"", obj.Length())
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print(""Data value at index"", i, 'is', obj.PrintByIndex(i))
# traverse
print(""\nTraverse linked list:"")
obj.Print()
print(""\nTraverse in reverse order:"")
obj.ReversePrint()"
1791,Write a Python program to Check for URL in a String,"# Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\"".,<>?«»“”‘’]))""
url = re.findall(regex,string)
return [x[0] for x in url]
# Driver Code
string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/'
print(""Urls: "", Find(string))"
1792,How to Calculate the determinant of a matrix using NumPy in Python,"# importing Numpy package
import numpy as np
# creating a 2X2 Numpy matrix
n_array = np.array([[50, 29], [30, 44]])
# Displaying the Matrix
print(""Numpy Matrix is:"")
print(n_array)
# calculating the determinant of matrix
det = np.linalg.det(n_array)
print(""\nDeterminant of given 2X2 matrix:"")
print(int(det))"
1793,Replace values in Pandas dataframe using regex in Python,"# importing pandas as pd
import pandas as pd
# Let's create a Dataframe
df = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
'Cost':[10000, 5000, 15000, 2000, 12000]})
# Let's create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
# Set the index
df.index = index_
# Let's print the dataframe
print(df)"
1794,Write a Python program to Factors Frequency Dictionary,"# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print(""The original list : "" + str(test_list))
res = dict()
# iterating till max element
for idx in range(1, max(test_list)):
res[idx] = 0
for key in test_list:
# checking for factor
if key % idx == 0:
res[idx] += 1
# printing result
print(""The constructed dictionary : "" + str(res))"
1795,Write a Python program to Convert Integer Matrix to String Matrix,"# Python3 code to demonstrate working of
# Convert Integer Matrix to String Matrix
# Using str() + list comprehension
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
# printing original list
print(""The original list : "" + str(test_list))
# using str() to convert each element to string
res = [[str(ele) for ele in sub] for sub in test_list]
# printing result
print(""The data type converted Matrix : "" + str(res))"
1796,Write a Python program to find smallest number in a list,"# Python program to find smallest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the first element
print(""Smallest element is:"", *list1[:1])"
1797,How to Change Tkinter LableFrame Border Color in Python,"# import tkinter
import tkinter as tk
# import ttk theme module for styling
import tkinter.ttk as ttk"
1798,Write a Python program to Filter the List of String whose index in second List contaons the given Substring,"# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using zip() + loop + in
# operator
# initializing list
test_list1 = [""Gfg"", ""is"", ""not"", ""best"", ""and"",
""not"", ""for"", ""CS""]
test_list2 = [""Its ok"", ""all ok"", ""wrong"", ""looks ok"",
""ok"", ""wrong"", ""ok"", ""thats ok""]
# printing original lists
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# initializing substr
sub_str = ""ok""
res = []
# using zip() to map by index
for ele1, ele2 in zip(test_list1, test_list2):
# checking for substring
if sub_str in ele2:
res.append(ele1)
# printing result
print(""The extracted list : "" + str(res))"
1799,Write a Python program to count positive and negative numbers in a list,"# Python program to count positive and negative numbers in a List
# list of numbers
list1 = [10, -21, 4, -45, 66, -93, 1]
pos_count, neg_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num >= 0:
pos_count += 1
else:
neg_count += 1
print(""Positive numbers in the list: "", pos_count)
print(""Negative numbers in the list: "", neg_count)"
1800,How to count unique values inside a list in Python,"# taking an input list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
# taking an input list
l1 = []
# taking an counter
count = 0
# travesing the array
for item in input_list:
if item not in l1:
count += 1
l1.append(item)
# printing the output
print(""No of unique items are:"", count)"
1801,Find the length of each string element in the Numpy array in Python,"# importing the numpy library as np
import numpy as np
# Create a numpy array
arr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])
# Print the array
print(arr)"
1802,Write a Python dictionary with keys having multiple inputs,"# Python code to demonstrate a dictionary
# with multiple inputs in a key.
import random as rn
# creating an empty dictionary
dict = {}
# Insert first triplet in dictionary
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z;
# Insert second triplet in dictionary
x, y, z = 5, 2, 4
dict[x, y, z] = x + y - z;
# print the dictionary
print(dict)"
1803,How to choose elements from the list with different probability using NumPy in Python,"# import numpy library
import numpy as np
# create a list
num_list = [10, 20, 30, 40, 50]
# uniformly select any element
# from the list
number = np.random.choice(num_list)
print(number)"
1804,Write a Python program to Words Frequency in String Shorthands,"# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
# printing original string
print(""The original string is : "" + str(test_str))
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
# printing result
print(""The words frequency : "" + str(res)) "
1805,Write a Python program to Count the frequency of matrix row length,"# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
[10, 12, 7], [4, 11]]
# printing original list
print(""The original list is : "" + str(test_list))
res = dict()
for sub in test_list:
# initializing incase of new length
if len(sub) not in res:
res[len(sub)] = 1
# increment in case of length present
else:
res[len(sub)] += 1
# printing result
print(""Row length frequencies : "" + str(res))"
1806,Find the average of an unknown number of inputs in Python,"
# function that takes arbitary
# number of inputs
def avgfun(*n):
sums = 0
for t in n:
sums = sums + t
avg = sums / len(n)
return avg
# Driver Code
result1 = avgfun(1, 2, 3)
result2 = avgfun(2, 6, 4, 8)
# Printing average of the list
print(round(result1, 2))
print(round(result2, 2))"
1807,Get row numbers of NumPy array having element larger than X in Python,"# importing library
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[10, -3, 30, 4, 5],
[3, 2, 5, -4, 5],
[9, 7, 3, 6, 5]
])
# declare specified value
X = 6
# view array
print(""Given Array:\n"", arr)
# finding out the row numbers
output = numpy.where(numpy.any(arr > X,
axis = 1))
# view output
print(""Result:\n"", output)"
1808,Write a Python program to get all subsets of given size of a set,"# Python Program to Print
# all subsets of given size of a set
import itertools
def findsubsets(s, n):
return list(itertools.combinations(s, n))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))"
1809,Write a Python program to find uncommon words from two Strings,"# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# count will contain all the word counts
count = {}
# insert words of string A to hash
for word in A.split():
count[word] = count.get(word, 0) + 1
# insert words of string B to hash
for word in B.split():
count[word] = count.get(word, 0) + 1
# return required list of words
return [word for word in count if count[word] == 1]
# Driver Code
A = ""Geeks for Geeks""
B = ""Learning from Geeks for Geeks""
# Print required answer
print(UncommonWords(A, B))"
1810,Creating a Pandas dataframe using list of tuples in Python,"# import pandas to use pandas DataFrame
import pandas as pd
# data in the form of list of tuples
data = [('Peter', 18, 7),
('Riff', 15, 6),
('John', 17, 8),
('Michel', 18, 7),
('Sheli', 17, 5) ]
# create DataFrame using data
df = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])
print(df) "
1811,"How to get the floor, ceiling and truncated values of the elements of a numpy array in Python","# Import the numpy library
import numpy as np
# Initialize numpy array
a = np.array([1.2])
# Get floor value
a = np.floor(a)
print(a)"
1812,How to iterate over files in directory using Python,"# import required module
import os
# assign directory
directory = 'files'
# iterate over files in
# that directory
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
# checking if it is a file
if os.path.isfile(f):
print(f)"
1813,Write a Python program to Elementwise AND in tuples,"# Python3 code to demonstrate working of
# Elementwise AND in tuples
# using zip() + generator expression
# initialize tuples
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
# printing original tuples
print(""The original tuple 1 : "" + str(test_tup1))
print(""The original tuple 2 : "" + str(test_tup2))
# Elementwise AND in tuples
# using zip() + generator expression
res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
# printing result
print(""The AND tuple : "" + str(res)) "
1814,Write a Python program to Remove Tuples from the List having every element as None,"# Python3 code to demonstrate working of
# Remove None Tuples from List
# Using all() + list comprehension
# initializing list
test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]
# printing original list
print(""The original list is : "" + str(test_list))
# negating result for discarding all None Tuples
res = [sub for sub in test_list if not all(ele == None for ele in sub)]
# printing result
print(""Removed None Tuples : "" + str(res))"
1815,Convert nested JSON to CSV in Python,"import json
def read_json(filename: str) -> dict:
try:
with open(filename, ""r"") as f:
data = json.loads(f.read())
except:
raise Exception(f""Reading {filename} file encountered an error"")
return data
def normalize_json(data: dict) -> dict:
new_data = dict()
for key, value in data.items():
if not isinstance(value, dict):
new_data[key] = value
else:
for k, v in value.items():
new_data[key + ""_"" + k] = v
return new_data
def generate_csv_data(data: dict) -> str:
# Defining CSV columns in a list to maintain
# the order
csv_columns = data.keys()
# Generate the first row of CSV
csv_data = "","".join(csv_columns) + ""\n""
# Generate the single record present
new_row = list()
for col in csv_columns:
new_row.append(str(data[col]))
# Concatenate the record with the column information
# in CSV format
csv_data += "","".join(new_row) + ""\n""
return csv_data
def write_to_file(data: str, filepath: str) -> bool:
try:
with open(filepath, ""w+"") as f:
f.write(data)
except:
raise Exception(f""Saving data to {filepath} encountered an error"")
def main():
# Read the JSON file as python dictionary
data = read_json(filename=""article.json"")
# Normalize the nested python dict
new_data = normalize_json(data=data)
# Pretty print the new dict object
print(""New dict:"", new_data)
# Generate the desired CSV data
csv_data = generate_csv_data(data=new_data)
# Save the generated CSV data to a CSV file
write_to_file(data=csv_data, filepath=""data.csv"")
if __name__ == '__main__':
main()"
1816,numpy.squeeze() in Python,"# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])
print (""Input array : "", in_arr)
print(""Shape of input array : "", in_arr.shape)
out_arr = geek.squeeze(in_arr)
print (""output squeezed array : "", out_arr)
print(""Shape of output array : "", out_arr.shape) "
1817,Write a Python program to Program to accept the strings which contains all vowels,"# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string) :
string = string.lower()
# set() function convert ""aeiou""
# string into set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set(""aeiou"")
# set() function convert empty
# dictionary into empty set
s = set({})
# looping through each
# character of the string
for char in string :
# Check for the character is present inside
# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels :
s.add(char)
else:
pass
# check the length of set s equal to length
# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels) :
print(""Accepted"")
else :
print(""Not Accepted"")
# Driver code
if __name__ == ""__main__"" :
string = ""SEEquoiaL""
# calling function
check(string)"
1818,Write a Python program to Extract Unique values dictionary values,"# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
res = list(sorted({ele for val in test_dict.values() for ele in val}))
# printing result
print(""The unique values list is : "" + str(res)) "
1819,Write a Python program to find Tuples with positive elements in List of tuples,"# Python3 code to demonstrate working of
# Positive Tuples in List
# Using list comprehension + all()
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
# printing original list
print(""The original list is : "" + str(test_list))
# all() to check each element
res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]
# printing result
print(""Positive elements Tuples : "" + str(res))"
1820,Replace NumPy array elements that doesn’t satisfy the given condition in Python,"# Importing Numpy module
import numpy as np
# Creating a 1-D Numpy array
n_arr = np.array([75.42436315, 42.48558583, 60.32924763])
print(""Given array:"")
print(n_arr)
print(""\nReplace all elements of array which are greater than 50. to 15.50"")
n_arr[n_arr > 50.] = 15.50
print(""New array :\n"")
print(n_arr)"
1821,Write a Python Program to Replace Specific Line in File,"with open('example.txt', 'r', encoding='utf-8') as file:
data = file.readlines()
print(data)
data[1] = ""Here is my modified Line 2\n""
with open('example.txt', 'w', encoding='utf-8') as file:
file.writelines(data)"
1822,Write a Python program to Least Frequent Character in String,"# Python 3 code to demonstrate
# Least Frequent Character in String
# naive method
# initializing string
test_str = ""GeeksforGeeks""
# printing original string
print (""The original string is : "" + test_str)
# using naive method to get
# Least Frequent Character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = min(all_freq, key = all_freq.get)
# printing result
print (""The minimum of all characters in GeeksforGeeks is : "" + str(res))"
1823,Write a Python program to print positive numbers in a list,"# Python program to print positive Numbers in a List
# list of numbers
list1 = [11, -21, 0, 45, 66, -93]
# iterating each number in list
for num in list1:
# checking condition
if num >= 0:
print(num, end = "" "")"
1824,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)"
1825,Write a Python program to How to search for a string in text files,"string1 = 'coding'
# opening a text file
file1 = open(""geeks.txt"", ""r"")
# setting flag and index to 0
flag = 0
index = 0
# Loop through the file line by line
for line in file1:
index + = 1
# checking string is present in line or not
if string1 in line:
flag = 1
break
# checking condition for string found or not
if flag == 0:
print('String', string1 , 'Not Found')
else:
print('String', string1, 'Found In Line', index)
# closing text file
file1.close() "
1826,Write a Python program to swap two elements in a list,"# Python3 program to swap elements
# at given positions
# Swap function
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))"
1827,Write a Python Program for ShellSort,"# Python program for implementation of Shell Sort
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n/2
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped
# order keep adding one more element until the entire array
# is gap sorted
while gap > 0:
for i in range(gap,n):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct
# location for a[i] is found
j = i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap /= 2
# Driver code to test above
arr = [ 12, 34, 54, 2, 3]
n = len(arr)
print (""Array before sorting:"")
for i in range(n):
print(arr[i]),
shellSort(arr)
print (""\nArray after sorting:"")
for i in range(n):
print(arr[i]),
# This code is contributed by Mohit Kumra"
1828,Write a Python program to Convert tuple to float value,"# Python3 code to demonstrate working of
# Convert tuple to float
# using join() + float() + str() + generator expression
# initialize tuple
test_tup = (4, 56)
# printing original tuple
print(""The original tuple : "" + str(test_tup))
# Convert tuple to float
# using join() + float() + str() + generator expression
res = float('.'.join(str(ele) for ele in test_tup))
# printing result
print(""The float after conversion from tuple is : "" + str(res))"
1829,Write a Python program to Remove empty tuples from a list,"# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
# using list comprehension
def Remove(tuples):
tuples = [t for t in tuples if t]
return tuples
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('',''),()]
print(Remove(tuples))"
1830,Write a Python program to Assign Frequency to Tuples,"# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using Counter() + items() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print(""The original list is : "" + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).items()]
# printing results
print(""Frequency Tuple list : "" + str(res))"
1831,Maximum of two numbers in Python,"# Python program to find the
# maximum of two numbers
def maximum(a, b):
if a >= b:
return a
else:
return b
# Driver code
a = 2
b = 4
print(maximum(a, b))"
1832,Simple Diamond Pattern in Python,"# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size//2+2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print *
if j < i-1:
print(' ', end="" "")
elif j > spaces:
print(' ', end="" "")
elif (i == 0 and j == 0) | (i == 0 and j == size-1):
print(' ', end="" "")
else:
print('*', end="" "")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()"
1833,Write a Python program to Maximum frequency character in String,"# Python 3 code to demonstrate
# Maximum frequency character in String
# naive method
# initializing string
test_str = ""GeeksforGeeks""
# printing original string
print (""The original string is : "" + test_str)
# using naive method to get
# Maximum frequency character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = max(all_freq, key = all_freq.get)
# printing result
print (""The maximum of all characters in GeeksforGeeks is : "" + str(res))"
1834,Write a Python program to check if the list contains three consecutive common numbers in Python,"# creating the array
arr = [4, 5, 5, 5, 3, 8]
# size of the list
size = len(arr)
# looping till length - 2
for i in range(size - 2):
# checking the conditions
if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]:
# printing the element as the
# conditions are satisfied
print(arr[i])"
1835,Visualize data from CSV file in Python,"import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('biostats.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter = ',')
for row in plots:
x.append(row[0])
y.append(int(row[2]))
plt.bar(x, y, color = 'g', width = 0.72, label = ""Age"")
plt.xlabel('Names')
plt.ylabel('Ages')
plt.title('Ages of different persons')
plt.legend()
plt.show()"
1836,Write a Python Dictionary to find mirror characters in a string,"# function to mirror characters of a string
def mirrorChars(input,k):
# create dictionary
original = 'abcdefghijklmnopqrstuvwxyz'
reverse = 'zyxwvutsrqponmlkjihgfedcba'
dictChars = dict(zip(original,reverse))
# separate out string after length k to change
# characters in mirror
prefix = input[0:k-1]
suffix = input[k-1:]
mirror = ''
# change into mirror
for i in range(0,len(suffix)):
mirror = mirror + dictChars[suffix[i]]
# concat prefix and mirrored part
print (prefix+mirror)
# Driver program
if __name__ == ""__main__"":
input = 'paradox'
k = 3
mirrorChars(input,k)"
1837,Write a Python program to find middle of a linked list using one traversal,"# Python 3 program to find the middle of a
# given linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Function to get the middle of
# the linked list
def printMiddle(self):
slow_ptr = self.head
fast_ptr = self.head
if self.head is not None:
while (fast_ptr is not None and fast_ptr.next is not None):
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
print(""The middle element is: "", slow_ptr.data)
# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()"
1838,How to check if a string starts with a substring using regex in Python,"# import library
import re
# define a function
def find(string, sample) :
# check substring present
# in a string or not
if (sample in string):
y = ""^"" + sample
# check if string starts
# with the substring
x = re.search(y, string)
if x :
print(""string starts with the given substring"")
else :
print(""string doesn't start with the given substring"")
else :
print(""entered string isn't a substring"")
# Driver code
string = ""geeks for geeks makes learning fun""
sample = ""geeks""
# function call
find(string, sample)
sample = ""makes""
# function call
find(string, sample)"
1839,Write a Python program to Replace index elements with elements in Other List,"# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print (""The lists after index elements replacements is : "" + str(res))"
1840,Dumping queue into list or array in Python,"# Python program to
# demonstrate queue implementation
# using collections.dequeue
from collections import deque
# Initializing a queue
q = deque()
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
# display the queue
print(""Initial queue"")
print(q,""\n"")
# display the type
print(type(q))"
1841,Write a Python program to Exceptional Split in String,"# Python3 code to demonstrate working of
# Exceptional Split in String
# Using loop + split()
# initializing string
test_str = ""gfg, is, (best, for), geeks""
# printing original string
print(""The original string is : "" + test_str)
# Exceptional Split in String
# Using loop + split()
temp = ''
res = []
check = 0
for ele in test_str:
if ele == '(':
check += 1
elif ele == ')':
check -= 1
if ele == ', ' and check == 0:
if temp.strip():
res.append(temp)
temp = ''
else:
temp += ele
if temp.strip():
res.append(temp)
# printing result
print(""The string after exceptional split : "" + str(res)) "
1842,Write a Python Lambda Functions,"# Python program to demonstrate
# lambda functions
string ='GeeksforGeeks'
# lambda returns a function object
print(lambda string : string)"
1843,Getting Unique values from a column in Pandas dataframe in Python,"# import pandas as pd
import pandas as pd
gapminder_csv_url ='http://bit.ly/2cLzoxH'
# load the data with pd.read_csv
record = pd.read_csv(gapminder_csv_url)
record.head()"
1844,Write a Python program to Find all duplicate characters in string,"from collections import Counter
def find_dup_char(input):
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
WC = Counter(input)
j = -1
# Finding no. of occurrence of a character
# and get the index of it.
for i in WC.values():
j = j + 1
if( i > 1 ):
print WC.keys()[j],
# Driver program
if __name__ == ""__main__"":
input = 'geeksforgeeks'
find_dup_char(input)"
1845,How to get the n-largest values of an array using NumPy in Python,"# import library
import numpy as np
# create numpy 1d-array
arr = np.array([2, 0, 1, 5,
4, 1, 9])
print(""Given array:"", arr)
# sort an array in
# ascending order
# np.argsort() return
# array of indices for
# sorted array
sorted_index_array = np.argsort(arr)
# sorted array
sorted_array = arr[sorted_index_array]
print(""Sorted array:"", sorted_array)
# we want 1 largest value
n = 1
# we are using negative
# indexing concept
# take n largest value
rslt = sorted_array[-n : ]
# show the output
print(""{} largest value:"".format(n),
rslt[0])"
1846,Scrape IMDB movie rating and details using Python,"from bs4 import BeautifulSoup
import requests
import re"
1847,Write a Python program to Merging two Dictionaries,"# Python code to merge dict using update() method
def Merge(dict1, dict2):
return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This return None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)"
1848,Write a Python Selenium – Find element by text,"
"
1849,Write a Python program to Key with maximum unique values,"# Python3 code to demonstrate working of
# Key with maximum unique values
# Using loop
# initializing dictionary
test_dict = {""Gfg"" : [5, 7, 5, 4, 5],
""is"" : [6, 7, 4, 3, 3],
""Best"" : [9, 9, 6, 5, 5]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
max_val = 0
max_key = None
for sub in test_dict:
# test for length using len()
# converted to set for duplicates removal
if len(set(test_dict[sub])) > max_val:
max_val = len(set(test_dict[sub]))
max_key = sub
# printing result
print(""Key with maximum unique values : "" + str(max_key)) "
1850,Convert covariance matrix to correlation matrix using Python,"import numpy as np
import pandas as pd
# loading in the iris dataset for demo purposes
dataset = pd.read_csv(""iris.csv"")
dataset.head()"
1851,How to Remove rows in Numpy array that contains non-numeric values in Python,"# Importing Numpy module
import numpy as np
# Creating 2X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, 3.8],
[41, np.nan, np.nan]])
print(""Given array:"")
print(n_arr)
print(""\nRemove all rows containing non-numeric elements"")
print(n_arr[~np.isnan(n_arr).any(axis=1)])"
1852,How to create filename containing date or time in Python,"# import module
from datetime import datetime
# get current date and time
current_datetime = datetime.now()
print(""Current date & time : "", current_datetime)
# convert datetime obj to string
str_current_datetime = str(current_datetime)
# create a file object along with extension
file_name = str_current_datetime+"".txt""
file = open(file_name, 'w')
print(""File created : "", file.name)
file.close()"
1853,Write a Python program to Intersection of two lists,"# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))"
1854,Write a Python program to Convert Matrix to Custom Tuple Matrix,"# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing List elements
add_list = ['Gfg', 'is', 'best']
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
for e in ele:
res.append((idx, e))
# printing result
print(""Matrix after conversion : "" + str(res))"
1855,How to convert a Python datetime.datetime to excel serial date number,"# Python3 code to illustrate the conversion of
# datetime.datetime to excel serial date number
# Importing datetime module
import datetime
# Calling the now() function to return
# current date and time
current_datetime = datetime.datetime.now()
# Calling the strftime() function to convert
# the above current datetime into excel serial date number
print(current_datetime.strftime('%x %X'))"
1856,How to round elements of the NumPy array to the nearest integer in Python,"import numpy as n
# create array
y = n.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
print(""Original array:"", end="" "")
print(y)
# rount to nearest integer
y = n.rint(y)
print(""After rounding off:"", end="" "")
print(y)"
1857,numpy string operations | find() function in Python,"# Python program explaining
# numpy.char.find() method
# importing numpy as geek
import numpy as geek
# input arrays
in_arr = geek.array(['aAaAaA', 'baA', 'abBABba'])
print (""Input array : "", in_arr)
# output arrays
out_arr = geek.char.find(in_arr, sub ='A')
print (""Output array: "", out_arr) "
1858,numpy string operations | join() function in Python,"# Python program explaining
# numpy.core.defchararray.join() method
# importing numpy
import numpy as geek
# input array
in_arr = geek.array(['Python', 'Numpy', 'Pandas'])
print (""Input original array : "", in_arr)
# creating the separator
sep = geek.array(['-', '+', '*'])
out_arr = geek.core.defchararray.join(sep, in_arr)
print (""Output joined array: "", out_arr) "
1859,numpy.negative() in Python,"# Python program explaining
# numpy.negative() function
import numpy as geek
in_num = 10
print (""Input number : "", in_num)
out_num = geek.negative(in_num)
print (""negative of input number : "", out_num) "
1860,Flatten a Matrix in Python using NumPy,"# importing numpy as np
import numpy as np
# declare matrix with np
gfg = np.array([[2, 3], [4, 5]])
# using array.flatten() method
flat_gfg = gfg.flatten()
print(flat_gfg)"
1861,Write a Python Program for Binary Search (Recursive and Iterative),"# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print(""Element is present at index"", str(result))
else:
print(""Element is not present in array"")"
1862,Scraping Reddit with Python and BeautifulSoup,"# import module
import requests
from bs4 import BeautifulSoup"
1863,Write a Python program to get all unique combinations of two Lists,"# python program to demonstrate
# unique combination of two lists
# using zip() and permutation of itertools
# import itertools package
import itertools
from itertools import permutations
# initialize lists
list_1 = [""a"", ""b"", ""c"",""d""]
list_2 = [1,4,9]
# create empty list to store the
# combinations
unique_combinations = []
# Getting all permutations of list_1
# with length of list_2
permut = itertools.permutations(list_1, len(list_2))
# zip() is called to pair each permutation
# and shorter list element into combination
for comb in permut:
zipped = zip(comb, list_2)
unique_combinations.append(list(zipped))
# printing unique_combination list
print(unique_combinations)"
1864,Create a list from rows in Pandas dataframe in Python,"# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)"
1865,Write a Python program to Word location in String,"# Python3 code to demonstrate working of
# Word location in String
# Using findall() + index()
import re
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print(""The original string is : "" + test_str)
# initializing word
wrd = 'best'
# Word location in String
# Using findall() + index()
test_str = test_str.split()
res = -1
for idx in test_str:
if len(re.findall(wrd, idx)) > 0:
res = test_str.index(idx) + 1
# printing result
print(""The location of word is : "" + str(res)) "
1866,How to count number of instances of a class in Python,"# code
class geeks:
# this is used to print the number
# of instances of a class
counter = 0
# constructor of geeks class
def __init__(self):
# increment
geeks.counter += 1
# object or instance of geeks class
g1 = geeks()
g2 = geeks()
g3 = geeks()
print(geeks.counter)"
1867,Write a Python program to check whether the string is Symmetrical or Palindrome,"# Python program to demonstrate
# symmetry and palindrome of the
# string
# Function to check whether the
# string is palindrome or not
def palindrome(a):
# finding the mid, start
# and last index of the string
mid = (len(a)-1)//2 #you can remove the -1 or you add <= sign in line 21
start = 0 #so that you can compare the middle elements also.
last = len(a)-1
flag = 0
# A loop till the mid of the
# string
while(start <= mid):
# comparing letters from right
# from the letters from left
if (a[start]== a[last]):
start += 1
last -= 1
else:
flag = 1
break;
# Checking the flag variable to
# check if the string is palindrome
# or not
if flag == 0:
print(""The entered string is palindrome"")
else:
print(""The entered string is not palindrome"")
# Function to check whether the
# string is symmetrical or not
def symmetry(a):
n = len(a)
flag = 0
# Check if the string's length
# is odd or even
if n%2:
mid = n//2 +1
else:
mid = n//2
start1 = 0
start2 = mid
while(start1 < mid and start2 < n):
if (a[start1]== a[start2]):
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
# Checking the flag variable to
# check if the string is symmetrical
# or not
if flag == 0:
print(""The entered string is symmetrical"")
else:
print(""The entered string is not symmetrical"")
# Driver code
string = 'amaama'
palindrome(string)
symmetry(string)"
1868,LRU Cache in Python using OrderedDict,"from collections import OrderedDict
class LRUCache:
# initialising capacity
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
# we return the value of the key
# that is queried in O(1) and return -1 if we
# don't find the key in out dict / cache.
# And also move the key to the end
# to show that it was recently used.
def get(self, key: int) -> int:
if key not in self.cache:
return -1
else:
self.cache.move_to_end(key)
return self.cache[key]
# first, we add / update the key by conventional methods.
# And also move the key to the end to show that it was recently used.
# But here we will also check whether the length of our
# ordered dictionary has exceeded our capacity,
# If so we remove the first key (least recently used)
def put(self, key: int, value: int) -> None:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last = False)
# RUNNER
# initializing our cache with the capacity of 2
cache = LRUCache(2)
cache.put(1, 1)
print(cache.cache)
cache.put(2, 2)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.put(3, 3)
print(cache.cache)
cache.get(2)
print(cache.cache)
cache.put(4, 4)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.get(3)
print(cache.cache)
cache.get(4)
print(cache.cache)
#This code was contributed by Sachin Negi"
1869,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')"
1870,Write a Python program to Ways to remove multiple empty spaces from string List,"# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
# initializing list
test_list = ['gfg', ' ', ' ', 'is', ' ', 'best']
# printing original list
print(""The original list is : "" + str(test_list))
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
if ele.strip():
res.append(ele)
# printing result
print(""List after filtering non-empty strings : "" + str(res)) "
1871,How to Change a Dictionary Into a Class in Python,"# Turns a dictionary into a class
class Dict2Class(object):
def __init__(self, my_dict):
for key in my_dict:
setattr(self, key, my_dict[key])
# Driver Code
if __name__ == ""__main__"":
# Creating the dictionary
my_dict = {""Name"": ""Geeks"",
""Rank"": ""1223"",
""Subject"": ""Python""}
result = Dict2Class(my_dict)
# printing the result
print(""After Converting Dictionary to Class : "")
print(result.Name, result.Rank, result.Subject)
print(type(result))"
1872,How to change border color in Tkinter widget in Python,"# import tkinter
from tkinter import *
# Create Tk object
window = Tk()
# Set the window title
window.title('GFG')
# Create a Frame for border
border_color = Frame(window, background=""red"")
# Label Widget inside the Frame
label = Label(border_color, text=""This is a Label widget"", bd=0)
# Place the widgets with border Frame
label.pack(padx=1, pady=1)
border_color.pack(padx=40, pady=40)
window.mainloop()"
1873,Write a Python program to Remove after substring in String,"# Python3 code to demonstrate working of
# Remove after substring in String
# Using index() + len() + slicing
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing sub string
sub_str = ""best""
# slicing off after length computation
res = test_str[:test_str.index(sub_str) + len(sub_str)]
# printing result
print(""The string after removal : "" + str(res)) "
1874,Create Address Book in Write a Python program to Using Tkinter,"# Import Module
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x500')
# Add Buttons, Label, ListBox
Name = StringVar()
Number = StringVar()
frame = Frame()
frame.pack(pady=10)
frame1 = Frame()
frame1.pack()
frame2 = Frame()
frame2.pack(pady=10)
Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT)
Entry(frame, textvariable = Name,width=50).pack()
Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT)
Entry(frame1, textvariable = Number,width=50).pack()
Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT)
address = Text(frame2,width=37,height=10)
address.pack()
Button(root,text=""Add"",font=""arial 12 bold"").place(x= 100, y=270)
Button(root,text=""View"",font=""arial 12 bold"").place(x= 100, y=310)
Button(root,text=""Delete"",font=""arial 12 bold"").place(x= 100, y=350)
Button(root,text=""Reset"",font=""arial 12 bold"").place(x= 100, y=390)
scroll_bar = Scrollbar(root, orient=VERTICAL)
select = Listbox(root, yscrollcommand=scroll_bar.set, height=12)
scroll_bar.config (command=select.yview)
scroll_bar.pack(side=RIGHT, fill=Y)
select.place(x=200,y=260)
# Execute Tkinter
root.mainloop()"
1875,Write a Python program to Remove Consecutive K element records,"# Python3 code to demonstrate working of
# Remove Consecutive K element records
# Using zip() + list comprehension
# initializing list
test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 6
# Remove Consecutive K element records
# Using zip() + list comprehension
res = [idx for idx in test_list if (K, K) not in zip(idx, idx[1:])]
# printing result
print(""The records after removal : "" + str(res)) "
1876,Find the size of a Set in Python,"import sys
# sample Sets
Set1 = {""A"", 1, ""B"", 2, ""C"", 3}
Set2 = {""Geek1"", ""Raju"", ""Geek2"", ""Nikhil"", ""Geek3"", ""Deepanshu""}
Set3 = {(1, ""Lion""), ( 2, ""Tiger""), (3, ""Fox"")}
# print the sizes of sample Sets
print(""Size of Set1: "" + str(sys.getsizeof(Set1)) + ""bytes"")
print(""Size of Set2: "" + str(sys.getsizeof(Set2)) + ""bytes"")
print(""Size of Set3: "" + str(sys.getsizeof(Set3)) + ""bytes"")"
1877,Adding and Subtracting Matrices in Python,"# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print(""Printing elements of first matrix"")
print(A)
print(""Printing elements of second matrix"")
print(B)
# adding two matrix
print(""Addition of two matrix"")
print(np.add(A, B))"
1878,Set update() in Python to do union of n arrays,"# Function to combine n arrays
def combineAll(input):
# cast first array as set and assign it
# to variable named as result
result = set(input[0])
# now traverse remaining list of arrays
# and take it's update with result variable
for array in input[1:]:
result.update(array)
return list(result)
# Driver program
if __name__ == ""__main__"":
input = [[1, 2, 2, 4, 3, 6],
[5, 1, 3, 4],
[9, 5, 7, 1],
[2, 4, 1, 3]]
print (combineAll(input))"
1879,Compute pearson product-moment correlation coefficients of two given NumPy arrays in Python,"# import library
import numpy as np
# create numpy 1d-array
array1 = np.array([0, 1, 2])
array2 = np.array([3, 4, 5])
# pearson product-moment correlation
# coefficients of the arrays
rslt = np.corrcoef(array1, array2)
print(rslt)"
1880,Write a Python program to Remove all duplicates words from a given sentence,"from collections import Counter
def remov_duplicates(input):
# split input string separated by space
input = input.split("" "")
# joins two adjacent elements in iterable way
for i in range(0, len(input)):
input[i] = """".join(input[i])
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
UniqW = Counter(input)
# joins two adjacent elements in iterable way
s = "" "".join(UniqW.keys())
print (s)
# Driver program
if __name__ == ""__main__"":
input = 'Python is great and Java is also great'
remov_duplicates(input)"
1881,Ranking Rows of Pandas DataFrame in Python,"# import the required packages
import pandas as pd
# Define the dictionary for converting to dataframe
movies = {'Name': ['The Godfather', 'Bird Box', 'Fight Club'],
'Year': ['1972', '2018', '1999'],
'Rating': ['9.2', '6.8', '8.8']}
df = pd.DataFrame(movies)
print(df)"
1882,Write a Python program to Convert key-values list to flat dictionary,"# Python3 code to demonstrate working of
# Convert key-values list to flat dictionary
# Using dict() + zip()
from itertools import product
# initializing dictionary
test_dict = {'month' : [1, 2, 3],
'name' : ['Jan', 'Feb', 'March']}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Convert key-values list to flat dictionary
# Using dict() + zip()
res = dict(zip(test_dict['month'], test_dict['name']))
# printing result
print(""Flattened dictionary : "" + str(res)) "
1883,Write a Python program to Convert Tuple Matrix to Tuple List,"# Python3 code to demonstrate working of
# Convert Tuple Matrix to Tuple List
# Using list comprehension + zip()
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
# printing original list
print(""The original list is : "" + str(test_list))
# flattening
temp = [ele for sub in test_list for ele in sub]
# joining to form column pairs
res = list(zip(*temp))
# printing result
print(""The converted tuple list : "" + str(res))"
1884,Write a Python program to Inversion in nested dictionary,"# Python3 code to demonstrate working of
# Inversion in nested dictionary
# Using loop + recursion
# utility function to get all paths till end
def extract_path(test_dict, path_way):
if not test_dict:
return [path_way]
temp = []
for key in test_dict:
temp.extend(extract_path(test_dict[key], path_way + [key]))
return temp
# function to compute inversion
def hlper_fnc(test_dict):
all_paths = extract_path(test_dict, [])
res = {}
for path in all_paths:
front = res
for ele in path[::-1]:
if ele not in front :
front[ele] = {}
front = front[ele]
return res
# initializing dictionary
test_dict = {""a"" : {""b"" : {""c"" : {}}},
""d"" : {""e"" : {}},
""f"" : {""g"" : {""h"" : {}}}}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# calling helper function for task
res = hlper_fnc(test_dict)
# printing result
print(""The inverted dictionary : "" + str(res)) "
1885,Write a Python program to Change column names and row indexes in Pandas DataFrame,"# first import the libraries
import pandas as pd
# Create a dataFrame using dictionary
df=pd.DataFrame({""Name"":['Tom','Nick','John','Peter'],
""Age"":[15,26,17,28]})
# Creates a dataFrame with
# 2 columns and 4 rows
df"
1886,How to get size of folder using Python,"# import module
import os
# assign size
size = 0
# assign folder path
Folderpath = 'C:/Users/Geetansh Sahni/Documents/R'
# get size
for path, dirs, files in os.walk(Folderpath):
for f in files:
fp = os.path.join(path, f)
size += os.path.getsize(fp)
# display size
print(""Folder size: "" + str(size))"
1887,Intersection of two arrays in Python ( Lambda expression and filter function ),"# Function to find intersection of two arrays
def interSection(arr1,arr2):
# filter(lambda x: x in arr1, arr2) -->
# filter element x from list arr2 where x
# also lies in arr1
result = list(filter(lambda x: x in arr1, arr2))
print (""Intersection : "",result)
# Driver program
if __name__ == ""__main__"":
arr1 = [1, 3, 4, 5, 7]
arr2 = [2, 3, 5, 6]
interSection(arr1,arr2)"
1888,Write a Python program to Convert set into a list,"# Python3 program to convert a
# set into a list
my_set = {'Geeks', 'for', 'geeks'}
s = list(my_set)
print(s)"
1889,Write a Python program to Creating a Pandas dataframe column based on a given condition,"# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011',
'11/11/2011', '11/12/2011'],
'Event' : ['Music', 'Poetry', 'Music', 'Music', 'Poetry']})
# Print the dataframe
print(df)"
1890,How to insert a space between characters of all the elements of a given NumPy array in Python,"# importing numpy as np
import numpy as np
# creating array of string
x = np.array([""geeks"", ""for"", ""geeks""],
dtype=np.str)
print(""Printing the Original Array:"")
print(x)
# inserting space using np.char.join()
r = np.char.join("" "", x)
print(""Printing the array after inserting space\
between the elements"")
print(r)"
1891,Write a Python program to Test substring order,"# Python3 code to demonstrate working of
# Test substring order
# Using join() + in operator + generator expression
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing substring
K = 'seek'
# concatenating required characters
temp = lambda sub: ''.join(chr for chr in sub if chr in set(K))
# checking in order
res = K in temp(test_str)
# printing result
print(""Is substring in order : "" + str(res)) "
1892,String slicing in Python to check if a string can become empty by recursive deletion,"def checkEmpty(input, pattern):
# If both are empty
if len(input)== 0 and len(pattern)== 0:
return 'true'
# If only pattern is empty
if len(pattern)== 0:
return 'true'
while (len(input) != 0):
# find sub-string in main string
index = input.find(pattern)
# check if sub-string founded or not
if (index ==(-1)):
return 'false'
# slice input string in two parts and concatenate
input = input[0:index] + input[index + len(pattern):]
return 'true'
# Driver program
if __name__ == ""__main__"":
input ='GEEGEEKSKS'
pattern ='GEEKS'
print (checkEmpty(input, pattern))"
1893,Write a Python program to How to get unique elements in nested tuple,"# Python3 code to demonstrate working of
# Unique elements in nested tuple
# Using nested loop + set()
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4)]
# printing original list
print(""The original list : "" + str(test_list))
# Unique elements in nested tuple
# Using nested loop + set()
res = []
temp = set()
for inner in test_list:
for ele in inner:
if not ele in temp:
temp.add(ele)
res.append(ele)
# printing result
print(""Unique elements in nested tuples are : "" + str(res))"
1894,How to count the frequency of unique values in NumPy array in Python,"# import library
import numpy as np
ini_array = np.array([10, 20, 5,
10, 8, 20,
8, 9])
# Get a tuple of unique values
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array,
return_counts = True)
# print unique values array
print(""Unique Values:"",
unique)
# print frequency array
print(""Frequency Values:"",
frequency)"
1895,How to calculate the element-wise absolute value of NumPy array in Python,"# import library
import numpy as np
# create a numpy 1d-array
array = np.array([1, -2, 3])
print(""Given array:\n"", array)
# find element-wise
# absolute value
rslt = np.absolute(array)
print(""Absolute array:\n"", rslt)"
1896,Write a Python program to Remove nested records from tuple,"# Python3 code to demonstrate working of
# Remove nested records
# using isinstance() + enumerate() + loop
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
# printing original tuple
print(""The original tuple : "" + str(test_tup))
# Remove nested records
# using isinstance() + enumerate() + loop
res = tuple()
for count, ele in enumerate(test_tup):
if not isinstance(ele, tuple):
res = res + (ele, )
# printing result
print(""Elements after removal of nested records : "" + str(res))"
1897,Write a Python program to Reverse a numpy array,"# Python code to demonstrate
# how to reverse numpy array
# using shortcut method
import numpy as np
# initialising numpy array
ini_array = np.array([1, 2, 3, 6, 4, 5])
# printing initial ini_array
print(""initial array"", str(ini_array))
# printing type of ini_array
print(""type of ini_array"", type(ini_array))
# using shortcut method to reverse
res = ini_array[::-1]
# printing result
print(""final array"", str(res))"
1898,Write a Python program to display half diamond pattern of numbers with star border,"# function to display the pattern up to n
def display(n):
print(""*"")
for i in range(1, n+1):
print(""*"", end="""")
# for loop to display number up to i
for j in range(1, i+1):
print(j, end="""")
# for loop to display number in reverse direction
for j in range(i-1, 0, -1):
print(j, end="""")
print(""*"", end="""")
print()
# for loop to display i in reverse direction
for i in range(n-1, 0, -1):
print(""*"", end="""")
for j in range(1, i+1):
print(j, end="""")
for j in range(i-1, 0, -1):
print(j, end="""")
print(""*"", end="""")
print()
print(""*"")
# driver code
n = 5
print('\nFor n =', n)
display(n)
n = 3
print('\nFor n =', n)
display(n)"
1899,Collapse multiple Columns in Pandas in Python,"# Python program to collapse
# multiple Columns using Pandas
import pandas as pd
# sample data
n = 3
Sample_1 = [57, 51, 6]
Sample_2 = [92, 16, 19]
Sample_3 = [15, 93, 71]
Sample_4 = [28, 73, 31]
sample_id = zip([""S""]*n, list(range(1, n + 1)))
s_names = [''.join([w[0], str(w[1])]) for w in sample_id]
d = {'s_names': s_names, 'Sample_1': Sample_1,
'Sample_2': Sample_2, 'Sample_3': Sample_3,
'Sample_4': Sample_4}
df_1 = pd.DataFrame(d)
mapping = {'Sample_1': 'Result_1',
'Sample_2': 'Result_1',
'Sample_3': 'Result_2',
'Sample_4': 'Result_2'}
df = df_1.set_index('s_names').groupby(mapping, axis = 1).sum()
df.reset_index(level = 0)"
1900,Write a Python program to Insertion at the beginning in OrderedDict,"# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
# inserting items in starting of dict
iniordered_dict.update({'manjeet':'3'})
iniordered_dict.move_to_end('manjeet', last = False)
# print result
print (""Resultant Dictionary : ""+str(iniordered_dict))"
1901,Using Timedelta and Period to create DateTime based indexes in Pandas in Python,"# importing pandas as pd
import pandas as pd
# Creating the timestamp
ts = pd.Timestamp('02-06-2018')
# Print the timestamp
print(ts)"
1902,Write a Python program to Sort Tuples by Total digits,"# Python3 code to demonstrate working of
# Sort Tuples by Total digits
# Using sort() + len() + sum()
def count_digs(tup):
# gets total digits in tuples
return sum([len(str(ele)) for ele in tup ])
# initializing list
test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]
# printing original list
print(""The original list is : "" + str(test_list))
# performing sort
test_list.sort(key = count_digs)
# printing result
print(""Sorted tuples : "" + str(test_list))"
1903,Write a Python program to reverse a stack,"# create class for stack
class Stack:
# create empty list
def __init__(self):
self.Elements = []
# push() for insert an element
def push(self, value):
self.Elements.append(value)
# pop() for remove an element
def pop(self):
return self.Elements.pop()
# empty() check the stack is empty of not
def empty(self):
return self.Elements == []
# show() display stack
def show(self):
for value in reversed(self.Elements):
print(value)
# Insert_Bottom() insert value at bottom
def BottomInsert(s, value):
# check the stack is empty or not
if s.empty():
# if stack is empty then call
# push() method.
s.push(value)
# if stack is not empty then execute
# else block
else:
popped = s.pop()
BottomInsert(s, value)
s.push(popped)
# Reverse() reverse the stack
def Reverse(s):
if s.empty():
pass
else:
popped = s.pop()
Reverse(s)
BottomInsert(s, popped)
# create object of stack class
stk = Stack()
stk.push(1)
stk.push(2)
stk.push(3)
stk.push(4)
stk.push(5)
print(""Original Stack"")
stk.show()
print(""\nStack after Reversing"")
Reverse(stk)
stk.show()"
1904,Explicitly define datatype in a Python function,"# function definition
def add(num1, num2):
print(""Datatype of num1 is "", type(num1))
print(""Datatype of num2 is "", type(num2))
return num1 + num2
# calling the function without
# explicitly declaring the datatypes
print(add(2, 3))
# calling the function by explicitly
# defining the datatype as float
print(add(float(2), float(3)))"
1905,Numpy count_nonzero method | Python,"# Python program explaining
# numpy.count_nonzero() function
# importing numpy as geek
import numpy as geek
arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]]
gfg = geek.count_nonzero(arr)
print (gfg) "
1906,Getting frequency counts of a columns in Pandas DataFrame in Python,"# importing pandas as pd
import pandas as pd
# sample dataframe
df = pd.DataFrame({'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g',
'bar', 'bar', 'foo', 'bar'],
'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] })
# frequency count of column A
count = df['A'].value_counts()
print(count)"
1907,Write a Python program to reverse the content of a file and store it in another file,"# Open the file in write mode
f1 = open(""output1.txt"", ""w"")
# Open the input file and get
# the content into a variable data
with open(""file.txt"", ""r"") as myfile:
data = myfile.read()
# For Full Reversing we will store the
# value of data into new variable data_1
# in a reverse order using [start: end: step],
# where step when passed -1 will reverse
# the string
data_1 = data[::-1]
# Now we will write the fully reverse
# data in the output1 file using
# following command
f1.write(data_1)
f1.close()"
1908,Write a Python program to sort a list of tuples by second Item,"# Python program to sort a list of tuples by the second Item
# Function to sort the list of tuples by its second item
def Sort_Tuple(tup):
# getting length of list of tuples
lst = len(tup)
for i in range(0, lst):
for j in range(0, lst-i-1):
if (tup[j][1] > tup[j + 1][1]):
temp = tup[j]
tup[j]= tup[j + 1]
tup[j + 1]= temp
return tup
# Driver Code
tup =[('for', 24), ('is', 10), ('Geeks', 28),
('Geeksforgeeks', 5), ('portal', 20), ('a', 15)]
print(Sort_Tuple(tup)) "
1909,Write a Python program to Group similar elements into Matrix,"# Python3 code to demonstrate working of
# Group similar elements into Matrix
# Using list comprehension + groupby()
from itertools import groupby
# initializing list
test_list = [1, 3, 5, 1, 3, 2, 5, 4, 2]
# printing original list
print(""The original list : "" + str(test_list))
# Group similar elements into Matrix
# Using list comprehension + groupby()
res = [list(val) for key, val in groupby(sorted(test_list))]
# printing result
print(""Matrix after grouping : "" + str(res))"
1910,Scrape LinkedIn Using Selenium And Beautiful Soup in Python,"from selenium import webdriver
from bs4 import BeautifulSoup
import time
# Creating a webdriver instance
driver = webdriver.Chrome(""Enter-Location-Of-Your-Web-Driver"")
# This instance will be used to log into LinkedIn
# Opening linkedIn's login page
driver.get(""https://linkedin.com/uas/login"")
# waiting for the page to load
time.sleep(5)
# entering username
username = driver.find_element_by_id(""username"")
# In case of an error, try changing the element
# tag used here.
# Enter Your Email Address
username.send_keys(""User_email"")
# entering password
pword = driver.find_element_by_id(""password"")
# In case of an error, try changing the element
# tag used here.
# Enter Your Password
pword.send_keys(""User_pass"")
# Clicking on the log in button
# Format (syntax) of writing XPath -->
# //tagname[@attribute='value']
driver.find_element_by_xpath(""//button[@type='submit']"").click()
# In case of an error, try changing the
# XPath used here."
1911,How to randomly select rows from Pandas DataFrame in Python,"# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
'Age':[27, 24, 22, 32, 15],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# select all columns
df"
1912,How to divide a polynomial to another using NumPy in Python,"# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5, -2, 5)
# g(x) = x +2
gx = (2, 1, 0)
# divide the polynomials
qx, rx = numpy.polynomial.polynomial.polydiv(px, gx)
# print the result
# quotiient
print(qx)
# remainder
print(rx)"
1913,Write a Python program to Numpy matrix.sum(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1; 12, 3]')
# applying matrix.sum() method
geek = gfg.sum()
print(geek)"
1914,Execute a String of Code in Python,"# Python program to illustrate use of exec to
# execute a given code as string.
# function illustrating how exec() functions.
def exec_code():
LOC = """"""
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
""""""
exec(LOC)
# Driver Code
exec_code()"
1915,Write a Python program to Remove suffix from string list,"# Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
# printing original list
print(""The original list : "" + str(test_list))
# initialize suffix
suff = 'x'
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
if word.endswith(suff):
test_list.remove(word)
# printing result
print(""List after removal of suffix elements : "" + str(test_list))"
1916,numpy.poly1d() in Python,"# Python code explaining
# numpy.poly1d()
# importing libraries
import numpy as np
# Constructing polynomial
p1 = np.poly1d([1, 2])
p2 = np.poly1d([4, 9, 5, 4])
print (""P1 : "", p1)
print (""\n p2 : \n"", p2)
# Solve for x = 2
print (""\n\np1 at x = 2 : "", p1(2))
print (""p2 at x = 2 : "", p2(2))
# Finding Roots
print (""\n\nRoots of P1 : "", p1.r)
print (""Roots of P2 : "", p2.r)
# Finding Coefficients
print (""\n\nCoefficients of P1 : "", p1.c)
print (""Coefficients of P2 : "", p2.coeffs)
# Finding Order
print (""\n\nOrder / Degree of P1 : "", p1.o)
print (""Order / Degree of P2 : "", p2.order)"
1917,Write a Python Code for time Complexity plot of Heap Sort,"# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
# find left child of node i
def left(i):
return 2 * i + 1
# find right child of node i
def right(i):
return 2 * i + 2
# calculate and return array size
def heapSize(A):
return len(A)-1
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
# print(""in heapy"", i)
l = left(i)
r = right(i)
# heapSize = len(A)
# print(""left"", l, ""Rightt"", r, ""Size"", heapSize)
if l<= heapSize(A) and A[l] > A[i] :
largest = l
else:
largest = i
if r<= heapSize(A) and A[r] > A[largest]:
largest = r
if largest != i:
# print(""Largest"", largest)
A[i], A[largest]= A[largest], A[i]
# print(""List"", A)
MaxHeapify(A, largest)
# this function makes a heapified array
def BuildMaxHeap(A):
for i in range(int(heapSize(A)/2)-1, -1, -1):
MaxHeapify(A, i)
# Sorting is done using heap of array
def HeapSort(A):
BuildMaxHeap(A)
B = list()
heapSize1 = heapSize(A)
for i in range(heapSize(A), 0, -1):
A[0], A[i]= A[i], A[0]
B.append(A[heapSize1])
A = A[:-1]
heapSize1 = heapSize1-1
MaxHeapify(A, 0)
# randomly generates list of different
# sizes and call HeapSort function
elements = list()
times = list()
for i in range(1, 10):
# generate some integers
a = randint(0, 1000 * i, 1000 * i)
# print(i)
start = time.clock()
HeapSort(a)
end = time.clock()
# print(""Sorted list is "", a)
print(len(a), ""Elements Sorted by HeapSort in "", end-start)
elements.append(len(a))
times.append(end-start)
plt.xlabel('List Length')
plt.ylabel('Time Complexity')
plt.plot(elements, times, label ='Heap Sort')
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal"
1918,Convert JSON data Into a Custom Python Object,"# importing the module
import json
from collections import namedtuple
# creating the data
data = '{""name"" : ""Geek"", ""id"" : 1, ""location"" : ""Mumbai""}'
# making the object
x = json.loads(data, object_hook =
lambda d : namedtuple('X', d.keys())
(*d.values()))
# accessing the JSON data as an object
print(x.name, x.id, x.location)"
1919,Write a Python counter and dictionary intersection example (Make a string using deletion and rearrangement),"# Python code to find if we can make first string
# from second by deleting some characters from
# second and rearranging remaining characters.
from collections import Counter
def makeString(str1,str2):
# convert both strings into dictionaries
# output will be like str1=""aabbcc"",
# dict1={'a':2,'b':2,'c':2}
# str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}
dict1 = Counter(str1)
dict2 = Counter(str2)
# take intersection of two dictionries
# output will be result = {'a':1,'b':2,'c':2}
result = dict1 & dict2
# compare resultant dictionary with first
# dictionary comparison first compares keys
# and then compares their corresponding values
return result == dict1
# Driver program
if __name__ == ""__main__"":
str1 = 'ABHISHEKsinGH'
str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
if (makeString(str1,str2)==True):
print(""Possible"")
else:
print(""Not Possible"")"
1920,Selecting rows in pandas DataFrame based on conditions in Python,"# importing pandas
import pandas as pd
record = {
'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ],
'Age': [21, 19, 20, 18, 17, 21],
'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'],
'Percentage': [88, 92, 95, 70, 65, 78] }
# create a dataframe
dataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print(""Given Dataframe :\n"", dataframe)
# selecting rows based on condition
rslt_df = dataframe[dataframe['Percentage'] > 80]
print('\nResult dataframe :\n', rslt_df)"
1921,Write a Python program to find the power of a number using recursion,"def power(N, P):
# if power is 0 then return 1
if P == 0:
return 1
# if power is 1 then number is
# returned
elif P == 1:
return N
else:
return (N*power(N, P-1))
# Driver program
N = 5
P = 2
print(power(N, P))"
1922,Write a Python program to Stack and StackSwitcher in GTK+ 3,"import gi
# Since a system can have multiple versions
# of GTK + installed, we want to make
# sure that we are importing GTK + 3.
gi.require_version(""Gtk"", ""3.0"")
from gi.repository import Gtk
class StackWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title =""Geeks for Geeks"")
self.set_border_width(10)
# Creating a box vertically oriented with a space of 100 pixel.
vbox = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 100)
self.add(vbox)
# Creating stack, transition type and transition duration.
stack = Gtk.Stack()
stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
stack.set_transition_duration(1000)
# Creating the check button.
checkbutton = Gtk.CheckButton(""Yes"")
stack.add_titled(checkbutton, ""check"", ""Check Button"")
# Creating label .
label = Gtk.Label()
label.set_markup(""Hello World"")
stack.add_titled(label, ""label"", ""Label"")
# Implementation of stack switcher.
stack_switcher = Gtk.StackSwitcher()
stack_switcher.set_stack(stack)
vbox.pack_start(stack_switcher, True, True, 0)
vbox.pack_start(stack, True, True, 0)
win = StackWindow()
win.connect(""destroy"", Gtk.main_quit)
win.show_all()
Gtk.main()"
1923,Assign Function to a Variable in Python,"def a():
print(""GFG"")
# assigning function to a variable
var=a
# calling the variable
var()"
1924,Looping through buttons in Tkinter in Python,"# Import package and it's modules
from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title(""GeekForGeeks"")
# Set geometry (widthxheight)
root.geometry('400x400')
# Execute Tkinter
root.mainloop()"
1925,How to Remove columns in Numpy array that contains non-numeric values in Python,"# Importing Numpy module
import numpy as np
# Creating 2X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, np.nan],
[41, 52.5, np.nan]])
print(""Given array:"")
print(n_arr)
print(""\nRemove all columns containing non-numeric elements "")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])"
1926,Write a Python program to interchange first and last elements in a list,"# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))"
1927,How to Sort data by Column in a CSV File in Python ,"# importing pandas package
import pandas as pandasForSortingCSV
# assign dataset
csvData = pandasForSortingCSV.read_csv(""sample.csv"")
# displaying unsorted data frame
print(""\nBefore sorting:"")
print(csvData)
# sort data frame
csvData.sort_values([""Salary""],
axis=0,
ascending=[False],
inplace=True)
# displaying sorted data frame
print(""\nAfter sorting:"")
print(csvData)"
1928,Write a Python program to Reverse Sort a String,"# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = ""geekforgeeks""
# printing original string
print(""The original string : "" + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = ''.join(sorted(test_string, reverse = True))
# print result
print(""String after reverse sorting : "" + str(res))"
1929,How to Scrape all PDF files in a Website in Python,"# for get the pdf files or url
import requests
# for tree traversal scraping in webpage
from bs4 import BeautifulSoup
# for input and output operations
import io
# For getting information about the pdfs
from PyPDF2 import PdfFileReader"
1930,Multiply matrices of complex numbers using NumPy in Python,"# importing numpy as library
import numpy as np
# creating matrix of complex number
x = np.array([2+3j, 4+5j])
print(""Printing First matrix:"")
print(x)
y = np.array([8+7j, 5+6j])
print(""Printing Second matrix:"")
print(y)
# vector dot product of two matrices
z = np.vdot(x, y)
print(""Product of first and second matrices are:"")
print(z)"
1931,Calculate the Euclidean distance using NumPy in Python,"# Python code to find Euclidean distance
# using linalg.norm()
import numpy as np
# initializing points in
# numpy arrays
point1 = np.array((1, 2, 3))
point2 = np.array((1, 1, 1))
# calculating Euclidean distance
# using linalg.norm()
dist = np.linalg.norm(point1 - point2)
# printing Euclidean distance
print(dist)"
1932,Write a Python program to Swap elements in String list,"# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
# printing original lists
print(""The original list is : "" + str(test_list))
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in test_list]
# printing result
print (""List after performing character swaps : "" + str(res))"
1933,Write a Python program to Kth Column Product in Tuple List,"# Python3 code to demonstrate working of
# Tuple List Kth Column Product
# using list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
# printing original list
print(""The original list is : "" + str(test_list))
# initialize K
K = 2
# Tuple List Kth Column Product
# using list comprehension + loop
res = prod([sub[K] for sub in test_list])
# printing result
print(""Product of Kth Column of Tuple List : "" + str(res))"
1934,Write a Python program to create a list of tuples from given list having number and its cube in each tuple,"# Python program to create a list of tuples
# from given list having number and
# its cube in each tuple
# creating a list
list1 = [1, 2, 5, 6]
# using list comprehension to iterate each
# values in list and create a tuple as specified
res = [(val, pow(val, 3)) for val in list1]
# print the result
print(res)"
1935,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()"
1936,Write a Python program to Find all close matches of input string from a list,"# Function to find all close matches of
# input string in given list of possible strings
from difflib import get_close_matches
def closeMatches(patterns, word):
print(get_close_matches(word, patterns))
# Driver program
if __name__ == ""__main__"":
word = 'appel'
patterns = ['ape', 'apple', 'peach', 'puppy']
closeMatches(patterns, word)"
1937,Write a Python program to Find fibonacci series upto n using lambda,"from functools import reduce
fib = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]],
range(n-2), [0, 1])
print(fib(5))"
1938,Sorting a CSV object by dates in Python,import pandas as pd
1939,Overuse of lambda expressions in Python,"# Python program showing a use
# lambda function
# performing a addition of three number
x1 = (lambda x, y, z: (x + y) * z)(1, 2, 3)
print(x1)
# function using a lambda function
x2 = (lambda x, y, z: (x + y) if (z == 0) else (x * y))(1, 2, 3)
print(x2) "
1940,Difference of two columns in Pandas dataframe in Python,"import pandas as pd
# Create a DataFrame
df1 = { 'Name':['George','Andrea','micheal',
'maggie','Ravi','Xien','Jalpa'],
'score1':[62,47,55,74,32,77,86],
'score2':[45,78,44,89,66,49,72]}
df1 = pd.DataFrame(df1,columns= ['Name','score1','score2'])
print(""Given Dataframe :\n"", df1)
# getting Difference
df1['Score_diff'] = df1['score1'] - df1['score2']
print(""\nDifference of score1 and score2 :\n"", df1)"
1941,"Open computer drives like C, D or E using Python","# import library
import os
# take Input from the user
query = input(""Which drive you have to open ? C , D or E: \n"")
# Check the condition for
# opening the C drive
if ""C"" in query or ""c"" in query:
os.startfile(""C:"")
# Check the condition for
# opening the D drive
elif ""D"" in query or ""d"" in query:
os.startfile(""D:"")
# Check the condition for
# opening the D drive
elif ""E"" in query or ""e"" in query:
os.startfile(""E:"")
else:
print(""Wrong Input"")"
1942,Write a Python Dictionary | Check if binary representations of two numbers are anagram,"# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1,num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin(num1)[2:]
bin2 = bin(num2)[2:]
# append zeros in shorter string
zeros = abs(len(bin1)-len(bin2))
if (len(bin1)>len(bin2)):
bin2 = zeros * '0' + bin2
else:
bin1 = zeros * '0' + bin1
# convert binary representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 == dict2:
print('Yes')
else:
print('No')
# Driver program
if __name__ == ""__main__"":
num1 = 8
num2 = 4
checkAnagram(num1,num2)
"
1943,Write a Python Program to Print Lines Containing Given String in File,"# Python Program to Print Lines
# Containing Given String in File
# input file name with extension
file_name = input(""Enter The File's Name: "")
# using try catch except to
# handle file not found error.
# entering try block
try:
# opening and reading the file
file_read = open(file_name, ""r"")
# asking the user to enter the string to be
# searched
text = input(""Enter the String: "")
# reading file content line by line.
lines = file_read.readlines()
new_list = []
idx = 0
# looping through each line in the file
for line in lines:
# if line have the input string, get the index
# of that line and put the
# line into newly created list
if text in line:
new_list.insert(idx, line)
idx += 1
# closing file after reading
file_read.close()
# if length of new list is 0 that means
# the input string doesn't
# found in the text file
if len(new_list)==0:
print(""\n\"""" +text+ ""\"" is not found in \"""" +file_name+ ""\""!"")
else:
# displaying the lines
# containing given string
lineLen = len(new_list)
print(""\n**** Lines containing \"""" +text+ ""\"" ****\n"")
for i in range(lineLen):
print(end=new_list[i])
print()
# entering except block
# if input file doesn't exist
except :
print(""\nThe file doesn't exist!"")"
1944,NumPy.histogram() Method in Python,"# Import libraries
import numpy as np
# Creating dataset
a = np.random.randint(100, size =(50))
# Creating histogram
np.histogram(a, bins = [0, 10, 20, 30, 40,
50, 60, 70, 80, 90,
100])
hist, bins = np.histogram(a, bins = [0, 10,
20, 30,
40, 50,
60, 70,
80, 90,
100])
# printing histogram
print()
print (hist)
print (bins)
print()"
1945,Write a Python program to find files having a particular extension using RegEx,"# import library
import re
# list of different types of file
filenames = [""gfg.html"", ""geeks.xml"",
""computer.txt"", ""geeksforgeeks.jpg""]
for file in filenames:
# search given pattern in the line
match = re.search(""\.xml$"", file)
# if match is found
if match:
print(""The file ending with .xml is:"",
file)"
1946,Write a Python program to Dictionary Values Mean,"# Python3 code to demonstrate working of
# Dictionary Values Mean
# Using loop + len()
# initializing dictionary
test_dict = {""Gfg"" : 4, ""is"" : 7, ""Best"" : 8, ""for"" : 6, ""Geeks"" : 10}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# loop to sum all values
res = 0
for val in test_dict.values():
res += val
# using len() to get total keys for mean computation
res = res / len(test_dict)
# printing result
print(""The computed mean : "" + str(res)) "
1947,How to iterate over rows in Pandas Dataframe in Python,"# importing pandas
import pandas as pd
# list of dicts
input_df = [{'name':'Sujeet', 'age':10},
{'name':'Sameer', 'age':11},
{'name':'Sumit', 'age':12}]
df = pd.DataFrame(input_df)
print('Original DataFrame: \n', df)
print('\nRows iterated using iterrows() : ')
for index, row in df.iterrows():
print(row['name'], row['age'])"
1948,Write a Python program to right rotate n-numbers by 1,"def print_pattern(n):
for i in range(1, n+1, 1):
for j in range(1, n+1, 1):
# check that if index i is
# equal to j
if i == j:
print(j, end="" "")
# if index i is less than j
if i <= j:
for k in range(j+1, n+1, 1):
print(k, end="" "")
for p in range(1, j, 1):
print(p, end="" "")
# print new line
print()
# Driver's code
print_pattern(3)"
1949,How to create filename containing date or time in Python,"# import module
from datetime import datetime
# get current date and time
current_datetime = datetime.now()
print(""Current date & time : "", current_datetime)
# convert datetime obj to string
str_current_datetime = str(current_datetime)
# create a file object along with extension
file_name = str_current_datetime+"".txt""
file = open(file_name, 'w')
print(""File created : "", file.name)
file.close()"
1950,numpy.swapaxes() function | Python,"# Python program explaining
# numpy.swapaxes() function
# importing numpy as geek
import numpy as geek
arr = geek.array([[2, 4, 6]])
gfg = geek.swapaxes(arr, 0, 1)
print (gfg)"
1951,Convert JSON to dictionary in Python,"# Python program to demonstrate
# Conversion of JSON data to
# dictionary
# importing the module
import json
# Opening JSON file
with open('data.json') as json_file:
data = json.load(json_file)
# Print the type of data variable
print(""Type:"", type(data))
# Print the data of dictionary
print(""\nPeople1:"", data['people1'])
print(""\nPeople2:"", data['people2'])"
1952,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)) "
1953,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))"
1954,Scrape LinkedIn Using Selenium And Beautiful Soup in Python,"from selenium import webdriver
from bs4 import BeautifulSoup
import time
# Creating a webdriver instance
driver = webdriver.Chrome(""Enter-Location-Of-Your-Web-Driver"")
# This instance will be used to log into LinkedIn
# Opening linkedIn's login page
driver.get(""https://linkedin.com/uas/login"")
# waiting for the page to load
time.sleep(5)
# entering username
username = driver.find_element_by_id(""username"")
# In case of an error, try changing the element
# tag used here.
# Enter Your Email Address
username.send_keys(""User_email"")
# entering password
pword = driver.find_element_by_id(""password"")
# In case of an error, try changing the element
# tag used here.
# Enter Your Password
pword.send_keys(""User_pass"")
# Clicking on the log in button
# Format (syntax) of writing XPath -->
# //tagname[@attribute='value']
driver.find_element_by_xpath(""//button[@type='submit']"").click()
# In case of an error, try changing the
# XPath used here."
1955,Write a Python program to Closest Pair to Kth index element in Tuple,"# Python3 code to demonstrate working of
# Closest Pair to Kth index element in Tuple
# Using enumerate() + loop
# initializing list
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing tuple
tup = (17, 23)
# initializing K
K = 1
# Closest Pair to Kth index element in Tuple
# Using enumerate() + loop
min_dif, res = 999999999, None
for idx, val in enumerate(test_list):
dif = abs(tup[K - 1] - val[K - 1])
if dif < min_dif:
min_dif, res = dif, idx
# printing result
print(""The nearest tuple to Kth index element is : "" + str(test_list[res])) "
1956,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))"
1957,Write a Python Program to Delete Specific Line from File,"# deleting a line
# based on the position
# opening the file in
# reading mode
try:
with open('months.txt', 'r') as fr:
# reading line by line
lines = fr.readlines()
# pointer for position
ptr = 1
# opening in writing mode
with open('months.txt', 'w') as fw:
for line in lines:
# we want to remove 5th line
if ptr != 5:
fw.write(line)
ptr += 1
print(""Deleted"")
except:
print(""Oops! something error"")"
1958,Write a Python program to Append Dictionary Keys and Values ( In order ) in dictionary,"# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using values() + keys() + list()
# initializing dictionary
test_dict = {""Gfg"" : 1, ""is"" : 3, ""Best"" : 2}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# + operator is used to perform adding keys and values
res = list(test_dict.keys()) + list(test_dict.values())
# printing result
print(""The ordered keys and values : "" + str(res)) "
1959,Write a Python program to Numpy np.polygrid2d() method,"# Python program explaining
# numpy.polygrid2d() method
# importing numpy as np
import numpy as np
from numpy.polynomial.polynomial import polygrid2d
# Input polynomial series coefficients
c = np.array([[1, 3, 5], [2, 4, 6]])
# using np.polygrid2d() method
ans = polygrid2d([7, 9], [8, 10], c)
print(ans)"
1960,Apply uppercase to a column in Pandas dataframe in Python,"# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
# calling head() method
# storing in new variable
data_top = data.head(10)
# display
data_top"
1961,Flattening JSON objects in Python,"# for a array value of a key
unflat_json = {'user' :
{'Rachel':
{'UserID':1717171717,
'Email': 'rachel1999@gmail.com',
'friends': ['John', 'Jeremy', 'Emily']
}
}
}
# Function for flattening
# json
def flatten_json(y):
out = {}
def flatten(x, name =''):
# If the Nested key-value
# pair is of dict type
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
# If the Nested key-value
# pair is of list type
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out
# Driver code
print(flatten_json(unflat_json))"
1962,Finding the largest file in a directory using Python,"import os
# folder path input
print(""Enter folder path"")
path = os.path.abspath(input())
# for storing size of each
# file
size = 0
# for storing the size of
# the largest file
max_size = 0
# for storing the path to the
# largest file
max_file =""""
# walking through the entire folder,
# including subdirectories
for folder, subfolders, files in os.walk(path):
# checking the size of each file
for file in files:
size = os.stat(os.path.join( folder, file )).st_size
# updating maximum size
if size>max_size:
max_size = size
max_file = os.path.join( folder, file )
print(""The largest file is: ""+max_file)
print('Size: '+str(max_size)+' bytes')"
1963,Write a Python program to Consecutive Kth column Difference in Tuple List,"# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using loop
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 1
res = []
for idx in range(0, len(test_list) - 1):
# getting difference using abs()
res.append(abs(test_list[idx][K] - test_list[idx + 1][K]))
# printing result
print(""Resultant tuple list : "" + str(res))"
1964,"Calculate the average, variance and standard deviation in Python using NumPy","# Python program to get average of a list
# Importing the NumPy module
import numpy as np
# Taking a list of elements
list = [2, 4, 4, 4, 5, 5, 7, 9]
# Calculating average using average()
print(np.average(list))"
1965,Write a Python Program for KMP Algorithm for Pattern Searching,"# Python program for KMP Algorithm
def KMPSearch(pat, txt):
M = len(pat)
N = len(txt)
# create lps[] that will hold the longest prefix suffix
# values for pattern
lps = [0]*M
j = 0 # index for pat[]
# Preprocess the pattern (calculate lps[] array)
computeLPSArray(pat, M, lps)
i = 0 # index for txt[]
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
print ""Found pattern at index "" + str(i-j)
j = lps[j-1]
# mismatch after j matches
elif i < N and pat[j] != txt[i]:
# Do not match lps[0..lps[j-1]] characters,
# they will match anyway
if j != 0:
j = lps[j-1]
else:
i += 1
def computeLPSArray(pat, M, lps):
len = 0 # length of the previous longest prefix suffix
lps[0] # lps[0] is always 0
i = 1
# the loop calculates lps[i] for i = 1 to M-1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
# This is tricky. Consider the example.
# AAACAAAA and i = 7. The idea is similar
# to search step.
if len != 0:
len = lps[len-1]
# Also, note that we do not increment i here
else:
lps[i] = 0
i += 1
txt = ""ABABDABACDABABCABAB""
pat = ""ABABCABAB""
KMPSearch(pat, txt)
# This code is contributed by Bhavya Jain"
1966,Write a Python program to Check if two strings are Rotationally Equivalent,"# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
# initializing strings
test_str1 = 'geeks'
test_str2 = 'eksge'
# printing original strings
print(""The original string 1 is : "" + str(test_str1))
print(""The original string 2 is : "" + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
res = False
for idx in range(len(test_str1)):
if test_str1[idx: ] + test_str1[ :idx] == test_str2:
res = True
break
# printing result
print(""Are two strings Rotationally equal ? : "" + str(res)) "
1967,numpy.percentile() in python,"# Python Program illustrating
# numpy.percentile() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print(""arr : "", arr)
print(""50th percentile of arr : "",
np.percentile(arr, 50))
print(""25th percentile of arr : "",
np.percentile(arr, 25))
print(""75th percentile of arr : "",
np.percentile(arr, 75))"
1968,Write a Python program to Similar characters Strings comparison,"# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using split() + sorted()
# initializing strings
test_str1 = 'e:e:k:s:g'
test_str2 = 'g:e:e:k:s'
# printing original strings
print(""The original string 1 is : "" + str(test_str1))
print(""The original string 2 is : "" + str(test_str2))
# initializing delim
delim = ':'
# == operator is used for comparison
res = sorted(test_str1.split(':')) == sorted(test_str2.split(':'))
# printing result
print(""Are strings similar : "" + str(res)) "
1969,Write a Python program to print even length words in a string,"# Python3 program to print
# even length words in a string
def printWords(s):
# split the string
s = s.split(' ')
# iterate in words of string
for word in s:
# if length is even
if len(word)%2==0:
print(word)
# Driver Code
s = ""i am muskan""
printWords(s) "
1970,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)) "
1971,Write a Python program to Stack using Doubly Linked List,"# A complete working Python program to demonstrate all
# stack operations using a doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.prev = None # Initialize prev as null
# Stack class contains a Node object
class Stack:
# Function to initialize head
def __init__(self):
self.head = None
# Function to add an element data in the stack
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
self.head.prev = new_node
new_node.next = self.head
new_node.prev = None
self.head = new_node
# Function to pop top element and return the element from the stack
def pop(self):
if self.head is None:
return None
elif self.head.next is None:
temp = self.head.data
self.head = None
return temp
else:
temp = self.head.data
self.head = self.head.next
self.head.prev = None
return temp
# Function to return top element in the stack
def top(self):
return self.head.data
# Function to return the size of the stack
def size(self):
temp = self.head
count = 0
while temp is not None:
count = count + 1
temp = temp.next
return count
# Function to check if the stack is empty or not
def isEmpty(self):
if self.head is None:
return True
else:
return False
# Function to print the stack
def printstack(self):
print(""stack elements are:"")
temp = self.head
while temp is not None:
print(temp.data, end =""->"")
temp = temp.next
# Code execution starts here
if __name__=='__main__':
# Start with the empty stack
stack = Stack()
# Insert 4 at the beginning. So stack becomes 4->None
print(""Stack operations using Doubly LinkedList"")
stack.push(4)
# Insert 5 at the beginning. So stack becomes 4->5->None
stack.push(5)
# Insert 6 at the beginning. So stack becomes 4->5->6->None
stack.push(6)
# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
stack.push(7)
# Print the stack
stack.printstack()
# Print the top element
print(""\nTop element is "", stack.top())
# Print the stack size
print(""Size of the stack is "", stack.size())
# pop the top element
stack.pop()
# pop the top element
stack.pop()
# two elements are popped
# Print the stack
stack.printstack()
# Print True if the stack is empty else False
print(""\nstack is empty:"", stack.isEmpty())
#This code is added by Suparna Raut"
1972,Write a Python Program to print a number diamond of any given size N in Rangoli Style,"def print_diamond(size):
# print the first triangle
# (the upper half)
for i in range (size):
# print from first row till
# middle row
rownum = i + 1
num_alphabet = 2 * rownum - 1
space_in_between_alphabets = num_alphabet - 1
total_spots = (2 * size - 1) * 2 - 1
total_space = total_spots - num_alphabet
space_leading_trailing = total_space - space_in_between_alphabets
lead_space = int(space_leading_trailing / 2)
trail_space = int(space_leading_trailing / 2)
# print the leading spaces
for j in range(lead_space):
print('-', end ='')
# determine the middle character
mid_char = (1 + size - 1) - int(num_alphabet / 2)
# start with the last character
k = 1 + size - 1
is_alphabet_printed = False
mid_char_reached = False
# print the numbers alternated by '-'
for j in range(num_alphabet + space_in_between_alphabets):
if not is_alphabet_printed:
print(str(k), end ='')
is_alphabet_printed = True
if k == mid_char:
mid_char_reached = True
if mid_char_reached == True:
k += 1
else:
k -= 1
else:
print('-', end ='')
is_alphabet_printed = False
# print the trailing spaces
for j in range(trail_space):
print('-', end ='')
# go to the next line
print('')
# print the rows after middle row
# till last row (the second triangle
# which is inverted, i.e., the lower half)
for i in range(size + 1, 2 * size):
rownum = i
num_alphabet = 2 * (2 * size - rownum) - 1
space_in_between_alphabets = num_alphabet - 1
total_spots = (2 * size - 1) * 2 - 1
total_space = total_spots - num_alphabet
space_leading_trailing = total_space - space_in_between_alphabets
lead_space = int(space_leading_trailing / 2)
trail_space = int(space_leading_trailing / 2)
# print the leading spaces
for j in range(lead_space):
print('-', end ='')
mid_char = (1 + size - 1) - int(num_alphabet / 2)
# start with the last char
k = 1 + size - 1
is_alphabet_printed = False
mid_char_reached = False
# print the numbers alternated by '-'
for j in range(num_alphabet + space_in_between_alphabets):
if not is_alphabet_printed:
print(str(k), end ='')
is_alphabet_printed = True
if k == mid_char:
mid_char_reached = True
if mid_char_reached == True:
k += 1
else:
k -= 1
else:
print('-', end ='')
is_alphabet_printed = False
# print the trailing spaces
for j in range(trail_space):
print('-', end ='')
# go to the next line
print('')
# Driver Code
if __name__ == '__main__':
n = 5
print_diamond(n)"
1973,How To Automate Google Chrome Using Foxtrot and Python,"# Import the required modules
from selenium import webdriver
import time
# Main Function
if __name__ == '__main__':
# Provide the email and password
email = ''
password = ''
options = webdriver.ChromeOptions()
options.add_argument(""--start-maximized"")
# Provide the path of chromedriver
# present on your system.
driver = webdriver.Chrome(
executable_path=""C:/chromedriver/chromedriver.exe"",
chrome_options=options)
driver.set_window_size(1920, 1080)
# Send a get request to the url
driver.get('https://auth.geeksforgeeks.org/')
time.sleep(5)
# Finds the input box by name
# in DOM tree to send both
# the provided email and password in it.
driver.find_element_by_name('user').send_keys(email)
driver.find_element_by_name('pass').send_keys(password)
# Find the signin button and click on it.
driver.find_element_by_css_selector(
'button.btn.btn-green.signin-button').click()
time.sleep(5)
# Returns the list of elements
# having the following css selector.
container = driver.find_elements_by_css_selector(
'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold')
# Extracts the text from name,
# institution, email_id css selector.
name = container[0].text
try:
institution = container[1].find_element_by_css_selector('a').text
except:
institution = container[1].text
email_id = container[2].text
# Output
print({""Name"": name, ""Institution"": institution,
""Email ID"": email})
# Quits the driver
driver.quit()"
1974,Program to Print K using Alphabets in Python,"// C++ Program to design the
// above pattern of K using alphabets
#include
using namespace std;
// Function to print
// the above Pattern
void display(int n)
{
int v = n;
// This loop is used
// for rows and prints
// the alphabets in
// decreasing order
while (v >= 0)
{
int c = 65;
// This loop is used
// for columns
for(int j = 0; j < v + 1; j++)
{
// chr() function converts the
// number to alphabet
cout << char(c + j) << "" "";
}
v--;
cout << endl;
}
// This loop is again used
// to rows and prints the
// half remaining pattern in
// increasing order
for(int i = 0; i < n + 1; i++)
{
int c = 65;
for(int j = 0; j < i + 1; j++)
{
cout << char(c + j) << "" "";
}
cout << endl;
}
}
// Driver code
int main()
{
int n = 5;
display(n);
return 0;
}
// This code is contributed by divyeshrabadiya07"
1975,How to drop one or multiple columns 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', 'B5'],
'C':['C1', 'C2', 'C3', 'C4', 'C5'],
'D':['D1', 'D2', 'D3', 'D4', 'D5'],
'E':['E1', 'E2', 'E3', 'E4', 'E5'] }
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
df"
1976,Write a Python Program to Replace Text in a File,"# Python program to replace text in a file
s = input(""Enter text to replace the existing contents:"")
f = open(""file.txt"", ""r+"")
# file.txt is an example here,
# it should be replaced with the file name
# r+ mode opens the file in read and write mode
f.truncate(0)
f.write(s)
f.close()
print(""Text successfully replaced"")"
1977,Remove multiple elements from a list in Python,"# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# Iterate each element in list
# and add them in variable total
for ele in list1:
if ele % 2 == 0:
list1.remove(ele)
# printing modified list
print(""New list after removing all even numbers: "", list1)"
1978,How to get column names in Pandas dataframe in Python,"# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
# calling head() method
# storing in new variable
data_top = data.head()
# display
data_top "
1979,Nested Lambda Function in Python,"# Python program to demonstrate
# nested lambda functions
f = lambda a = 2, b = 3:lambda c: a+b+c
o = f()
print(o(4))"
1980,Write a Python program to Sort Dictionary key and values List,"# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
'is': [2, 10, 3],
'best': [19, 4]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
res[key] = sorted(test_dict[key])
# printing result
print(""The sorted dictionary : "" + str(res)) "
1981,Write a Python program to Remove punctuation from string,"# Python3 code to demonstrate working of
# Removing punctuations in string
# Using loop + punctuation string
# initializing string
test_str = ""Gfg, is best : for ! Geeks ;""
# printing original string
print(""The original string is : "" + test_str)
# initializing punctuations string
punc = '''!()-[]{};:'""\,<>./?@#$%^&*_~'''
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele in punc:
test_str = test_str.replace(ele, """")
# printing result
print(""The string after punctuation filter : "" + test_str)"
1982,Reset Index in Pandas Dataframe in Python,"# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
'Age':[27, 24, 22, 32, 15],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] }
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
df"
1983,Write a Python program to numpy.nanmean() function,"# Python code to demonstrate the
# use of numpy.nanmean
import numpy as np
# create 2d array with nan value.
arr = np.array([[20, 15, 37], [47, 13, np.nan]])
print(""Shape of array is"", arr.shape)
print(""Mean of array without using nanmean function:"",
np.mean(arr))
print(""Using nanmean function:"", np.nanmean(arr))"
1984,Write a Python program to Row-wise element Addition in Tuple Matrix,"# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing Custom eles
cus_eles = [6, 7, 8]
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
res = [[sub + (cus_eles[idx], ) for sub in val] for idx, val in enumerate(test_list)]
# printing result
print(""The matrix after row elements addition : "" + str(res)) "
1985,Write a Python program to Assigning Subsequent Rows to Matrix first row elements,"# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using dictionary comprehension
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
# printing original list
print(""The original list : "" + str(test_list))
# pairing each 1st col with next rows in Matrix
res = {test_list[0][ele] : test_list[ele + 1] for ele in range(len(test_list) - 1)}
# printing result
print(""The Assigned Matrix : "" + str(res))"
1986,Write a Python program to Split by repeating substring,"# Python3 code to demonstrate working of
# Split by repeating substring
# Using * operator + len()
# initializing string
test_str = ""gfggfggfggfggfggfggfggfg""
# printing original string
print(""The original string is : "" + test_str)
# initializing target
K = 'gfg'
# Split by repeating substring
# Using * operator + len()
temp = len(test_str) // len(str(K))
res = [K] * temp
# printing result
print(""The split string is : "" + str(res)) "
1987,Write a Python program to Ways to remove multiple empty spaces from string List,"# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
# initializing list
test_list = ['gfg', ' ', ' ', 'is', ' ', 'best']
# printing original list
print(""The original list is : "" + str(test_list))
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
if ele.strip():
res.append(ele)
# printing result
print(""List after filtering non-empty strings : "" + str(res)) "
1988,Ways to convert string to dictionary in Python,"# Python implementation of converting
# a string into a dictionary
# initialising string
str = "" Jan = January; Feb = February; Mar = March""
# At first the string will be splitted
# at the occurence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split(""="") for subString in str.split("";""))
# printing the generated dictionary
print(dictionary)"
1989,Write a Python program to Sum of number digits in List,"# Python3 code to demonstrate
# Sum of number digits in List
# using loop + str()
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print(""The original list is : "" + str(test_list))
# Sum of number digits in List
# using loop + str()
res = []
for ele in test_list:
sum = 0
for digit in str(ele):
sum += int(digit)
res.append(sum)
# printing result
print (""List Integer Summation : "" + str(res))"
1990,Get the index of maximum value in DataFrame column in Python,"# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
df.head(10)"
1991,Getting the time since OS startup using Python,"# for using os.popen()
import os
# sending the uptime command as an argument to popen()
# and saving the returned result (after truncating the trailing \n)
t = os.popen('uptime -p').read()[:-1]
print(t)"
1992,Write a Python program to Get Function Signature,"from inspect import signature
# declare a function gfg with some
# parameter
def gfg(x:str, y:int):
pass
# with the help of signature function
# store signature of the function in
# variable t
t = signature(gfg)
# print the signature of the function
print(t)
# print the annonation of the parameter
# of the function
print(t.parameters['x'])
# print the annonation of the parameter
# of the function
print(t.parameters['y'].annotation)"
1993,numpy.diff() in Python,"# Python program explaining
# numpy.diff() method
# importing numpy
import numpy as geek
# input array
arr = geek.array([1, 3, 4, 7, 9])
print(""Input array : "", arr)
print(""First order difference : "", geek.diff(arr))
print(""Second order difference : "", geek.diff(arr, n = 2))
print(""Third order difference : "", geek.diff(arr, n = 3))"
1994,Compute the Kronecker product of two multidimension NumPy arrays in Python,"# Importing required modules
import numpy
# Creating arrays
array1 = numpy.array([[1, 2], [3, 4]])
print('Array1:\n', array1)
array2 = numpy.array([[5, 6], [7, 8]])
print('\nArray2:\n', array2)
# Computing the Kronecker Product
kroneckerProduct = numpy.kron(array1, array2)
print('\nArray1 ⊗ Array2:')
print(kroneckerProduct)"
1995,Menu driven Python program to execute Linux commands,"# importing the module
import os
# sets the text colour to green
os.system(""tput setaf 2"")
print(""Launching Terminal User Interface"")
# sets the text color to red
os.system(""tput setaf 1"")
print(""\t\tWELCOME TO Terminal User Interface\t\t\t"")
# sets the text color to white
os.system(""tput setaf 7"")
print(""\t-------------------------------------------------"")
print(""Entering local device"")
while True:
print(""""""
1.Print date
2.Print cal
3.Configure web
4.Configure docker
5.Add user
6.Delete user
7.Create a file
8.Create a folder
9.Exit"""""")
ch=int(input(""Enter your choice: ""))
if(ch == 1):
os.system(""date"")
elif ch == 2:
os.system(""cal"")
elif ch == 3:
os.system(""yum install httpd -y"")
os.system(""systemctl start httpd"")
os.system(""systemctl status httpd"")
elif ch == 4:
os.system(""yum install docker-ce -y"")
os.system(""systemctl start docker"")
os.system(""systemctl status docker"")
elif ch == 5:
new_user=input(""Enter the name of new user: "")
os.system(""sudo useradd {}"".format(new_user))
os.system(""id -u {}"".format(new_user) )
elif ch == 6:
del_user=input(""Enter the name of the user to delete: "")
os.system(""sudo userdel {}"".format(del_user))
elif ch == 7:
filename=input(""Enter the filename: "")
f=os.system(""sudo touch {}"".format(filename))
if f!=0:
print(""Some error occurred"")
else:
print(""File created successfully"")
elif ch == 8:
foldername=input(""Enter the foldername: "")
f=os.system(""sudo mkdir {}"".format(foldername))
if f!=0:
print(""Some error occurred"")
else:
print(""Folder created successfully"")
elif ch == 9:
print(""Exiting application"")
exit()
else:
print(""Invalid entry"")
input(""Press enter to continue"")
os.system(""clear"")"
1996,Calculate average values of two given NumPy arrays in Python,"# import library
import numpy as np
# create a numpy 1d-arrays
arr1 = np.array([3, 4])
arr2 = np.array([1, 0])
# find average of NumPy arrays
avg = (arr1 + arr2) / 2
print(""Average of NumPy arrays:\n"",
avg)"
1997,Write a Python program to Extract elements with Frequency greater than K,"# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using count() + loop
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print(""The original list : "" + str(test_list))
# initializing K
K = 2
res = []
for i in test_list:
# using count() to get count of elements
freq = test_list.count(i)
# checking if not already entered in results
if freq > K and i not in res:
res.append(i)
# printing results
print(""The required elements : "" + str(res))"
1998,Write a Python program to Maximum Consecutive Substring Occurrence,"# Python3 code to demonstrate working of
# Maximum Consecutive Substring Occurrence
# Using max() + re.findall()
import re
# initializing string
test_str = 'geeksgeeks are geeks for all geeksgeeksgeeks'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing subs
sub_str = 'geeks'
# Maximum Consecutive Substring Occurrence
# Using max() + re.findall()
res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len)
# printing result
print(""The maximum run of Substring : "" + res) "
1999,Write a Python program to Convert List to List of dictionaries,"# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using dictionary comprehension + loop
# initializing lists
test_list = [""Gfg"", 3, ""is"", 8, ""Best"", 10, ""for"", 18, ""Geeks"", 33]
# printing original list
print(""The original list : "" + str(test_list))
# initializing key list
key_list = [""name"", ""number""]
# loop to iterate through elements
# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
# printing result
print(""The constructed dictionary list : "" + str(res))"
2000,Iterate over a set in Python,"# Creating a set using string
test_set = set(""geEks"")
# Iterating using for loop
for val in test_set:
print(val)"
2001,How to read multiple text files from folder in Python,"# Import Module
import os
# Folder Path
path = ""Enter Folder Path""
# Change the directory
os.chdir(path)
# Read text File
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
# iterate through all file
for file in os.listdir():
# Check whether file is in text format or not
if file.endswith("".txt""):
file_path = f""{path}\{file}""
# call read text file function
read_text_file(file_path)"
2002,Write a Python program to Remove items from Set,"# Python program to remove elements from set
# Using the pop() method
def Remove(initial_set):
while initial_set:
initial_set.pop()
print(initial_set)
# Driver Code
initial_set = set([12, 10, 13, 15, 8, 9])
Remove(initial_set)"
2003,Write a Python program to Last business day of every month in year,"# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using loop + max() + calendar.monthcalendar
import calendar
# initializing year
year = 1997
# printing Year
print(""The original year : "" + str(year))
# initializing weekday
weekdy = 5
# iterating for all months
res = []
for month in range(1, 13):
# max gets last friday of each month of 1997
res.append(str(max(week[weekdy]
for week in calendar.monthcalendar(year, month))) +
""/"" + str(month)+ ""/"" + str(year))
# printing
print(""Last weekdays of year : "" + str(res))"
2004,Converting a 10 digit phone number to US format using Regex in Python,"import re
def convert_phone_number(phone):
# actual pattern which only change this line
num = re.sub(r'(?
using namespace std;
// Function to print the
// half diamond star pattern
void halfDiamondStar(int N)
{
int i, j;
// Loop to print the upper half
// diamond pattern
for (i = 0; i < N; i++) {
for (j = 0; j < i + 1; j++)
cout << ""*"";
cout << ""\n"";
}
// Loop to print the lower half
// diamond pattern
for (i = 1; i < N; i++) {
for (j = i; j < N; j++)
cout << ""*"";
cout << ""\n"";
}
}
// Driver Code
int main()
{
int N = 5;
// Function Call
halfDiamondStar(N);
}"
2008,Scrape Table from Website using Write a Python program to Selenium,"
Selenium Table
Name
Class
Vinayak
12
Ishita
10
"
2009,Write a Python program to Cross Pairing in Tuple List,"# Python3 code to demonstrate working of
# Cross Pairing in Tuple List
# Using list comprehension
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
# printing original lists
print(""The original list 1 : "" + str(test_list1))
print(""The original list 2 : "" + str(test_list2))
# corresponding loop in list comprehension
res = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]]
# printing result
print(""The mapped tuples : "" + str(res))"
2010,Write a Python program to Convert dictionary to K sized dictionaries,"# Python3 code to demonstrate working of
# Convert dictionary to K Keys dictionaries
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# initializing K
K = 2
res = []
count = 0
flag = 0
indict = dict()
for key in test_dict:
indict[key] = test_dict[key]
count += 1
# checking for K size and avoiding empty dict using flag
if count % K == 0 and flag:
res.append(indict)
# reinitializing dictionary
indict = dict()
count = 0
flag = 1
# printing result
print(""The converted list : "" + str(res)) "
2011,Write a Python program to Numpy matrix.max(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[64, 1; 12, 3]')
# applying matrix.max() method
geeks = gfg.max()
print(geeks)"
2012,Find words which are greater than given length k in Python,"// C++ program to find all string
// which are greater than given length k
#include
using namespace std;
// function find string greater than
// length k
void string_k(string s, int k)
{
// create the empty string
string w = """";
// iterate the loop till every space
for(int i = 0; i < s.size(); i++)
{
if(s[i] != ' ')
// append this sub string in
// string w
w = w + s[i];
else {
// if length of current sub
// string w is greater than
// k then print
if(w.size() > k)
cout << w << "" "";
w = """";
}
}
}
// Driver code
int main()
{
string s = ""geek for geeks"";
int k = 3;
s = s + "" "";
string_k(s, k);
return 0;
}
// This code is contributed by
// Manish Shaw (manishshaw1)"
2013,Creating Pandas dataframe using list of lists in Python,"# Import pandas library
import pandas as pd
# initialize list of lists
data = [['Geeks', 10], ['for', 15], ['geeks', 20]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
print(df )"
2014,Write a Python program to Convert Tuple Matrix to Tuple List,"# Python3 code to demonstrate working of
# Convert Tuple Matrix to Tuple List
# Using list comprehension + zip()
# initializing list
test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]
# printing original list
print(""The original list is : "" + str(test_list))
# flattening
temp = [ele for sub in test_list for ele in sub]
# joining to form column pairs
res = list(zip(*temp))
# printing result
print(""The converted tuple list : "" + str(res))"
2015,Write a Python Program to Reverse a linked list,"# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next'
#variable is getting created in each loop.
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print ""Given Linked List""
llist.printList()
llist.reverse()
print ""\nReversed Linked List""
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)"
2016,numpy.sqrt() in Python,"# Python program explaining
# numpy.sqrt() method
# importing numpy
import numpy as geek
# applying sqrt() method on integer numbers
arr1 = geek.sqrt([1, 4, 9, 16])
arr2 = geek.sqrt([6, 10, 18])
print(""square-root of an array1 : "", arr1)
print(""square-root of an array2 : "", arr2)"
2017,How to Remove repetitive characters from words of the given Pandas DataFrame using Regex in Python,"# importing required libraries
import pandas as pd
import re
# creating Dataframe with column
# as name and common_comments
df = pd.DataFrame(
{
'name' : ['Akash', 'Ayush', 'Diksha',
'Priyanka', 'Radhika'],
'common_comments' : ['hey buddy meet me today ',
'sorry bro i cant meet',
'hey akash i love geeksforgeeks',
'twiiter is the best way to comment',
'geeksforgeeks is good for learners']
},
columns = ['name', 'common_comments']
)
# printing Dataframe
df"
2018,Convert a column to row name/index in Pandas in Python,"# importing pandas as pd
import pandas as pd
# Creating a dict of lists
data = {'Name':[""Akash"", ""Geeku"", ""Pankaj"", ""Sumitra"",""Ramlal""],
'Branch':[""B.Tech"", ""MBA"", ""BCA"", ""B.Tech"", ""BCA""],
'Score':[""80"",""90"",""60"", ""30"", ""50""],
'Result': [""Pass"",""Pass"",""Pass"",""Fail"",""Fail""]}
# creating a dataframe
df = pd.DataFrame(data)
df"
2019,Write a Python program to count number of vowels using sets in given string,"# Python3 code to count vowel in
# a string using set
# Function to count vowel
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set(""aeiouAEIOU"")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print(""No. of vowels :"", count)
# Driver code
str = ""GeeksforGeeks""
# Function Call
vowel_count(str)"
2020,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"
2021,Write a Python program to AND operation between Tuples,"# Python3 code to demonstrate working of
# Cross Tuple AND operation
# using map() + lambda
# initialize tuples
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
# printing original tuples
print(""The original tuple 1 : "" + str(test_tup1))
print(""The original tuple 2 : "" + str(test_tup2))
# Cross Tuple AND operation
# using map() + lambda
res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2))
# printing result
print(""Resultant tuple after AND operation : "" + str(res))"
2022,Write a Python program to Search an Element in a Circular Linked List,"# Python program to Search an Element
# in a Circular Linked List
# Class to define node of the linked list
class Node:
def __init__(self,data):
self.data = data;
self.next = None;
class CircularLinkedList:
# Declaring Circular Linked List
def __init__(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
# Adds new nodes to the Circular Linked List
def add(self,data):
# Declares a new node to be added
newNode = Node(data);
# Checks if the Circular
# Linked List is empty
if self.head.data is None:
# If list is empty then new node
# will be the first node
# to be added in the Circular Linked List
self.head = newNode;
self.tail = newNode;
newNode.next = self.head;
else:
# If a node is already present then
# tail of the last node will point to
# new node
self.tail.next = newNode;
# New node will become new tail
self.tail = newNode;
# New Tail will point to the head
self.tail.next = self.head;
# Function to search the element in the
# Circular Linked List
def findNode(self,element):
# Pointing the head to start the search
current = self.head;
i = 1;
# Declaring f = 0
f = 0;
# Check if the list is empty or not
if(self.head == None):
print(""Empty list"");
else:
while(True):
# Comparing the elements
# of each node to the
# element to be searched
if(current.data == element):
# If the element is present
# then incrementing f
f += 1;
break;
# Jumping to next node
current = current.next;
i = i + 1;
# If we reach the head
# again then element is not
# present in the list so
# we will break the loop
if(current == self.head):
break;
# Checking the value of f
if(f > 0):
print(""element is present"");
else:
print(""element is not present"");
# Driver Code
if __name__ == '__main__':
# Creating a Circular Linked List
'''
Circular Linked List we will be working on:
1 -> 2 -> 3 -> 4 -> 5 -> 6
'''
circularLinkedList = CircularLinkedList();
#Adding nodes to the list
circularLinkedList.add(1);
circularLinkedList.add(2);
circularLinkedList.add(3);
circularLinkedList.add(4);
circularLinkedList.add(5);
circularLinkedList.add(6);
# Searching for node 2 in the list
circularLinkedList.findNode(2);
#Searching for node in the list
circularLinkedList.findNode(7);"
2023,Write a Python program to Odd Frequency Characters,"# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + defaultdict()
from collections import defaultdict
# helper_function
def hlper_fnc(test_str):
cntr = defaultdict(int)
for ele in test_str:
cntr[ele] += 1
return [val for val, chr in cntr.items() if chr % 2 != 0]
# initializing string
test_str = 'geekforgeeks is best for geeks'
# printing original string
print(""The original string is : "" + str(test_str))
# Odd Frequency Characters
# Using list comprehension + defaultdict()
res = hlper_fnc(test_str)
# printing result
print(""The Odd Frequency Characters are : "" + str(res))"
2024,Write a Python program to Program to print duplicates from a list of integers,"# Python program to print
# duplicates from a list
# of integers
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
50, -20, 60, 60, -20, -20]
print (Repeat(list1))
# This code is contributed
# by Sandeep_anand"
2025,Write a Python set to check if string is panagram,"# import from string all ascii_lowercase and asc_lower
from string import ascii_lowercase as asc_lower
# function to check if all elements are present or not
def check(s):
return set(asc_lower) - set(s.lower()) == set([])
# driver code
string =""The quick brown fox jumps over the lazy dog""
if(check(string)== True):
print(""The string is a pangram"")
else:
print(""The string isn't a pangram"")"
2026,Write a Python program to Split String of list on K character,"# Python3 code to demonstrate
# Split String of list on K character
# using loop + split()
# Initializing list
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
# printing original list
print(""The original list is : "" + str(test_list))
K = ' '
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
sub = ele.split(K)
res.extend(sub)
# printing result
print (""The extended list after split strings : "" + str(res))"
2027,Write a Python program to Test if string is subset of another,"# Python3 code to demonstrate working of
# Test if string is subset of another
# Using all()
# initializing strings
test_str1 = ""geeksforgeeks""
test_str2 = ""gfks""
# printing original string
print(""The original string is : "" + test_str1)
# Test if string is subset of another
# Using all()
res = all(ele in test_str1 for ele in test_str2)
# printing result
print(""Does string contains all the characters of other list? : "" + str(res)) "
2028,Write a Python program to Remove Reduntant Substrings from Strings List,"# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using enumerate() + join() + sort()
# initializing list
test_list = [""Gfg"", ""Gfg is best"", ""Geeks"", ""Gfg is for Geeks""]
# printing original list
print(""The original list : "" + str(test_list))
# using loop to iterate for each string
test_list.sort(key = len)
res = []
for idx, val in enumerate(test_list):
# concatenating all next values and checking for existence
if val not in ', '.join(test_list[idx + 1:]):
res.append(val)
# printing result
print(""The filtered list : "" + str(res))"
2029,Extract time from datetime in Python,"# import important module
import datetime
from datetime import datetime
# Create datetime string
datetime_str = ""24AUG2001101010""
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str,
""%d%b%Y%H%M%S"")
# It will print the datetime object
print(datetime_obj)
# extract the time from datetime_obj
time = datetime_obj.time()
# it will print time that
# we have extracted from datetime obj
print(time) "
2030,How to lowercase column names in Pandas dataframe in Python,"# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'bODAY', 'MinA', 'Peter', 'nicky'],
'B': ['masters', 'graduate', 'graduate',
'Masters', 'Graduate'],
'C': [27, 23, 21, 23, 24]})
df"
2031,Convert the column type from string to datetime format in Pandas dataframe in Python,"# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({'Date':['11/8/2011', '04/23/2008', '10/2/2019'],
'Event':['Music', 'Poetry', 'Theatre'],
'Cost':[10000, 5000, 15000]})
# Print the dataframe
print(df)
# Now we will check the data type
# of the 'Date' column
df.info()"
2032,Write a Python program to find the character position of Kth word from a list of strings,"# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = [""geekforgeeks"", ""is"", ""best"", ""for"", ""geeks""]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print(""Index of character at Kth position word : "" + str(res))"
2033,How to access different rows of a multidimensional NumPy array in Python,"# Importing Numpy module
import numpy as np
# Creating a 3X3 2-D Numpy array
arr = np.array([[10, 20, 30],
[40, 5, 66],
[70, 88, 94]])
print(""Given Array :"")
print(arr)
# Access the First and Last rows of array
res_arr = arr[[0,2]]
print(""\nAccessed Rows :"")
print(res_arr)"
2034,Scientific GUI Calculator using Tkinter in Python,"from tkinter import *
import math
import tkinter.messagebox"
2035,Matrix Multiplication in NumPy in Python,"# importing the module
import numpy as np
# creating two matrices
p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]]
print(""Matrix p :"")
print(p)
print(""Matrix q :"")
print(q)
# computing product
result = np.dot(p, q)
# printing the result
print(""The matrix multiplication is :"")
print(result)"
2036,Scraping And Finding Ordered Words In A Dictionary using Python,"# Python program to find ordered words
import requests
# Scrapes the words from the URL below and stores
# them in a list
def getWords():
# contains about 2500 words
url = ""http://www.puzzlers.org/pub/wordlists/unixdict.txt""
fetchData = requests.get(url)
# extracts the content of the webpage
wordList = fetchData.content
# decodes the UTF-8 encoded text and splits the
# string to turn it into a list of words
wordList = wordList.decode(""utf-8"").split()
return wordList
# function to determine whether a word is ordered or not
def isOrdered():
# fetching the wordList
collection = getWords()
# since the first few of the elements of the
# dictionary are numbers, getting rid of those
# numbers by slicing off the first 17 elements
collection = collection[16:]
word = ''
for word in collection:
result = 'Word is ordered'
i = 0
l = len(word) - 1
if (len(word) < 3): # skips the 1 and 2 lettered strings
continue
# traverses through all characters of the word in pairs
while i < l:
if (ord(word[i]) > ord(word[i+1])):
result = 'Word is not ordered'
break
else:
i += 1
# only printing the ordered words
if (result == 'Word is ordered'):
print(word,': ',result)
# execute isOrdered() function
if __name__ == '__main__':
isOrdered()"
2037,Write a Python program to Reverse All Strings in String List,"# Python3 code to demonstrate
# Reverse All Strings in String List
# using list comprehension
# initializing list
test_list = [""geeks"", ""for"", ""geeks"", ""is"", ""best""]
# printing original list
print (""The original list is : "" + str(test_list))
# using list comprehension
# Reverse All Strings in String List
res = [i[::-1] for i in test_list]
# printing result
print (""The reversed string list is : "" + str(res))"
2038,Write a Python program to Count Strings with substring String List,"# Python code to demonstrate
# Count Strings with substring String List
# using list comprehension + len()
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
# printing original list
print (""The original list is : "" + str(test_list))
# initializing substring
subs = 'Geek'
# using list comprehension + len()
# Count Strings with substring String List
res = len([i for i in test_list if subs in i])
# printing result
print (""All strings count with given substring are : "" + str(res))"
2039,Write a Python program to Remove words containing list characters,"# Python3 code to demonstrate
# Remove words containing list characters
# using list comprehension + all()
from itertools import groupby
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# initializing char list
char_list = ['g', 'o']
# printing original list
print (""The original list is : "" + str(test_list))
# printing character list
print (""The character list is : "" + str(char_list))
# Remove words containing list characters
# using list comprehension + all()
res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]
# printing result
print (""The filtered strings are : "" + str(res))"
2040,Write a Python program to Convert JSON to string,"import json
# create a sample json
a = {""name"" : ""GeeksforGeeks"", ""Topic"" : ""Json to String"", ""Method"": 1}
# Convert JSON to String
y = json.dumps(a)
print(y)
print(type(y))"
2041,Write a Python Program for Rabin-Karp Algorithm for Pattern Searching,"# Following program is the python implementation of
# Rabin Karp Algorithm given in CLRS book
# d is the number of characters in the input alphabet
d = 256
# pat -> pattern
# txt -> text
# q -> A prime number
def search(pat, txt, q):
M = len(pat)
N = len(txt)
i = 0
j = 0
p = 0 # hash value for pattern
t = 0 # hash value for txt
h = 1
# The value of h would be ""pow(d, M-1)% q""
for i in xrange(M-1):
h = (h * d)% q
# Calculate the hash value of pattern and first window
# of text
for i in xrange(M):
p = (d * p + ord(pat[i]))% q
t = (d * t + ord(txt[i]))% q
# Slide the pattern over text one by one
for i in xrange(N-M + 1):
# Check the hash values of current window of text and
# pattern if the hash values match then only check
# for characters on by one
if p == t:
# Check for characters one by one
for j in xrange(M):
if txt[i + j] != pat[j]:
break
j+= 1
# if p == t and pat[0...M-1] = txt[i, i + 1, ...i + M-1]
if j == M:
print ""Pattern found at index "" + str(i)
# Calculate hash value for next window of text: Remove
# leading digit, add trailing digit
if i < N-M:
t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q
# We might get negative values of t, converting it to
# positive
if t < 0:
t = t + q
# Driver program to test the above function
txt = ""GEEKS FOR GEEKS""
pat = ""GEEK""
q = 101 # A prime number
search(pat, txt, q)
# This code is contributed by Bhavya Jain"
2042,Write a Python program to Uncommon elements in Lists of List,"# Python 3 code to demonstrate
# Uncommon elements in List
# using naive method
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
# printing both lists
print (""The original list 1 : "" + str(test_list1))
print (""The original list 2 : "" + str(test_list2))
# using naive method
# Uncommon elements in List
res_list = []
for i in test_list1:
if i not in test_list2:
res_list.append(i)
for i in test_list2:
if i not in test_list1:
res_list.append(i)
# printing the uncommon
print (""The uncommon of two lists is : "" + str(res_list))"
2043,Write a Python program to split and join a string,"# Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(' ')
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-'.join(list_string)
return string
# Driver Function
if __name__ == '__main__':
string = 'Geeks for Geeks'
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)"
2044,Create a Numpy array with random values | Python,"# Python Program to create numpy array
# filled with random values
import numpy as geek
b = geek.empty(2, dtype = int)
print(""Matrix b : \n"", b)
a = geek.empty([2, 2], dtype = int)
print(""\nMatrix a : \n"", a) "
2045,Write a Python program to Numpy np.polygrid3d() method,"# Python program explaining
# numpy.polygrid3d() method
# importing numpy as np
import numpy as np
from numpy.polynomial.polynomial import polygrid3d
# Input polynomial series coefficients
c = np.array([[1, 3, 5], [2, 4, 6], [10, 11, 12]])
# using np.polygrid3d() method
ans = polygrid3d([7, 9], [8, 10], [5, 6], c)
print(ans)"
2046,Write a Python program to Replace multiple words with K,"# Python3 code to demonstrate working of
# Replace multiple words with K
# Using join() + split() + list comprehension
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing word list
word_list = [""best"", 'CS', 'for']
# initializing replace word
repl_wrd = 'gfg'
# Replace multiple words with K
# Using join() + split() + list comprehension
res = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])
# printing result
print(""String after multiple replace : "" + str(res)) "
2047,Reindexing in Pandas DataFrame in Python,"# import numpy and pandas module
import pandas as pd
import numpy as np
column=['a','b','c','d','e']
index=['A','B','C','D','E']
# create a dataframe of random values of array
df1 = pd.DataFrame(np.random.rand(5,5),
columns=column, index=index)
print(df1)
print('\n\nDataframe after reindexing rows: \n',
df1.reindex(['B', 'D', 'A', 'C', 'E']))"
2048,Quote Guessing Game using Web Scraping in Python,"import requests
from bs4 import BeautifulSoup
from csv import writer
from time import sleep
from random import choice
# list to store scraped data
all_quotes = []
# this part of the url is constant
base_url = ""http://quotes.toscrape.com/""
# this part of the url will keep changing
url = ""/page/1""
while url:
# concatenating both urls
# making request
res = requests.get(f""{base_url}{url}"")
print(f""Now Scraping{base_url}{url}"")
soup = BeautifulSoup(res.text, ""html.parser"")
# extracting all elements
quotes = soup.find_all(class_=""quote"")
for quote in quotes:
all_quotes.append({
""text"": quote.find(class_=""text"").get_text(),
""author"": quote.find(class_=""author"").get_text(),
""bio-link"": quote.find(""a"")[""href""]
})
next_btn = soup.find(_class=""next"")
url = next_btn.find(""a"")[""href""] if next_btn else None
sleep(2)
quote = choice(all_quotes)
remaining_guesses = 4
print(""Here's a quote: "")
print(quote[""text""])
guess = ''
while guess.lower() != quote[""author""].lower() and remaining_guesses > 0:
guess = input(
f""Who said this quote? Guesses remaining {remaining_guesses}"")
if guess == quote[""author""]:
print(""CONGRATULATIONS!!! YOU GOT IT RIGHT"")
break
remaining_guesses -= 1
if remaining_guesses == 3:
res = requests.get(f""{base_url}{quote['bio-link']}"")
soup = BeautifulSoup(res.text, ""html.parser"")
birth_date = soup.find(class_=""author-born-date"").get_text()
birth_place = soup.find(class_=""author-born-location"").get_text()
print(
f""Here's a hint: The author was born on {birth_date}{birth_place}"")
elif remaining_guesses == 2:
print(
f""Here's a hint: The author's first name starts with: {quote['author'][0]}"")
elif remaining_guesses == 1:
last_initial = quote[""author""].split("" "")[1][0]
print(
f""Here's a hint: The author's last name starts with: {last_initial}"")
else:
print(
f""Sorry, you ran out of guesses. The answer was {quote['author']}"")"
2049,Scraping Indeed Job Data Using Python,"# import module
import requests
from bs4 import BeautifulSoup
# user define function
# Scrape the data
# and get in string
def getdata(url):
r = requests.get(url)
return r.text
# Get Html code using parse
def html_code(url):
# pass the url
# into getdata function
htmldata = getdata(url)
soup = BeautifulSoup(htmldata, 'html.parser')
# return html code
return(soup)
# filter job data using
# find_all function
def job_data(soup):
# find the Html tag
# with find()
# and convert into string
data_str = """"
for item in soup.find_all(""a"", class_=""jobtitle turnstileLink""):
data_str = data_str + item.get_text()
result_1 = data_str.split(""\n"")
return(result_1)
# filter company_data using
# find_all function
def company_data(soup):
# find the Html tag
# with find()
# and convert into string
data_str = """"
result = """"
for item in soup.find_all(""div"", class_=""sjcl""):
data_str = data_str + item.get_text()
result_1 = data_str.split(""\n"")
res = []
for i in range(1, len(result_1)):
if len(result_1[i]) > 1:
res.append(result_1[i])
return(res)
# driver nodes/main function
if __name__ == ""__main__"":
# Data for URL
job = ""data+science+internship""
Location = ""Noida%2C+Uttar+Pradesh""
url = ""https://in.indeed.com/jobs?q=""+job+""&l=""+Location
# Pass this URL into the soup
# which will return
# html string
soup = html_code(url)
# call job and company data
# and store into it var
job_res = job_data(soup)
com_res = company_data(soup)
# Traverse the both data
temp = 0
for i in range(1, len(job_res)):
j = temp
for j in range(temp, 2+temp):
print(""Company Name and Address : "" + com_res[j])
temp = j
print(""Job : "" + job_res[i])
print(""-----------------------------"")"
2050,Adding and Subtracting Matrices in Python,"# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print(""Printing elements of first matrix"")
print(A)
print(""Printing elements of second matrix"")
print(B)
# adding two matrix
print(""Addition of two matrix"")
print(np.add(A, B))"
2051,How to read all CSV files in a folder in Pandas in Python,"# import necessary libraries
import pandas as pd
import os
import glob
# use glob to get all the csv files
# in the folder
path = os.getcwd()
csv_files = glob.glob(os.path.join(path, ""*.csv""))
# loop over the list of csv files
for f in csv_files:
# read the csv file
df = pd.read_csv(f)
# print the location and filename
print('Location:', f)
print('File Name:', f.split(""\\"")[-1])
# print the content
print('Content:')
display(df)
print()"
2052,Minimum of two numbers in Python,"# Python program to find the
# minimum of two numbers
def minimum(a, b):
if a <= b:
return a
else:
return b
# Driver code
a = 2
b = 4
print(minimum(a, b))"
2053,String slicing in Python to rotate a string,"# Function to rotate string left and right by d length
def rotate(input,d):
# slice string in two parts for left and right
Lfirst = input[0 : d]
Lsecond = input[d :]
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
# now concatenate two parts together
print (""Left Rotation : "", (Lsecond + Lfirst) )
print (""Right Rotation : "", (Rsecond + Rfirst))
# Driver program
if __name__ == ""__main__"":
input = 'GeeksforGeeks'
d=2
rotate(input,d) "
2054,Find sum and average of List in Python,"# Python program to find the sum
# and average of the list
L = [4, 5, 1, 2, 9, 7, 10, 8]
# variable to store the sum of
# the list
count = 0
# Finding the sum
for i in L:
count += i
# divide the total elements by
# number of elements
avg = count/len(L)
print(""sum = "", count)
print(""average = "", avg)"
2055,Write a Python program to find second largest number in a list,"# Python program to find second largest
# number in a list
# list of numbers - length of
# list should be at least 2
list1 = [10, 20, 4, 45, 99]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)
for i in range(2,n):
if list1[i]>mx:
secondmax=mx
mx=list1[i]
elif list1[i]>secondmax and \
mx != list1[i]:
secondmax=list1[i]
print(""Second highest number is : "",\
str(secondmax))"
2056,Write a Python program to Loop through files of certain extensions,"# importing the library
import os
# giving directory name
dirname = 'D:\\AllData'
# giving file extension
ext = ('.exe', 'jpg')
# iterating over all files
for files in os.listdir(dirname):
if files.endswith(ext):
print(files) # printing file name of desired extension
else:
continue"
2057,Write a Python program to print all odd numbers in a range,"# Python program to print odd Numbers in given range
start, end = 4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 != 0:
print(num, end = "" "")"
2058,Write a Python program to Multiply 2d numpy array corresponding to 1d array,"# Python code to demonstrate
# multiplication of 2d array
# with 1d array
import numpy as np
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
ini_array2 = np.array([0, 2, 3])
# printing initial arrays
print(""initial array"", str(ini_array1))
# Multiplying arrays
result = ini_array1 * ini_array2[:, np.newaxis]
# printing result
print(""New resulting array: "", result)"
2059,Write a Python program to Replace all occurrences of a substring in a string,"# Python3 code to demonstrate working of
# Swap Binary substring
# Using translate()
# initializing string
test_str = ""geeksforgeeks""
# printing original string
print(""The original string is : "" + test_str)
# Swap Binary substring
# Using translate()
temp = str.maketrans(""geek"", ""abcd"")
test_str = test_str.translate(temp)
# printing result
print(""The string after swap : "" + str(test_str)) "
2060,Convert multiple JSON files to CSV Python,"# importing packages
import pandas as pd
# load json file using pandas
df1 = pd.read_json('file1.json')
# view data
print(df1)
# load json file using pandas
df2 = pd.read_json('file2.json')
# view data
print(df2)
# use pandas.concat method
df = pd.concat([df1,df2])
# view the concatenated dataframe
print(df)
# convert dataframe to csv file
df.to_csv(""CSV.csv"",index=False)
# load the resultant csv file
result = pd.read_csv(""CSV.csv"")
# and view the data
print(result)"
2061,Create Pandas Series using NumPy functions in Python,"# import pandas and numpy
import pandas as pd
import numpy as np
# series with numpy linspace()
ser1 = pd.Series(np.linspace(3, 33, 3))
print(ser1)
# series with numpy linspace()
ser2 = pd.Series(np.linspace(1, 100, 10))
print(""\n"", ser2)
"
2062,Write a Python program to capitalize the first and last character of each word in a string,"# Python program to capitalize
# first and last character of
# each word of a String
# Function to do the same
def word_both_cap(str):
#lamda function for capitalizing the
# first and last letter of words in
# the string
return ' '.join(map(lambda s: s[:-1]+s[-1].upper(),
s.title().split()))
# Driver's code
s = ""welcome to geeksforgeeks""
print(""String before:"", s)
print(""String after:"", word_both_cap(str))"
2063,Write a Python program to Queue using Doubly Linked List,"# A complete working Python program to demonstrate all
# Queue operations using doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.prev = None # Initialize prev as null
# Queue class contains a Node object
class Queue:
# Function to initialize head
def __init__(self):
self.head = None
self.last=None
# Function to add an element data in the Queue
def enqueue(self, data):
if self.last is None:
self.head =Node(data)
self.last =self.head
else:
self.last.next = Node(data)
self.last.next.prev=self.last
self.last = self.last.next
# Function to remove first element and return the element from the queue
def dequeue(self):
if self.head is None:
return None
else:
temp= self.head.data
self.head = self.head.next
self.head.prev=None
return temp
# Function to return top element in the queue
def first(self):
return self.head.data
# Function to return the size of the queue
def size(self):
temp=self.head
count=0
while temp is not None:
count=count+1
temp=temp.next
return count
# Function to check if the queue is empty or not
def isEmpty(self):
if self.head is None:
return True
else:
return False
# Function to print the stack
def printqueue(self):
print(""queue elements are:"")
temp=self.head
while temp is not None:
print(temp.data,end=""->"")
temp=temp.next
# Code execution starts here
if __name__=='__main__':
# Start with the empty queue
queue = Queue()
print(""Queue operations using doubly linked list"")
# Insert 4 at the end. So queue becomes 4->None
queue.enqueue(4)
# Insert 5 at the end. So queue becomes 4->5None
queue.enqueue(5)
# Insert 6 at the end. So queue becomes 4->5->6->None
queue.enqueue(6)
# Insert 7 at the end. So queue becomes 4->5->6->7->None
queue.enqueue(7)
# Print the queue
queue.printqueue()
# Print the first element
print(""\nfirst element is "",queue.first())
# Print the queue size
print(""Size of the queue is "",queue.size())
# remove the first element
queue.dequeue()
# remove the first element
queue.dequeue()
# first two elements are removed
# Print the queue
print(""After applying dequeue() two times"")
queue.printqueue()
# Print True if queue is empty else False
print(""\nqueue is empty:"",queue.isEmpty())"
2064,Create a new column in Pandas DataFrame based on the existing columns in Python,"# importing pandas as pd
import pandas as pd
# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)"
2065,Write a Python Code for time Complexity plot of Heap Sort,"# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
# find left child of node i
def left(i):
return 2 * i + 1
# find right child of node i
def right(i):
return 2 * i + 2
# calculate and return array size
def heapSize(A):
return len(A)-1
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
# print(""in heapy"", i)
l = left(i)
r = right(i)
# heapSize = len(A)
# print(""left"", l, ""Rightt"", r, ""Size"", heapSize)
if l<= heapSize(A) and A[l] > A[i] :
largest = l
else:
largest = i
if r<= heapSize(A) and A[r] > A[largest]:
largest = r
if largest != i:
# print(""Largest"", largest)
A[i], A[largest]= A[largest], A[i]
# print(""List"", A)
MaxHeapify(A, largest)
# this function makes a heapified array
def BuildMaxHeap(A):
for i in range(int(heapSize(A)/2)-1, -1, -1):
MaxHeapify(A, i)
# Sorting is done using heap of array
def HeapSort(A):
BuildMaxHeap(A)
B = list()
heapSize1 = heapSize(A)
for i in range(heapSize(A), 0, -1):
A[0], A[i]= A[i], A[0]
B.append(A[heapSize1])
A = A[:-1]
heapSize1 = heapSize1-1
MaxHeapify(A, 0)
# randomly generates list of different
# sizes and call HeapSort function
elements = list()
times = list()
for i in range(1, 10):
# generate some integers
a = randint(0, 1000 * i, 1000 * i)
# print(i)
start = time.clock()
HeapSort(a)
end = time.clock()
# print(""Sorted list is "", a)
print(len(a), ""Elements Sorted by HeapSort in "", end-start)
elements.append(len(a))
times.append(end-start)
plt.xlabel('List Length')
plt.ylabel('Time Complexity')
plt.plot(elements, times, label ='Heap Sort')
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal"
2066,Calculate the sum of the diagonal elements of a NumPy array in Python,"# importing Numpy package
import numpy as np
# creating a 3X3 Numpy matrix
n_array = np.array([[55, 25, 15],
[30, 44, 2],
[11, 45, 77]])
# Displaying the Matrix
print(""Numpy Matrix is:"")
print(n_array)
# calculating the Trace of a matrix
trace = np.trace(n_array)
print(""\nTrace of given 3X3 matrix:"")
print(trace)"
2067,Menu Driven Python program for opening the required software Application,"# import os library
import os
# infinite while loop
while True:
print(""Hello! user choose your tool"")
print(""Choose your tool :-\n"")
print(""-> mousepad"")
print(""-> chrome"")
print(""-> vlc"")
print(""-> virtualbox"")
print(""-> camera"")
print(""-> telegram"")
print(""-> firefox"")
print(""-> codeblocks"")
print(""-> screenshot"")
print(""-> task-manager"")
print(""-> libreoffice impress / presentation"")
print(""-> libreoffice writer / text editor / notepad"")
print(""-> libreoffice clac / spreadsheets"")
print(""-> libreoffice"")
print(""-> jupyter notebook\n"")
print(""chat with system:-"",end=' ')
# take input from user
p = input()
# check conditions
if ((""do not"" in p) or (""dont"" in p) or (""don't"" in p)):
print(""OK user\n"")
elif ((""open"" in p) or (""start"" in p) or (""run"" in p) or (""execute"" in p) or (""launch"" in p) or (""activate"" in p)):
if ((""mousepad"" in p) or (""editor"" in p)):
# run mention application
os.system(""mousepad"")
elif ((""vlc"" in p) or (""media player"" in p)):
os.system(""vlc"")
elif ((""virtualbox"" in p) or (""virtual machine"" in p) or (""virtual tool"" in p)):
os.system(""virtualbox"")
elif ((""camera"" in p) or (""cheese"" in p)):
os.system(""cheese"")
elif (""telegram"" in p):
os.system(""telegram-desktop"")
elif (""codeblocks"" in p):
os.system(""codeblocks"")
elif (""taskmanager"" in p):
os.system(""xfce4-taskmanager"")
elif (""screenshot"" in p):
os.system(""xfce4-screenshooter"")
elif ((""jupyter"" in p) or (""notebook"" in p)):
os.system(""jupyter notebook"")
elif ((""libreoffice impress"" in p) or (""presentation tool"" in p)):
os.system(""libreoffice --impress"")
elif ((""libreoffice writer"" in p) or (""text editor"" in p)):
os.system(""libreoffice --writer"")
elif (""notepad"" in p):
os.system(""notepad"")
elif ((""libreoffice calc"" in p) or (""spreadsheet"" in p)):
os.system(""libreoffice --calc"")
elif (""libreoffice"" in p):
os.system(""libreoffice"")
elif (""chrome"" in p):
os.system(""google-chrome-stable"")
elif ((""firefox"" in p) or (""mozilla"" in p)):
os.system(""firefox"")
else :
print(""don't support"")
# terminating infinite while loop
elif ((""quit"" in p) or (""exit"" in p) or (""stop"" in p) or (""close"" in p) or (""deactivate"" in p) or (""terminate"" in p)):
print(""Thnank You!"")
break
else :
print(""don't support"")"
2068,How to create an empty and a full NumPy array in Python,"# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty((3, 4), dtype=int)
print(""Empty Array"")
print(empa)
# Create a full array
flla = np.full([3, 3], 55, dtype=int)
print(""\n Full Array"")
print(flla)"
2069,Write a Python program to Mirror Image of String,"# Python3 code to demonstrate working of
# Mirror Image of String
# Using Mirror Image of String
# initializing strings
test_str = 'void'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing mirror dictionary
mir_dict = {'b':'d', 'd':'b', 'i':'i', 'o':'o', 'v':'v', 'w':'w', 'x':'x'}
res = ''
# accessing letters from dictionary
for ele in test_str:
if ele in mir_dict:
res += mir_dict[ele]
# if any character not present, flagging to be invalid
else:
res = ""Not Possible""
break
# printing result
print(""The mirror string : "" + str(res)) "
2070,Write a Python program to Substituting patterns in text using regex,"# Python implementation of substituting a
# specific text pattern in a string using regex
# importing regex module
import re
# Function to perform
# operations on the strings
def substitutor():
# a string variable
sentence1 = ""It is raining outside.""
# replacing text 'raining' in the string
# variable sentence1 with 'sunny' thus
# passing first parameter as raining
# second as sunny, third as the
# variable name in which string is stored
# and printing the modified string
print(re.sub(r""raining"", ""sunny"", sentence1))
# a string variable
sentence2 = ""Thank you very very much.""
# replacing text 'very' in the string
# variable sentence2 with 'so' thus
# passing parameters at their
# appropriate positions and printing
# the modified string
print(re.sub(r""very"", ""so"", sentence2))
# Driver Code:
substitutor()"
2071,Write a Python Program for Odd-Even Sort / Brick Sort,"# Python Program to implement
# Odd-Even / Brick Sort
def oddEvenSort(arr, n):
# Initially array is unsorted
isSorted = 0
while isSorted == 0:
isSorted = 1
temp = 0
for i in range(1, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSorted = 0
for i in range(0, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSorted = 0
return
arr = [34, 2, 10, -9]
n = len(arr)
oddEvenSort(arr, n);
for i in range(0, n):
print(arr[i], end ="" "")
# Code Contribute by Mohit Gupta_OMG <(0_o)>"
2072,Find the size of a Tuple in Python,"import sys
# sample Tuples
Tuple1 = (""A"", 1, ""B"", 2, ""C"", 3)
Tuple2 = (""Geek1"", ""Raju"", ""Geek2"", ""Nikhil"", ""Geek3"", ""Deepanshu"")
Tuple3 = ((1, ""Lion""), ( 2, ""Tiger""), (3, ""Fox""), (4, ""Wolf""))
# print the sizes of sample Tuples
print(""Size of Tuple1: "" + str(sys.getsizeof(Tuple1)) + ""bytes"")
print(""Size of Tuple2: "" + str(sys.getsizeof(Tuple2)) + ""bytes"")
print(""Size of Tuple3: "" + str(sys.getsizeof(Tuple3)) + ""bytes"")"
2073,Ways to sort list of dictionaries by values in Write a Python program to Using itemgetter,"# Python code demonstrate the working of sorted()
# and itemgetter
# importing ""operator"" for implementing itemgetter
from operator import itemgetter
# Initializing list of dictionaries
lis = [{ ""name"" : ""Nandini"", ""age"" : 20},
{ ""name"" : ""Manjeet"", ""age"" : 20 },
{ ""name"" : ""Nikhil"" , ""age"" : 19 }]
# using sorted and itemgetter to print list sorted by age
print ""The list printed sorting by age: ""
print sorted(lis, key=itemgetter('age'))
print (""\r"")
# using sorted and itemgetter to print list sorted by both age and name
# notice that ""Manjeet"" now comes before ""Nandini""
print ""The list printed sorting by age and name: ""
print sorted(lis, key=itemgetter('age', 'name'))
print (""\r"")
# using sorted and itemgetter to print list sorted by age in descending order
print ""The list printed sorting by age in descending order: ""
print sorted(lis, key=itemgetter('age'),reverse = True)"
2074,"Saving Text, JSON, and CSV to a File in Python","# Python program to demonstrate
# opening a file
# Open function to open the file ""myfile.txt""
# (same directory) in read mode and store
# it's reference in the variable file1
file1 = open(""myfile.txt"")
# Reading from file
print(file1.read())
file1.close() "
2075,Write a Python program to Sort lists in tuple,"# Python3 code to demonstrate working of
# Sort lists in tuple
# Using tuple() + sorted() + generator expression
# Initializing tuple
test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5])
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# Sort lists in tuple
# Using tuple() + sorted() + generator expression
res = tuple((sorted(sub) for sub in test_tup))
# printing result
print(""The tuple after sorting lists : "" + str(res))"
2076,Write a Python Program to Reverse the Content of a File using Stack,"# Python3 code to reverse the lines
# of a file using Stack.
# Creating Stack class (LIFO rule)
class Stack:
def __init__(self):
# Creating an empty stack
self._arr = []
# Creating push() method.
def push(self, val):
self._arr.append(val)
def is_empty(self):
# Returns True if empty
return len(self._arr) == 0
# Creating Pop method.
def pop(self):
if self.is_empty():
print(""Stack is empty"")
return
return self._arr.pop()
# Creating a function which will reverse
# the lines of a file and Overwrites the
# given file with its contents line-by-line
# reversed
def reverse_file(filename):
S = Stack()
original = open(filename)
for line in original:
S.push(line.rstrip(""\n""))
original.close()
output = open(filename, 'w')
while not S.is_empty():
output.write(S.pop()+""\n"")
output.close()
# Driver Code
filename = ""GFG.txt""
# Calling the reverse_file function
reverse_file(filename)
# Now reading the content of the file
with open(filename) as file:
for f in file.readlines():
print(f, end ="""")"
2077,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)"
2078,Multithreaded Priority Queue in Python,"import queue
import threading
import time
thread_exit_Flag = 0
class sample_Thread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print (""initializing "" + self.name)
process_data(self.name, self.q)
print (""Exiting "" + self.name)
# helper function to process data
def process_data(threadName, q):
while not thread_exit_Flag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print (""% s processing % s"" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
thread_list = [""Thread-1"", ""Thread-2"", ""Thread-3""]
name_list = [""A"", ""B"", ""C"", ""D"", ""E""]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for thread_name in thread_list:
thread = sample_Thread(threadID, thread_name, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for items in name_list:
workQueue.put(items)
queueLock.release()
# Wait for the queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
thread_exit_Flag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print (""Exit Main Thread"")"
2079,How to Add padding to a tkinter widget only on one side in Python,"# Python program to add padding
# to a widget only on left-side
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title(""Vinayak App"")
# Maximize the window screen
width = app.winfo_screenwidth()
height = app.winfo_screenheight()
app.geometry(""%dx%d"" % (width, height))
# Construct the label in your app
l1 = Label(app, text='Geeks For Geeks')
# Give the leftmost padding
l1.grid(padx=(200, 0), pady=(0, 0))
# Make the loop for displaying app
app.mainloop()"
2080,How to switch to new window in Selenium for Python,"# import modules
from selenium import webdriver
import time
# provide the path for chromedriver
PATH = ""C:/chromedriver.exe""
# pass on the path to driver for working
driver = webdriver.Chrome(PATH) "
2081,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)) "
2082,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))"
2083,How to search and replace text in a file in Python ,"# creating a variable and storing the text
# that we want to search
search_text = ""dummy""
# creating a variable and storing the text
# that we want to add
replace_text = ""replaced""
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt', 'r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = file.read()
# Searching and replacing the text
# using the replace() function
data = data.replace(search_text, replace_text)
# Opening our text file in write only
# mode to write the replaced content
with open(r'SampleFile.txt', 'w') as file:
# Writing the replaced data in our
# text file
file.write(data)
# Printing Text replaced
print(""Text replaced"")"
2084,Convert CSV to JSON using Python,"import csv
import json
# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):
# create a dictionary
data = {}
# Open a csv reader called DictReader
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
# Convert each row into a dictionary
# and add it to data
for rows in csvReader:
# Assuming a column named 'No' to
# be the primary key
key = rows['No']
data[key] = rows
# Open a json writer, and use the json.dumps()
# function to dump data
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))
# Driver Code
# Decide the two file paths according to your
# computer system
csvFilePath = r'Names.csv'
jsonFilePath = r'Names.json'
# Call the make_json function
make_json(csvFilePath, jsonFilePath)"
2085,How to Print Multiple Arguments in Python,"def GFG(name, num):
print(""Hello from "", name + ', ' + num)
GFG(""geeks for geeks"", ""25"")"
2086,Write a Python program to Remove duplicate values across Dictionary Values,"# Python3 code to demonstrate working of
# Remove duplicate values across Dictionary Values
# Using Counter() + list comprehension
from collections import Counter
# initializing dictionary
test_dict = {'Manjeet' : [1, 4, 5, 6],
'Akash' : [1, 8, 9],
'Nikhil': [10, 22, 4],
'Akshat': [5, 11, 22]}
# printing original dictionary
print(""The original dictionary : "" + str(test_dict))
# Remove duplicate values across Dictionary Values
# Using Counter() + list comprehension
cnt = Counter()
for idx in test_dict.values():
cnt.update(idx)
res = {idx: [key for key in j if cnt[key] == 1]
for idx, j in test_dict.items()}
# printing result
print(""Uncommon elements records : "" + str(res)) "
2087,How to check horoscope using Python ,"import requests
from bs4 import BeautifulSoup"
2088,Write a Python program to Adding Tuple to List and vice – versa,"# Python3 code to demonstrate working of
# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)
# initializing list
test_list = [5, 6, 7]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing tuple
test_tup = (9, 10)
# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)
test_list += test_tup
# printing result
print(""The container after addition : "" + str(test_list))"
2089,How to check if a Python variable exists,"def func():
# defining local variable
a_variable = 0
# using locals() function
# for checking existence in symbol table
is_local_var = ""a_variable"" in locals()
# printing result
print(is_local_var)
# driver code
func()"
2090,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 "
2091,Write a Python program to numpy.isin() method,"# import numpy
import numpy as np
# using numpy.isin() method
gfg1 = np.array([1, 2, 3, 4, 5])
lis = [1, 3, 5]
gfg = np.isin(gfg1, lis)
print(gfg)"
2092,"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))"
2093,"Write a Python program to Get number of characters, words, spaces and lines in a file","# Python implementation to compute
# number of characters, words, spaces
# and lines in a file
# Function to count number
# of characters, words, spaces
# and lines in a file
def counter(fname):
# variable to store total word count
num_words = 0
# variable to store total line count
num_lines = 0
# variable to store total character count
num_charc = 0
# variable to store total space count
num_spaces = 0
# opening file using with() method
# so that file gets closed
# after completion of work
with open(fname, 'r') as f:
# loop to iterate file
# line by line
for line in f:
# incrementing value of
# num_lines with each
# iteration of loop to
# store total line count
num_lines += 1
# declaring a variable word
# and assigning its value as Y
# because every file is
# supposed to start with
# a word or a character
word = 'Y'
# loop to iterate every
# line letter by letter
for letter in line:
# condition to check
# that the encountered character
# is not white space and a word
if (letter != ' ' and word == 'Y'):
# incrementing the word
# count by 1
num_words += 1
# assigning value N to
# variable word because until
# space will not encounter
# a word can not be completed
word = 'N'
# condition to check
# that the encountered character
# is a white space
elif (letter == ' '):
# incrementing the space
# count by 1
num_spaces += 1
# assigning value Y to
# variable word because after
# white space a word
# is supposed to occur
word = 'Y'
# loop to iterate every
# letter character by
# character
for i in letter:
# condition to check
# that the encountered character
# is not white space and not
# a newline character
if(i !="" "" and i !=""\n""):
# incrementing character
# count by 1
num_charc += 1
# printing total word count
print(""Number of words in text file: "", num_words)
# printing total line count
print(""Number of lines in text file: "", num_lines)
# printing total character count
print('Number of characters in text file: ', num_charc)
# printing total space count
print('Number of spaces in text file: ', num_spaces)
# Driver Code:
if __name__ == '__main__':
fname = 'File1.txt'
try:
counter(fname)
except:
print('File not found')"
2094,Split a text column into two columns in Pandas DataFrame in Python,"# import Pandas as pd
import pandas as pd
# create a new data frame
df = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'],
'Age':[32, 34, 36]})
print(""Given Dataframe is :\n"",df)
# bydefault splitting is done on the basis of single space.
print(""\nSplitting 'Name' column into two different columns :\n"",
df.Name.str.split(expand=True))"
2095,Write a Python program to Creating DataFrame from dict of narray/lists,"# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Category':['Array', 'Stack', 'Queue'],
'Marks':[20, 21, 19]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df )"
2096,Write a Python program to Numpy np.eigvals() method,"# import numpy
from numpy import linalg as LA
# using np.eigvals() method
gfg = LA.eigvals([[1, 2], [3, 4]])
print(gfg)"
2097,Saving a Networkx graph in GEXF format and visualize using Gephi in Python,"# importing the required module
import networkx as nx
# making a simple graph with 1 node.
G = nx.path_graph(10)
# saving graph created above in gexf format
nx.write_gexf(G, ""geeksforgeeks.gexf"")"
2098,How to Sort CSV by multiple columns in Python ,"# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv(""diamonds.csv"")
# sorting data frame by a column
data.sort_values(""carat"", axis=0, ascending=True,
inplace=True, na_position='first')
# display
data.head(10)"
2099,Write a Python program to Extract Symmetric Tuples,"# Python3 code to demonstrate working of
# Extract Symmetric Tuples
# Using dictionary comprehension + set()
# initializing list
test_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
# printing original list
print(""The original list is : "" + str(test_list))
# Extract Symmetric Tuples
# Using dictionary comprehension + set()
temp = set(test_list) & {(b, a) for a, b in test_list}
res = {(a, b) for a, b in temp if a < b}
# printing result
print(""The Symmetric tuples : "" + str(res)) "
2100,Write a Python program to Remove keys with substring values,"# Python3 code to demonstrate working of
# Remove keys with substring values
# Using any() + generator expression
# initializing dictionary
test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}
# printing original dictionary
print(""The original dictionary : "" + str(test_dict))
# initializing substrings
sub_list = ['love', 'good']
# Remove keys with substring values
# Using any() + generator expression
res = dict()
for key, val in test_dict.items():
if not any(ele in val for ele in sub_list):
res[key] = val
# printing result
print(""Filtered Dictionary : "" + str(res)) "
2101,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)"
2102,Map function and Lambda expression in Python to replace characters,"# Function to replace a character c1 with c2
# and c2 with c1 in a string S
def replaceChars(input,c1,c2):
# create lambda to replace c1 with c2, c2
# with c1 and other will remain same
# expression will be like ""lambda x:
# x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2""
# and map it onto each character of string
newChars = map(lambda x: x if (x!=c1 and x!=c2) else \
c1 if (x==c2) else c2,input)
# now join each character without space
# to print resultant string
print (''.join(newChars))
# Driver program
if __name__ == ""__main__"":
input = 'grrksfoegrrks'
c1 = 'e'
c2 = 'r'
replaceChars(input,c1,c2)"
2103,Validate an IP address using Python without using RegEx,"# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# check number of periods
if s.count('.') != 3:
return 'Invalid Ip address'
l = list(map(str, s.split('.')))
# check range of each number between periods
for ele in l:
if int(ele) < 0 or int(ele) > 255:
return 'Invalid Ip address'
return 'Valid Ip address'
# Driver Code
print(isValidIP('666.1.2.2'))"
2104,Write a Python program to Consecutive characters frequency,"# Python3 code to demonstrate working of
# Consecutive characters frequency
# Using list comprehension + groupby()
from itertools import groupby
# initializing string
test_str = ""geekksforgggeeks""
# printing original string
print(""The original string is : "" + test_str)
# Consecutive characters frequency
# Using list comprehension + groupby()
res = [len(list(j)) for _, j in groupby(test_str)]
# printing result
print(""The Consecutive characters frequency : "" + str(res)) "
2105,How to save a NumPy array to a text file in Python,"# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
file = open(""file1.txt"", ""w+"")
# Saving the array in a text file
content = str(Array)
file.write(content)
file.close()
# Displaying the contents of the text file
file = open(""file1.txt"", ""r"")
content = file.read()
print(""\nContent in file1.txt:\n"", content)
file.close()"
2106,Select any row from a Dataframe using iloc[] and iat[] in Pandas in Python,"import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Create an empty list
Row_list =[]
# Iterate over each row
for i in range((df.shape[0])):
# Using iloc to access the values of
# the current row denoted by ""i""
Row_list.append(list(df.iloc[i, :]))
# Print the first 3 elements
print(Row_list[:3])"
2107,How to multiply a polynomial to another using NumPy in Python,"# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5, -2, 5)
# q(x) = 2(x**2) + (-5)x +2
qx = (2, -5, 2)
# mul the polynomials
rx = numpy.polynomial.polynomial.polymul(px, qx)
# print the resultant polynomial
print(rx)"
2108,Creating a Pandas Series from Dictionary in Python,"# import the pandas lib as pd
import pandas as pd
# create a dictionary
dictionary = {'A' : 10, 'B' : 20, 'C' : 30}
# create a series
series = pd.Series(dictionary)
print(series)"
2109,Compute the median of the flattened NumPy array in Python,"# importing numpy as library
import numpy as np
# creating 1 D array with odd no of
# elements
x_odd = np.array([1, 2, 3, 4, 5, 6, 7])
print(""\nPrinting the Original array:"")
print(x_odd)
# calculating median
med_odd = np.median(x_odd)
print(""\nMedian of the array that contains \
odd no of elements:"")
print(med_odd)"
2110,How to check whether specified values are present in NumPy array in Python,"# importing Numpy package
import numpy as np
# creating a Numpy array
n_array = np.array([[2, 3, 0],
[4, 1, 6]])
print(""Given array:"")
print(n_array)
# Checking whether specific values
# are present in ""n_array"" or not
print(2 in n_array)
print(0 in n_array)
print(6 in n_array)
print(50 in n_array)
print(10 in n_array)"
2111,Write a Python program to Possible Substring count from String,"# Python3 code to demonstrate working of
# Possible Substring count from String
# Using min() + list comprehension + count()
# initializing string
test_str = ""gekseforgeeks""
# printing original string
print(""The original string is : "" + str(test_str))
# initializing arg string
arg_str = ""geeks""
# using min and count to get minimum possible
# occurrence of character
res = min(test_str.count(char) // arg_str.count(char) for char in set(arg_str))
# printing result
print(""Possible substrings count : "" + str(res))"
2112,Create a Numpy array filled with all ones in Python,"# Python Program to create array with all ones
import numpy as geek
a = geek.ones(3, dtype = int)
print(""Matrix a : \n"", a)
b = geek.ones([3, 3], dtype = int)
print(""\nMatrix b : \n"", b) "
2113,How to check which Button was clicked in Tkinter in Python,"# Python program to determine which
# button was pressed in tkinter
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Create a function with one paramter, i.e., of
# the text you want to show when button is clicked
def which_button(button_press):
# Printing the text when a button is clicked
print(button_press)
# Creating and displaying of button b1
b1 = Button(app, text=""Apple"",
command=lambda m=""It is an apple"": which_button(m))
b1.grid(padx=10, pady=10)
# Creating and displaying of button b2
b2 = Button(app, text=""Banana"",
command=lambda m=""It is a banana"": which_button(m))
b2.grid(padx=10, pady=10)
# Make the infinite loop for displaying the app
app.mainloop()"
2114,Make a Pandas DataFrame with two-dimensional list | Python,"# import pandas as pd
import pandas as pd
# List1
lst = [['Geek', 25], ['is', 30],
['for', 26], ['Geeksforgeeks', 22]]
# creating df object with columns specified
df = pd.DataFrame(lst, columns =['Tag', 'number'])
print(df )"
2115,Write a Python program to Convert a list of Tuples into Dictionary,"# Python code to convert into dictionary
def Convert(tup, di):
for a, b in tup:
di.setdefault(a, []).append(b)
return di
# Driver Code
tups = [(""akash"", 10), (""gaurav"", 12), (""anand"", 14),
(""suraj"", 20), (""akhil"", 25), (""ashish"", 30)]
dictionary = {}
print (Convert(tups, dictionary))"
2116,Bisect Algorithm Functions in Python,"# Python code to demonstrate the working of
# bisect(), bisect_left() and bisect_right()
# importing ""bisect"" for bisection operations
import bisect
# initializing list
li = [1, 3, 4, 4, 4, 6, 7]
# using bisect() to find index to insert new element
# returns 5 ( right most possible index )
print (""The rightmost index to insert, so list remains sorted is : "", end="""")
print (bisect.bisect(li, 4))
# using bisect_left() to find index to insert new element
# returns 2 ( left most possible index )
print (""The leftmost index to insert, so list remains sorted is : "", end="""")
print (bisect.bisect_left(li, 4))
# using bisect_right() to find index to insert new element
# returns 4 ( right most possible index )
print (""The rightmost index to insert, so list remains sorted is : "", end="""")
print (bisect.bisect_right(li, 4, 0, 4))"
2117,Handling missing keys in Python dictionaries,"# Python code to demonstrate Dictionary and
# missing value error
# initializing Dictionary
d = { 'a' : 1 , 'b' : 2 }
# trying to output value of absent key
print (""The value associated with 'c' is : "")
print (d['c'])"
2118,Construct a DataFrame in Pandas using string data in Python,"# importing pandas as pd
import pandas as pd
# import the StrinIO function
# from io module
from io import StringIO
# wrap the string data in StringIO function
StringData = StringIO(""""""Date;Event;Cost
10/2/2011;Music;10000
11/2/2011;Poetry;12000
12/2/2011;Theatre;5000
13/2/2011;Comedy;8000
"""""")
# let's read the data using the Pandas
# read_csv() function
df = pd.read_csv(StringData, sep ="";"")
# Print the dataframe
print(df)"
2119,Write a Python program to sort a list of tuples alphabetically,"# Python program to sort a
# list of tuples alphabetically
# Function to sort the list of
# tuples
def SortTuple(tup):
# Getting the length of list
# of tuples
n = len(tup)
for i in range(n):
for j in range(n-i-1):
if tup[j][0] > tup[j + 1][0]:
tup[j], tup[j + 1] = tup[j + 1], tup[j]
return tup
# Driver's code
tup = [(""Amana"", 28), (""Zenat"", 30), (""Abhishek"", 29),
(""Nikhil"", 21), (""B"", ""C"")]
print(SortTuple(tup))"
2120,numpy string operations | lower() function in Python,"# Python Program explaining
# numpy.char.lower() 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.lower(in_arr)
print (""output lowercased array :"", out_arr)"
2121,numpy.random.laplace() in Python,"# import numpy
import numpy as np
import matplotlib.pyplot as plt
# Using numpy.random.laplace() method
gfg = np.random.laplace(1.45, 15, 1000)
count, bins, ignored = plt.hist(gfg, 30, density = True)
plt.show()"
2122,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)"
2123,Write a Python Program for Bitonic Sort,"# Python program for Bitonic Sort. Note that this program
# works only when size of input is a power of 2.
# The parameter dir indicates the sorting direction, ASCENDING
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
# then a[i] and a[j] are interchanged.*/
def compAndSwap(a, i, j, dire):
if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] > a[j]):
a[i],a[j] = a[j],a[i]
# It recursively sorts a bitonic sequence in ascending order,
# if dir = 1, and in descending order otherwise (means dir=0).
# The sequence to be sorted starts at index position low,
# the parameter cnt is the number of elements to be sorted.
def bitonicMerge(a, low, cnt, dire):
if cnt > 1:
k = cnt/2
for i in range(low , low+k):
compAndSwap(a, i, i+k, dire)
bitonicMerge(a, low, k, dire)
bitonicMerge(a, low+k, k, dire)
# This function first produces a bitonic sequence by recursively
# sorting its two halves in opposite sorting orders, and then
# calls bitonicMerge to make them in the same order
def bitonicSort(a, low, cnt,dire):
if cnt > 1:
k = cnt/2
bitonicSort(a, low, k, 1)
bitonicSort(a, low+k, k, 0)
bitonicMerge(a, low, cnt, dire)
# Caller of bitonicSort for sorting the entire array of length N
# in ASCENDING order
def sort(a,N, up):
bitonicSort(a,0, N, up)
# Driver code to test above
a = [3, 7, 4, 8, 6, 2, 1, 5]
n = len(a)
up = 1
sort(a, n, up)
print (""\n\nSorted array is"")
for i in range(n):
print(""%d"" %a[i]),"
2124,Write a Python program to Ways to remove a key from dictionary,"# Python code to demonstrate
# removal of dict. pair
# using del
# Initializing dictionary
test_dict = {""Arushi"" : 22, ""Anuradha"" : 21, ""Mani"" : 21, ""Haritha"" : 21}
# Printing dictionary before removal
print (""The dictionary before performing remove is : "" + str(test_dict))
# Using del to remove a dict
# removes Mani
del test_dict['Mani']
# Printing dictionary after removal
print (""The dictionary after remove is : "" + str(test_dict))
# Using del to remove a dict
# raises exception
del test_dict['Manjeet']"
2125,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"
2126,Reverse words in a given String in Python,"# Function to reverse words of string
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# finally return the joined string
return reverse_sentence
if __name__ == ""__main__"":
input = 'geeks quiz practice code'
print (rev_sentence(input))"
2127,Write a Python program to Row-wise element Addition in Tuple Matrix,"# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing Custom eles
cus_eles = [6, 7, 8]
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
res = [[sub + (cus_eles[idx], ) for sub in val] for idx, val in enumerate(test_list)]
# printing result
print(""The matrix after row elements addition : "" + str(res)) "
2128,Write a Python Program to print hollow half diamond hash pattern,"# python program to print
# hollow half diamond star
# function to print hollow
# half diamond star
def hollow_half_diamond(N):
# this for loop is for
# printing upper half
for i in range( 1, N + 1):
for j in range(1, i + 1):
# this is the condition to
# print ""#"" only on the
# boundaries
if i == j or j == 1:
print(""#"", end ="" "")
# print "" ""(space) on the rest
# of the area
else:
print("" "", end ="" "")
print()
# this for loop is to print lower half
for i in range(N - 1, 0, -1):
for j in range(1, i + 1):
if j == 1 or i == j:
print(""#"", end ="" "")
else:
print("" "", end ="" "")
print()
# Driver Code
if __name__ == ""__main__"":
N = 7
hollow_half_diamond( N )
"
2129,Compute the condition number of a given matrix using NumPy in Python,"# Importing library
import numpy as np
# Creating a 2X2 matrix
matrix = np.array([[4, 2], [3, 1]])
print(""Original matrix:"")
print(matrix)
# Output
result = np.linalg.cond(matrix)
print(""Condition number of the matrix:"")
print(result)"
2130,How to extract paragraph from a website and save it as a text file in Python,"import urllib.request
from bs4 import BeautifulSoup
# here we have to pass url and path
# (where you want to save ur text file)
urllib.request.urlretrieve(""https://www.geeksforgeeks.org/grep-command-in-unixlinux/?ref=leftbar-rightbar"",
""/home/gpt/PycharmProjects/pythonProject1/test/text_file.txt"")
file = open(""text_file.txt"", ""r"")
contents = file.read()
soup = BeautifulSoup(contents, 'html.parser')
f = open(""test1.txt"", ""w"")
# traverse paragraphs from soup
for data in soup.find_all(""p""):
sum = data.get_text()
f.writelines(sum)
f.close()"
2131,Write a Python program to Minimum number of subsets with distinct elements using Counter,"# Python program to find Minimum number of
# subsets with distinct elements using Counter
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
def minSubsets(input):
# calculate frequency of each element
freqDict = Counter(input)
# get list of all frequency values
# print maximum from it
print (max(freqDict.values()))
# Driver program
if __name__ == ""__main__"":
input = [1, 2, 3, 3]
minSubsets(input)"
2132,How to add one polynomial to another using NumPy in Python,"# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5,-2,5)
# q(x) = 2(x**2) + (-5)x +2
qx = (2,-5,2)
# add the polynomials
rx = numpy.polynomial.polynomial.polyadd(px,qx)
# print the resultant polynomial
print(rx)"
2133,Write a Python program to Numpy matrix.mean(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[64, 1; 12, 3]')
# applying matrix.mean() method
geeks = gfg.mean()
print(geeks)"
2134,Write a Python program to Remove empty List from List,"# Python3 code to demonstrate
# Remove empty List from List
# using list comprehension
# Initializing list
test_list = [5, 6, [], 3, [], [], 9]
# printing original list
print(""The original list is : "" + str(test_list))
# Remove empty List from List
# using list comprehension
res = [ele for ele in test_list if ele != []]
# printing result
print (""List after empty list removal : "" + str(res))"
2135,Write a Python program to Read CSV Column into List without header,"import csv
# reading data from a csv file 'Data.csv'
with open('Data.csv', newline='') as file:
reader = csv.reader(file, delimiter = ' ')
# store the headers in a separate variable,
# move the reader object to point on the next row
headings = next(reader)
# output list to store all rows
Output = []
for row in reader:
Output.append(row[:])
for row_num, rows in enumerate(Output):
print('data in row number {} is {}'.format(row_num+1, rows))
print('headers were: ', headings)"
2136,Write a Python program to Create Nested Dictionary using given List,"# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using loop + zip()
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
# printing original dictionary and list
print(""The original dictionary is : "" + str(test_dict))
print(""The original list is : "" + str(test_list))
# using zip() and loop to perform
# combining and assignment respectively.
res = {}
for key, ele in zip(test_list, test_dict.items()):
res[key] = dict([ele])
# printing result
print(""The mapped dictionary : "" + str(res)) "
2137,Split a column in Pandas dataframe and get part of it in Python,"import pandas as pd
import numpy as np
df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',
'Geek4_id', 'Geek5_id'],
'Geek_A': [1, 1, 3, 2, 4],
'Geek_B': [1, 2, 3, 4, 6],
'Geek_R': np.random.randn(5)})
# Geek_A Geek_B Geek_ID Geek_R
# 0 1 1 Geek1_id random number
# 1 1 2 Geek2_id random number
# 2 3 3 Geek3_id random number
# 3 2 4 Geek4_id random number
# 4 4 6 Geek5_id random number
print(df.Geek_ID.str.split('_').str[0])"
2138,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)"
2139,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))"
2140,Write a Python Program for Pigeonhole Sort,"# Python program to implement Pigeonhole Sort */
# source code : ""https://en.wikibooks.org/wiki/
# Algorithm_Implementation/Sorting/Pigeonhole_sort""
def pigeonhole_sort(a):
# size of range of values in the list
# (ie, number of pigeonholes we need)
my_min = min(a)
my_max = max(a)
size = my_max - my_min + 1
# our list of pigeonholes
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert type(x) is int, ""integers only please""
holes[x - my_min] += 1
# Put the elements back into the array in order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + my_min
i += 1
a = [8, 3, 2, 7, 4, 6, 8]
print(""Sorted order is : "", end ="" "")
pigeonhole_sort(a)
for i in range(0, len(a)):
print(a[i], end ="" "")
"
2141,Write a Python program to Replace Substrings from String List,"# Python3 code to demonstrate
# Replace Substrings from String List
# using loop + replace() + enumerate()
# Initializing list1
test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
test_list2 = [['Geeks', 'Gks'], ['And', '&'], ['Computer', 'Comp']]
# printing original lists
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# Replace Substrings from String List
# using loop + replace() + enumerate()
sub = dict(test_list2)
for key, val in sub.items():
for idx, ele in enumerate(test_list1):
if key in ele:
test_list1[idx] = ele.replace(key, val)
# printing result
print (""The list after replacement : "" + str(test_list1))"
2142,"Write a Python dictionary, set and counter to check if frequencies can become same","# Function to Check if frequency of all characters
# can become same by one removal
from collections import Counter
def allSame(input):
# calculate frequency of each character
# and convert string into dictionary
dict=Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same)>2:
print('No')
elif len (same)==2 and same[1]-same[0]>1:
print('No')
else:
print('Yes')
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == ""__main__"":
input = 'xxxyyzzt'
allSame(input)"
2143,Creating a dataframe from Pandas series in Python,"import pandas as pd
import matplotlib.pyplot as plt
author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']
auth_series = pd.Series(author)
print(auth_series)"
2144,Write a Python program to print even numbers in a list,"# Python program to print Even Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
print(num, end = "" "")"
2145,Write a Python program to Sort Dictionary by Values Summation,"# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using dictionary comprehension + sum() + sorted()
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# summing all the values using sum()
temp1 = {val: sum(int(idx) for idx in key)
for val, key in test_dict.items()}
# using sorted to perform sorting as required
temp2 = sorted(temp1.items(), key = lambda ele : temp1[ele[0]])
# rearrange into dictionary
res = {key: val for key, val in temp2}
# printing result
print(""The sorted dictionary : "" + str(res)) "
2146,numpy.moveaxis() function | Python,"# Python program explaining
# numpy.moveaxis() function
# importing numpy as geek
import numpy as geek
arr = geek.zeros((1, 2, 3, 4))
gfg = geek.moveaxis(arr, 0, -1).shape
print (gfg)"
2147,Write a Python program to Test if Substring occurs in specific position,"# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using loop
# initializing string
test_str = ""Gfg is best""
# printing original string
print(""The original string is : "" + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = ""best""
# Test if Substring occurs in specific position
# Using loop
res = True
k = 0
for idx in range(len(test_str)):
if idx >= i and idx < j:
if test_str[idx] != substr[k]:
res = False
break
k = k + 1
# printing result
print(""Does string contain substring at required position ? : "" + str(res)) "
2148,Write a Python program to Elements Frequency in Mixed Nested Tuple,"# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
# helper_fnc
def flatten(test_tuple):
for tup in test_tuple:
if isinstance(tup, tuple):
yield from flatten(tup)
else:
yield tup
# initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
# printing original tuple
print(""The original tuple : "" + str(test_tuple))
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
res = {}
for ele in flatten(test_tuple):
if ele not in res:
res[ele] = 0
res[ele] += 1
# printing result
print(""The elements frequency : "" + str(res))"
2149,Write a Python program to Permutation of a given string using inbuilt function,"# Function to find permutations of a given string
from itertools import permutations
def allPermutations(str):
# Get all permutations of string 'ABC'
permList = permutations(str)
# print all permutations
for perm in list(permList):
print (''.join(perm))
# Driver program
if __name__ == ""__main__"":
str = 'ABC'
allPermutations(str)"
2150,Write a Python program to Scoring Matrix using Dictionary,"# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using loop
# initializing list
test_list = [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing test dict
test_dict = {'gfg' : 5, 'is' : 10, 'best' : 13, 'for' : 2, 'geeks' : 15}
# Scoring Matrix using Dictionary
# Using loop
res = []
for sub in test_list:
sum = 0
for val in sub:
if val in test_dict:
sum += test_dict[val]
res.append(sum)
# printing result
print(""The Row scores : "" + str(res)) "
2151,Write a Python Lambda with underscore as an argument,"remainder = lambda num: num % 2
print(remainder(5))"
2152,Find a matrix or vector norm using NumPy in Python,"# import library
import numpy as np
# initialize vector
vec = np.arange(10)
# compute norm of vector
vec_norm = np.linalg.norm(vec)
print(""Vector norm:"")
print(vec_norm)"
2153,Conditional operation on Pandas DataFrame columns in Python,"# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'],
'Last Price':[1200, 1500, 1600, 352],
'Updated Price':[1250, 1450, 1550, 400],
'Discount':[10, 10, 10, 10]})
# Print the dataframe
print(df)"
2154,Write a Python program for removing i-th character from a string,"# Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
# Characters before the i-th indexed
# is stored in a variable a
a = string[ : i]
# Characters after the nth indexed
# is stored in a variable b
b = string[i + 1: ]
# Returning string after removing
# nth indexed character.
return a + b
# Driver Code
if __name__ == '__main__':
string = ""geeksFORgeeks""
# Remove nth index element
i = 5
# Print the new string
print(remove(string, i))"
2155,Concatenated string with uncommon characters in Python,"# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# take intersection of two sets to get list of
# common characters
common = list(set1 & set2)
# separate out characters in each string
# which are not common in both strings
result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common]
# join each character without space to get
# final string
print( ''.join(result) )
# Driver program
if __name__ == ""__main__"":
str1 = 'aacdb'
str2 = 'gafd'
uncommonConcat(str1,str2) "
2156,Clean the string data in the given Pandas Dataframe in Python,"# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':[' UMbreLla', ' maTress', 'BaDmintoN ', 'Shuttle'],
'Updated_Price':[1250, 1450, 1550, 400],
'Discount':[10, 8, 15, 10]})
# Print the dataframe
print(df)"
2157,Write a Python program to a Sort Matrix by index-value equality count,"# Python3 code to demonstrate working of
# Sort Matrix by index-value equality count
# Using sort() + len() + enumerate()
def get_idx_ele_count(row):
# getting required count
# element and index compared, if equal added
# in list, length computed using len()
return len([ele for idx, ele in enumerate(row) if ele == idx])
# initializing list
test_list = [[3, 1, 2, 5, 4], [0, 1, 2, 3, 4],
[6, 5, 4, 3, 2], [0, 5, 4, 2]]
# printing original list
print(""The original list is : "" + str(test_list))
# inplace sorting using sort()
test_list.sort(key=get_idx_ele_count)
# printing result
print(""Sorted List : "" + str(test_list))"
2158,How to subtract one polynomial to another using NumPy in Python,"# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5,-2,5)
# q(x) = 2(x**2) + (-5)x +2
qx = (2,-5,2)
# subtract the polynomials
rx = numpy.polynomial.polynomial.polysub(px,qx)
# print the resultant polynomial
print(rx)"
2159,Write a Python program to Convert numeric words to numbers,"# Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using join() + split()
help_dict = {
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'zero' : '0'
}
# initializing string
test_str = ""zero four zero one""
# printing original string
print(""The original string is : "" + test_str)
# Convert numeric words to numbers
# Using join() + split()
res = ''.join(help_dict[ele] for ele in test_str.split())
# printing result
print(""The string after performing replace : "" + res) "
2160,Write a Python program to Sort String list by K character frequency,"# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
# initializing list
test_list = [""geekforgeeks"", ""is"", ""best"", ""for"", ""geeks""]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 'e'
# ""-"" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -ele.count(K))
# printing results
print(""Sorted String : "" + str(res))"
2161,Write a Python program to Swap elements in String list,"# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
# printing original lists
print(""The original list is : "" + str(test_list))
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in test_list]
# printing result
print (""List after performing character swaps : "" + str(res))"
2162,Write a Python program to Difference between two lists,"# Python code t get difference of two lists
# Using set()
def Diff(li1, li2):
return list(set(li1) - set(li2)) + list(set(li2) - set(li1))
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
print(Diff(li1, li2))"
2163,numpy string operations | count() function in Python,"# Python program explaining
# numpy.char.count() method
# importing numpy as geek
import numpy as geek
# input arrays
in_arr = geek.array(['Sayantan', ' Sayan ', 'Sayansubhra'])
print (""Input array : "", in_arr)
# output arrays
out_arr = geek.char.count(in_arr, sub ='an')
print (""Output array: "", out_arr) "
2164,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))"
2165,Write a Python program to Specific Characters Frequency in String List,"# Python3 code to demonstrate working of
# Specific Characters Frequency in String List
# Using join() + Counter()
from collections import Counter
# initializing lists
test_list = [""geeksforgeeks is best for geeks""]
# printing original list
print(""The original list : "" + str(test_list))
# char list
chr_list = ['e', 'b', 'g']
# dict comprehension to retrieve on certain Frequencies
res = {key:val for key, val in dict(Counter("""".join(test_list))).items() if key in chr_list}
# printing result
print(""Specific Characters Frequencies : "" + str(res))"
2166,Write a Python program to Sort dictionaries list by Key’s Value list index,"# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda
# initializing lists
test_list = [{""Gfg"" : [6, 7, 8], ""is"" : 9, ""best"" : 10},
{""Gfg"" : [2, 0, 3], ""is"" : 11, ""best"" : 19},
{""Gfg"" : [4, 6, 9], ""is"" : 16, ""best"" : 1}]
# printing original list
print(""The original list : "" + str(test_list))
# initializing K
K = ""Gfg""
# initializing idx
idx = 2
# using sorted() to perform sort in basis of 1 parameter key and
# index
res = sorted(test_list, key = lambda ele: ele[K][idx])
# printing result
print(""The required sort order : "" + str(res))"
2167,Find the size of a Dictionary in Python,"import sys
# sample Dictionaries
dic1 = {""A"": 1, ""B"": 2, ""C"": 3}
dic2 = {""Geek1"": ""Raju"", ""Geek2"": ""Nikhil"", ""Geek3"": ""Deepanshu""}
dic3 = {1: ""Lion"", 2: ""Tiger"", 3: ""Fox"", 4: ""Wolf""}
# print the sizes of sample Dictionaries
print(""Size of dic1: "" + str(sys.getsizeof(dic1)) + ""bytes"")
print(""Size of dic2: "" + str(sys.getsizeof(dic2)) + ""bytes"")
print(""Size of dic3: "" + str(sys.getsizeof(dic3)) + ""bytes"")"
2168,Write a Python program to find the type of IP Address using Regex,"# Python program to find the type of Ip address
# re module provides support
# for regular expressions
import re
# Make a regular expression
# for validating an Ipv4
ipv4 = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$'''
# Make a regular expression
# for validating an Ipv6
ipv6 = '''(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|
([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:)
{1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1
,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}
:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{
1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA
-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a
-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0
-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,
4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}
:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9
])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0
-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]
|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]
|1{0,1}[0-9]){0,1}[0-9]))'''
# Define a function for finding
# the type of Ip address
def find(Ip):
# pass the regular expression
# and the string in search() method
if re.search(ipv4, Ip):
print(""IPv4"")
elif re.search(ipv6, Ip):
print(""IPv6"")
else:
print(""Neither"")
# Driver Code
if __name__ == '__main__' :
# Enter the Ip address
Ip = ""192.0.2.126""
# calling run function
find(Ip)
Ip = ""3001:0da8:75a3:0000:0000:8a2e:0370:7334""
find(Ip)
Ip = ""36.12.08.20.52""
find(Ip)"
2169,Write a Python: Get List of all empty Directories,"# Python program to list out
# all the empty directories
import os
# List to store all empty
# directories
empty = []
# Traversing through Test
for root, dirs, files in os.walk('Test'):
# Checking the size of tuple
if not len(dirs) and not len(files):
# Adding the empty directory to
# list
empty.append(root)
Print(""Empty Directories:"")
print(empty)"
2170,Generate Random Numbers From The Uniform Distribution using NumPy in Python,"# importing module
import numpy as np
# numpy.random.uniform() method
r = np.random.uniform(size=4)
# printing numbers
print(r)"
2171,Write a Python program to print odd numbers in a List,"# Python program to print odd Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# iterating each number in list
for num in list1:
# checking condition
if num % 2 != 0:
print(num, end = "" "")"
2172,Write a Python program to Check if a given string is binary string or not,"# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string) :
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {'0', '1'}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {'0'} or p == {'1'}:
print(""Yes"")
else :
print(""No"")
# driver code
if __name__ == ""__main__"" :
string = ""101010000111""
# function calling
check(string)"
2173,Write a Python program to Extract tuples having K digit elements,"# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
# Using all() + list comprehension
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 2
# using len() and str() to check length and
# perform string conversion
res = [sub for sub in test_list if all(len(str(ele)) == K for ele in sub)]
# printing result
print(""The Extracted tuples : "" + str(res))"
2174,Write a Python program to Convert Nested Tuple to Custom Key Dictionary,"# Python3 code to demonstrate working of
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
# printing original tuple
print(""The original tuple : "" + str(test_tuple))
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}
for sub in test_tuple]
# printing result
print(""The converted dictionary : "" + str(res))"
2175,Using dictionary to remap values in Pandas DataFrame columns in Python,"# importing pandas as pd
import pandas as pd
# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)"
2176,Remove all the occurrences of an element from a list in Python,"# Python 3 code to demonstrate
# the removal of all occurrences of a
# given item using list comprehension
def remove_items(test_list, item):
# using list comprehension to perform the task
res = [i for i in test_list if i != item]
return res
# driver code
if __name__==""__main__"":
# initializing the list
test_list = [1, 3, 4, 6, 5, 1]
# the item which is to be removed
item = 1
# printing the original list
print (""The original list is : "" + str(test_list))
# calling the function remove_items()
res = remove_items(test_list, item)
# printing result
print (""The list after performing the remove operation is : "" + str(res))"
2177,Insert row at given position in Pandas Dataframe in Python,"# importing pandas as pd
import pandas as pd
# Let's create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '12/2/2011', '13/2/2011', '14/2/2011'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Let's visualize the dataframe
print(df)"
2178,Write a Python program to Matrix Row subset,"# Python3 code to demonstrate working of
# Matrix Row subset
# Using any() + all() + list comprehension
# initializing lists
test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing check Matrix
check_matr = [[2, 3], [1, 2], [9, 0]]
# Matrix Row subset
# Using any() + all() + list comprehension
res = [ele for ele in check_matr if any(all(a in sub for a in ele)
for sub in test_list)]
# printing result
print(""Matrix row subsets : "" + str(res)) "
2179,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))"
2180,How to create a list of object in Python class,"# Python3 code here creating class
class geeks:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# creating list
list = []
# appending instances to list
list.append( geeks('Akash', 2) )
list.append( geeks('Deependra', 40) )
list.append( geeks('Reaper', 44) )
for obj in list:
print( obj.name, obj.roll, sep =' ' )
# We can also access instances attributes
# as list[0].name, list[0].roll and so on."
2181,Write a Python Program for Recursive Insertion Sort,"# Recursive Python program for insertion sort
# Recursive function to sort an array using insertion sort
def insertionSortRecursive(arr, n):
# base case
if n <= 1:
return
# Sort first n-1 elements
insertionSortRecursive(arr, n - 1)
# Insert last element at its correct position in sorted array.
last = arr[n - 1]
j = n - 2
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j >= 0 and arr[j] > last):
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = last
# Driver program to test insertion sort
if __name__ == '__main__':
A = [-7, 11, 6, 0, -3, 5, 10, 2]
n = len(A)
insertionSortRecursive(A, n)
print(A)
# Contributed by Harsh Valecha,
# Edited by Abraar Masud Nafiz."
2182,How to get values of an NumPy array at certain index positions in Python,"# Importing Numpy module
import numpy as np
# Creating 1-D Numpy array
a1 = np.array([11, 10, 22, 30, 33])
print(""Array 1 :"")
print(a1)
a2 = np.array([1, 15, 60])
print(""Array 2 :"")
print(a2)
print(""\nTake 1 and 15 from Array 2 and put them in\
1st and 5th position of Array 1"")
a1.put([0, 4], a2)
print(""Resultant Array :"")
print(a1)"
2183,Write a Python program to Convert Binary tuple to Integer,"# Python3 code to demonstrate working of
# Convert Binary tuple to Integer
# Using join() + list comprehension + int()
# initializing tuple
test_tup = (1, 1, 0, 1, 0, 0, 1)
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# using int() with base to get actual number
res = int("""".join(str(ele) for ele in test_tup), 2)
# printing result
print(""Decimal number is : "" + str(res)) "
2184,How to Download All Images from a Web Page in Python,"from bs4 import *
import requests
import os
# CREATE FOLDER
def folder_create(images):
try:
folder_name = input(""Enter Folder Name:- "")
# folder creation
os.mkdir(folder_name)
# if folder exists with that name, ask another name
except:
print(""Folder Exist with that name!"")
folder_create()
# image downloading start
download_images(images, folder_name)
# DOWNLOAD ALL IMAGES FROM THAT URL
def download_images(images, folder_name):
# intitial count is zero
count = 0
# print total images found in URL
print(f""Total {len(images)} Image Found!"")
# checking if images is not zero
if len(images) != 0:
for i, image in enumerate(images):
# From image tag ,Fetch image Source URL
# 1.data-srcset
# 2.data-src
# 3.data-fallback-src
# 4.src
# Here we will use exception handling
# first we will search for ""data-srcset"" in img tag
try:
# In image tag ,searching for ""data-srcset""
image_link = image[""data-srcset""]
# then we will search for ""data-src"" in img
# tag and so on..
except:
try:
# In image tag ,searching for ""data-src""
image_link = image[""data-src""]
except:
try:
# In image tag ,searching for ""data-fallback-src""
image_link = image[""data-fallback-src""]
except:
try:
# In image tag ,searching for ""src""
image_link = image[""src""]
# if no Source URL found
except:
pass
# After getting Image Source URL
# We will try to get the content of image
try:
r = requests.get(image_link).content
try:
# possibility of decode
r = str(r, 'utf-8')
except UnicodeDecodeError:
# After checking above condition, Image Download start
with open(f""{folder_name}/images{i+1}.jpg"", ""wb+"") as f:
f.write(r)
# counting number of image downloaded
count += 1
except:
pass
# There might be possible, that all
# images not download
# if all images download
if count == len(images):
print(""All Images Downloaded!"")
# if all images not download
else:
print(f""Total {count} Images Downloaded Out of {len(images)}"")
# MAIN FUNCTION START
def main(url):
# content of URL
r = requests.get(url)
# Parse HTML Code
soup = BeautifulSoup(r.text, 'html.parser')
# find all images in URL
images = soup.findAll('img')
# Call folder create function
folder_create(images)
# take url
url = input(""Enter URL:- "")
# CALL MAIN FUNCTION
main(url)"
2185,Write a Python program to Get list of running processes,"import wmi
# Initializing the wmi constructor
f = wmi.WMI()
# Printing the header for the later columns
print(""pid Process name"")
# Iterating through all the running processes
for process in f.Win32_Process():
# Displaying the P_ID and P_Name of the process
print(f""{process.ProcessId:<10} {process.Name}"")"
2186,Write a Python program to Split String on vowels,"# Python3 code to demonstrate working of
# Split String on vowels
# Using split() + regex
import re
# initializing strings
test_str = 'GFGaBste4oCS'
# printing original string
print(""The original string is : "" + str(test_str))
# splitting on vowels
# constructing vowels list
# and separating using | operator
res = re.split('a|e|i|o|u', test_str)
# printing result
print(""The splitted string : "" + str(res))"
2187,Write a Python program to Ways to add row/columns in numpy array,"# Python code to demonstrate
# adding columns in numpy array
import numpy as np
ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]])
# printing initial array
print(""initial_array : "", str(ini_array));
# Array to be added as column
column_to_be_added = np.array([1, 2, 3])
# Adding column to numpy array
result = np.hstack((ini_array, np.atleast_2d(column_to_be_added).T))
# printing result
print (""resultant array"", str(result))"
2188,Write a Python program to Flatten a 2d numpy array into 1d array,"# Python code to demonstrate
# flattening a 2d numpy array
# into 1d array
import numpy as np
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
# printing initial arrays
print(""initial array"", str(ini_array1))
# Multiplying arrays
result = ini_array1.flatten()
# printing result
print(""New resulting array: "", result)"
2189,Calculate the sum of all columns in a 2D NumPy array in Python,"# importing required libraries
import numpy
# explicit function to compute column wise sum
def colsum(arr, n, m):
for i in range(n):
su = 0;
for j in range(m):
su += arr[j][i]
print(su, end = "" "")
# creating the 2D Array
TwoDList = [[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]]
TwoDArray = numpy.array(TwoDList)
# displaying the 2D Array
print(""2D Array:"")
print(TwoDArray)
# printing the sum of each column
print(""\nColumn-wise Sum:"")
colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))"
2190,Returning a function from a function – Python,"# define two methods
# second method that will be returned
# by first method
def B():
print(""Inside the method B."")
# first method that return second method
def A():
print(""Inside the method A."")
# return second method
return B
# form a object of first method
# i.e; second method
returned_function = A()
# call second method by first method
returned_function()"
2191,Write a Python program to numpy.fill_diagonal() method,"# import numpy
import numpy as np
# using numpy.fill_diagonal() method
array = np.array([[1, 2], [2, 1]])
np.fill_diagonal(array, 5)
print(array)"
2192,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)))"
2193,Write a Python program to print all negative numbers in a range,"# Python program to print negative Numbers in given range
start, end = -4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num < 0:
print(num, end = "" "")"
2194,Formatting float column of Dataframe in Pandas in Python,"# import pandas lib as pd
import pandas as pd
# create the data dictionary
data = {'Month' : ['January', 'February', 'March', 'April'],
'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}
# create the dataframe
dataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])
print(""Given Dataframe :\n"", dataframe)
# round to two decimal places in python pandas
pd.options.display.float_format = '{:.2f}'.format
print('\nResult :\n', dataframe)"
2195,Write a Python program to Flatten Tuples List to String,"# Python3 code to demonstrate working of
# Flatten Tuples List to String
# using join() + list comprehension
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
# printing original tuples list
print(""The original list : "" + str(test_list))
# Flatten Tuples List to String
# using join() + list comprehension
res = ' '.join([idx for tup in test_list for idx in tup])
# printing result
print(""Tuple list converted to String is : "" + res)"
2196,Write a Python program to Remove Dictionary Key Words,"# Python3 code to demonstrate working of
# Remove Dictionary Key Words
# Using split() + loop + replace()
# initializing string
test_str = 'gfg is best for geeks'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing Dictionary
test_dict = {'geeks' : 1, 'best': 6}
# Remove Dictionary Key Words
# Using split() + loop + replace()
for key in test_dict:
if key in test_str.split(' '):
test_str = test_str.replace(key, """")
# printing result
print(""The string after replace : "" + str(test_str)) "
2197,Convert “unknown format” strings to datetime objects in Python,"# Python3 code to illustrate the conversion of
# ""unknown format"" strings to DateTime objects
# Importing parser from the dateutil.parser
import dateutil.parser as parser
# Initializing an unknown format date string
date_string = ""19750503T080120""
# Calling the parser to parse the above
# specified unformatted date string
# into a datetime objects
date_time = parser.parse(date_string)
# Printing the converted datetime object
print(date_time)"
2198,Compute the outer product of two given vectors using NumPy in Python,"# Importing library
import numpy as np
# Creating two 1-D arrays
array1 = np.array([6,2])
array2 = np.array([2,5])
print(""Original 1-D arrays:"")
print(array1)
print(array2)
# Output
print(""Outer Product of the two array is:"")
result = np.outer(array1, array2)
print(result)"
2199,Write a Python Program for Linear Search,"# Searching an element in a list/array in python
# can be simply done using \'in\' operator
# Example:
# if x in arr:
# print arr.index(x)
# If you want to implement Linear Search in python
# Linearly search x in arr[]
# If x is present then return its location
# else return -1
def search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1"
2200,How to resize Image in Write a Python program to Tkinter,"# Import Module
from tkinter import *
from PIL import Image, ImageTk"
2201,Implementation of XOR Linked List in Python,"# import required module
import ctypes
# create node class
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
self.head = None
self.tail = None
self.__nodes = []
# method to insert node at beginning
def InsertAtStart(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.head.npx = id(node) ^ self.head.npx
node.npx = id(self.head)
self.head = node
self.__nodes.append(node)
# method to insert node at end
def InsertAtEnd(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.tail.npx = id(node) ^ self.tail.npx
node.npx = id(self.tail)
self.tail = node
self.__nodes.append(node)
# method to remove node at beginning
def DeleteAtStart(self):
if self.isEmpty(): # If list is empty
return ""List is empty !""
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif (0 ^ self.head.npx) == id(self.tail): # If list has 2 nodes
self.head = self.tail
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
res = self.head.value
x = self.__type_cast(0 ^ self.head.npx) # Address of next node
y = (id(self.head) ^ x.npx) # Address of next of next node
self.head = x
self.head.npx = 0 ^ y
return res
# method to remove node at end
def DeleteAtEnd(self):
if self.isEmpty(): # If list is empty
return ""List is empty !""
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif self.__type_cast(0 ^ self.head.npx) == (self.tail): # If list has 2 nodes
self.tail = self.head
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
prev_id = 0
node = self.head
next_id = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
res = node.value
x = self.__type_cast(prev_id).npx ^ id(node)
y = self.__type_cast(prev_id)
y.npx = x ^ 0
self.tail = y
return res
# method to traverse linked list
def Print(self):
""""""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list.""""""
if self.head != None:
prev_id = 0
node = self.head
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print(""List is empty !"")
# method to traverse linked list in reverse order
def ReversePrint(self):
# Print Values is reverse order.
""""""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list.""""""
if self.head != None:
prev_id = 0
node = self.tail
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print(""List is empty !"")
# method to get length of linked list
def Length(self):
if not self.isEmpty():
prev_id = 0
node = self.head
next_id = 1
count = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
count += 1
else:
return count
else:
return 0
# method to get node data value by index
def PrintByIndex(self, index):
prev_id = 0
node = self.head
for i in range(index):
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
else:
return ""Value dosn't found index out of range.""
return node.value
# method to check if the liked list is empty or not
def isEmpty(self):
if self.head is None:
return True
return False
# method to return a new instance of type
def __type_cast(self, id):
return ctypes.cast(id, ctypes.py_object).value
# Driver Code
# create object
obj = XorLinkedList()
# insert nodes
obj.InsertAtEnd(2)
obj.InsertAtEnd(3)
obj.InsertAtEnd(4)
obj.InsertAtStart(0)
obj.InsertAtStart(6)
obj.InsertAtEnd(55)
# display length
print(""\nLength:"", obj.Length())
# traverse
print(""\nTraverse linked list:"")
obj.Print()
print(""\nTraverse in reverse order:"")
obj.ReversePrint()
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print(""Data value at index"", i, 'is', obj.PrintByIndex(i))
# removing nodes
print(""\nDelete Last Node: "", obj.DeleteAtEnd())
print(""\nDelete First Node: "", obj.DeleteAtStart())
# new length
print(""\nUpdated length:"", obj.Length())
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print(""Data value at index"", i, 'is', obj.PrintByIndex(i))
# traverse
print(""\nTraverse linked list:"")
obj.Print()
print(""\nTraverse in reverse order:"")
obj.ReversePrint()"
2202,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"
2203,Write a Python program to Convert Nested dictionary to Mapped Tuple,"# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
'best' : {'x' : 8, 'y' : 3}}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
res = [(key, tuple(sub[key] for sub in test_dict.values()))
for key in test_dict['gfg']]
# printing result
print(""The grouped dictionary : "" + str(res)) "
2204,Write a Python program to Remove K length Duplicates from String,"# Python3 code to demonstrate working of
# Remove K length Duplicates from String
# Using loop + slicing
# initializing strings
test_str = 'geeksforfreeksfo'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing K
K = 3
memo = set()
res = []
for idx in range(0, len(test_str) - K):
# slicing K length substrings
sub = test_str[idx : idx + K]
# checking for presence
if sub not in memo:
memo.add(sub)
res.append(sub)
res = ''.join(res[ele] for ele in range(0, len(res), K))
# printing result
print(""The modified string : "" + str(res)) "
2205,Calculate the QR decomposition of a given matrix using NumPy in Python,"import numpy as np
# Original matrix
matrix1 = np.array([[1, 2, 3], [3, 4, 5]])
print(matrix1)
# Decomposition of the said matrix
q, r = np.linalg.qr(matrix1)
print('\nQ:\n', q)
print('\nR:\n', r)"
2206,Count of groups having largest size while grouping according to sum of its digits in Python,"// C++ implementation to Count the
// number of groups having the largest
// size where groups are according
// to the sum of its digits
#include
using namespace std;
// function to return sum of digits of i
int sumDigits(int n){
int sum = 0;
while(n)
{
sum += n%10;
n /= 10;
}
return sum;
}
// Create the dictionary of unique sum
map constDict(int n){
// dictionary that contain
// unique sum count
map d;
for(int i = 1; i < n + 1; ++i){
// calculate the sum of its digits
int sum1 = sumDigits(i);
if(d.find(sum1) == d.end())
d[sum1] = 1;
else
d[sum1] += 1;
}
return d;
}
// function to find the
// largest size of group
int countLargest(int n){
map d = constDict(n);
int size = 0;
// count of largest size group
int count = 0;
for(auto it = d.begin(); it != d.end(); ++it){
int k = it->first;
int val = it->second;
if(val > size){
size = val;
count = 1;
}
else if(val == size)
count += 1;
}
return count;
}
// Driver code
int main()
{
int n = 13;
int group = countLargest(n);
cout << group << endl;
return 0;
}"
2207,Capitalize first letter of a column in Pandas dataframe in Python,"# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'],
'B': ['masters', 'graduate', 'graduate',
'Masters', 'Graduate'],
'C': [27, 23, 21, 23, 24]})
df"
2208,Write a Python program to Replace negative value with zero in numpy array,"# Python code to demonstrate
# to replace negative value with 0
import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print(""initial array"", ini_array1)
# code to replace all negative value with 0
ini_array1[ini_array1<0] = 0
# printing result
print(""New resulting array: "", ini_array1)"
2209,Write a Python Program for Cocktail Sort,"# Python program for implementation of Cocktail Sort
def cocktailSort(a):
n = len(a)
swapped = True
start = 0
end = n-1
while (swapped==True):
# reset the swapped flag on entering the loop,
# because it might be true from a previous
# iteration.
swapped = False
# loop from left to right same as the bubble
# sort
for i in range (start, end):
if (a[i] > a[i+1]) :
a[i], a[i+1]= a[i+1], a[i]
swapped=True
# if nothing moved, then array is sorted.
if (swapped==False):
break
# otherwise, reset the swapped flag so that it
# can be used in the next stage
swapped = False
# move the end point back by one, because
# item at the end is in its rightful spot
end = end-1
# from right to left, doing the same
# comparison as in the previous stage
for i in range(end-1, start-1,-1):
if (a[i] > a[i+1]):
a[i], a[i+1] = a[i+1], a[i]
swapped = True
# increase the starting point, because
# the last stage would have moved the next
# smallest number to its rightful spot.
start = start+1
# Driver code to test above
a = [5, 1, 4, 2, 8, 0, 2]
cocktailSort(a)
print(""Sorted array is:"")
for i in range(len(a)):
print (""%d"" %a[i]),"
2210,Changing the colour of Tkinter Menu Bar in Python,"# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Set the title and geometry to your app
app.title(""Geeks For Geeks"")
app.geometry(""800x500"")
# Create menubar by setting the color
menubar = Menu(app, background='blue', fg='white')
# Declare file and edit for showing in menubar
file = Menu(menubar, tearoff=False, background='yellow')
edit = Menu(menubar, tearoff=False, background='pink')
# Add commands in in file menu
file.add_command(label=""New"")
file.add_command(label=""Exit"", command=app.quit)
# Add commands in edit menu
edit.add_command(label=""Cut"")
edit.add_command(label=""Copy"")
edit.add_command(label=""Paste"")
# Display the file and edit declared in previous step
menubar.add_cascade(label=""File"", menu=file)
menubar.add_cascade(label=""Edit"", menu=edit)
# Displaying of menubar in the app
app.config(menu=menubar)
# Make infinite loop for displaying app on screen
app.mainloop()"
2211,Write a Python program to Check order of character in string using OrderedDict( ),"# Function to check if string follows order of
# characters defined by a pattern
from collections import OrderedDict
def checkOrder(input, pattern):
# create empty OrderedDict
# output will be like {'a': None,'b': None, 'c': None}
dict = OrderedDict.fromkeys(input)
# traverse generated OrderedDict parallel with
# pattern string to check if order of characters
# are same or not
ptrlen = 0
for key,value in dict.items():
if (key == pattern[ptrlen]):
ptrlen = ptrlen + 1
# check if we have traverse complete
# pattern string
if (ptrlen == (len(pattern))):
return 'true'
# if we come out from for loop that means
# order was mismatched
return 'false'
# Driver program
if __name__ == ""__main__"":
input = 'engineers rock'
pattern = 'egr'
print (checkOrder(input,pattern)) "
2212,Get the index of minimum value in DataFrame column in Python,"# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
df.head(10)"
2213,Write a Python program to Multiply Adjacent elements,"# Python3 code to demonstrate working of
# Adjacent element multiplication
# using zip() + generator expression + tuple
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
# printing original tuple
print(""The original tuple : "" + str(test_tup))
# Adjacent element multiplication
# using zip() + generator expression + tuple
res = tuple(i * j for i, j in zip(test_tup, test_tup[1:]))
# printing result
print(""Resultant tuple after multiplication : "" + str(res))"
2214,numpy string operations | not_equal() function in Python,"# Python program explaining
# numpy.char.not_equal() method
# importing numpy
import numpy as geek
# input arrays
in_arr1 = geek.array('numpy')
print (""1st Input array : "", in_arr1)
in_arr2 = geek.array('nump')
print (""2nd Input array : "", in_arr2)
# checking if they are not equal
out_arr = geek.char.not_equal(in_arr1, in_arr2)
print (""Output array: "", out_arr) "
2215,How to compute the eigenvalues and right eigenvectors of a given square array using NumPY in Python,"# importing numpy library
import numpy as np
# create numpy 2d-array
m = np.array([[1, 2],
[2, 3]])
print(""Printing the Original square array:\n"",
m)
# finding eigenvalues and eigenvectors
w, v = np.linalg.eig(m)
# printing eigen values
print(""Printing the Eigen values of the given square array:\n"",
w)
# printing eigen vectors
print(""Printing Right eigenvectors of the given square array:\n""
v)"
2216,Write a Python Program for Cycle Sort,"# Python program to impleament cycle sort
def cycleSort(array):
writes = 0
# Loop through the array to find cycles to rotate.
for cycleStart in range(0, len(array) - 1):
item = array[cycleStart]
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# If the item is already there, this is not a cycle.
if pos == cycleStart:
continue
# Otherwise, put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
# Rotate the rest of the cycle.
while pos != cycleStart:
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# Put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
return writes
# driver code
arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
n = len(arr)
cycleSort(arr)
print(""After sort : "")
for i in range(0, n) :
print(arr[i], end = \' \')
# Code Contributed by Mohit Gupta_OMG <(0_o)>"
2217,"Write a Python dictionary, set and counter to check if frequencies can become same","# Function to Check if frequency of all characters
# can become same by one removal
from collections import Counter
def allSame(input):
# calculate frequency of each character
# and convert string into dictionary
dict=Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same)>2:
print('No')
elif len (same)==2 and same[1]-same[0]>1:
print('No')
else:
print('Yes')
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == ""__main__"":
input = 'xxxyyzzt'
allSame(input)"
2218,Describe a NumPy Array in Python,"import numpy as np
# sample array
arr = np.array([4, 5, 8, 5, 6, 4,
9, 2, 4, 3, 6])
print(arr)"
2219,How to split the element of a given NumPy array with spaces in Python,"import numpy as np
# Original Array
array = np.array(['PHP C# Python C Java C++'], dtype=np.str)
print(array)
# Split the element of the said array with spaces
sparr = np.char.split(array)
print(sparr)"
2220,Numpy size() function | Python,"# Python program explaining
# numpy.size() method
# importing numpy
import numpy as np
# Making a random array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
# By default, give the total number of elements.
print(np.size(arr))"
2221,Write a Python program to Successive Characters Frequency,"# Python3 code to demonstrate working of
# Successive Characters Frequency
# Using count() + loop + re.findall()
import re
# initializing string
test_str = 'geeksforgeeks is best for geeks. A geek should take interest.'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing word
que_word = ""geek""
# Successive Characters Frequency
# Using count() + loop + re.findall()
temp = []
for sub in re.findall(que_word + '.', test_str):
temp.append(sub[-1])
res = {que_word : temp.count(que_word) for que_word in temp}
# printing result
print(""The Characters Frequency is : "" + str(res))"
2222,Write a Python program to Right and Left Shift characters in String,"# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print(""The original string is : "" + test_str)
# initializing right rot
r_rot = 7
# initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = (test_str * 3)[len(test_str) + r_rot - l_rot :
2 * len(test_str) + r_rot - l_rot]
# printing result
print(""The string after rotation is : "" + str(res)) "
2223,Write a Python program to Stack using Doubly Linked List,"# A complete working Python program to demonstrate all
# stack operations using a doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.prev = None # Initialize prev as null
# Stack class contains a Node object
class Stack:
# Function to initialize head
def __init__(self):
self.head = None
# Function to add an element data in the stack
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
self.head.prev = new_node
new_node.next = self.head
new_node.prev = None
self.head = new_node
# Function to pop top element and return the element from the stack
def pop(self):
if self.head is None:
return None
elif self.head.next is None:
temp = self.head.data
self.head = None
return temp
else:
temp = self.head.data
self.head = self.head.next
self.head.prev = None
return temp
# Function to return top element in the stack
def top(self):
return self.head.data
# Function to return the size of the stack
def size(self):
temp = self.head
count = 0
while temp is not None:
count = count + 1
temp = temp.next
return count
# Function to check if the stack is empty or not
def isEmpty(self):
if self.head is None:
return True
else:
return False
# Function to print the stack
def printstack(self):
print(""stack elements are:"")
temp = self.head
while temp is not None:
print(temp.data, end =""->"")
temp = temp.next
# Code execution starts here
if __name__=='__main__':
# Start with the empty stack
stack = Stack()
# Insert 4 at the beginning. So stack becomes 4->None
print(""Stack operations using Doubly LinkedList"")
stack.push(4)
# Insert 5 at the beginning. So stack becomes 4->5->None
stack.push(5)
# Insert 6 at the beginning. So stack becomes 4->5->6->None
stack.push(6)
# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
stack.push(7)
# Print the stack
stack.printstack()
# Print the top element
print(""\nTop element is "", stack.top())
# Print the stack size
print(""Size of the stack is "", stack.size())
# pop the top element
stack.pop()
# pop the top element
stack.pop()
# two elements are popped
# Print the stack
stack.printstack()
# Print True if the stack is empty else False
print(""\nstack is empty:"", stack.isEmpty())
#This code is added by Suparna Raut"
2224,Different ways to convert a Python dictionary to a NumPy array,"# importing required librariess
import numpy as np
from ast import literal_eval
# creating class of string
name_list = """"""{
""column0"": {""First_Name"": ""Akash"",
""Second_Name"": ""kumar"", ""Interest"": ""Coding""},
""column1"": {""First_Name"": ""Ayush"",
""Second_Name"": ""Sharma"", ""Interest"": ""Cricket""},
""column2"": {""First_Name"": ""Diksha"",
""Second_Name"": ""Sharma"",""Interest"": ""Reading""},
""column3"": {""First_Name"":"" Priyanka"",
""Second_Name"": ""Kumari"", ""Interest"": ""Dancing""}
}""""""
print(""Type of name_list created:\n"",
type(name_list))
# converting string type to dictionary
t = literal_eval(name_list)
# printing the original dictionary
print(""\nPrinting the original Name_list dictionary:\n"",
t)
print(""Type of original dictionary:\n"",
type(t))
# converting dictionary to numpy array
result_nparra = np.array([[v[j] for j in ['First_Name', 'Second_Name',
'Interest']] for k, v in t.items()])
print(""\nConverted ndarray from the Original dictionary:\n"",
result_nparra)
# printing the type of converted array
print(""Type:\n"", type(result_nparra))"
2225,Write a Python Set | Check whether a given string is Heterogram or not,"# Function to Check whether a given string is Heterogram or not
def heterogram(input):
# separate out list of alphabets using list comprehension
# ord function returns ascii value of character
alphabets = [ ch for ch in input if ( ord(ch) >= ord('a') and ord(ch) <= ord('z') )]
# convert list of alphabets into set and
# compare lengths
if len(set(alphabets))==len(alphabets):
print ('Yes')
else:
print ('No')
# Driver program
if __name__ == ""__main__"":
input = 'the big dwarf only jumps'
heterogram(input)"
2226,How to find the number of arguments in a Python function,"def no_of_argu(*args):
# using len() method in args to count
return(len(args))
a = 1
b = 3
# arguments passed
n = no_of_argu(1, 2, 4, a)
# result printed
print("" The number of arguments are: "", n)"
2227,Return the Index label if some condition is satisfied over a column in Pandas Dataframe in Python,"# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'],
'Last_Price':[1200, 1500, 1600, 352],
'Updated_Price':[1250, 1450, 1550, 400],
'Discount':[10, 10, 10, 10]})
# Create the indexes
df.index =['Item 1', 'Item 2', 'Item 3', 'Item 4']
# Print the dataframe
print(df)"
2228,Program to check if a string contains any special character in Python,"// C++ program to check if a string
// contains any special character
// import required packages
#include
#include
using namespace std;
// Function checks if the string
// contains any special character
void run(string str)
{
// Make own character set
regex regx(""[@_!#$%^&*()<>?/|}{~:]"");
// Pass the string in regex_search
// method
if(regex_search(str, regx) == 0)
cout << ""String is accepted"";
else
cout << ""String is not accepted."";
}
// Driver Code
int main()
{
// Enter the string
string str = ""Geeks$For$Geeks"";
// Calling run function
run(str);
return 0;
}
// This code is contributed by Yash_R"
2229,Convert Python datetime to epoch,"# import datetime module
import datetime
# convert datetime to epoch using strftime from
# time stamp 2021/7/7/1/2/1
# for linux:
epoch = datetime.datetime(2021, 7, 7, 1, 2, 1).strftime('%s')
# for windows:
# epoch = datetime.datetime(2021, 7,7 , 1,2,1).strftime('%S')
print(epoch)
# convert datetime to epoch using strftime from
# time stamp 2021/3/3/4/3/4
epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).strftime('%s')
print(epoch)
# convert datetime to epoch using strftime from
# time stamp 2021/7/7/12/12/34
epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).strftime('%s')
print(epoch)
# convert datetime to epoch using strftime from
# time stamp 2021/7/7/12/56/00
epoch = datetime.datetime(2021, 7, 7, 12, 56, 0).strftime('%s')
print(epoch)"
2230,How to get the Daily News using Python,"import requests
from bs4 import BeautifulSoup"
2231,Convert Set to String in Python,"# create a set
s = {'a', 'b', 'c', 'd'}
print(""Initially"")
print(""The datatype of s : "" + str(type(s)))
print(""Contents of s : "", s)
# convert Set to String
s = str(s)
print(""\nAfter the conversion"")
print(""The datatype of s : "" + str(type(s)))
print(""Contents of s : "" + s)"
2232,Write a Python Program to print all Possible Combinations from the three Digits,"# Python program to print all
# the possible combinations
def comb(L):
for i in range(3):
for j in range(3):
for k in range(3):
# check if the indexes are not
# same
if (i!=j and j!=k and i!=k):
print(L[i], L[j], L[k])
# Driver Code
comb([1, 2, 3])"
2233,Write a Python program to Check if String Contain Only Defined Characters using Regex,"# _importing module
import re
def check(str, pattern):
# _matching the strings
if re.search(pattern, str):
print(""Valid String"")
else:
print(""Invalid String"")
# _driver code
pattern = re.compile('^[1234]+$')
check('2134', pattern)
check('349', pattern)"
2234,Write a Python program to Maximum and Minimum in a Set,"# Python code to get the maximum element from a set
def MAX(sets):
return (max(sets))
# Driver Code
sets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])
print(MAX(sets))"
2235,Remove all duplicates from a given string in Python,"from collections import OrderedDict
# Function to remove all duplicates from string
# and order does not matter
def removeDupWithoutOrder(str):
# set() --> A Set is an unordered collection
# data type that is iterable, mutable,
# and has no duplicate elements.
# """".join() --> It joins two adjacent elements in
# iterable with any symbol defined in
# """" ( double quotes ) and returns a
# single string
return """".join(set(str))
# Function to remove all duplicates from string
# and keep the order of characters same
def removeDupWithOrder(str):
return """".join(OrderedDict.fromkeys(str))
# Driver program
if __name__ == ""__main__"":
str = ""geeksforgeeks""
print (""Without Order = "",removeDupWithoutOrder(str))
print (""With Order = "",removeDupWithOrder(str)) "
2236,Write a Python Program for Iterative Merge Sort,"# Recursive Python Program for merge sort
def merge(left, right):
if not len(left) or not len(right):
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
def mergesort(list):
if len(list) < 2:
return list
middle = len(list)/2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
seq = [12, 11, 13, 5, 6, 7]
print(""Given array is"")
print(seq);
print(""\n"")
print(""Sorted array is"")
print(mergesort(seq))
# Code Contributed by Mohit Gupta_OMG "
2237,Repeat all the elements of a NumPy array of strings in Python,"# importing the module
import numpy as np
# created array of strings
arr = np.array(['Akash', 'Rohit', 'Ayush',
'Dhruv', 'Radhika'], dtype = np.str)
print(""Original Array :"")
print(arr)
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 3)
print(""\nNew array :"")
print(new_array)"
2238,Write a Python Program to Reverse Every Kth row in a Matrix,"# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using reversed() + loop
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
[3, 6], [3, 7, 4], [2, 9]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 3
res = []
for idx, ele in enumerate(test_list):
# checking for K multiple
if (idx + 1) % K == 0:
# reversing using reversed
res.append(list(reversed(ele)))
else:
res.append(ele)
# printing result
print(""After reversing every Kth row: "" + str(res))"
2239,How to scrape multiple pages using Selenium in Python,"# importing necessary packages
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# for holding the resultant list
element_list = []
for page in range(1, 3, 1):
page_url = ""https://webscraper.io/test-sites/e-commerce/static/computers/laptops?page="" + str(page)
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(page_url)
title = driver.find_elements_by_class_name(""title"")
price = driver.find_elements_by_class_name(""price"")
description = driver.find_elements_by_class_name(""description"")
rating = driver.find_elements_by_class_name(""ratings"")
for i in range(len(title)):
element_list.append([title[i].text, price[i].text, description[i].text, rating[i].text])
print(element_list)
#closing the driver
driver.close()"
2240,Write a Python program to Order Tuples by List,"# Python3 code to demonstrate working of
# Order Tuples by List
# Using dict() + list comprehension
# initializing list
test_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing order list
ord_list = ['Geeks', 'best', 'CS', 'Gfg']
# Order Tuples by List
# Using dict() + list comprehension
temp = dict(test_list)
res = [(key, temp[key]) for key in ord_list]
# printing result
print(""The ordered tuple list : "" + str(res)) "
2241,Write a Python program to select Random value form list of lists,"# Python3 code to demonstrate working of
# Random Matrix Element
# Using chain.from_iterables() + random.choice()
from itertools import chain
import random
# initializing list
test_list = [[4, 5, 5], [2, 7, 4], [8, 6, 3]]
# printing original list
print(""The original list is : "" + str(test_list))
# choice() for random number, from_iterables for flattening
res = random.choice(list(chain.from_iterable(test_list)))
# printing result
print(""Random number from Matrix : "" + str(res))"
2242,Write a Python program to Check if a given string is binary string or not,"# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string) :
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {'0', '1'}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {'0'} or p == {'1'}:
print(""Yes"")
else :
print(""No"")
# driver code
if __name__ == ""__main__"" :
string = ""101010000111""
# function calling
check(string)"
2243,How to make a NumPy array read-only in Python,"import numpy as np
a = np.zeros(11)
print(""Before any change "")
print(a)
a[1] = 2
print(""Before after first change "")
print(a)
a.flags.writeable = False
print(""After making array immutable on attempting second change "")
a[1] = 7"
2244,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)) "
2245,Limited rows selection with given column in Pandas | Python,"# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# select three rows and two columns
print(df.loc[1:3, ['Name', 'Qualification']])"
2246,Write a Python program to print Pascal’s Triangle,"# Print Pascal's Triangle in Python
from math import factorial
# input n
n = 5
for i in range(n):
for j in range(n-i+1):
# for left spacing
print(end="" "")
for j in range(i+1):
# nCr = n!/((n-r)!*r!)
print(factorial(i)//(factorial(j)*factorial(i-j)), end="" "")
# for new line
print()"
2247,How to Extract Wikipedia Data in Python,"import wikipedia
wikipedia.summary(""Python (programming language)"")"
2248,Get all rows in a Pandas DataFrame containing given substring in Python,"# importing pandas
import pandas as pd
# Creating the dataframe with dict of lists
df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'],
'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'],
'Position': ['PG', 'PG', 'UG', 'PG', 'UG'],
'Number': [3, 4, 7, 11, 5],
'Age': [33, 25, 34, 35, 28],
'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'],
'Weight': [89, 79, 113, 78, 84],
'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'],
'Salary': [99999, 99994, 89999, 78889, 87779]},
index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5'])
print(df, ""\n"")
print(""Check PG values in Position column:\n"")
df1 = df['Position'].str.contains(""PG"")
print(df1)"
2249,Write a Python program to Filter Strings combination of K substrings,"# Python3 code to demonstrate working of
# Filter Strings combination of K substrings
# Using permutations() + map() + join() + set() + loop
from itertools import permutations
# initializing list
test_list = [""geeks4u"", ""allbest"", ""abcdef""]
# printing string
print(""The original list : "" + str(test_list))
# initializing substring list
substr_list = [""s4u"", ""est"", ""al"", ""ge"", ""ek"", ""def"", ""lb""]
# initializing K
K = 3
# getting all permutations
perms = list(set(map(''.join, permutations(substr_list, r = K))))
# using loop to check permutations with list
res = []
for ele in perms:
if ele in test_list:
res.append(ele)
# printing results
print(""Strings after joins : "" + str(res))"
2250,Scrape and Save Table Data in CSV file using Selenium in Python,"from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
import pandas as pd
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import csv"
2251,Program to print window pattern in Python,"// C++ program to print the pattern
// hollow square with plus inside it
// window pattern
#include
using namespace std;
// Function to print pattern n means
// number of rows which we want
void window_pattern (int n)
{
int c, d;
// If n is odd then we will have
// only one middle element
if (n % 2 != 0)
{
c = (n / 2) + 1;
d = 0;
}
// If n is even then we will have two
// values
else
{
c = (n / 2) + 1;
d = n / 2 ;
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
// If i,j equals to corner row or
// column then ""*""
if (i == 1 || j == 1 ||
i == n || j == n)
cout << ""* "";
else
{
// If i,j equals to the middle
// row or column then ""*""
if (i == c || j == c)
cout << ""* "";
else if (i == d || j == d)
cout << ""* "";
else
cout << "" "";
}
}
cout << '\n';
}
}
// Driver Code
int main()
{
int n = 7;
window_pattern(n);
return 0;
}
// This code is contributed by himanshu77"
2252,Lambda expression in Python to rearrange positive and negative numbers,"# Function to rearrange positive and negative elements
def Rearrange(arr):
# First lambda expression returns list of negative numbers
# in arr.
# Second lambda expression returns list of positive numbers
# in arr.
return [x for x in arr if x < 0] + [x for x in arr if x >= 0]
# Driver function
if __name__ == ""__main__"":
arr = [12, 11, -13, -5, 6, -7, 5, -3, -6]
print (Rearrange(arr))"
2253,Write a Python program to Sort by Frequency of second element in Tuple List,"# Python3 code to demonstrate working of
# Sort by Frequency of second element in Tuple List
# Using sorted() + loop + defaultdict() + lambda
from collections import defaultdict
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
# printing original list
print(""The original list is : "" + str(test_list))
# constructing mapping
freq_map = defaultdict(int)
for idx, val in test_list:
freq_map[val] += 1
# performing sort of result
res = sorted(test_list, key = lambda ele: freq_map[ele[1]], reverse = True)
# printing results
print(""Sorted List of tuples : "" + str(res))"
2254,Write a Python program to count Even and Odd numbers in a List,"# Python program to count Even
# and Odd numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print(""Even numbers in the list: "", even_count)
print(""Odd numbers in the list: "", odd_count)"
2255,Write a Python program to Test if List contains elements in Range,"# Python3 code to demonstrate
# Test if List contains elements in Range
# using loop
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print(""The original list is : "" + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using loop
res = True
for ele in test_list:
if ele < i or ele >= j :
res = False
break
# printing result
print (""Does list contain all elements in range : "" + str(res))"
2256,Select row with maximum and minimum value in Pandas dataframe in Python,"# importing pandas and numpy
import pandas as pd
import numpy as np
# data of 2018 drivers world championship
dict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen',
'Verstappen', 'Bottas', 'Ricciardo',
'Hulkenberg', 'Perez', 'Magnussen',
'Sainz', 'Alonso', 'Ocon', 'Leclerc',
'Grosjean', 'Gasly', 'Vandoorne',
'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'],
'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56,
53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1],
'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37,
22, 21, 32, 22, 26, 28, 20, 29, 23]}
# creating dataframe using DataFrame constructor
df = pd.DataFrame(dict1)
print(df.head(10))"
2257,"Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even in Python","// C++ program for
// the above approach
#include
using namespace std;
void sub_mat_even(int N)
{
// Counter to initialize
// the values in 2-D array
int K = 1;
// To create a 2-D array
// from to 1 to N*2
int A[N][N];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
A[i][j] = K;
K++;
}
}
// If found even we reverse
// the alternate row elements
// to get all diagonal elements
// as all even or all odd
if(N % 2 == 0)
{
for(int i = 0; i < N; i++)
{
if(i % 2 == 1)
{
int s = 0;
int l = N - 1;
// Reverse the row
while(s < l)
{
swap(A[i][s],
A[i][l]);
s++;
l--;
}
}
}
}
// Print the formed array
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cout << A[i][j] << "" "";
}
cout << endl;
}
}
// Driver code
int main()
{
int N = 4;
// Function call
sub_mat_even(N);
}
// This code is contributed by mishrapriyanshu557"
2258,Write a Python program to Swap commas and dots in a String,"# Python code to replace, with . and vice-versa
def Replace(str1):
maketrans = str1.maketrans
final = str1.translate(maketrans(',.', '.,', ' '))
return final.replace(',', "", "")
# Driving Code
string = ""14, 625, 498.002""
print(Replace(string))"
2259,Write a Python program to Filter Range Length Tuples,"# Python3 code to demonstrate working of
# Filter Range Length Tuples
# Using list comprehension + len()
# Initializing list
test_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
# printing original list
print(""The original list is : "" + str(test_list))
# Initializing desired lengths
i, j = 2, 3
# Filter Range Length Tuples
# Using list comprehension + len()
res = [sub for sub in test_list if len(sub) >= i and len(sub) <= j]
# printing result
print(""The tuple list after filtering range records : "" + str(res))"
2260,How to rename columns in Pandas DataFrame in Python,"# Import pandas package
import pandas as pd
# Define a dictionary containing ICC rankings
rankings = {'test': ['India', 'South Africa', 'England',
'New Zealand', 'Australia'],
'odi': ['England', 'India', 'New Zealand',
'South Africa', 'Pakistan'],
't20': ['Pakistan', 'India', 'Australia',
'England', 'New Zealand']}
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
# Before renaming the columns
print(rankings_pd)
rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)
# After renaming the columns
print(""\nAfter modifying first column:\n"", rankings_pd.columns)"
2261,Write a Python program to print all positive numbers in a range,"# Python program to print positive Numbers in given range
start, end = -4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num >= 0:
print(num, end = "" "")"
2262,Write a Python program to Numpy matrix.round(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[6.4, 1.3; 12.7, 32.3]')
# applying matrix.round() method
geeks = gfg.round()
print(geeks)"
2263,Write a Python program to Elements frequency in Tuple,"# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using defaultdict()
from collections import defaultdict
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
res = defaultdict(int)
for ele in test_tup:
# incrementing frequency
res[ele] += 1
# printing result
print(""Tuple elements frequency is : "" + str(dict(res)))"
2264,Get n-smallest values from a particular column in Pandas DataFrame in Python,"# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
df.head(10)"
2265,Write a Python program to Retain records with N occurrences of K,"# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + list comprehension
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() + list comprehension
res = [ele for ele in test_list if ele.count(K) == N]
# printing result
print(""Filtered tuples : "" + str(res))"
2266,numpy matrix operations | rand() function in Python,"# Python program explaining
# numpy.matlib.rand() function
# importing matrix library from numpy
import numpy as geek
import numpy.matlib
# desired 3 x 4 random output matrix
out_mat = geek.matlib.rand((3, 4))
print (""Output matrix : "", out_mat) "
2267,Write a Python program to Convert list of nested dictionary into Pandas dataframe,"# importing pandas
import pandas as pd
# List of nested dictionary initialization
list = [
{
""Student"": [{""Exam"": 90, ""Grade"": ""a""},
{""Exam"": 99, ""Grade"": ""b""},
{""Exam"": 97, ""Grade"": ""c""},
],
""Name"": ""Paras Jain""
},
{
""Student"": [{""Exam"": 89, ""Grade"": ""a""},
{""Exam"": 80, ""Grade"": ""b""}
],
""Name"": ""Chunky Pandey""
}
]
#print(list)"
2268,Write a Python program to Swapping Hierarchy in Nested Dictionaries,"# Python3 code to demonstrate working of
# Swapping Hierarchy in Nested Dictionaries
# Using loop + items()
# initializing dictionary
test_dict = {'Gfg': { 'a' : [1, 3], 'b' : [3, 6], 'c' : [6, 7, 8]},
'Best': { 'a' : [7, 9], 'b' : [5, 3, 2], 'd' : [0, 1, 0]}}
# printing original dictionary
print(""The original dictionary : "" + str(test_dict))
# Swapping Hierarchy in Nested Dictionaries
# Using loop + items()
res = dict()
for key, val in test_dict.items():
for key_in, val_in in val.items():
if key_in not in res:
temp = dict()
else:
temp = res[key_in]
temp[key] = val_in
res[key_in] = temp
# printing result
print(""The rearranged dictionary : "" + str(res))"
2269,How to get all 2D diagonals of a 3D NumPy array in Python,"# Import the numpy package
import numpy as np
# Create 3D-numpy array
# of 4 rows and 4 columns
arr = np.arange(3 * 4 * 4).reshape(3, 4, 4)
print(""Original 3d array:\n"",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print(""2d diagonal array:\n"",
diag_arr)"
2270,Write a Python Counter to find the size of largest subset of anagram words,"# Function to find the size of largest subset
# of anagram words
from collections import Counter
def maxAnagramSize(input):
# split input string separated by space
input = input.split("" "")
# sort each string in given list of strings
for i in range(0,len(input)):
input[i]=''.join(sorted(input[i]))
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
freqDict = Counter(input)
# get maximum value of frequency
print (max(freqDict.values()))
# Driver program
if __name__ == ""__main__"":
input = 'ant magenta magnate tan gnamate'
maxAnagramSize(input)"
2271,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"
2272,How to Convert an image to NumPy array and saveit to CSV file using Python,"# import required libraries
from PIL import Image
import numpy as gfg
# read an image
img = Image.open('geeksforgeeks.jpg')
# convert image object into array
imageToMatrice = gfg.asarray(img)
# printing shape of image
print(imageToMatrice.shape)"
2273,Write a Python program to build flashcard using class in Python,"class flashcard:
def __init__(self, word, meaning):
self.word = word
self.meaning = meaning
def __str__(self):
#we will return a string
return self.word+' ( '+self.meaning+' )'
flash = []
print(""welcome to flashcard application"")
#the following loop will be repeated until
#user stops to add the flashcards
while(True):
word = input(""enter the name you want to add to flashcard : "")
meaning = input(""enter the meaning of the word : "")
flash.append(flashcard(word, meaning))
option = int(input(""enter 0 , if you want to add another flashcard : ""))
if(option):
break
# printing all the flashcards
print(""\nYour flashcards"")
for i in flash:
print("">"", i)"
2274,Write a Python program to Divide date range to N equal duration,"# Python3 code to demonstrate working of
# Convert date range to N equal durations
# Using loop
import datetime
# initializing dates
test_date1 = datetime.datetime(1997, 1, 4)
test_date2 = datetime.datetime(1997, 1, 30)
# printing original dates
print(""The original date 1 is : "" + str(test_date1))
print(""The original date 2 is : "" + str(test_date2))
# initializing N
N = 7
temp = []
# getting diff.
diff = ( test_date2 - test_date1) // N
for idx in range(0, N):
# computing new dates
temp.append((test_date1 + idx * diff))
# using strftime to convert to userfriendly
# format
res = []
for sub in temp:
res.append(sub.strftime(""%Y/%m/%d %H:%M:%S""))
# printing result
print(""N equal duration dates : "" + str(res))"
2275,How to create multiple CSV files from existing CSV file using Pandas in Python,"import pandas as pd
# initialise data dictionary.
data_dict = {'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Gender': [""Male"", ""Female"", ""Female"", ""Male"",
""Male"", ""Female"", ""Male"", ""Male"",
""Female"", ""Male""],
'Age': [20, 21, 19, 18, 25, 26, 32, 41, 20, 19],
'Annual Income(k$)': [10, 20, 30, 10, 25, 60, 70,
15, 21, 22],
'Spending Score': [30, 50, 48, 84, 90, 65, 32, 46,
12, 56]}
# Create DataFrame
data = pd.DataFrame(data_dict)
# Write to CSV file
data.to_csv(""Customers.csv"")
# Print the output.
print(data)"
2276,Change Data Type for one or more columns in Pandas Dataframe in Python,"# importing pandas as pd
import pandas as pd
# sample dataframe
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [1.1, '1.0', '1.3', 2, 5] })
# converting all columns to string type
df = df.astype(str)
print(df.dtypes)"
2277,Convert Text file to JSON in Python,"# Python program to convert text
# file to JSON
import json
# the file to be converted to
# json format
filename = 'data.txt'
# dictionary where the lines from
# text will be stored
dict1 = {}
# creating dictionary
with open(filename) as fh:
for line in fh:
# reads each line and trims of extra the spaces
# and gives only the valid words
command, description = line.strip().split(None, 1)
dict1[command] = description.strip()
# creating json file
# the JSON file is named as test1
out_file = open(""test1.json"", ""w"")
json.dump(dict1, out_file, indent = 4, sort_keys = False)
out_file.close()"
2278,Write a Python program to Read CSV Columns Into List,"# importing module
from pandas import *
# reading CSV file
data = read_csv(""company_sales_data.csv"")
# converting column data to list
month = data['month_number'].tolist()
fc = data['facecream'].tolist()
fw = data['facewash'].tolist()
tp = data['toothpaste'].tolist()
sh = data['shampoo'].tolist()
# printing list data
print('Facecream:', fc)
print('Facewash:', fw)
print('Toothpaste:', tp)
print('Shampoo:', sh)"
2279,Write a Python program to Search an Element in a Circular Linked List,"# Python program to Search an Element
# in a Circular Linked List
# Class to define node of the linked list
class Node:
def __init__(self,data):
self.data = data;
self.next = None;
class CircularLinkedList:
# Declaring Circular Linked List
def __init__(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
# Adds new nodes to the Circular Linked List
def add(self,data):
# Declares a new node to be added
newNode = Node(data);
# Checks if the Circular
# Linked List is empty
if self.head.data is None:
# If list is empty then new node
# will be the first node
# to be added in the Circular Linked List
self.head = newNode;
self.tail = newNode;
newNode.next = self.head;
else:
# If a node is already present then
# tail of the last node will point to
# new node
self.tail.next = newNode;
# New node will become new tail
self.tail = newNode;
# New Tail will point to the head
self.tail.next = self.head;
# Function to search the element in the
# Circular Linked List
def findNode(self,element):
# Pointing the head to start the search
current = self.head;
i = 1;
# Declaring f = 0
f = 0;
# Check if the list is empty or not
if(self.head == None):
print(""Empty list"");
else:
while(True):
# Comparing the elements
# of each node to the
# element to be searched
if(current.data == element):
# If the element is present
# then incrementing f
f += 1;
break;
# Jumping to next node
current = current.next;
i = i + 1;
# If we reach the head
# again then element is not
# present in the list so
# we will break the loop
if(current == self.head):
break;
# Checking the value of f
if(f > 0):
print(""element is present"");
else:
print(""element is not present"");
# Driver Code
if __name__ == '__main__':
# Creating a Circular Linked List
'''
Circular Linked List we will be working on:
1 -> 2 -> 3 -> 4 -> 5 -> 6
'''
circularLinkedList = CircularLinkedList();
#Adding nodes to the list
circularLinkedList.add(1);
circularLinkedList.add(2);
circularLinkedList.add(3);
circularLinkedList.add(4);
circularLinkedList.add(5);
circularLinkedList.add(6);
# Searching for node 2 in the list
circularLinkedList.findNode(2);
#Searching for node in the list
circularLinkedList.findNode(7);"
2280,Isoformat to datetime – Python,"# importing datetime module
from datetime import datetime
# Getting today's date
todays_Date = datetime.now()
# Get date into the isoformat
isoformat_date = todays_Date.isoformat()
# print the type of date
print(type(isoformat_date))
# convert string date into datetime format
result = datetime.fromisoformat(isoformat_date)
print(type(result))"
2281,Drop rows from the dataframe based on certain condition applied on a column in Python,"# importing pandas as pd
import pandas as pd
# Read the csv file and construct the
# dataframe
df = pd.read_csv('nba.csv')
# Visualize the dataframe
print(df.head(15)
# Print the shape of the dataframe
print(df.shape)"
2282,Categorize Password as Strong or Weak using Regex in Python,"# Categorizing password as Strong or
# Weak in Python using Regex
import re
# Function to categorize password
def password(v):
# the password should not be a
# newline or space
if v == ""\n"" or v == "" "":
return ""Password cannot be a newline or space!""
# the password length should be in
# between 9 and 20
if 9 <= len(v) <= 20:
# checks for occurrence of a character
# three or more times in a row
if re.search(r'(.)\1\1', v):
return ""Weak Password: Same character repeats three or more times in a row""
# checks for occurrence of same string
# pattern( minimum of two character length)
# repeating
if re.search(r'(..)(.*?)\1', v):
return ""Weak password: Same string pattern repetition""
else:
return ""Strong Password!""
else:
return ""Password length must be 9-20 characters!""
# Main method
def main():
# Driver code
print(password(""Qggf!@ghf3""))
print(password(""Gggksforgeeks""))
print(password(""aaabnil1gu""))
print(password(""Aasd!feasn""))
print(password(""772*hd897""))
print(password("" ""))
# Driver Code
if __name__ == '__main__':
main()"
2283,Create a Pandas Series from array in Python,"# importing Pandas & numpy
import pandas as pd
import numpy as np
# numpy array
data = np.array(['a', 'b', 'c', 'd', 'e'])
# creating series
s = pd.Series(data)
print(s)"
2284,Write a Python program to Find the Number Occurring Odd Number of Times using Lambda expression and reduce function,"# Python program to Find the Number
# Occurring Odd Number of Times
# using Lambda expression and reduce function
from functools import reduce
def oddTimes(input):
# write lambda expression and apply
# reduce function over input list
# until single value is left
# expression reduces value of a ^ b into single value
# a starts from 0 and b from 1
# ((((((1 ^ 2)^3)^2)^3)^1)^3)
print (reduce(lambda a, b: a ^ b, input))
# Driver program
if __name__ == ""__main__"":
input = [1, 2, 3, 2, 3, 1, 3]
oddTimes(input)"
2285,Possible Words using given characters in Python,"# Function to print words which can be created
# using given set of characters
def charCount(word):
dict = {}
for i in word:
dict[i] = dict.get(i, 0) + 1
return dict
def possible_words(lwords, charSet):
for word in lwords:
flag = 1
chars = charCount(word)
for key in chars:
if key not in charSet:
flag = 0
else:
if charSet.count(key) != chars[key]:
flag = 0
if flag == 1:
print(word)
if __name__ == ""__main__"":
input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
possible_words(input, charSet)"
2286,Write a Python program to Custom sorting in list of tuples,"# Python3 code to demonstrate working of
# Custom sorting in list of tuples
# Using sorted() + lambda
# Initializing list
test_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
# printing original list
print(""The original list is : "" + str(test_list))
# Custom sorting in list of tuples
# Using sorted() + lambda
res = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))
# printing result
print(""The tuple after custom sorting is : "" + str(res))"
2287,Write a Python program to Skew Nested Tuple Summation,"# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using infinite loop
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
res = 0
while test_tup:
res += test_tup[0]
# assigning inner tuple as original
test_tup = test_tup[1]
# printing result
print(""Summation of 1st positions : "" + str(res)) "
2288,Write a Python program to Filter Tuples by Kth element from List,"# Python3 code to demonstrate working of
# Filter Tuples by Kth element from List
# Using list comprehension
# initializing list
test_list = [(""GFg"", 5, 9), (""is"", 4, 3), (""best"", 10, 29)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing check_list
check_list = [4, 2, 8, 10]
# initializing K
K = 1
# checking for presence on Kth element in list
# one liner
res = [sub for sub in test_list if sub[K] in check_list]
# printing result
print(""The filtered tuples : "" + str(res))"
2289,How to get list of parameters name from a function in Python,"# import required modules
import inspect
import collections
# use signature()
print(inspect.signature(collections.Counter))"
2290,Different ways to clear a list in Python,"# Python program to clear a list
# using clear() method
# Creating list
GEEK = [6, 0, 4, 1]
print('GEEK before clear:', GEEK)
# Clearing list
GEEK.clear()
print('GEEK after clear:', GEEK) "
2291,Write a Python program to extract Strings between HTML Tags,"# importing re module
import re
# initializing string
test_str = 'Gfg is Best. I love Reading CS from it.'
# printing original string
print(""The original string is : "" + str(test_str))
# initializing tag
tag = ""b""
# regex to extract required strings
reg_str = ""<"" + tag + "">(.*?)"" + tag + "">""
res = re.findall(reg_str, test_str)
# printing result
print(""The Strings extracted : "" + str(res))"
2292,Rename a folder of images using Tkinter in Python,"# Python 3 code to rename multiple image
# files in a directory or folder
import os
from tkinter import messagebox
import cv2
from tkinter import filedialog
from tkinter import *
height1 = 0
width1 = 0
# Function to select folder to rename images
def get_folder_path():
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
return folder_selected
# Function to rename multiple files
def submit():
source = src_dir.get()
src_dir.set("""")
global width1
global height1
input_folder = get_folder_path()
i = 0
for img_file in os.listdir(input_folder):
file_name = os.path.splitext(img_file)[0]
extension = os.path.splitext(img_file)[1]
if extension == '.jpg':
src = os.path.join(input_folder, img_file)
img = cv2.imread(src)
h, w, c = img.shape
dst = source + '-' + str(i) + '-' + str(w) + ""x"" + str(h) + "".jpg""
dst = os.path.join(input_folder, dst)
# rename() function will rename all the files
os.rename(src, dst)
i += 1
messagebox.showinfo(""Done"", ""All files renamed successfully !!"")
# Driver Code
if __name__ == '__main__':
top = Tk()
top.geometry(""450x300"")
top.title(""Image Files Renamer"")
top.configure(background =""Dark grey"")
# For Input Label
input_path = Label(top,
text =""Enter Name to Rename files:"",
bg =""Dark grey"").place(x = 40, y = 60)
# For Input Textbox
src_dir = StringVar()
input_path_entry_area = Entry(top,
textvariable = src_dir,
width = 50).place(x = 40, y = 100)
# For submit button
submit_button = Button(top,
text =""Submit"",
command = submit).place(x = 200, y = 150)
top.mainloop()"
2293,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)"
2294,Write a Python program to Numpy matrix.sort(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1; 12, 3]')
# applying matrix.sort() method
gfg.sort()
print(gfg)"
2295,Write a Python program to Group Elements in Matrix,"# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using dictionary comprehension + loop
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
# printing original list
print(""The original list : "" + str(test_list))
# initializing empty dictionary with default empty list
res = {idx[0]: [] for idx in test_list}
# using loop for grouping
for idx in test_list:
res[idx[0]].append(idx[1])
# printing result
print(""The Grouped Matrix : "" + str(res))"
2296,Write a Python Program to Convert String Matrix Representation to Matrix,"import re
# initializing string
test_str = ""[gfg,is],[best,for],[all,geeks]""
# printing original string
print(""The original string is : "" + str(test_str))
flat_1 = re.findall(r""\[(.+?)\]"", test_str)
res = [sub.split("","") for sub in flat_1]
# printing result
print(""The type of result : "" + str(type(res)))
print(""Converted Matrix : "" + str(res))"
2297,How to get selected value from listbox in tkinter in Python,"# Python3 program to get selected
# value(s) from tkinter listbox
# Import tkinter
from tkinter import *
# Create the root window
root = Tk()
root.geometry('180x200')
# Create a listbox
listbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE)
# Inserting the listbox items
listbox.insert(1, ""Data Structure"")
listbox.insert(2, ""Algorithm"")
listbox.insert(3, ""Data Science"")
listbox.insert(4, ""Machine Learning"")
listbox.insert(5, ""Blockchain"")
# Function for printing the
# selected listbox value(s)
def selected_item():
# Traverse the tuple returned by
# curselection method and print
# corresponding value(s) in the listbox
for i in listbox.curselection():
print(listbox.get(i))
# Create a button widget and
# map the command parameter to
# selected_item function
btn = Button(root, text='Print Selected', command=selected_item)
# Placing the button and listbox
btn.pack(side='bottom')
listbox.pack()
root.mainloop()"
2298,Write a Python program to Modulo of tuple elements,"# Python3 code to demonstrate working of
# Tuple modulo
# using zip() + generator expression
# initialize tuples
test_tup1 = (10, 4, 5, 6)
test_tup2 = (5, 6, 7, 5)
# printing original tuples
print(""The original tuple 1 : "" + str(test_tup1))
print(""The original tuple 2 : "" + str(test_tup2))
# Tuple modulo
# using zip() + generator expression
res = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
# printing result
print(""The modulus tuple : "" + str(res))"
2299,Write a Python Script to change name of a file to its timestamp,"import time
import os
# Getting the path of the file
f_path = ""/location/to/gfg.png""
# Obtaining the creation time (in seconds)
# of the file/folder (datatype=int)
t = os.path.getctime(f_path)
# Converting the time to an epoch string
# (the output timestamp string would
# be recognizable by strptime() without
# format quantifers)
t_str = time.ctime(t)
# Converting the string to a time object
t_obj = time.strptime(t_str)
# Transforming the time object to a timestamp
# of ISO 8601 format
form_t = time.strftime(""%Y-%m-%d %H:%M:%S"", t_obj)
# Since colon is an invalid character for a
# Windows file name Replacing colon with a
# similar looking symbol found in unicode
# Modified Letter Colon "" "" (U+A789)
form_t = form_t.replace("":"", ""꞉"")
# Renaming the filename to its timestamp
os.rename(
f_path, os.path.split(f_path)[0] + '/' + form_t + os.path.splitext(f_path)[1])"
2300,Write a Python program to count Even and Odd numbers in a List,"# Python program to count Even
# and Odd numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print(""Even numbers in the list: "", even_count)
print(""Odd numbers in the list: "", odd_count)"
2301,Write a Python program to Frequency of numbers in String,"# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + len()
import re
# initializing string
test_str = ""geeks4feeks is No. 1 4 geeks""
# printing original string
print(""The original string is : "" + test_str)
# Frequency of numbers in String
# Using re.findall() + len()
res = len(re.findall(r'\d+', test_str))
# printing result
print(""Count of numerics in string : "" + str(res)) "
2302,Write a Python Program to Sort the list according to the column using lambda,"# Python code to sorting list
# according to the column
# sortarray function is defined
def sortarray(array):
for i in range(len(array[0])):
# sorting array in ascending
# order specific to column i,
# here i is the column index
sortedcolumn = sorted(array, key = lambda x:x[i])
# After sorting array Column 1
print(""Sorted array specific to column {}, \
{}"".format(i, sortedcolumn))
# Driver code
if __name__ == '__main__':
# array of size 3 X 2
array = [['java', 1995], ['c++', 1983],
['python', 1989]]
# passing array in sortarray function
sortarray(array)"
2303,Reversing a List in Python,"# Reversing a list using reversed()
def Reverse(lst):
return [ele for ele in reversed(lst)]
# Driver Code
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))"
2304,Dictionary and counter in Python to find winner of election,"# Function to find winner of an election where votes
# are represented as candidate names
from collections import Counter
def winner(input):
# convert list of candidates into dictionary
# output will be likes candidates = {'A':2, 'B':4}
votes = Counter(input)
# create another dictionary and it's key will
# be count of votes values will be name of
# candidates
dict = {}
for value in votes.values():
# initialize empty list to each key to
# insert candidate names having same
# number of votes
dict[value] = []
for (key,value) in votes.items():
dict[value].append(key)
# sort keys in descending order to get maximum
# value of votes
maxVote = sorted(dict.keys(),reverse=True)[0]
# check if more than 1 candidates have same
# number of votes. If yes, then sort the list
# first and print first element
if len(dict[maxVote])>1:
print (sorted(dict[maxVote])[0])
else:
print (dict[maxVote][0])
# Driver program
if __name__ == ""__main__"":
input =['john','johnny','jackie','johnny',
'john','jackie','jamie','jamie',
'john','johnny','jamie','johnny',
'john']
winner(input)"
2305,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()"
2306,How to convert a list and tuple into NumPy arrays in Python,"import numpy as np
# list
list1 = [3, 4, 5, 6]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.asarray(list1)
print(type(array1))
print(array1)
print()
# tuple
tuple1 = ([8, 4, 6], [1, 2, 3])
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.asarray(tuple1)
print(type(array2))
print(array2)"
2307,Write a Python program to find largest number in a list,"# Python program to find largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the last element
print(""Largest element is:"", list1[-1])"
2308,Write a Python program to Removing duplicates from tuple,"# Python3 code to demonstrate working of
# Removing duplicates from tuple
# using tuple() + set()
# initialize tuple
test_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3)
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# Removing duplicates from tuple
# using tuple() + set()
res = tuple(set(test_tup))
# printing result
print(""The tuple after removing duplicates : "" + str(res))"
2309,Write a Python program to Find missing and additional values in two lists,"# Python program to find the missing
# and additional elements
# examples of lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
# prints the missing and additional elements in list2
print(""Missing values in second list:"", (set(list1).difference(list2)))
print(""Additional values in second list:"", (set(list2).difference(list1)))
# prints the missing and additional elements in list1
print(""Missing values in first list:"", (set(list2).difference(list1)))
print(""Additional values in first list:"", (set(list1).difference(list2)))"
2310,Shuffle a deck of card with OOPS in Python,"# Import required modules
from random import shuffle
# Define a class to create
# all type of cards
class Cards:
global suites, values
suites = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
def __init__(self):
pass
# Define a class to categorize each card
class Deck(Cards):
def __init__(self):
Cards.__init__(self)
self.mycardset = []
for n in suites:
for c in values:
self.mycardset.append((c)+"" ""+""of""+"" ""+n)
# Method to remove a card from the deck
def popCard(self):
if len(self.mycardset) == 0:
return ""NO CARDS CAN BE POPPED FURTHER""
else:
cardpopped = self.mycardset.pop()
print(""Card removed is"", cardpopped)
# Define a class gto shuffle the deck of cards
class ShuffleCards(Deck):
# Constructor
def __init__(self):
Deck.__init__(self)
# Method to shuffle cards
def shuffle(self):
if len(self.mycardset) < 52:
print(""cannot shuffle the cards"")
else:
shuffle(self.mycardset)
return self.mycardset
# Method to remove a card from the deck
def popCard(self):
if len(self.mycardset) == 0:
return ""NO CARDS CAN BE POPPED FURTHER""
else:
cardpopped = self.mycardset.pop()
return (cardpopped)
# Driver Code
# Creating objects
objCards = Cards()
objDeck = Deck()
# Player 1
player1Cards = objDeck.mycardset
print('\n Player 1 Cards: \n', player1Cards)
# Creating object
objShuffleCards = ShuffleCards()
# Player 2
player2Cards = objShuffleCards.shuffle()
print('\n Player 2 Cards: \n', player2Cards)
# Remove some cards
print('\n Removing a card from the deck:', objShuffleCards.popCard())
print('\n Removing another card from the deck:', objShuffleCards.popCard())"
2311,How to extract youtube data in Python,"from youtube_statistics import YTstats
# paste the API key generated by you here
API_KEY = ""AIzaSyA-0KfpLK04NpQN1XghxhSlzG-WkC3DHLs""
# paste the channel id here
channel_id = ""UC0RhatS1pyxInC00YKjjBqQ""
yt = YTstats(API_KEY, channel_id)
yt.get_channel_statistics()
yt.dump()"
2312,Check whether the given string is Palindrome using Stack in Python,"// C++ implementation of the approach
#include
using namespace std;
// Function that returns true
// if string is a palindrome
bool isPalindrome(string s)
{
int length = s.size();
// Creating a Stack
stack st;
// Finding the mid
int i, mid = length / 2;
for (i = 0; i < mid; i++) {
st.push(s[i]);
}
// Checking if the length of the string
// is odd, if odd then neglect the
// middle character
if (length % 2 != 0) {
i++;
}
char ele;
// While not the end of the string
while (s[i] != '\0')
{
ele = st.top();
st.pop();
// If the characters differ then the
// given string is not a palindrome
if (ele != s[i])
return false;
i++;
}
return true;
}
// Driver code
int main()
{
string s = ""madam"";
if (isPalindrome(s)) {
cout << ""Yes"";
}
else {
cout << ""No"";
}
return 0;
}
// This Code is Contributed by Harshit Srivastava"
2313,Write a Python program to Maximum occurring Substring from list,"# Python3 code to demonstrate working of
# Maximum occurring Substring from list
# Using regex() + groupby() + max() + lambda
import re
import itertools
# initializing string
test_str = ""gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb""
test_list = ['gfg', 'is', 'best']
# printing original string and list
print(""The original string is : "" + test_str)
print(""The original list is : "" + str(test_list))
# Maximum occurring Substring from list
# Using regex() + groupby() + max() + lambda
seqs = re.findall(str.join('|', test_list), test_str)
grps = [(key, len(list(j))) for key, j in itertools.groupby(seqs)]
res = max(grps, key = lambda ele : ele[1])
# printing result
print(""Maximum frequency substring : "" + str(res[0]))"
2314,Write a Python program to check if a string has at least one letter and one number,"def checkString(str):
# intializing flag variable
flag_l = False
flag_n = False
# checking for letter and numbers in
# given string
for i in str:
# if string has letter
if i.isalpha():
flag_l = True
# if string has number
if i.isdigit():
flag_n = True
# returning and of flag
# for checking required condition
return flag_l and flag_n
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))"
2315,Write a Python program to count number of vowels using sets in given string,"# Python3 code to count vowel in
# a string using set
# Function to count vowel
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set(""aeiouAEIOU"")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print(""No. of vowels :"", count)
# Driver code
str = ""GeeksforGeeks""
# Function Call
vowel_count(str)"
2316,Write a Python program to Convert Matrix to Custom Tuple Matrix,"# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing List elements
add_list = ['Gfg', 'is', 'best']
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
for e in ele:
res.append((idx, e))
# printing result
print(""Matrix after conversion : "" + str(res))"
2317,Write a Python program to List product excluding duplicates,"# Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print (""The original list is : "" + str(test_list))
# using naive method
# Duplication Removal List Product
res = []
for i in test_list:
if i not in res:
res.append(i)
res = prod(res)
# printing list after removal
print (""Duplication removal list product : "" + str(res))"
2318,Write a Python program to Cloning or Copying a list,"# Python program to copy or clone a list
# Using the Slice Operator
def Cloning(li1):
li_copy = li1[:]
return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print(""Original List:"", li1)
print(""After Cloning:"", li2)"
2319,How to add timestamp to CSV file in Python,"# Importing required modules
import csv
from datetime import datetime
# Here we are storing our data in a
# variable. We'll add this data in
# our csv file
rows = [['GeeksforGeeks1', 'GeeksforGeeks2'],
['GeeksforGeeks3', 'GeeksforGeeks4'],
['GeeksforGeeks5', 'GeeksforGeeks6']]
# Opening the CSV file in read and
# write mode using the open() module
with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file:
# creating the csv writer
file_write = csv.writer(file)
# storing current date and time
current_date_time = datetime.now()
# Iterating over all the data in the rows
# variable
for val in rows:
# Inserting the date and time at 0th
# index
val.insert(0, current_date_time)
# writing the data in csv file
file_write.writerow(val)"
2320,Write a Python Program to Count Words in Text File,"# creating variable to store the
# number of words
number_of_words = 0
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt','r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = file.read()
# Splitting the data into seperate lines
# using the split() function
lines = data.split()
# Adding the length of the
# lines in our number_of_words
# variable
number_of_words += len(lines)
# Printing total number of words
print(number_of_words)"
2321,Convert a NumPy array into a csv file in Python,"# import necessary libraries
import pandas as pd
import numpy as np
# create a dummy array
arr = np.arange(1,11).reshape(2,5)
# display the array
print(arr)
# convert array into dataframe
DF = pd.DataFrame(arr)
# save the dataframe as a csv file
DF.to_csv(""data1.csv"")"
2322,How to add a border around a NumPy array in Python,"# importing Numpy package
import numpy as np
# Creating a 2X2 Numpy matrix
array = np.ones((2, 2))
print(""Original array"")
print(array)
print(""\n0 on the border and 1 inside the array"")
# constructing border of 0 around 2D identity matrix
# using np.pad()
array = np.pad(array, pad_width=1, mode='constant',
constant_values=0)
print(array)"
2323,Write a Python program to Filter out integers from float numpy array,"# Python code to demonstrate
# filtering integers from numpy array
# containing integers and float
import numpy as np
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
# printing initial array
print (""initial array : "", str(ini_array))
# filtering integers
result = ini_array[ini_array != ini_array.astype(int)]
# printing resultant
print (""final array"", result)"
2324,Write a Python program to Remove Tuples of Length K,"# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using list comprehension
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print(""The original list : "" + str(test_list))
# initializing K
K = 1
# 1 liner to perform task
# filter just lengths other than K
# len() used to compute length
res = [ele for ele in test_list if len(ele) != K]
# printing result
print(""Filtered list : "" + str(res))"
2325,Write a Python program to Program to accept the strings which contains all vowels,"# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string) :
string = string.lower()
# set() function convert ""aeiou""
# string into set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set(""aeiou"")
# set() function convert empty
# dictionary into empty set
s = set({})
# looping through each
# character of the string
for char in string :
# Check for the character is present inside
# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels :
s.add(char)
else:
pass
# check the length of set s equal to length
# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels) :
print(""Accepted"")
else :
print(""Not Accepted"")
# Driver code
if __name__ == ""__main__"" :
string = ""SEEquoiaL""
# calling function
check(string)"
2326,What are the allowed characters in Python function names,"# Python program to demonstrate
# that keywords cant be used as
# identifiers
def calculate_sum(a, b):
return a + b
x = 2
y = 5
print(calculate_sum(x,y))
# def and if is a keyword, so
# this would give invalid
# syntax error
def = 12
if = 2
print(calculate_sum(def, if))"
2327,Find the number of rows and columns of a given matrix using NumPy in Python,"import numpy as np
matrix= np.arange(1,9).reshape((3, 3))
# Original matrix
print(matrix)
# Number of rows and columns of the said matrix
print(matrix.shape)"
2328,Write a Python program to Group Sublists by another List,"# Python3 code to demonstrate
# Group Sublists by another List
# using loop + generator(yield)
# helper function
def grp_ele(test_list1, test_list2):
temp = []
for i in test_list1:
if i in test_list2:
if temp:
yield temp
temp = []
yield i
else:
temp.append(i)
if temp:
yield temp
# Initializing lists
test_list1 = [8, 5, 9, 11, 3, 7]
test_list2 = [9, 11]
# printing original lists
print(""The original list 1 is : "" + str(test_list1))
print(""The original list 2 is : "" + str(test_list2))
# Group Sublists by another List
# using loop + generator(yield)
res = list(grp_ele(test_list1, test_list2))
# printing result
print (""The Grouped list is : "" + str(res))"
2329,Kill a Process by name using Python,"import os, signal
def process():
# Ask user for the name of process
name = input(""Enter process Name: "")
try:
# iterating through each instance of the process
for line in os.popen(""ps ax | grep "" + name + "" | grep -v grep""):
fields = line.split()
# extracting Process ID from the output
pid = fields[0]
# terminating process
os.kill(int(pid), signal.SIGKILL)
print(""Process Successfully terminated"")
except:
print(""Error Encountered while running script"")
process()"
2330,Write a Python program to Print an Inverted Star Pattern,"# python 3 code to print inverted star
# pattern
# n is the number of rows in which
# star is going to be printed.
n=11
# i is going to be enabled to
# range between n-i t 0 with a
# decrement of 1 with each iteration.
# and in print function, for each iteration,
# ” ” is multiplied with n-i and ‘*’ is
# multiplied with i to create correct
# space before of the stars.
for i in range (n, 0, -1):
print((n-i) * ' ' + i * '*')"
2331,Combining a one and a two-dimensional NumPy Array in Python,"# importing Numpy package
import numpy as np
num_1d = np.arange(5)
print(""One dimensional array:"")
print(num_1d)
num_2d = np.arange(10).reshape(2,5)
print(""\nTwo dimensional array:"")
print(num_2d)
# Combine 1-D and 2-D arrays and display
# their elements using numpy.nditer()
for a, b in np.nditer([num_1d, num_2d]):
print(""%d:%d"" % (a, b),)"
2332,Write a Python program to Ways to find length of list,"# Python code to demonstrate
# length of list
# using naive method
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
# Printing test_list
print (""The list is : "" + str(test_list))
# Finding length of list
# using loop
# Initializing counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
print (""Length of list using naive method is : "" + str(counter))"
2333,Write a Python program to Sorting string using order defined by another string,"# Python program to sort a string and return
# its reverse string according to pattern string
# This function will return the reverse of sorted string
# according to the pattern
def sortbyPattern(pat, str):
priority = list(pat)
# Create a dictionary to store priority of each character
myDict = { priority[i] : i for i in range(len(priority))}
str = list(str)
# Pass lambda function as key in sort function
str.sort( key = lambda ele : myDict[ele])
# Reverse the string using reverse()
str.reverse()
new_str = ''.join(str)
return new_str
if __name__=='__main__':
pat = ""asbcklfdmegnot""
str = ""eksge""
new_str = sortbyPattern(pat, str)
print(new_str)"
2334,Ways to convert string to dictionary in Python,"# Python implementation of converting
# a string into a dictionary
# initialising string
str = "" Jan = January; Feb = February; Mar = March""
# At first the string will be splitted
# at the occurence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split(""="") for subString in str.split("";""))
# printing the generated dictionary
print(dictionary)"
2335,Functions that accept variable length key value pair as arguments in Python,"# using kwargs
# in functions
def printKwargs(**kwargs):
print(kwargs)
# driver code
if __name__ == ""__main__"":
printKwargs(Argument_1='gfg', Argument_2='GFG')"
2336,Lambda with if but without else in Python,"# Lambda function with if but without else.
square = lambda x : x*x if(x > 0)
print(square(6))"
2337,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)"
2338,Sorting objects of user defined class in Python,"print(sorted([1,26,3,9]))
print(sorted(""Geeks foR gEEks"".split(), key=str.lower))"
2339,Write a Python program to Numpy matrix.tolist(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1, 12, 3]')
# applying matrix.tolist() method
geek = gfg.tolist()
print(geek)"
2340,Write a Python program to Maximum record value key in dictionary,"# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using loop
# initializing dictionary
test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},
'is' : {'Manjeet' : 8, 'Himani' : 9},
'best' : {'Manjeet' : 10, 'Himani' : 15}}
# printing original dictionary
print(""The original dictionary is : "" + str(test_dict))
# initializing search key
key = 'Himani'
# Maximum record value key in dictionary
# Using loop
res = None
res_max = 0
for sub in test_dict:
if test_dict[sub][key] > res_max:
res_max = test_dict[sub][key]
res = sub
# printing result
print(""The required key is : "" + str(res)) "
2341,How to build an array of all combinations of two NumPy arrays in Python,"# importing Numpy package
import numpy as np
# creating 2 numpy arrays
array_1 = np.array([1, 2])
array_2 = np.array([4, 6])
print(""Array-1"")
print(array_1)
print(""\nArray-2"")
print(array_2)
# combination of elements of array_1 and array_2
# using numpy.meshgrid().T.reshape()
comb_array = np.array(np.meshgrid(array_1, array_2)).T.reshape(-1, 2)
print(""\nCombine array:"")
print(comb_array)"
2342,Write a Python program to Sum of tuple elements,"# Python3 code to demonstrate working of
# Tuple summation
# Using list() + sum()
# initializing tup
test_tup = (7, 8, 9, 1, 10, 7)
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# Tuple elements inversions
# Using list() + sum()
res = sum(list(test_tup))
# printing result
print(""The summation of tuple elements are : "" + str(res)) "
2343,Print anagrams together in Python using List and Dictionary,"# Function to return all anagrams together
def allAnagram(input):
# empty dictionary which holds subsets
# of all anagrams together
dict = {}
# traverse list of strings
for strVal in input:
# sorted(iterable) method accepts any
# iterable and rerturns list of items
# in ascending order
key = ''.join(sorted(strVal))
# now check if key exist in dictionary
# or not. If yes then simply append the
# strVal into the list of it's corresponding
# key. If not then map empty list onto
# key and then start appending values
if key in dict.keys():
dict[key].append(strVal)
else:
dict[key] = []
dict[key].append(strVal)
# traverse dictionary and concatenate values
# of keys together
output = """"
for key,value in dict.items():
output = output + ' '.join(value) + ' '
return output
# Driver function
if __name__ == ""__main__"":
input=['cat', 'dog', 'tac', 'god', 'act']
print (allAnagram(input)) "
2344,Write a Python program to Check if a Substring is Present in a Given String,"# function to check if small string is
# there in big string
def check(string, sub_str):
if (string.find(sub_str) == -1):
print(""NO"")
else:
print(""YES"")
# driver code
string = ""geeks for geeks""
sub_str =""geek""
check(string, sub_str)"
2345,NumPy – Fibonacci Series using Binet Formula in Python,"import numpy as np
# We are creating an array contains n = 10 elements
# for getting first 10 Fibonacci numbers
a = np.arange(1, 11)
lengthA = len(a)
# splitting of terms for easiness
sqrtFive = np.sqrt(5)
alpha = (1 + sqrtFive) / 2
beta = (1 - sqrtFive) / 2
# Implementation of formula
# np.rint is used for rounding off to integer
Fn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive))
print(""The first {} numbers of Fibonacci series are {} . "".format(lengthA, Fn))"
2346,Count distinct substrings of a string using Rabin Karp algorithm in Python,"# importing libraries
import sys
import math as mt
t = 1
# store prime to reduce overflow
mod = 9007199254740881
for ___ in range(t):
# string to check number of distinct substring
s = 'abcd'
# to store substrings
l = []
# to store hash values by Rabin Karp algorithm
d = {}
for i in range(len(s)):
suma = 0
pre = 0
# Number of input alphabets
D = 256
for j in range(i, len(s)):
# calculate new hash value by adding next element
pre = (pre*D+ord(s[j])) % mod
# store string length if non repeat
if d.get(pre, -1) == -1:
l.append([i, j])
d[pre] = 1
# resulting length
print(len(l))
# resulting distinct substrings
for i in range(len(l)):
print(s[l[i][0]:l[i][1]+1], end="" "")"
2347,Write a Python program to Check if two lists have at-least one element common,"# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result
# driver code
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_data(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_data(a, b))"
2348,Find length of a string in python (4 ways),"# Python code to demonstrate string length
# using len
str = ""geeks""
print(len(str))"
2349,Write a Python program to Convert List of Dictionaries to List of Lists,"# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
{'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
{'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
# printing original list
print(""The original list is : "" + str(test_list))
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
res = []
for idx, sub in enumerate(test_list, start = 0):
if idx == 0:
res.append(list(sub.keys()))
res.append(list(sub.values()))
else:
res.append(list(sub.values()))
# printing result
print(""The converted list : "" + str(res)) "
2350,"Write a Python program to Extract Key’s Value, if Key Present in List and Dictionary","# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using all() + list comprehension
# initializing list
test_list = [""Gfg"", ""is"", ""Good"", ""for"", ""Geeks""]
# initializing Dictionary
test_dict = {""Gfg"" : 2, ""is"" : 4, ""Best"" : 6}
# initializing K
K = ""Gfg""
# printing original list and Dictionary
print(""The original list : "" + str(test_list))
print(""The original Dictionary : "" + str(test_dict))
# using all() to check for occurrence in list and dict
# encapsulating list and dictionary keys in list
res = None
if all(K in sub for sub in [test_dict, test_list]):
res = test_dict[K]
# printing result
print(""Extracted Value : "" + str(res))"
2351,Write a Python Program to print digit pattern,"# function to print the pattern
def pattern(n):
# traverse through the elements
# in n assuming it as a string
for i in n:
# print | for every line
print(""|"", end = """")
# print i number of * s in
# each line
print(""*"" * int(i))
# get the input as string
n = ""41325""
pattern(n)"
2352,Finding the k smallest values of a NumPy array in Python,"# importing the modules
import numpy as np
# creating the array
arr = np.array([23, 12, 1, 3, 4, 5, 6])
print(""The Original Array Content"")
print(arr)
# value of k
k = 4
# sorting the array
arr1 = np.sort(arr)
# k smallest number of array
print(k, ""smallest elements of the array"")
print(arr1[:k])"
2353,How to Build a Simple Auto-Login Bot with Python,"# Used to import the webdriver from selenium
from selenium import webdriver
import os
# Get the path of chromedriver which you have install
def startBot(username, password, url):
path = ""C:\\Users\\hp\\Downloads\\chromedriver""
# giving the path of chromedriver to selenium websriver
driver = webdriver.Chrome(path)
# opening the website in chrome.
driver.get(url)
# find the id or name or class of
# username by inspecting on username input
driver.find_element_by_name(
""id/class/name of username"").send_keys(username)
# find the password by inspecting on password input
driver.find_element_by_name(
""id/class/name of password"").send_keys(password)
# click on submit
driver.find_element_by_css_selector(
""id/class/name/css selector of login button"").click()
# Driver Code
# Enter below your login credentials
username = ""Enter your username""
password = ""Enter your password""
# URL of the login page of site
# which you want to automate login.
url = ""Enter the URL of login page of website""
# Call the function
startBot(username, password, url)"
2354,Write a Python program to Print Heart Pattern,"# define size n = even only
n = 8
# so this heart can be made n//2 part left,
# n//2 part right, and one middle line
# i.e; columns m = n + 1
m = n+1
# loops for upper part
for i in range(n//2-1):
for j in range(m):
# condition for printing stars to GFG upper line
if i == n//2-2 and (j == 0 or j == m-1):
print(""*"", end="" "")
# condition for printing stars to left upper
elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \
or (j-i == m//2-n//2+3 and j > m//4)):
print(""*"", end="" "")
# condition for printing stars to right upper
elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \
or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)):
print(""*"", end="" "")
# condition for printing spaces
else:
print("" "", end="" "")
print()
# loops for lower part
for i in range(n//2-1, n):
for j in range(m):
# condition for printing stars
if (i-j == n//2-1) or (i+j == n-1+m//2):
print('*', end="" "")
# condition for printing GFG
elif i == n//2-1:
if j == m//2-1 or j == m//2+1:
print('G', end="" "")
elif j == m//2:
print('F', end="" "")
else:
print(' ', end="" "")
# condition for printing spaces
else:
print(' ', end="" "")
print()"
2355,How to open two files together in Python,"# opening both the files in reading modes
with open(""file1.txt"") as f1, open(""file2.txt"") as f2:
# reading f1 contents
line1 = f1.readline()
# reading f2 contents
line2 = f2.readline()
# printing contents of f1 followed by f2
print(line1, line2)"
2356,Access the elements of a Series in Pandas in Python,"# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
ser = pd.Series(df['Name'])
ser.head(10)
# or simply df['Name'].head(10)"
2357,Write a Python program to Numpy matrix.min(),"# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[64, 1; 12, 3]')
# applying matrix.min() method
geeks = gfg.min()
print(geeks)"
2358,Write a Python Library for Linked List,"# importing module
import collections
# initialising a deque() of arbitary length
linked_lst = collections.deque()
# filling deque() with elements
linked_lst.append('first')
linked_lst.append('second')
linked_lst.append('third')
print(""elements in the linked_list:"")
print(linked_lst)
# adding element at an arbitary position
linked_lst.insert(1, 'fourth')
print(""elements in the linked_list:"")
print(linked_lst)
# deleting the last element
linked_lst.pop()
print(""elements in the linked_list:"")
print(linked_lst)
# removing a specific element
linked_lst.remove('fourth')
print(""elements in the linked_list:"")
print(linked_lst)"
2359,Creating a Pandas Series from Lists in Python,"# import pandas as pd
import pandas as pd
# create Pandas Series with default index values
# default index ranges is from 0 to len(list) - 1
x = pd.Series(['Geeks', 'for', 'Geeks'])
# print the Series
print(x)"
2360,Write a Python program to All substrings Frequency in String,"# Python3 code to demonstrate working of
# All substrings Frequency in String
# Using loop + list comprehension
# initializing string
test_str = ""abababa""
# printing original string
print(""The original string is : "" + str(test_str))
# list comprehension to extract substrings
temp = [test_str[idx: j] for idx in range(len(test_str))
for j in range(idx + 1, len(test_str) + 1)]
# loop to extract final result of frequencies
res = {}
for idx in temp:
if idx not in res.keys():
res[idx] = 1
else:
res[idx] += 1
# printing result
print(""Extracted frequency dictionary : "" + str(res)) "
2361,Write a Python program to Join Tuples if similar initial element,"# Python3 code to demonstrate working of
# Join Tuples if similar initial element
# Using loop
# initializing list
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
# printing original list
print(""The original list is : "" + str(test_list))
# Join Tuples if similar initial element
# Using loop
res = []
for sub in test_list:
if res and res[-1][0] == sub[0]:
res[-1].extend(sub[1:])
else:
res.append([ele for ele in sub])
res = list(map(tuple, res))
# printing result
print(""The extracted elements : "" + str(res)) "
2362,Write a Python Set | Pairs of complete strings in two sets,"# Function to find pairs of complete strings
# in two sets of strings
def completePair(set1,set2):
# consider all pairs of string from
# set1 and set2
count = 0
for str1 in set1:
for str2 in set2:
result = str1 + str2
# push all alphabets of concatenated
# string into temporary set
tmpSet = set([ch for ch in result if (ord(ch)>=ord('a') and ord(ch)<=ord('z'))])
if len(tmpSet)==26:
count = count + 1
print (count)
# Driver program
if __name__ == ""__main__"":
set1 = ['abcdefgh', 'geeksforgeeks','lmnopqrst', 'abc']
set2 = ['ijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyz']
completePair(set1,set2)"
2363,Write a Python Selenium – Find Button by text,"# Import Library
from selenium import webdriver
import time
# set webdriver path here it may vary
# Its the location where you have downloaded the ChromeDriver
driver = webdriver.Chrome(executable_path=r""C:\\chromedriver.exe"")
# Get the target URL
driver.get('https://html.com/tags/button/')
# Wait for 5 seconds to load the webpage completely
time.sleep(5)
# Find the button using text
driver.find_element_by_xpath('//button[normalize-space()=""Click me!""]').click()
time.sleep(5)
# Close the driver
driver.close()"
2364,Check if element exists in list in Python,"# Python code to demonstrate
# checking of element existence
# using loops and in
# Initializing list
test_list = [ 1, 6, 3, 5, 3, 4 ]
print(""Checking if 4 exists in list ( using loop ) : "")
# Checking if 4 exists in list
# using loop
for i in test_list:
if(i == 4) :
print (""Element Exists"")
print(""Checking if 4 exists in list ( using in ) : "")
# Checking if 4 exists in list
# using in
if (4 in test_list):
print (""Element Exists"")"
2365,Box Blur Algorithm – With Python implementation,"def square_matrix(square):
"""""" This function will calculate the value x
(i.e. blurred pixel value) for each 3 * 3 blur image.
""""""
tot_sum = 0
# Calculate sum of all the pixels in 3 * 3 matrix
for i in range(3):
for j in range(3):
tot_sum += square[i][j]
return tot_sum // 9 # return the average of the sum of pixels
def boxBlur(image):
""""""
This function will calculate the blurred
image for given n * n image.
""""""
square = [] # This will store the 3 * 3 matrix
# which will be used to find its blurred pixel
square_row = [] # This will store one row of a 3 * 3 matrix and
# will be appended in square
blur_row = [] # Here we will store the resulting blurred
# pixels possible in one row
# and will append this in the blur_img
blur_img = [] # This is the resulting blurred image
# number of rows in the given image
n_rows = len(image)
# number of columns in the given image
n_col = len(image[0])
# rp is row pointer and cp is column pointer
rp, cp = 0, 0
# This while loop will be used to
# calculate all the blurred pixel in the first row
while rp <= n_rows - 3:
while cp <= n_col-3:
for i in range(rp, rp + 3):
for j in range(cp, cp + 3):
# append all the pixels in a row of 3 * 3 matrix
square_row.append(image[i][j])
# append the row in the square i.e. 3 * 3 matrix
square.append(square_row)
square_row = []
# calculate the blurred pixel for given 3 * 3 matrix
# i.e. square and append it in blur_row
blur_row.append(square_matrix(square))
square = []
# increase the column pointer
cp = cp + 1
# append the blur_row in blur_image
blur_img.append(blur_row)
blur_row = []
rp = rp + 1 # increase row pointer
cp = 0 # start column pointer from 0 again
# Return the resulting pixel matrix
return blur_img
# Driver code
image = [[7, 4, 0, 1],
[5, 6, 2, 2],
[6, 10, 7, 8],
[1, 4, 2, 0]]
print(boxBlur(image))"
2366,How to get element-wise true division of an array using Numpy in Python,"# import library
import numpy as np
# create 1d-array
x = np.arange(5)
print(""Original array:"",
x)
# apply true division
# on each array element
rslt = np.true_divide(x, 4)
print(""After the element-wise division:"",
rslt)"
2367,Evaluate Einstein’s summation convention of two multidimensional NumPy arrays in Python,"# Importing library
import numpy as np
# Creating two 2X2 matrix
matrix1 = np.array([[1, 2], [0, 2]])
matrix2 = np.array([[0, 1], [3, 4]])
print(""Original matrix:"")
print(matrix1)
print(matrix2)
# Output
result = np.einsum(""mk,kn"", matrix1, matrix2)
print(""Einstein’s summation convention of the two matrix:"")
print(result)"
2368,numpy.searchsorted() in Python,"# Python program explaining
# searchsorted() function
import numpy as geek
# input array
in_arr = [2, 3, 4, 5, 6]
print (""Input array : "", in_arr)
# the number which we want to insert
num = 4
print(""The number which we want to insert : "", num)
out_ind = geek.searchsorted(in_arr, num)
print (""Output indices to maintain sorted array : "", out_ind)"
2369,Write a Python program to Merging two Dictionaries,"# Python code to merge dict using update() method
def Merge(dict1, dict2):
return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This return None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)"
2370,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)"
2371,numpy.var() in Python,"# Python Program illustrating
# numpy.var() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print(""arr : "", arr)
print(""var of arr : "", np.var(arr))
print(""\nvar of arr : "", np.var(arr, dtype = np.float32))
print(""\nvar of arr : "", np.var(arr, dtype = np.float64)) "
2372,How to add time onto a DateTime object in Python,"# Python3 code to illustrate the addition
# of time onto the datetime object
# Importing datetime
import datetime
# Initializing a date and time
date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)
print(""Original time:"")
print(date_and_time)
# Calling the timedelta() function
time_change = datetime.timedelta(minutes=75)
new_time = date_and_time + time_change
# Printing the new datetime object
print(""changed time:"")
print(new_time)"
2373,Convert JSON to CSV in Python,"# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()"
2374,Extract IP address from file using Python,"# importing the module
import re
# opening and reading the file
with open('C:/Users/user/Desktop/New Text Document.txt') as fh:
fstring = fh.readlines()
# declaring the regex pattern for IP addresses
pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
# initializing the list object
lst=[]
# extracting the IP addresses
for line in fstring:
lst.append(pattern.search(line)[0])
# displaying the extracted IP addresses
print(lst)"
2375,Write a Python program to Sort String by Custom Integer Substrings,"# Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using sorted() + zip() + lambda + regex()
import re
# initializing list
test_list = [""Good at 4"", ""Wake at 7"", ""Work till 6"", ""Sleep at 11""]
# printing original list
print(""The original list : "" + str(test_list))
# initializing substring list
subord_list = [""6"", ""7"", ""4"", ""11""]
# creating inverse mapping with index
temp_dict = {val: key for key, val in enumerate(subord_list)}
# custom sorting
temp_list = sorted([[ele, temp_dict[re.search(""(\d+)$"", ele).group()]] \
for ele in test_list], key = lambda x: x[1])
# compiling result
res = [ele for ele in list(zip(*temp_list))[0]]
# printing result
print(""The sorted list : "" + str(res))"
2376,numpy.var() in Python,"# Python Program illustrating
# numpy.var() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print(""arr : "", arr)
print(""var of arr : "", np.var(arr))
print(""\nvar of arr : "", np.var(arr, dtype = np.float32))
print(""\nvar of arr : "", np.var(arr, dtype = np.float64)) "
2377,numpy.loadtxt() in Python,"# Python program explaining
# loadtxt() function
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
c = StringIO(""0 1 2 \n3 4 5"")
d = geek.loadtxt(c)
print(d)"
2378,Retweet Tweet using Selenium in Python,"from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass"
2379,Write a Python lambda,"# Python program to demonstrate
# lambda functions
string ='GeeksforGeeks'
# lambda returns a function object
print(lambda string : string)"
2380,Write a Python program to Replace String by Kth Dictionary value,"# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using list comprehension
# initializing list
test_list = [""Gfg"", ""is"", ""Best""]
# printing original list
print(""The original list : "" + str(test_list))
# initializing subs. Dictionary
subs_dict = {
""Gfg"" : [5, 6, 7],
""is"" : [7, 4, 2],
}
# initializing K
K = 2
# using list comprehension to solve
# problem using one liner
res = [ele if ele not in subs_dict else subs_dict[ele][K]
for ele in test_list]
# printing result
print(""The list after substitution : "" + str(res))"
2381,Lambda and filter in Python Examples,"# Python Program to find numbers divisible
# by thirteen from a list using anonymous
# function
# Take a list of numbers.
my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]
# use anonymous function to filter and comparing
# if divisible or not
result = list(filter(lambda x: (x % 13 == 0), my_list))
# printing the result
print(result) "
2382,Get n-largest values from a particular column in Pandas DataFrame in Python,"# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv(""https://media.geeksforgeeks.org/wp-content/uploads/nba.csv"")
df.head(10)"
2383,Write a Python program to Replace Different characters in String at Once,"# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using join() + generator expression
# initializing string
test_str = 'geeksforgeeks is best'
# printing original String
print(""The original string is : "" + str(test_str))
# initializing mapping dictionary
map_dict = {'e':'1', 'b':'6', 'i':'4'}
# generator expression to construct vals
# join to get string
res = ''.join(idx if idx not in map_dict else map_dict[idx] for idx in test_str)
# printing result
print(""The converted string : "" + str(res))"
2384,Write a Python program to Replace all Characters of a List Except the given character,"# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using list comprehension and conditional expressions
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
# printing original list
print(""The original list : "" + str(test_list))
# initializing repl_chr
repl_chr = '$'
# initializing retain chararter
ret_chr = 'G'
# list comprehension to remake list after replacement
res = [ele if ele == ret_chr else repl_chr for ele in test_list]
# printing result
print(""List after replacement : "" + str(res))"
2385,Write a Python program to Group Similar items to Dictionary Values List,"# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using defaultdict + loop
from collections import defaultdict
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
# printing original list
print(""The original list : "" + str(test_list))
# using defaultdict for default list
res = defaultdict(list)
for ele in test_list:
# appending Similar values
res[ele].append(ele)
# printing result
print(""Similar grouped dictionary : "" + str(dict(res)))"
2386,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)) "
2387,Pandas | Basic of Time Series Manipulation in Python,"import pandas as pd
from datetime import datetime
import numpy as np
range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019',
freq ='Min')
print(range_date)"
2388,Write a Python program to print all even numbers in a range,"# Python program to print Even Numbers in given range
start, end = 4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 == 0:
print(num, end = "" "")"
2389,numpy string operations | swapcase() function in Python,"# Python Program explaining
# numpy.char.swapcase() 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.swapcase(in_arr)
print (""output swapcasecased array :"", out_arr)"
2390,Write a Python program to find tuples which have all elements divisible by K from a list of tuples,"# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using list comprehension + all()
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 6
# all() used to filter elements
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
# printing result
print(""K Multiple elements tuples : "" + str(res))"
2391,Write a Python program to Convert Tuple to Tuple Pair,"# Python3 code to demonstrate working of
# Convert Tuple to Tuple Pair
# Using product() + next()
from itertools import product
# initializing tuple
test_tuple = ('G', 'F', 'G')
# printing original tuple
print(""The original tuple : "" + str(test_tuple))
# Convert Tuple to Tuple Pair
# Using product() + next()
test_tuple = iter(test_tuple)
res = list(product(next(test_tuple), test_tuple))
# printing result
print(""The paired records : "" + str(res))"
2392,Write a Python program to Remove Reduntant Substrings from Strings List,"# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using enumerate() + join() + sort()
# initializing list
test_list = [""Gfg"", ""Gfg is best"", ""Geeks"", ""Gfg is for Geeks""]
# printing original list
print(""The original list : "" + str(test_list))
# using loop to iterate for each string
test_list.sort(key = len)
res = []
for idx, val in enumerate(test_list):
# concatenating all next values and checking for existence
if val not in ', '.join(test_list[idx + 1:]):
res.append(val)
# printing result
print(""The filtered list : "" + str(res))"
2393,How to compute numerical negative value for all elements in a given NumPy array in Python,"# importing library
import numpy as np
# creating a array
x = np.array([-1, -2, -3,
1, 2, 3, 0])
print(""Printing the Original array:"",
x)
# converting array elements to
# its corresponding negative value
r1 = np.negative(x)
print(""Printing the negative value of the given array:"",
r1)"
2394,Convert binary to string using Python,"# Python3 code to demonstrate working of
# Converting binary to string
# Using BinarytoDecimal(binary)+chr()
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return (decimal)
# Driver's code
# initializing binary data
bin_data ='10001111100101110010111010111110011'
# print binary data
print(""The binary value is:"", bin_data)
# initializing a empty string for
# storing the string data
str_data =' '
# slicing the input and converting it
# in decimal and then converting it in string
for i in range(0, len(bin_data), 7):
# slicing the bin_data from index range [0, 6]
# and storing it as integer in temp_data
temp_data = int(bin_data[i:i + 7])
# passing temp_data in BinarytoDecimal() function
# to get decimal value of corresponding temp_data
decimal_data = BinaryToDecimal(temp_data)
# Deccoding the decimal value returned by
# BinarytoDecimal() function, using chr()
# function which return the string corresponding
# character for given ASCII value, and store it
# in str_data
str_data = str_data + chr(decimal_data)
# printing the result
print(""The Binary value after string conversion is:"",
str_data)"
2395,Working with large CSV files in Python,"# import required modules
import pandas as pd
import numpy as np
import time
# time taken to read data
s_time = time.time()
df = pd.read_csv(""gender_voice_dataset.csv"")
e_time = time.time()
print(""Read without chunks: "", (e_time-s_time), ""seconds"")
# data
df.sample(10)"
2396,Write a Python program to find the Strongest Neighbour,"# define a function for finding
# the maximum for adjacent
# pairs in the array
def maximumAdjacent(arr1, n):
# array to store the max
# value between adjacent pairs
arr2 = []
# iterate from 1 to n - 1
for i in range(1, n):
# find max value between
# adjacent pairs gets
# stored in r
r = max(arr1[i], arr1[i-1])
# add element
arr2.append(r)
# printing the elements
for ele in arr2 :
print(ele,end="" "")
if __name__ == ""__main__"" :
# size of the input array
n = 6
# input array
arr1 = [1,2,2,3,4,5]
# function calling
maximumAdjacent(arr1, n)"
2397,Write a Python Program for BogoSort or Permutation Sort,"# Python program for implementation of Bogo Sort
import random
# Sorts array a[0..n-1] using Bogo sort
def bogoSort(a):
n = len(a)
while (is_sorted(a)== False):
shuffle(a)
# To check if array is sorted or not
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
# To generate permutation of the array
def shuffle(a):
n = len(a)
for i in range (0,n):
r = random.randint(0,n-1)
a[i], a[r] = a[r], a[i]
# Driver code to test above
a = [3, 2, 4, 1, 0, 5]
bogoSort(a)
print(""Sorted array :"")
for i in range(len(a)):
print (""%d"" %a[i]),"
2398,Write a Python program to Convert Character Matrix to single String,"# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + list comprehension
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
# printing original list
print(""The original list is : "" + str(test_list))
# Convert Character Matrix to single String
# Using join() + list comprehension
res = ''.join(ele for sub in test_list for ele in sub)
# printing result
print(""The String after join : "" + res) "
2399,Write a Python program to Flatten tuple of List to tuple,"# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using sum() + tuple()
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
# printing original tuple
print(""The original tuple : "" + str(test_tuple))
# Flatten tuple of List to tuple
# Using sum() + tuple()
res = tuple(sum(test_tuple, []))
# printing result
print(""The flattened tuple : "" + str(res))"
2400,Program to reverse a linked list using Stack in Python,"// C/C++ program to reverse linked list
// using stack
#include
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to
the head of a list and an int, push a new
node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// Function to reverse linked list
Node *reverseList(Node* head)
{
// Stack to store elements of list
stack stk;
// Push the elements of list to stack
Node* ptr = head;
while (ptr->next != NULL) {
stk.push(ptr);
ptr = ptr->next;
}
// Pop from stack and replace
// current nodes value'
head = ptr;
while (!stk.empty()) {
ptr->next = stk.top();
ptr = ptr->next;
stk.pop();
}
ptr->next = NULL;
return head;
}
// Function to print the Linked list
void printList(Node* head)
{
while (head) {
cout << head->data << "" "";
head = head->next;
}
}
// Driver Code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->2->3->4->5 */
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
head = reverseList(head);
printList(head);
return 0;
}"
2401,Write a Python program to Unique Tuple Frequency (Order Irrespective),"# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using tuple() + list comprehension + sorted() + len()
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
# printing original list
print(""The original list is : "" + str(test_list))
# Using tuple() + list comprehension + sorted() + len()
# Size computed after conversion to set
res = len(list(set(tuple(sorted(sub)) for sub in test_list)))
# printing result
print(""Unique tuples Frequency : "" + str(res)) "
2402,Write a Python program to find the character position of Kth word from a list of strings,"# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = [""geekforgeeks"", ""is"", ""best"", ""for"", ""geeks""]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print(""Index of character at Kth position word : "" + str(res))"
2403,Ways to remove i’th character from string in Python,"# Python code to demonstrate
# method to remove i'th character
# Naive Method
# Initializing String
test_str = ""GeeksForGeeks""
# Printing original string
print (""The original string is : "" + test_str)
# Removing char at pos 3
# using loop
new_str = """"
for i in range(len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
# Printing string after removal
print (""The string after removal of i'th character : "" + new_str)"
2404,Ways to sort list of dictionaries by values in Write a Python program to Using lambda function,"# Python code demonstrate the working of
# sorted() with lambda
# Initializing list of dictionaries
lis = [{ ""name"" : ""Nandini"", ""age"" : 20},
{ ""name"" : ""Manjeet"", ""age"" : 20 },
{ ""name"" : ""Nikhil"" , ""age"" : 19 }]
# using sorted and lambda to print list sorted
# by age
print ""The list printed sorting by age: ""
print sorted(lis, key = lambda i: i['age'])
print (""\r"")
# using sorted and lambda to print list sorted
# by both age and name. Notice that ""Manjeet""
# now comes before ""Nandini""
print ""The list printed sorting by age and name: ""
print sorted(lis, key = lambda i: (i['age'], i['name']))
print (""\r"")
# using sorted and lambda to print list sorted
# by age in descending order
print ""The list printed sorting by age in descending order: ""
print sorted(lis, key = lambda i: i['age'],reverse=True)"
2405,How to read numbers in CSV files in Python,"import csv
# creating a nested list of roll numbers,
# subjects and marks scored by each roll number
marks = [
[""RollNo"", ""Maths"", ""Python""],
[1000, 80, 85],
[2000, 85, 89],
[3000, 82, 90],
[4000, 83, 98],
[5000, 82, 90]
]
# using the open method with 'w' mode
# for creating a new csv file 'my_csv' with .csv extension
with open('my_csv.csv', 'w', newline = '') as file:
writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC,
delimiter = ' ')
writer.writerows(marks)
# opening the 'my_csv' file to read its contents
with open('my_csv.csv', newline = '') as file:
reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC,
delimiter = ' ')
# storing all the rows in an output list
output = []
for row in reader:
output.append(row[:])
for rows in output:
print(rows)"
2406,Find the roots of the polynomials using NumPy in Python,"# import numpy library
import numpy as np
# Enter the coefficients of the poly in the array
coeff = [1, 2, 1]
print(np.roots(coeff))"
2407,Write a Python program to find the sum of all items in a dictionary,"# Python3 Program to find sum of
# all items in a Dictionary
# Function to print sum
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b':200, 'c':300}
print(""Sum :"", returnSum(dict))"
2408,Write a Python program to Extract words starting with K in String List,"# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = [""Gfg is best"", ""Gfg is for geeks"", ""I love G4G""]
# printing original list
print(""The original list is : "" + str(test_list))
# initializing K
K = ""g""
res = []
for sub in test_list:
# splitting phrases
temp = sub.split()
for ele in temp:
# checking for matching elements
if ele[0].lower() == K.lower():
res.append(ele)
# printing result
print(""The filtered elements : "" + str(res))"
2409,Write a Python program to Find Mean of a List of Numpy Array,"# Python code to find mean of every numpy array in list
# Importing module
import numpy as np
# List Initialization
Input = [np.array([1, 2, 3]),
np.array([4, 5, 6]),
np.array([7, 8, 9])]
# Output list initialization
Output = []
# using np.mean()
for i in range(len(Input)):
Output.append(np.mean(Input[i]))
# Printing output
print(Output)"
2410,Write a Python program to Numpy np.char.endswith() method,"# import numpy
import numpy as np
# using np.char.endswith() method
a = np.array(['geeks', 'for', 'geeks'])
gfg = np.char.endswith(a, 'ks')
print(gfg)"
2411,Write a Python program to Find common elements in three sorted arrays by dictionary intersection,"# Function to find common elements in three
# sorted arrays
from collections import Counter
def commonElement(ar1,ar2,ar3):
# first convert lists into dictionary
ar1 = Counter(ar1)
ar2 = Counter(ar2)
ar3 = Counter(ar3)
# perform intersection operation
resultDict = dict(ar1.items() & ar2.items() & ar3.items())
common = []
# iterate through resultant dictionary
# and collect common elements
for (key,val) in resultDict.items():
for i in range(0,val):
common.append(key)
print(common)
# Driver program
if __name__ == ""__main__"":
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
commonElement(ar1,ar2,ar3)"
2412,Write a Python program to Remove duplicate lists in tuples (Preserving Order),"# Python3 code to demonstrate working of
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
# Initializing tuple
test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
temp = set()
res = [ele for ele in test_tup if not(tuple(ele) in temp or temp.add(tuple(ele)))]
# printing result
print(""The unique lists tuple is : "" + str(res))"
2413,Program to print the diamond shape in Python,"// C++ program to print diamond shape
// with 2n rows
#include
using namespace std;
// Prints diamond pattern with 2n rows
void printDiamond(int n)
{
int space = n - 1;
// run loop (parent loop)
// till number of rows
for (int i = 0; i < n; i++)
{
// loop for initially space,
// before star printing
for (int j = 0;j < space; j++)
cout << "" "";
// Print i+1 stars
for (int j = 0; j <= i; j++)
cout << ""* "";
cout << endl;
space--;
}
// Repeat again in reverse order
space = 0;
// run loop (parent loop)
// till number of rows
for (int i = n; i > 0; i--)
{
// loop for initially space,
// before star printing
for (int j = 0; j < space; j++)
cout << "" "";
// Print i stars
for (int j = 0;j < i;j++)
cout << ""* "";
cout << endl;
space++;
}
}
// Driver code
int main()
{
printDiamond(5);
return 0;
}
// This is code is contributed
// by rathbhupendra"
2414,Write a Python program to Extract Indices of substring matches,"# Python3 code to demonstrate working of
# Extract Indices of substring matches
# Using loop + enumerate()
# initializing list
test_list = [""Gfg is good"", ""for Geeks"", ""I love Gfg"", ""Its useful""]
# initializing K
K = ""Gfg""
# printing original list
print(""The original list : "" + str(test_list))
# using loop to iterate through list
res = []
for idx, ele in enumerate(test_list):
if K in ele:
res.append(idx)
# printing result
print(""The indices list : "" + str(res))"
2415,Write a Python program to Test if tuple is distinct,"# Python3 code to demonstrate working of
# Test if tuple is distinct
# Using loop
# initialize tuple
test_tup = (1, 4, 5, 6, 1, 4)
# printing original tuple
print(""The original tuple is : "" + str(test_tup))
# Test if tuple is distinct
# Using loop
res = True
temp = set()
for ele in test_tup:
if ele in temp:
res = False
break
temp.add(ele)
# printing result
print(""Is tuple distinct ? : "" + str(res))"
2416,Write a Python program to Creating DataFrame from dict of narray/lists,"# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Category':['Array', 'Stack', 'Queue'],
'Marks':[20, 21, 19]}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
print(df )"
2417,Create a list from rows in Pandas DataFrame | Set 2 in Python,"# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)"
2418,Selenium – Search for text on page in Python,"# import webdriver
from selenium import webdriver
# create webdriver object
driver = webdriver.Chrome()
# URL of the website
url = ""https://www.geeksforgeeks.org/""
# Opening the URL
driver.get(url)
# Getting current URL source code
get_source = driver.page_source
# Text you want to search
search_text = ""Floor""
# print True if text is present else False
print(search_text in get_source)"
2419,Write a Python program to Reverse Row sort in Lists of List,"# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print (""The original list is : "" + str(test_list))
# Reverse Row sort in Lists of List
# using loop
for ele in test_list:
ele.sort(reverse = True)
# printing result
print (""The reverse sorted Matrix is : "" + str(test_list))"
2420,Print with your own font using Python !!,"# Python3 code to print input in your own font
name = ""GEEK""
# To take input from User
# name = input(""Enter your name: \n\n"")
length = len(name)
l = """"
for x in range(0, length):
c = name[x]
c = c.upper()
if (c == ""A""):
print(""..######..\n..#....#..\n..######.."", end = "" "")
print(""\n..#....#..\n..#....#..\n\n"")
elif (c == ""B""):
print(""..######..\n..#....#..\n..#####..."", end = "" "")
print(""\n..#....#..\n..######..\n\n"")
elif (c == ""C""):
print(""..######..\n..#.......\n..#......."", end = "" "")
print(""\n..#.......\n..######..\n\n"")
elif (c == ""D""):
print(""..#####...\n..#....#..\n..#....#.."", end = "" "")
print(""\n..#....#..\n..#####...\n\n"")
elif (c == ""E""):
print(""..######..\n..#.......\n..#####..."", end = "" "")
print(""\n..#.......\n..######..\n\n"")
elif (c == ""F""):
print(""..######..\n..#.......\n..#####..."", end = "" "")
print(""\n..#.......\n..#.......\n\n"")
elif (c == ""G""):
print(""..######..\n..#.......\n..#.####.."", end = "" "")
print(""\n..#....#..\n..#####...\n\n"")
elif (c == ""H""):
print(""..#....#..\n..#....#..\n..######.."", end = "" "")
print(""\n..#....#..\n..#....#..\n\n"")
elif (c == ""I""):
print(""..######..\n....##....\n....##...."", end = "" "")
print(""\n....##....\n..######..\n\n"")
elif (c == ""J""):
print(""..######..\n....##....\n....##...."", end = "" "")
print(""\n..#.##....\n..####....\n\n"")
elif (c == ""K""):
print(""..#...#...\n..#..#....\n..##......"", end = "" "")
print(""\n..#..#....\n..#...#...\n\n"")
elif (c == ""L""):
print(""..#.......\n..#.......\n..#......."", end = "" "")
print(""\n..#.......\n..######..\n\n"")
elif (c == ""M""):
print(""..#....#..\n..##..##..\n..#.##.#.."", end = "" "")
print(""\n..#....#..\n..#....#..\n\n"")
elif (c == ""N""):
print(""..#....#..\n..##...#..\n..#.#..#.."", end = "" "")
print(""\n..#..#.#..\n..#...##..\n\n"")
elif (c == ""O""):
print(""..######..\n..#....#..\n..#....#.."", end = "" "")
print(""\n..#....#..\n..######..\n\n"")
elif (c == ""P""):
print(""..######..\n..#....#..\n..######.."", end = "" "")
print(""\n..#.......\n..#.......\n\n"")
elif (c == ""Q""):
print(""..######..\n..#....#..\n..#.#..#.."", end = "" "")
print(""\n..#..#.#..\n..######..\n\n"")
elif (c == ""R""):
print(""..######..\n..#....#..\n..#.##..."", end = "" "")
print(""\n..#...#...\n..#....#..\n\n"")
elif (c == ""S""):
print(""..######..\n..#.......\n..######.."", end = "" "")
print(""\n.......#..\n..######..\n\n"")
elif (c == ""T""):
print(""..######..\n....##....\n....##...."", end = "" "")
print(""\n....##....\n....##....\n\n"")
elif (c == ""U""):
print(""..#....#..\n..#....#..\n..#....#.."", end = "" "")
print(""\n..#....#..\n..######..\n\n"")
elif (c == ""V""):
print(""..#....#..\n..#....#..\n..#....#.."", end = "" "")
print(""\n...#..#...\n....##....\n\n"")
elif (c == ""W""):
print(""..#....#..\n..#....#..\n..#.##.#.."", end = "" "")
print(""\n..##..##..\n..#....#..\n\n"")
elif (c == ""X""):
print(""..#....#..\n...#..#...\n....##...."", end = "" "")
print(""\n...#..#...\n..#....#..\n\n"")
elif (c == ""Y""):
print(""..#....#..\n...#..#...\n....##...."", end = "" "")
print(""\n....##....\n....##....\n\n"")
elif (c == ""Z""):
print(""..######..\n......#...\n.....#...."", end = "" "")
print(""\n....#.....\n..######..\n\n"")
elif (c == "" ""):
print(""..........\n..........\n.........."", end = "" "")
print(""\n..........\n\n"")
elif (c == "".""):
print(""----..----\n\n"")"
2421,Write a Python Program to Generate Random binary string,"# Python program for random
# binary string generation
import random
# Function to create the
# random binary string
def rand_key(p):
# Variable to store the
# string
key1 = """"
# Loop to find the string
# of desired length
for i in range(p):
# randint function to generate
# 0, 1 randomly and converting
# the result into str
temp = str(random.randint(0, 1))
# Concatenatin the random 0, 1
# to the final result
key1 += temp
return(key1)
# Driver Code
n = 7
str1 = rand_key(n)
print(""Desired length random binary string is: "", str1)"
2422,"Write a Python program to Count Uppercase, Lowercase, special character and numeric values using Regex","import re
string = ""ThisIsGeeksforGeeks !, 123""
# Creating separate lists using
# the re.findall() method.
uppercase_characters = re.findall(r""[A-Z]"", string)
lowercase_characters = re.findall(r""[a-z]"", string)
numerical_characters = re.findall(r""[0-9]"", string)
special_characters = re.findall(r""[, .!?]"", string)
print(""The no. of uppercase characters is"", len(uppercase_characters))
print(""The no. of lowercase characters is"", len(lowercase_characters))
print(""The no. of numerical characters is"", len(numerical_characters))
print(""The no. of special characters is"", len(special_characters))"
2423,Count the number of white spaces in a Sentence,"
str=input(""Enter the String:"")
count = 0
for i in range(len(str)):
if str[i] == ' ':
count+=1
print(""Number of white space in a string are "",count)"
2424,Find the nth term in the Fibonacci series using Recursion,"def NthFibonacciNumber(n): if n==0: return 0 elif(n==1): return 1 else: return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2)n=int(input(""Enter the N value:""))print(""Nth Fibonacci Number is:"",NthFibonacciNumber(n))"
2425,Search a specified integer in an array,"
arr=[]
temp=0
pos=0
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the search element:"")
ele=int(input())
print(""Array elements are:"")
for i in range(0,size):
print(arr[i],end="" "")
for i in range(0,size):
if arr[i] == ele:
temp = 1
if temp==1:
print(""\nElement found...."")
else:
print(""\nElement not found...."")"
2426,Convert Lowercase to Uppercase using the inbuilt function,"
str=input(""Enter the String(Lower case):"")
print(""Upper case String is:"", str.upper())"
2427,"
Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
","
def NumGenerator(n):
for i in range(n+1):
if i%5==0 and i%7==0:
yield i
n=int(raw_input())
values = []
for i in NumGenerator(n):
values.append(str(i))
print "","".join(values)
"
2428,Python Program to Search for an Element in the Linked List without using Recursion,"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 is not None:
print(current.data, end = ' ')
current = current.next
def find_index(self, key):
current = self.head
index = 0
while current:
if current.data == key:
return index
current = current.next
index = index + 1
return -1
a_llist = LinkedList()
for data in [4, -3, 1, 0, 9, 11]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()
key = int(input('What data item would you like to search for? '))
index = a_llist.find_index(key)
if index == -1:
print(str(key) + ' was not found.')
else:
print(str(key) + ' is at index ' + str(index) + '.')"
2429,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)"
2430,Program to convert Octal To Hexadecimal,"
i=0
octal=int(input(""Enter Octal number:""))
Hex=['0']*50
decimal = 0
sem = 0
#Octal to decimal covert
while octal!=0:
decimal=decimal+(octal%10)*pow(8,sem);
sem+=1
octal=octal// 10
#Decimal to Hexadecimal
while decimal!=0:
rem=decimal%16
#Convert Integer to char
if rem<10:
Hex[i]=chr(rem+48)#48 Ascii=0
i+=1
else:
Hex[i]=chr(rem+55) #55 Ascii=7
i+=1
decimal//=16
print(""Hexadecimal number is:"")
for j in range(i-1,-1,-1):
print(Hex[j],end="""")"
2431,Program to find square root of a number,"
import math
num=int(input(""Enter the Number:""))
print(""Square root of "",num,"" is : "",math.sqrt(num))"
2432,Find the power of a number using recursion,"def Power(num1,num2): if num2==0: return 1 return num1*Power(num1, num2-1)num1=int(input(""Enter the base value:""))num2=int(input(""Enter the power value:""))print(""Power of Number Using Recursion is:"",Power(num1,num2))"
2433,Convert a decimal number to hexadecimal using recursion,"str3=""""def DecimalToHexadecimal(n): global str3 if(n!=0): rem = n % 16 if (rem < 10): str3 += (chr)(rem + 48) # 48 Ascii = 0 else: str3 += (chr)(rem + 55) #55 Ascii = 7 DecimalToHexadecimal(n // 16) return str3n=int(input(""Enter the Decimal Value:""))str=DecimalToHexadecimal(n)print(""Hexadecimal Value of Decimal number is:"",''.join(reversed(str)))"
2434,Python Program to Generate Gray Codes using Recursion,"def get_gray_codes(n):
""""""Return n-bit Gray code in a list.""""""
if n == 0:
return ['']
first_half = get_gray_codes(n - 1)
second_half = first_half.copy()
first_half = ['0' + code for code in first_half]
second_half = ['1' + code for code in reversed(second_half)]
return first_half + second_half
n = int(input('Enter the number of bits: '))
codes = get_gray_codes(n)
print('All {}-bit Gray Codes:'.format(n))
print(codes)"
2435,Write a program to print the pattern,"
print(""Enter the row and column size:"");
row_size=int(input())
for out in range(1,row_size+1):
for i in range(0,row_size):
print(out,end="""")
print(""\r"")"
2436,Python Program to Remove the Characters of Odd Index Values in a String,"def modify(string):
final = """"
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string=raw_input(""Enter string:"")
print(""Modified string is:"")
print(modify(string))"
2437,Python Program to Generate all the Divisors of an Integer,"
n=int(input(""Enter an integer:""))
print(""The divisors of the number are:"")
for i in range(1,n+1):
if(n%i==0):
print(i)"
2438,Program to print series 0 2 6 12 20 30 42 ...N,"n=int(input(""Enter the range of number(Limit):""))i=1while i<=n: print((i*i)-i,end="" "") i+=1"
2439,Python Program to Reverse a String Using Recursion,"def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input(""Enter the string to be reversed: ""))
print(reverse(a))"
2440,Python Program To Find the Smallest and Largest Elements in the Binary Search Tree,"class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)
def search(self, key):
if self.key > key:
if self.left is not None:
return self.left.search(key)
else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key)
else:
return None
return self
class BSTree:
def __init__(self):
self.root = None
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
def search(self, key):
if self.root is not None:
return self.root.search(key)
def get_smallest(self):
if self.root is not None:
current = self.root
while current.left is not None:
current = current.left
return current.key
def get_largest(self):
if self.root is not None:
current = self.root
while current.right is not None:
current = current.right
return current.key
bstree = BSTree()
print('Menu (this assumes no duplicate keys)')
print('add ')
print('smallest')
print('largest')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
if operation == 'smallest':
smallest = bstree.get_smallest()
print('Smallest element: {}'.format(smallest))
if operation == 'largest':
largest = bstree.get_largest()
print('Largest element: {}'.format(largest))
elif operation == 'quit':
break"
2441,Python Program to Implement Comb Sort,"def comb_sort(alist):
def swap(i, j):
alist[i], alist[j] = alist[j], alist[i]
gap = len(alist)
shrink = 1.3
no_swap = False
while not no_swap:
gap = int(gap/shrink)
if gap < 1:
gap = 1
no_swap = True
else:
no_swap = False
i = 0
while i + gap < len(alist):
if alist[i] > alist[i + gap]:
swap(i, i + gap)
no_swap = False
i = i + 1
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
comb_sort(alist)
print('Sorted list: ', end='')
print(alist)"
2442,Check whether a given matrix is an identity matrix or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
# check Diagonal elements are 1 and rest elements are 0
point=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
# check for diagonals element
if i == j and matrix[i][j] != 1:
point=1
break
#check for rest elements
elif i!=j and matrix[i][j]!=0:
point=1
break
if point==1:
print(""Given Matrix is not an identity matrix."")
else:
print(""Given Matrix is an identity matrix."")"
2443,"Program to print series 1,22,333,4444...n","n=int(input(""Enter the range of number(Limit):""))for out in range(n+1): for i in range(out): print(out,end="""") print(end="" "")"
2444,Multiply two numbers without using multiplication(*) operator,"
num1=int(input(""Enter the First numbers :""))
num2=int(input(""Enter the Second number:""))
sum=0
for i in range(1,num1+1):
sum=sum+num2
print(""The multiplication of "",num1,"" and "",num2,"" is "",sum)
"
2445,Program to count the number of digits in an integer.,"
''' Write
a Python program to count the number of digits in an integer. or
Write a program to count the
number of digits in an integer using
Python '''
n=int(input(""Enter a number:""))
count=0
while n>0:
n=int(n/10)
count+=1
print(""The number of digits in the number is"", count)
"
2446,"Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.
:","Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for k in d.keys():
print k
printDict()
"
2447,"
Assuming that we have some email addresses in the ""username@companyname.com"" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.
","import re
emailAddress = raw_input()
pat2 = ""(\w+)@(\w+)\.(com)""
r2 = re.match(pat2,emailAddress)
print r2.group(2)
"
2448,Remove duplicate elements in an array ,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
arr.sort()
j=0
#Remove duplicate element
for i in range(0, size-1):
if arr[i] != arr[i + 1]:
arr[j]=arr[i]
j+=1
arr[j] = arr[size - 1]
j+=1
print(""After removing duplicate element array is"")
for i in range(0, j):
print(arr[i],end="" "")"
2449,Python Program to Find the Binary Equivalent of a Number without Using Recursion,"n=int(input(""Enter a number: ""))
a=[]
while(n>0):
dig=n%2
a.append(dig)
n=n//2
a.reverse()
print(""Binary Equivalent is: "")
for i in a:
print(i,end="" "")"
2450,"Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.
:","Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[5:]
printList()
"
2451,Python Program to Find the GCD of Two Numbers,"import fractions
a=int(input(""Enter the first number:""))
b=int(input(""Enter the second number:""))
print(""The GCD of the two numbers is"",fractions.gcd(a,b))"
2452,Python Program to Implement Floyd-Warshall Algorithm,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def floyd_warshall(g):
""""""Return dictionaries distance and next_v.
distance[u][v] is the shortest distance from vertex u to v.
next_v[u][v] is the next vertex after vertex v in the shortest path from u
to v. It is None if there is no path between them. next_v[u][u] should be
None for all u.
g is a Graph object which can have negative edge weights.
""""""
distance = {v:dict.fromkeys(g, float('inf')) for v in g}
next_v = {v:dict.fromkeys(g, None) for v in g}
for v in g:
for n in v.get_neighbours():
distance[v][n] = v.get_weight(n)
next_v[v][n] = n
for v in g:
distance[v][v] = 0
next_v[v][v] = None
for p in g:
for v in g:
for w in g:
if distance[v][w] > distance[v][p] + distance[p][w]:
distance[v][w] = distance[v][p] + distance[p][w]
next_v[v][w] = next_v[v][p]
return distance, next_v
def print_path(next_v, u, v):
""""""Print shortest path from vertex u to v.
next_v is a dictionary where next_v[u][v] is the next vertex after vertex u
in the shortest path from u to v. It is None if there is no path between
them. next_v[u][u] should be None for all u.
u and v are Vertex objects.
""""""
p = u
while (next_v[p][v]):
print('{} -> '.format(p.get_key()), end='')
p = next_v[p][v]
print('{} '.format(v.get_key()), end='')
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('floyd-warshall')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')
elif operation == 'floyd-warshall':
distance, next_v = floyd_warshall(g)
print('Shortest distances:')
for start in g:
for end in g:
if next_v[start][end]:
print('From {} to {}: '.format(start.get_key(),
end.get_key()),
end = '')
print_path(next_v, start, end)
print('(distance {})'.format(distance[start][end]))
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2453,Find the maximum 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 maximum element of the given 2d array
max=-sys.maxsize-1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]>=max:
max=matrix[i][j]
# Display the largest element of the given matrix
print(""The Maximum element of the Given 2d array is: "",max)"
2454,Program to remove all numbers from a String,"
str=input(""Enter the String:"")
str2 = []
i = 0
while i < len(str):
ch = str[i]
if not(ch >= '0' and ch <= '9'):
str2.append(ch)
i += 1
Final_String = ''.join(str2)
print(""After removing numbers string is:"",Final_String)"
2455,Write a program to Display your name and some Message ,"
print(""Sourav Patra"")
print(""Welcome to Python"")
print(""Welcome to our page www.csinfo360.com"")
print(""Programming Practice"")
print(""Thank you!"")
"
2456,Program to check two matrix are equal or not,"# Get size of 1st matrix
row_size=int(input(""Enter the row Size Of the 1st Matrix:""))
col_size=int(input(""Enter the columns Size Of the 1st Matrix:""))
# Get size of 2nd matrix
row_size1=int(input(""Enter the row Size Of the 1st Matrix:""))
col_size1=int(input(""Enter the columns Size Of the 2nd Matrix:""))
matrix=[]
# Taking input of the 1st matrix
print(""Enter the 1st Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the 2nd Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compare two matrices
point=0
if row_size==row_size1 and col_size==col_size1:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != matrix1[i][j]:
point=1
break
else:
print(""Two matrices are not equal."")
exit(0)
if point==1:
print(""Two matrices are not equal."")
else:
print(""Two matrices are equal."")"
2457,Program to find the nth Hashed number,"
print(""Enter the Nth value:"")
rangenumber=int(input())
num = 1
c = 0
letest = 0
while (c != rangenumber):
num2=num
num1=num
sum=0
while(num1!=0):
rem=num1%10
num1=num1//10
sum=sum+rem
if(num2%sum==0):
c+=1
letest=num
num = num + 1
print(rangenumber,""th Harshad number is "", letest);
"
2458,Program to print series 1 9 17 33 49 73 97 ...N,"n=int(input(""Enter the range of number(Limit):""))i=1pr=0while i<=n: if(i%2==0): pr=2*pow(i, 2) +1 print(pr,end="" "") else: pr = 2*pow(i, 2) - 1 print(pr, end="" "") i+=1"
2459,Program to convert Decimal to Hexadecimal,"
i=0
dec=int(input(""Enter Decimal number: ""))
Hex=['0']*50
while dec!=0:
rem=dec%16;
#Convert Integer to char
if rem<10:
Hex[i]=chr(rem+48)#48 Ascii=0
i+=1
else:
Hex[i]=chr(rem+55) #55 Ascii=7
i+=1
dec//=16
print(""Hexadecimal number is:"")
for j in range(i-1,-1,-1):
print(Hex[j],end="""")"
2460,Python Program to Print Largest Even and Largest Odd Number in a List,"
n=int(input(""Enter the number of elements to be in the list:""))
b=[]
for i in range(0,n):
a=int(input(""Element: ""))
b.append(a)
c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1+1
for j in d:
count2=count2+1
print(""Largest even number:"",c[count1-1])
print(""Largest odd number"",d[count2-1])"
2461,"Program to print series 2,15,41,80...n","
print(""Enter the range of number(Limit):"")
n=int(input())
i=1
value=2
while(i<=n):
print(value,end="" "")
value+=i*13
i+=1"
2462,"Python Program to Construct a Tree & Perform Insertion, Deletion, Display","class Tree:
def __init__(self, data=None, parent=None):
self.key = data
self.children = []
self.parent = parent
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def remove(self):
parent = self.parent
index = parent.children.index(self)
parent.children.remove(self)
for child in reversed(self.children):
parent.children.insert(index, child)
child.parent = parent
def bfs_display(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')
tree = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('remove ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
new_node.parent = ref_node
ref_node.add(new_node)
elif operation == 'remove':
data = int(do[1])
to_remove = tree.search(data)
if tree == to_remove:
if tree.children == []:
tree = None
else:
leaf = tree.children[0]
while leaf.children != []:
leaf = leaf.children[0]
leaf.parent.children.remove(leaf)
leaf.parent = None
leaf.children = tree.children
tree = leaf
else:
to_remove.remove()
elif operation == 'display':
if tree is not None:
print('BFS traversal display: ', end='')
tree.bfs_display()
print()
else:
print('Tree is empty.')
elif operation == 'quit':
break"
2463,Python Program to Reverse only First N Elements of 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, n):
if n == 0:
return
before = None
current = llist.head
if current is None:
return
after = current.next
for i in range(n):
current.next = before
before = current
current = after
if after is None:
break
after = after.next
llist.head.next = current
llist.head = before
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))
n = int(input('Enter the number of elements you want to reverse in the list: '))
reverse_llist(a_llist, n)
print('The new list: ')
a_llist.display()"
2464,Python Program to Solve Rod Cutting Problem using Dynamic Programming with Memoization,"def cut_rod(p, n):
""""""Take a list p of prices and the rod length n and return lists r and s.
r[i] is the maximum revenue that you can get and s[i] is the length of the
first piece to cut from a rod of length i.""""""
# r[i] is the maximum revenue for rod length i
# r[i] = -1 means that r[i] has not been calculated yet
r = [-1]*(n + 1)
# s[i] is the length of the initial cut needed for rod length i
# s[0] is not needed
s = [-1]*(n + 1)
cut_rod_helper(p, n, r, s)
return r, s
def cut_rod_helper(p, n, r, s):
""""""Take a list p of prices, the rod length n, a list r of maximum revenues
and a list s of initial cuts and return the maximum revenue that you can get
from a rod of length n.
Also, populate r and s based on which subproblems need to be solved.
""""""
if r[n] >= 0:
return r[n]
if n == 0:
q = 0
else:
q = -1
for i in range(1, n + 1):
temp = p[i] + cut_rod_helper(p, n - i, r, s)
if q < temp:
q = temp
s[n] = i
r[n] = q
return q
n = int(input('Enter the length of the rod in inches: '))
# p[i] is the price of a rod of length i
# p[0] is not needed, so it is set to None
p = [None]
for i in range(1, n + 1):
price = input('Enter the price of a rod of length {} in: '.format(i))
p.append(int(price))
r, s = cut_rod(p, n)
print('The maximum revenue that can be obtained:', r[n])
print('The rod needs to be cut into length(s) of ', end='')
while n > 0:
print(s[n], end=' ')
n -= s[n]"
2465,Python Program to Count the Number of Vowels Present in a String using Sets,"s=raw_input(""Enter string:"")
count = 0
vowels = set(""aeiou"")
for letter in s:
if letter in vowels:
count += 1
print(""Count of the vowels is:"")
print(count)"
2466,Find out all Disarium numbers present within a given range,"
import math
print(""Enter a range:"")
range1=int(input())
range2=int(input())
print(""Disarium numbers between "",range1,"" and "",range2,"" are: "")
for i in range(range1,range2+1):
num =i
c = 0
while num != 0:
num //= 10
c += 1
num = i
sum = 0
while num != 0:
rem = num % 10
sum += math.pow(rem, c)
num //= 10
c -= 1
if sum == i:
print(i,end="" "")"
2467,Python Program to Modify the Linked List such that All Even Numbers appear before all the Odd Numbers in the Modified 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 get_node(self, index):
current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def insert_at_beg(self, new_node):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def move_even_before_odd(llist):
current = llist.head
while current:
temp = current.next
if current.data % 2 == 0:
llist.remove(current)
llist.insert_at_beg(current)
current = temp
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))
move_even_before_odd(a_llist)
print('The new list: ')
a_llist.display()"
2468,Program to display a lower triangular matrix,"# 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()])
#Display Lower triangular matrix
print(""Lower Triangular Matrix is:\n"")
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i=row_size-print_control_x+1: print(""*"",end="""") else: print("" "", end="""") if out <= row_size // 2: print_control_x+=1 else: print_control_x-=1 print(""\r"")"
2471,Python Program to Implement Fibonacci Heap,"import math
class FibonacciTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0
def add_at_end(self, t):
self.children.append(t)
self.order = self.order + 1
class FibonacciHeap:
def __init__(self):
self.trees = []
self.least = None
self.count = 0
def insert(self, key):
new_tree = FibonacciTree(key)
self.trees.append(new_tree)
if (self.least is None or key < self.least.key):
self.least = new_tree
self.count = self.count + 1
def get_min(self):
if self.least is None:
return None
return self.least.key
def extract_min(self):
smallest = self.least
if smallest is not None:
for child in smallest.children:
self.trees.append(child)
self.trees.remove(smallest)
if self.trees == []:
self.least = None
else:
self.least = self.trees[0]
self.consolidate()
self.count = self.count - 1
return smallest.key
def consolidate(self):
aux = (floor_log2(self.count) + 1)*[None]
while self.trees != []:
x = self.trees[0]
order = x.order
self.trees.remove(x)
while aux[order] is not None:
y = aux[order]
if x.key > y.key:
x, y = y, x
x.add_at_end(y)
aux[order] = None
order = order + 1
aux[order] = x
self.least = None
for k in aux:
if k is not None:
self.trees.append(k)
if (self.least is None
or k.key < self.least.key):
self.least = k
def floor_log2(x):
return math.frexp(x)[1] - 1
fheap = FibonacciHeap()
print('Menu')
print('insert ')
print('min get')
print('min extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
fheap.insert(data)
elif operation == 'min':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Minimum value: {}'.format(fheap.get_min()))
elif suboperation == 'extract':
print('Minimum value removed: {}'.format(fheap.extract_min()))
elif operation == 'quit':
break"
2472,Program to Find sum of series 1+(1+3)+(1+3+5)+....+N,"
print(""Enter the range of number(Limit):"")
n = int(input())
i = 1
sum = 0
while (i <= n):
for j in range(1, i + 1,2):
sum+=j
i += 2
print(""The sum of the series = "", sum)"
2473,Program to Find nth Neon Number ,"
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
sqr = num * num
# Sum of digit
sum = 0
while sqr != 0:
rem = sqr % 10
sum += rem
sqr //= 10
if sum == num:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Magic number is "",latest)"
2474,Python Program to Take the Temperature in Celcius and Covert it to Farenheit,"
celsius=int(input(""Enter the temperature in celcius:""))
f=(celsius*1.8)+32
print(""Temperature in farenheit is:"",f)"
2475,Find all non repeated characters in a string,"str=input(""Enter Your String:"")arr=[0]*256for i in range(len(str)): if str[i]!=' ': num=ord(str[i]) arr[num]+=1ch=' 'print(""All Non-repeating character in a given string is: "",end="""")for i in range(len(str)): if arr[ord(str[i])] ==1: ch=str[i] print(ch,end="" "")"
2476,Print Fibonacci Series using recursion,"def FibonacciSeries(n): if n==0: return 0 elif(n==1): return 1 else: return FibonacciSeries(n-1)+FibonacciSeries(n-2)n=int(input(""Enter the Limit:""))print(""All Fibonacci Numbers in the given Range are:"")for i in range(0,n): print(FibonacciSeries(i),end="" "")"
2477,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
"
2478,Python Program to Find the LCM of Two Numbers,"a=int(input(""Enter the first number:""))
b=int(input(""Enter the second number:""))
if(a>b):
min1=a
else:
min1=b
while(1):
if(min1%a==0 and min1%b==0):
print(""LCM is:"",min1)
break
min1=min1+1"
2479,Convert temperature from Fahrenheit to Celsius ,"
fahrenheit=int(input(""Enter degree in fahrenheit: ""))
celsius= (fahrenheit-32)*5/9;
print(""Degree in celsius is"",celsius)"
2480,Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.,"s = raw_input()
d={""UPPER CASE"":0, ""LOWER CASE"":0}
for c in s:
if c.isupper():
d[""UPPER CASE""]+=1
elif c.islower():
d[""LOWER CASE""]+=1
else:
pass
print ""UPPER CASE"", d[""UPPER CASE""]
print ""LOWER CASE"", d[""LOWER CASE""]
"
2481,Program to Find subtraction of two matrices,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Subtraction of two matrices
sub_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sub_matrix[i][j]=matrix[i][j]-matrix1[i][j]
# display the Subtraction of two matrices
print(""Subtraction of the two Matrices is:"")
for m in sub_matrix:
print(m)"
2482,Python Program to Find the Length of a List Using Recursion,"def length(lst):
if not lst:
return 0
return 1 + length(lst[1::2]) + length(lst[2::2])
a=[1,2,3]
print(""Length of the string is: "")
print(a)"
2483,Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.,"values=raw_input()
l=values.split("","")
t=tuple(l)
print l
print t
"
2484, Find the sum of N numbers in an array,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = float(input())
arr.append(num)
sum=0.0
for j in range(0,size):
sum+= arr[j]
print(""sum of "",size,"" number : "",sum)"
2485,Program to check whether a matrix is diagonal or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
# check except Diagonal elements are 0 or not
point=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
# check for diagonals element
if i!=j and matrix[i][j]!=0:
point=1
break
if point==1:
print(""Given Matrix is not a diagonal Matrix."")
else:
print(""Given Matrix is a diagonal Matrix."")"
2486,Program to check whether a matrix is symmetric or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
if row_size!=col_size:
print(""Given Matrix is not a Square Matrix."")
else:
#compute the transpose matrix
tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0, row_size):
for j in range(0, col_size):
tran_matrix[i][j] = matrix[j][i]
# check given matrix elements and transpose
# matrix elements are same or not.
flag=0
for i in range(0, row_size):
for j in range(0, col_size):
if matrix[i][j] != tran_matrix[i][j]:
flag=1
break
if flag==1:
print(""Given Matrix is not a symmetric Matrix."")
else:
print(""Given Matrix is a symmetric Matrix."")"
2487,Program to Find nth Evil Number,"
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
one_c = 0
num1 = num
while num1 != 0:
if num1 % 2 == 1:
one_c += 1
num1 //= 2
if one_c % 2 == 0:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Evil number is "",latest)"
2488,Python Program to Print Table of a Given Number,"
n=int(input(""Enter the number to print the tables for:""))
for i in range(1,11):
print(n,""x"",i,""="",n*i)"
2489,Python Program to Implement Heapsort,"def heapsort(alist):
build_max_heap(alist)
for i in range(len(alist) - 1, 0, -1):
alist[0], alist[i] = alist[i], alist[0]
max_heapify(alist, index=0, size=i)
def parent(i):
return (i - 1)//2
def left(i):
return 2*i + 1
def right(i):
return 2*i + 2
def build_max_heap(alist):
length = len(alist)
start = parent(length - 1)
while start >= 0:
max_heapify(alist, index=start, size=length)
start = start - 1
def max_heapify(alist, index, size):
l = left(index)
r = right(index)
if (l < size and alist[l] > alist[index]):
largest = l
else:
largest = index
if (r < size and alist[r] > alist[largest]):
largest = r
if (largest != index):
alist[largest], alist[index] = alist[index], alist[largest]
max_heapify(alist, largest, size)
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
heapsort(alist)
print('Sorted list: ', end='')
print(alist)"
2490,Python Program to Count Number of Non Leaf Nodes of a given Tree,"class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def count_nonleaf_nodes(self):
nonleaf_count = 0
if self.children != []:
nonleaf_count = 1
for child in self.children:
nonleaf_count = nonleaf_count + child.count_nonleaf_nodes()
return nonleaf_count
tree = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('count')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)
elif operation == 'count':
if tree is None:
print('Tree is empty.')
else:
count = tree.count_nonleaf_nodes()
print('Number of nonleaf nodes: {}'.format(count))
elif operation == 'quit':
break"
2491,Python Program to Count the Number of Lines in a Text File,"fname = input(""Enter file name: "")
num_lines = 0
with open(fname, 'r') as f:
for line in f:
num_lines += 1
print(""Number of lines:"")
print(num_lines)"
2492,Program to print multiplication table of a given number,
2493,Check if two arrays are the disjoint or not,"
arr=[]
arr2=[]
size = int(input(""Enter the size of the 1st array: ""))
size2 = int(input(""Enter the size of the 2nd array: ""))
print(""Enter the Element of the 1st array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the Element of the 2nd array:"")
for i in range(0,size2):
num2 = int(input())
arr2.append(num2)
count=0
for i in range(0, size):
for j in range(0, size2):
if arr[i] == arr2[j]:
count+=1
if count>=1:
print(""Arrays are not disjoint."")
else:
print(""Arrays are disjoint."")"
2494,Print every character of a string twice,"str=input(""Enter Your String:"")for inn in range(0,len(str)): print(str[inn]+str[inn],end="""")"
2495,Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.,"s = raw_input()
words = [word for word in s.split("" "")]
print "" "".join(sorted(list(set(words))))
"
2496,Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List,"import random
a=[]
n=int(input(""Enter number of elements:""))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)"
2497,Write a program to calculate compound interest,"principle=float(input(""Enter principle:""))
rate=float(input(""Enter rate(%):""))
n=float(input(""Enter n:""))
time=float(input(""Enter time:""))
amount=principle*pow(1+(rate/100.0)/n,n*time)
print(""The compound interest is"",amount)"
2498,"Define a class named American and its subclass NewYorker.
:","
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
print anAmerican
print aNewYorker
"
2499,Program to compute the area and perimeter of Rhombus,"
print(""Enter the two Diagonals Value:"")
p=int(input())
q=int(input())
a=int(input(""Enter the length of the side value:""))
area=(p*q)/2.0
perimeter=(4*a)
print(""Area of the Rhombus = "",area)
print(""Perimeter of the Rhombus = "",perimeter)
"
2500, Program to Print the Hollow Diamond Star Pattern,"
row_size=int(input(""Enter the row size:""))
print_control_x=row_size//2+1
for out in range(1,row_size+1):
for inn in range(1,row_size+1):
if inn==print_control_x or inn==row_size-print_control_x+1:
print(""*"",end="""")
else:
print("" "", end="""")
if out <= row_size // 2:
print_control_x-=1
else:
print_control_x+=1
print(""\r"")"
2501,Remove duplicate words from string,"str=input(""Enter Your String:"")sub_str=str.split("" "")len1=len(sub_str)print(""After removing duplicate words from a given String is:"")for inn in range(len1): out=inn+1 while out= p + 1: sub_str[p]=sub_str[p+1] len1-=1 else: out+=1for inn in range(len1): print(sub_str[inn],end="" "")"
2502,"
Please write a program to shuffle and print the list [3,6,7,8].
:","
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
"
2503,Write a program to Find the nth Perfect Number,"
'''Write a Python
program to find the nth perfect number. or Write a
program to find the nth perfect number using Python '''
print(""Enter a Nth Number:"")
rangenumber=int(input())
c = 0
letest = 0
num = 1
while (c != rangenumber):
sum = 0
for i in range(num):
if (num % i == 0):
sum = sum + i
if (sum == num):
c+=1
letest = num
num = num + 1
print(rangenumber,""th perfect number is "",letest)
"
2504,Python Program to Count Number of Leaf Node in a Tree,"class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def count_leaf_nodes(self):
leaf_nodes = []
self.count_leaf_nodes_helper(leaf_nodes)
return len(leaf_nodes)
def count_leaf_nodes_helper(self, leaf_nodes):
if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_nodes_helper(leaf_nodes)
tree = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('count')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)
elif operation == 'count':
if tree is None:
print('Tree is empty.')
else:
count = tree.count_leaf_nodes()
print('Number of leaf nodes: {}'.format(count))
elif operation == 'quit':
break"
2505,Python Program to Create a Class and Compute the Area and the Perimeter of the Circle,"import math
class circle():
def __init__(self,radius):
self.radius=radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius
r=int(input(""Enter radius of circle: ""))
obj=circle(r)
print(""Area of circle:"",round(obj.area(),2))
print(""Perimeter of circle:"",round(obj.perimeter(),2))"
2506,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)"
2507,Python Program to Count all Paths in a Grid with Holes using Dynamic Programming with Memoization,"def count_paths(m, n, holes):
""""""Return number of paths from (0, 0) to (m, n) in an m x n grid.
holes is a list of tuples (x, y) where each tuple is a coordinate which is
blocked for a path.
""""""
paths = [[-1]*(m + 1) for _ in range(n + 1)]
return count_paths_helper(m, n, holes, paths, n, m)
def count_paths_helper(m, n, holes, paths, x, y):
""""""Return number of paths from (0, 0) to (x, y) in an m x n grid.
holes is a list of tuples (x, y) where each tuple is a coordinate which is
blocked for a path.
The function uses the table paths (implemented as a list of lists) where
paths[a][b] will store the number of paths from (0, 0) to (a, b).
""""""
if paths[x][y] >= 0:
return paths[x][y]
if (x, y) in holes:
q = 0
elif x == 0 and y == 0:
q = 1
elif x == 0:
q = count_paths_helper(m, n, holes, paths, x, y - 1)
elif y == 0:
q = count_paths_helper(m, n, holes, paths, x - 1, y)
else:
q = count_paths_helper(m, n, holes, paths, x - 1, y) \
+ count_paths_helper(m, n, holes, paths, x, y - 1)
paths[x][y] = q
return q
m, n = input('Enter m, n for the size of the m x n grid (m rows and n columns): ').split(',')
m = int(m)
n = int(n)
print('Enter the coordinates of holes on each line (empty line to stop): ')
holes = []
while True:
hole = input('')
if not hole.strip():
break
hole = hole.split(',')
hole = (int(hole[0]), int(hole[1]))
holes.append(hole)
count = count_paths(m, n, holes)
print('Number of paths from (0, 0) to ({}, {}): {}.'.format(n, m, count))"
2508,Check whether an alphabet is vowel or consonant,"
alphabet=input(""Enter an alphabet:"")
if(alphabet=='a' or alphabet=='A' or alphabet=='e' or alphabet=='E' or alphabet=='i' or alphabet=='I' or alphabet=='o' or alphabet=='O' or alphabet=='u' or alphabet=='U'):
print(""It is Vowel"")
else:
print(""It is Consonant"")"
2509,Program to check whether a matrix is diagonal or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
# check except Diagonal elements are 0 or not
point=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
# check for diagonals element
if i!=j and matrix[i][j]!=0:
point=1
break
if point==1:
print(""Given Matrix is not a diagonal Matrix."")
else:
print(""Given Matrix is a diagonal Matrix."")"
2510," Define a class, which have a class parameter and have a same instance parameter.
:","class Person:
# Define the class parameter ""name""
name = ""Person""
def __init__(self, name = None):
# self.name is the instance parameter
self.name = name
jeffrey = Person(""Jeffrey"")
print ""%s name is %s"" % (Person.name, jeffrey.name)
nico = Person()
nico.name = ""Nico""
print ""%s name is %s"" % (Person.name, nico.name)
"
2511,Find 2nd smallest digit in a given number,"
'''Write a Python
program to Find 2nd smallest digit in a given number. or Write a
program to Find 2nd smallest digit in a given number using Python '''
import sys
print(""Enter the Number :"")
num=int(input())
smallest=sys.maxsize
sec_smallest=sys.maxsize
while num > 0:
reminder = num % 10
if smallest >= reminder:
sec_smallest=smallest
smallest = reminder
elif reminder <= sec_smallest:
sec_smallest=reminder
num =num // 10
print(""The Second Smallest Digit is "", sec_smallest)
"
2512,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= Sec_Largest:
Sec_Largest = reminder
num =num // 10
print(""The Second Largest Digit is :"", Sec_Largest)
"
2513,Division Two Numbers Operator without using Division(/) operator,"
num1=int(input(""Enter first number:""))
num2=int(input(""Enter second number:""))
div=0
while num1>=num2:
num1=num1-num2
div+=1
print(""Division of two number is "",div)
"
2514,Program to check whether a matrix is symmetric or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
if row_size!=col_size:
print(""Given Matrix is not a Square Matrix."")
else:
#compute the transpose matrix
tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0, row_size):
for j in range(0, col_size):
tran_matrix[i][j] = matrix[j][i]
# check given matrix elements and transpose
# matrix elements are same or not.
flag=0
for i in range(0, row_size):
for j in range(0, col_size):
if matrix[i][j] != tran_matrix[i][j]:
flag=1
break
if flag==1:
print(""Given Matrix is not a symmetric Matrix."")
else:
print(""Given Matrix is a symmetric Matrix."")"
2515,Python Program to Find if Directed Graph contains Cycle using DFS,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def is_cycle_present(graph):
""""""Return True if cycle is present in the graph.""""""
on_stack = set()
visited = set()
for v in graph:
if v not in visited:
if is_cycle_present_helper(v, visited, on_stack):
return True
return False
def is_cycle_present_helper(v, visited, on_stack):
""""""Return True if the DFS traversal starting at vertex v detects a
cycle. Uses set visited to keep track of nodes that have been visited. Uses
set on_stack to keep track of nodes that are 'on the stack' of the recursive
calls.""""""
if v in on_stack:
return True
on_stack.add(v)
for dest in v.get_neighbours():
if dest not in visited:
if is_cycle_present_helper(dest, visited, on_stack):
return True
on_stack.remove(v)
visited.add(v)
return False
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('cycle')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_edge_exist(v1, v2):
g.add_edge(v1, v2)
else:
print('Edge already exists.')
elif operation == 'cycle':
if is_cycle_present(g):
print('Cycle present.')
else:
print('Cycle not present.')
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2516,Check if one array is a subset of another array or not ,"
arr=[]
arr2=[]
size = int(input(""Enter the size of the 1st array: ""))
size2 = int(input(""Enter the size of the 2nd array: ""))
print(""Enter the Element of the 1st array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the Element of the 2nd array:"")
for i in range(0,size2):
num2 = int(input())
arr2.append(num2)
count=0
for i in range(0, size):
for j in range(0, size2):
if arr[i] == arr2[j]:
count+=1
if count==size2:
print(""Array two is a subset of array one."")
else:
print(""Array two is not a subset of array one."")"
2517,Selection Sort Program in Python | Java | C | C++,"
size=int(input(""Enter the size of the array:""));
arr=[]
print(""Enter the element of the array:"");
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Before Sorting Array Elements are: "",arr)
for out in range(0,size-1):
min = out
for inn in range(out+1, size):
if arr[inn] < arr[min]:
min = inn
temp=arr[out]
arr[out]=arr[min]
arr[min]=temp
print(""\nAfter Sorting Array Elements are: "",arr)
"
2518, Program to print the Half Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
for out in range(row_size+1):
for i in range(1,out+1):
print(i,end="""")
print(""\r"")
"
2519,Longest palindromic substring in a string,"def reverse(s): str = """" for i in s: str = i + str return strstr=input(""Enter Your String:"")sub_str=str.split("" "")sub_str1=[]p=0flag=0maxInd=0max=0str_rev=""""print(""Palindrome Substring are:"")for inn in range(len(sub_str)): str_rev= sub_str[inn] if reverse(str_rev).__eq__(sub_str[inn]): sub_str1.append(sub_str[inn]) print(sub_str1[p]) p +=1 flag = 1len2 = pif flag==1: max = len(sub_str1[0]) for inn in range(0,len2): len1 = len(sub_str1[inn]) if len1 > max: max=len1 maxInd=inn print(""Longest palindrome Substring is "",sub_str1[maxInd])else: print(""No palindrome Found"")"
2520,Program to Convert Binary to Hexadecimal,"print(""Enter a binary number:"")
binary=input()
if(len(binary)%4==1):
binary=""000""+binary
if(len(binary)%4==2):
binary=""00""+binary
if(len(binary)%4==3):
binary=""0""+binary
hex=""""
len=int(len(binary)/4)
print(""len:"",len)
i=0
j=0
k=4
decimal=0
while(iMax_diff: Max_diff = abs(arr[j] - arr[i])print(""Maximum difference between two Element is "",Max_diff)"
2525,Python Program to Illustrate the Operations of Singly Linked List,"class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_beg(self, new_node):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
print('Menu')
print('insert after ')
print('insert before ')
print('insert at beg')
print('insert at end')
print('remove ')
print('quit')
while True:
print('The list: ', end = '')
a_llist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_llist.insert_at_beg(new_node)
elif position == 'end':
a_llist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_llist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_llist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_llist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_llist.get_node(index)
if node is None:
print('No such index.')
continue
a_llist.remove(node)
elif operation == 'quit':
break"
2526,"Program to print series 6,11,21,36,56...n","n=int(input(""Enter the range of number(Limit):""))i=1pr=6diff=5while i<=n: print(pr,end="" "") pr = pr + diff diff = diff + 5 i+=1"
2527,Python Program to Find the Total Sum of a Nested List Using Recursion,"def sum1(lst):
total = 0
for element in lst:
if (type(element) == type([])):
total = total + sum1(element)
else:
total = total + element
return total
print( ""Sum is:"",sum1([[1,2],[3,4]]))"
2528, Program to print the Full Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
np=1
for out in range(0,row_size):
for in1 in range(row_size-1,out,-1):
print("" "",end="""")
for in2 in range(0, np):
print(np,end="""")
np+=2
print(""\r"")
"
2529,"Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.
The numbers obtained should be printed in a comma-separated sequence on a single line.
:","values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print "","".join(values)
"
2530,Check whether two strings are equal or not,"
str=input(""Enter the 1st String:"")
str1=input(""Enter the 2nd String:"")
if(len(str)==len(str1)):
print(""Two strings are equal."")
else:
print(""Two strings are not equal."")"
2531, Program to print the Alphabet Inverted Half Pyramid Pattern,"
print(""Enter the row and column size:"")
row_size=input()
for out in range(ord(row_size),ord('A')-1,-1):
for i in range(ord(row_size)-1,out-1,-1):
print("" "",end="""")
for p in range(ord('A'), out+1):
print(chr(p),end="""")
print(""\r"")
"
2532,"
Please write a program to randomly print a integer number between 7 and 15 inclusive.
:","
import random
print random.randrange(7,16)
"
2533,Python Program to Check Whether a Given Year is a Leap Year,"
year=int(input(""Enter year to be checked:""))
if(year%4==0 and year%100!=0 or year%400==0):
print(""The year is a leap year!)
else:
print(""The year isn't a leap year!)"
2534,Python Program to Find Longest Common Subsequence using Dynamic Programming with Bottom-Up Approach,"def lcs(u, v):
""""""Return c where c[i][j] contains length of LCS of u[i:] and v[j:].""""""
c = [[-1]*(len(v) + 1) for _ in range(len(u) + 1)]
for i in range(len(u) + 1):
c[i][len(v)] = 0
for j in range(len(v)):
c[len(u)][j] = 0
for i in range(len(u) - 1, -1, -1):
for j in range(len(v) - 1, -1, -1):
if u[i] == v[j]:
c[i][j] = 1 + c[i + 1][j + 1]
else:
c[i][j] = max(c[i + 1][j], c[i][j + 1])
return c
def print_lcs(u, v, c):
""""""Print one LCS of u and v using table c.""""""
i = j = 0
while not (i == len(u) or j == len(v)):
if u[i] == v[j]:
print(u[i], end='')
i += 1
j += 1
elif c[i][j + 1] > c[i + 1][j]:
j += 1
else:
i += 1
u = input('Enter first string: ')
v = input('Enter second string: ')
c = lcs(u, v)
print('Longest Common Subsequence: ', end='')
print_lcs(u, v, c)"
2535,Write a program to print the pattern,"
print(""Enter the row and column size:"")
row_size=int(input())
for out in range(row_size,0,-1):
for i in range(row_size,0,-1):
print(i,end="""")
print(""\r"")
"
2536,Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively,"def check(string,ch):
if not string:
return 0
elif string[0]==ch:
return 1+check(string[1:],ch)
else:
return check(string[1:],ch)
string=raw_input(""Enter string:"")
ch=raw_input(""Enter character to check:"")
print(""Count is:"")
print(check(string,ch))"
2537,"Check whether a given Character is Upper case, Lower case, Number or Special Character","
ch=input(""Enter a character:"")
if(ch>='a' and ch<='z'):
print(""The character is lower case"")
elif(ch>='A' and ch<='Z'):
print(""The character is upper case"")
elif(ch>='0' and ch<='9'):
print(""The character is number"")
else:
print(""It is a special character"")
"
2538,"Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
:","Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
"
2539,Program to Find gcd or hcf of two numbers,"
print(""Enter two number to find G.C.D"")
num1=int(input())
num2=int(input())
while(num1!=num2):
if (num1 > num2):
num1 = num1 - num2
else:
num2= num2 - num1
print(""G.C.D is"",num1)
"
2540,Python Program to Solve Fractional Knapsack Problem using Greedy Algorithm,"def fractional_knapsack(value, weight, capacity):
""""""Return maximum value of items and their fractional amounts.
(max_value, fractions) is returned where max_value is the maximum value of
items with total weight not more than capacity.
fractions is a list where fractions[i] is the fraction that should be taken
of item i, where 0 <= i < total number of items.
value[i] is the value of item i and weight[i] is the weight of item i
for 0 <= i < n where n is the number of items.
capacity is the maximum weight.
""""""
# index = [0, 1, 2, ..., n - 1] for n items
index = list(range(len(value)))
# contains ratios of values to weight
ratio = [v/w for v, w in zip(value, weight)]
# index is sorted according to value-to-weight ratio in decreasing order
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0]*len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity/weight[i]
max_value += value[i]*capacity/weight[i]
break
return max_value, fractions
n = int(input('Enter number of items: '))
value = input('Enter the values of the {} item(s) in order: '
.format(n)).split()
value = [int(v) for v in value]
weight = input('Enter the positive weights of the {} item(s) in order: '
.format(n)).split()
weight = [int(w) for w in weight]
capacity = int(input('Enter maximum weight: '))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print('The maximum value of items that can be carried:', max_value)
print('The fractions in which the items should be taken:', fractions)"
2541,Shortest palindromic substring in a string,"def reverse(s): str = """" for i in s: str = i + str return strstr=input(""Enter Your String:"")sub_str=str.split("" "")sub_str1=[]p=0flag=0minInd=0min=0str_rev=""""print(""Palindrome Substrings are:"")for inn in range(len(sub_str)): str_rev= sub_str[inn] if reverse(str_rev).__eq__(sub_str[inn]): sub_str1.append(sub_str[inn]) print(sub_str1[p]) p +=1 flag = 1len2 = pif flag==1: min = len(sub_str1[0]) for inn in range(0,len2): len1 = len(sub_str1[inn]) if len1 < min: min=len1 minInd=inn print(""Smallest palindrome Substring is "",sub_str1[minInd])else: print(""No palindrome Found"")"
2542,Count number of uppercase letters in a string using Recursion,"count=0def NumberOfUpperCase(str,i): global count if (str[i] >= 'A' and str[i] <= 'Z'): count+=1 if (i >0): NumberOfUpperCase(str, i - 1) return countstr=input(""Enter your String:"")NoOfUppercase=NumberOfUpperCase(str,len(str)-1)if(NoOfUppercase==0): print(""No UpperCase Letter present in a given string."")else: print(""Number Of UpperCase Letter Present in a given String is:"",NoOfUppercase)"
2543,Bidirectional Bubble Sort Program in Python | Java | C | C++,"
size=int(input(""Enter the size of the array:""));
arr=[]
print(""Enter the element of the array:"");
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Before Sorting Array Element are: "",arr)
low = 0
high= size-1
while low < high:
for inn in range(low, high):
if arr[inn] > arr[inn+1]:
temp=arr[inn]
arr[inn]=arr[inn+1]
arr[inn+1]=temp
high-=1
for inn in range(high,low,-1):
if arr[inn] < arr[inn-1]:
temp=arr[inn]
arr[inn]=arr[inn-1]
arr[inn-1]=temp
low+=1
print(""\nAfter Sorting Array Element are: "",arr)"
2544,Print the marks obtained by a student in five tests,"import arrayarr=array.array('i', [95,88,77,45,69])print(""Marks obtained by a student in five tests are:"")for i in range(0,5): print(arr[i],end="" "")"
2545,Check if two arrays are equal or not,"
arr=[]
arr2=[]
size = int(input(""Enter the size of the 1st array: ""))
size2 = int(input(""Enter the size of the 2nd array: ""))
print(""Enter the Element of the 1st array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the Element of the 2nd array:"")
for i in range(0,size2):
num2 = int(input())
arr2.append(num2)
arr.sort()
arr2.sort()
flag=1
if size != size2:
flag=0
else:
for i in range(0, size):
if arr[i] != arr2[i]:
flag=0
if flag==0:
print(""Not same...."")
else:
print(""same...."")"
2546,Python Program to Print nth Fibonacci Number using Dynamic Programming with Memoization,"def fibonacci(n):
""""""Return the nth Fibonacci number.""""""
# r[i] will contain the ith Fibonacci number
r = [-1]*(n + 1)
return fibonacci_helper(n, r)
def fibonacci_helper(n, r):
""""""Return the nth Fibonacci number and store the ith Fibonacci number in
r[i] for 0 <= i <= n.""""""
if r[n] >= 0:
return r[n]
if (n == 0 or n == 1):
q = n
else:
q = fibonacci_helper(n - 1, r) + fibonacci_helper(n - 2, r)
r[n] = q
return q
n = int(input('Enter n: '))
ans = fibonacci(n)
print('The nth Fibonacci number:', ans)"
2547,Convert decimal to binary using recursion,"def DecimalToBinary(n): if n==0: return 0 else: return (n% 2 + 10 * DecimalToBinary(n // 2))n=int(input(""Enter the Decimal Value:""))print(""Binary Value of Decimal number is:"",DecimalToBinary(n))"
2548,Python Program to Read a Number n and Compute n+nn+nnn,"
n=int(input(""Enter a number n: ""))
temp=str(n)
t1=temp+temp
t2=temp+temp+temp
comp=n+int(t1)+int(t2)
print(""The value is:"",comp)"
2549,Python Program to Print all Numbers in a Range Divisible by a Given Number,"
lower=int(input(""Enter lower range limit:""))
upper=int(input(""Enter upper range limit:""))
n=int(input(""Enter the number to be divided by:""))
for i in range(lower,upper+1):
if(i%n==0):
print(i)"
2550,Program to convert decimal to octal using while loop,"sem=1
octal=0
print(""Enter the Decimal Number:"")
number=int(input())
while(number !=0):
octal=octal+(number%8)*sem
number=number//8
sem=int(sem*10)
print(""Octal Number is "",octal)
"
2551,Python Program to Determine all Pythagorean Triplets in the Range,"limit=int(input(""Enter upper limit:""))
c=0
m=2
while(climit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1"
2552, Program to print the Solid Half Diamond Number Pattern,"row_size=int(input(""Enter the row size:""))for out in range(row_size,-(row_size+1),-1): for inn in range(row_size,abs(out)-1,-1): print(inn,end="""") print(""\r"")"
2553,Check whether number is Evil Number or Not,"
num=int(input(""Enter a number:""))
one_c=0
while num!=0:
if num%2==1:
one_c+=1
num//=2
if one_c%2==0:
print(""It is an Evil Number."")
else:
print(""It is Not an Evil Number."")"
2554,Check a given number is an Automorphic number using recursion,"def check_AutomorphicNumber(num): sqr = num * num if (num > 0): if (num % 10 != sqr % 10): return -1 else: check_AutomorphicNumber(num // 10) return 0 return 0num=int(input(""Enter a number:""))if (check_AutomorphicNumber(num) == 0): print(""It is an Automorphic Number."")else: print(""It is not an Automorphic Number."")"
2555,Python Program to Read a Text File and Print all the Numbers Present in the Text File,"fname = input(""Enter file name: "")
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter)"
2556,Python Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers,"
lower=int(input(""Enter the lower range:""))
upper=int(input(""Enter the upper range:""))
for i in range (lower,upper+1):
if(i%7==0 and i%5==0):
print(i)"
2557,Python Program to Check whether 2 Linked Lists are Same,"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 is_equal(llist1, llist2):
current1 = llist1.head
current2 = llist2.head
while (current1 and current2):
if current1.data != current2.data:
return False
current1 = current1.next
current2 = current2.next
if current1 is None and current2 is None:
return True
else:
return False
llist1 = LinkedList()
llist2 = LinkedList()
data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))
data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))
if is_equal(llist1, llist2):
print('The two linked lists are the same.')
else:
print('The two linked list are not the same.', end = '')"
2558,Python Program to Implement Binary Tree using Linked List,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('quit')
while True:
print('inorder traversal of binary tree: ', end='')
if btree is not None:
btree.inorder()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'quit':
break"
2559,Program to compute the area and perimeter of Hexagon,"
import math
print(""Enter the length of the side:"")
a=int(input())
area=(3*math.sqrt(3)*math.pow(a,2))/2.0
perimeter=(6*a)
print(""Area of the Hexagon = "",area)
print(""Perimeter of the Hexagon = "",perimeter)
"
2560,"
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
","
def f(n):
if n==0:
return 0
else:
return f(n-1)+100
n=int(raw_input())
print f(n)
"
2561,Program to find the sum of an upper triangular matrix,"# 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()])
#Calculate sum of Upper triangular matrix element
sum=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i>j:
sum += matrix[i][j]
# display the sum of the Upper triangular matrix element
print(""Sum of Upper Triangular Matrix Elements is: "",sum)"
2562,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="" "")"
2563,Program to convert Octal To Hexadecimal,"
i=0
octal=int(input(""Enter Octal number:""))
Hex=['0']*50
decimal = 0
sem = 0
#Octal to decimal covert
while octal!=0:
decimal=decimal+(octal%10)*pow(8,sem);
sem+=1
octal=octal// 10
#Decimal to Hexadecimal
while decimal!=0:
rem=decimal%16
#Convert Integer to char
if rem<10:
Hex[i]=chr(rem+48)#48 Ascii=0
i+=1
else:
Hex[i]=chr(rem+55) #55 Ascii=7
i+=1
decimal//=16
print(""Hexadecimal number is:"")
for j in range(i-1,-1,-1):
print(Hex[j],end="""")"
2564,Program to print mirrored right triangle star pattern,"
print(""Enter the row size:"")
row_size=int(input())
for out in range(row_size+1):
for j in range(row_size-out):
print("" "",end="""")
for p in range(out+1):
print(""*"",end="""")
print(""\r"")"
2565,"
Please generate a random float where the value is between 10 and 100 using Python math module.
:","
import random
print random.random()*100
"
2566,Find a pair with given sum in the array,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)sum=int(input(""Enter the Sum Value:""))flag=0for i in range(0,size-1): for j in range(i+1, size): if arr[i]+arr[j]==sum: flag=1 print(""Given sum pairs of elements are "", arr[i],"" and "", arr[j],"".\n"")if flag==0: print(""Given sum Pair is not Present."")"
2567,Minimum difference between two elements in an array,"import sysarr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)Min_diff=sys.maxsizefor i in range(0,size-1): for j in range(i+1, size): if abs(arr[j]-arr[i])= 0 and temp < alist[j]):
alist[j + 1] = alist[j]
j = j - 1
alist[j + 1] = temp
alist = input('Enter the list of (nonnegative) numbers: ').split()
alist = [int(x) for x in alist]
sorted_list = bucket_sort(alist)
print('Sorted list: ', end='')
print(sorted_list)"
2569,Python Program to Minimize Lateness using Greedy Algorithm,"def minimize_lateness(ttimes, dtimes):
""""""Return minimum max lateness and the schedule to obtain it.
(min_lateness, schedule) is returned.
Lateness of a request i is L(i) = finish time of i - deadline of if
request i finishes after its deadline.
The maximum lateness is the maximum value of L(i) over all i.
min_lateness is the minimum value of the maximum lateness that can be
achieved by optimally scheduling the requests.
schedule is a list that contains the indexes of the requests ordered such
that minimum maximum lateness is achieved.
ttime[i] is the time taken to complete request i.
dtime[i] is the deadline of request i.
""""""
# index = [0, 1, 2, ..., n - 1] for n requests
index = list(range(len(dtimes)))
# sort according to deadlines
index.sort(key=lambda i: dtimes[i])
min_lateness = 0
start_time = 0
for i in index:
min_lateness = max(min_lateness,
(ttimes[i] + start_time) - dtimes[i])
start_time += ttimes[i]
return min_lateness, index
n = int(input('Enter number of requests: '))
ttimes = input('Enter the time taken to complete the {} request(s) in order: '
.format(n)).split()
ttimes = [int(tt) for tt in ttimes]
dtimes = input('Enter the deadlines of the {} request(s) in order: '
.format(n)).split()
dtimes = [int(dt) for dt in dtimes]
min_lateness, schedule = minimize_lateness(ttimes, dtimes)
print('The minimum maximum lateness:', min_lateness)
print('The order in which the requests should be scheduled:', schedule)"
2570,Print the Full Pyramid Alphabet Pattern,"row_size=int(input(""Enter the row size:""))np=1for out in range(0,row_size): for inn in range(row_size-1,out,-1): print("" "",end="""") for p in range(0, np): print(chr(out+65),end="""") np+=2 print(""\r"")"
2571,Program to find the nth Magic Number,"
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num3 = num
num1 = num
sum = 0
# Sum of digit
while num1 != 0:
rem = num1 % 10
sum += rem
num1 //= 10
# Reverse of sum
rev = 0
num2 = sum
while num2 != 0:
rem2 = num2 % 10
rev = rev * 10 + rem2
num2 //= 10
if sum * rev == num3:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Magic number is "",letest)"
2572,Find a pair with given sum in the array,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)sum=int(input(""Enter the Sum Value:""))flag=0for i in range(0,size-1): for j in range(i+1, size): if arr[i]+arr[j]==sum: flag=1 print(""Given sum pairs of elements are "", arr[i],"" and "", arr[j],"".\n"")if flag==0: print(""Given sum Pair is not Present."")"
2573,Program to compute the perimeter of Trapezoid,"
print(""Enter the value of base:"")
a=int(input())
b=int(input())
print(""Enter the value of side:"")
c=int(input())
d=int(input())
perimeter=a+b+c+d
print(""Perimeter of the Trapezoid = "",perimeter)
"
2574,"With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.","n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
"
2575,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))"
2576,Python Program to Implement Shell Sort,"def gaps(size):
# uses the gap sequence 2^k - 1: 1, 3, 7, 15, 31, ...
length = size.bit_length()
for k in range(length - 1, 0, -1):
yield 2**k - 1
def shell_sort(alist):
def insertion_sort_with_gap(gap):
for i in range(gap, len(alist)):
temp = alist[i]
j = i - gap
while (j >= 0 and temp < alist[j]):
alist[j + gap] = alist[j]
j = j - gap
alist[j + gap] = temp
for g in gaps(len(alist)):
insertion_sort_with_gap(g)
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
shell_sort(alist)
print('Sorted list: ', end='')
print(alist)"
2577,Merge Sort Program in Python | Java | C | C++,"
def merge(arr,first,mid,last):
n1 = (mid - first + 1)
n2 = (last - mid)
Left=[0]*n1
Right=[0]*n2
for i in range(n1):
Left[i] = arr[i + first]
for j in range(n2):
Right[j] = arr[mid + j + 1];
k = first
i = 0
j = 0
while i < n1 and j < n2:
if Left[i] <= Right[j]:
arr[k]=Left[i]
i+=1
else:
arr[k]=Right[j]
j+=1
k+=1
while i < n1:
arr[k] = Left[i]
i +=1
k +=1
while j < n2 :
arr[k] = Right[j]
j +=1
k +=1
def mergesort(arr,first,last):
if(first='a' and ch <= 'z') or (ch >= 'A' and ch<= 'Z') or (ch >= '0' and ch <= '9') or (ch == '\0'):
str2.append(ch)
i += 1
Final_String = ''.join(str2)
print(""After removing special character letter string is:"",Final_String)"
2590,"Program to print series 6,9,14,21,30,41,54...N","
print(""Enter the range of number(Limit):"")
n=int(input())
i=1
j=3
value=6
while(i<=n):
print(value,end="" "")
value+=j
j+=2
i+=1"
2591,Check whether number is Neon Number or Not.,"
num=int(input(""Enter a number:""))
sqr=num*num
#Sum of digit
sum=0
while sqr!=0:
rem = sqr % 10
sum += rem
sqr //= 10
if sum==num:
print(""It is a Neon Number."")
else:
print(""It is not a Neon Number."")"
2592, Program to print the Solid Inverted Half Diamond Alphabet Pattern,"row_size=int(input(""Enter the row size:""))for out in range(row_size,-(row_size+1),-1): for in1 in range(1,abs(out)+1): print("" "",end="""") for p in range(abs(out),row_size+1): print((chr)(p+65),end="""") print(""\r"")"
2593,Print array elements in reverse order,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
temp=size
while(temp>=0):
for k in range(0,temp-1,1):
temp2=arr[k]
arr[k]=arr[k+1]
arr[k+1]=temp2
temp-=1
print(""After reversing array is :"")
for i in range(0, size):
print(arr[i],end="" "")"
2594,Python Program to Implement Queues using Stacks,"class Queue:
def __init__(self):
self.inbox = Stack()
self.outbox = Stack()
def is_empty(self):
return (self.inbox.is_empty() and self.outbox.is_empty())
def enqueue(self, data):
self.inbox.push(data)
def dequeue(self):
if self.outbox.is_empty():
while not self.inbox.is_empty():
popped = self.inbox.pop()
self.outbox.push(popped)
return self.outbox.pop()
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
a_queue = Queue()
while True:
print('enqueue ')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
if a_queue.is_empty():
print('Queue is empty.')
else:
dequeued = a_queue.dequeue()
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break"
2595,Print the most occurring elements in an array,"
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
for i in range(0, size):
if arr[i]>=max:
max=arr[i]
for i in range(0,max+1):
freq.append(0)
for i in range(0, size):
freq[arr[i]]+=1
most_oc=0
most_v=0
for i in range(0, size):
if freq[arr[i]] > most_oc:
most_oc = freq[arr[i]]
most_v = arr[i]
print(""The Most occurring Number "",most_v,"" occurs "",most_oc,"" times."")"
2596,Program to find the sum of series 1/1+1/2+1/3..+1/N,"
print(""Enter the range of number:"")
n=int(input())
print(""Enter the value of x:"");
x=int(input())
sum=0
i=1
while(i<=n):
sum+=pow(x,i)
i+=2
print(""The sum of the series = "",sum)"
2597,"Python Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display Operations","class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.first = None
self.last = None
def get_node(self, index):
current = self.first
for i in range(index):
if current is None:
return None
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.prev = ref_node
if ref_node.next is None:
self.last = new_node
else:
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
new_node.next = ref_node
if ref_node.prev is None:
self.first = new_node
else:
new_node.prev = ref_node.prev
new_node.prev.next = new_node
ref_node.prev = new_node
def insert_at_beg(self, new_node):
if self.first is None:
self.first = new_node
self.last = new_node
else:
self.insert_before(self.first, new_node)
def insert_at_end(self, new_node):
if self.last is None:
self.last = new_node
self.first = new_node
else:
self.insert_after(self.last, new_node)
def remove(self, node):
if node.prev is None:
self.first = node.next
else:
node.prev.next = node.next
if node.next is None:
self.last = node.prev
else:
node.next.prev = node.prev
def display(self):
current = self.first
while current:
print(current.data, end = ' ')
current = current.next
a_dllist = DoublyLinkedList()
print('Menu')
print('insert after ')
print('insert before ')
print('insert at beg')
print('insert at end')
print('remove ')
print('quit')
while True:
print('The list: ', end = '')
a_dllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_dllist.insert_at_beg(new_node)
elif position == 'end':
a_dllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_dllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_dllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_dllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_dllist.get_node(index)
if node is None:
print('No such index.')
continue
a_dllist.remove(node)
elif operation == 'quit':
break"
2598,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()"
2599,Python Program to Find the Length of the Linked List using Recursion,"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 length(self):
return self.length_helper(self.head)
def length_helper(self, current):
if current is None:
return 0
return 1 + self.length_helper(current.next)
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))
print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')"
2600,Python Program to Sum All the Items in a Dictionary,"d={'A':100,'B':540,'C':239}
print(""Total sum of values in the dictionary:"")
print(sum(d.values()))"
2601,Program to Find nth Pronic Number,"
import math
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
flag = 0
for j in range(0, num + 1):
if j * (j + 1) == num:
flag = 1
break
if flag == 1:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Pronic number is "",letest)
"
2602,Find words Starting with given characters(Prefix),"str=input(""Enter Your String:"")ch=input(""Enter the Character:"")sub_str=str.split("" "")print(""All the words starting with "",ch,"" are:"")for inn in range(0,len(sub_str)): if sub_str[inn].startswith(ch): print(sub_str[inn],end="" "")"
2603,Program to find sum of series 1+4-9+16-25+.....+N,"
import math
print(""Enter the range of number(Limit):"")
n=int(input())
i=2
sum=1
while(i<=n):
if(i%2==0):
sum+=pow(i,2)
else:
sum-=pow(i,2)
i+=1
print(""The sum of the series = "",sum)"
2604,"Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
:","Solution
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
if tp[i]%2==0:
li.append(tp[i])
tp2=tuple(li)
print tp2
"
2605, 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"")
"
2606,Python Program to Sort the List According to the Second Element in Sublist,"a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j][1]>a[j+1][1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print(a)"
2607,Python Program to Check if a Number is a Strong Number,"
sum1=0
num=int(input(""Enter a number:""))
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print(""The number is a strong number"")
else:
print(""The number is not a strong number"")"
2608,"
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
:","
import random
print random.sample([i for i in range(100,201) if i%2==0], 5)
"
2609,Find the shortest word in a string,"str=input(""Enter Your String:"")sub_str=str.split("" "")minInd=0min=0min = len(sub_str[0])for inn in range(0,len(sub_str)): len1 = len(sub_str[inn]) if len1 < min: min=len1 minInd=innprint(""Smallest Substring(Word) is "",sub_str[minInd])"
2610,"
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()
"
2611,Program to display a lower triangular matrix,"# 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()])
#Display Lower triangular matrix
print(""Lower Triangular Matrix is:\n"")
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i 0:
print(u[lcw_i:lcw_i + length_lcw])"
2617,Python Program to Find Longest Common Substring using Dynamic Programming with Memoization,"def lcw(u, v):
""""""Return length of an LCW of strings u and v and its starting indexes.
(l, i, j) is returned where l is the length of an LCW of the strings u, v
where the LCW starts at index i in u and index j in v.
""""""
c = [[-1]*(len(v) + 1) for _ in range(len(u) + 1)]
lcw_i = lcw_j = -1
length_lcw = 0
for i in range(len(u)):
for j in range(len(v)):
temp = lcw_starting_at(u, v, c, i, j)
if length_lcw < temp:
length_lcw = temp
lcw_i = i
lcw_j = j
return length_lcw, lcw_i, lcw_j
def lcw_starting_at(u, v, c, i, j):
""""""Return length of the LCW starting at u[i:] and v[j:] and fill table c.
c[i][j] contains the length of the LCW at the start of u[i:] and v[j:].
This function fills in c as smaller subproblems for solving c[i][j] are
solved.""""""
if c[i][j] >= 0:
return c[i][j]
if i == len(u) or j == len(v):
q = 0
elif u[i] != v[j]:
q = 0
else:
q = 1 + lcw_starting_at(u, v, c, i + 1, j + 1)
c[i][j] = q
return q
u = input('Enter first string: ')
v = input('Enter second string: ')
length_lcw, lcw_i, lcw_j = lcw(u, v)
print('Longest Common Subword: ', end='')
if length_lcw > 0:
print(u[lcw_i:lcw_i + length_lcw])"
2618,Python Program to Print All Permutations of a String in Lexicographic Order without Recursion,"from math import factorial
def print_permutations_lexicographic_order(s):
""""""Print all permutations of string s in lexicographic order.""""""
seq = list(s)
# there are going to be n! permutations where n = len(seq)
for _ in range(factorial(len(seq))):
# print permutation
print(''.join(seq))
# find p such that seq[p:] is the largest sequence with elements in
# descending lexicographic order
p = len(seq) - 1
while p > 0 and seq[p - 1] > seq[p]:
p -= 1
# reverse seq[p:]
seq[p:] = reversed(seq[p:])
if p > 0:
# find q such that seq[q] is the smallest element in seq[p:] such that
# seq[q] > seq[p - 1]
q = p
while seq[p - 1] > seq[q]:
q += 1
# swap seq[p - 1] and seq[q]
seq[p - 1], seq[q] = seq[q], seq[p - 1]
s = input('Enter the string: ')
print_permutations_lexicographic_order(s)"
2619,Find the Smallest digit in a number,"
'''Write a Python
program to add find the Smallest digit in a number. or Write a
program to add find the Smallest digit in a number using Python '''
print(""Enter the Number :"")
num=int(input())
smallest=num%10
while num > 0:
reminder = num % 10
if smallest > reminder:
smallest = reminder
num =int(num / 10)
print(""The Smallest Digit is "", smallest)
"
2620,Python Program to Put Even and Odd elements in a List into Two Different Lists,"a=[]
n=int(input(""Enter number of elements:""))
for i in range(1,n+1):
b=int(input(""Enter element:""))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print(""The even list"",even)
print(""The odd list"",odd)"
2621,Program to find the transpose of a matrix,"# 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 transpose of two matrices
tran_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0,row_size):
for j in range(0,col_size):
tran_matrix[i][j]=matrix[j][i]
# display transpose of the matrix
print(""Transpose of the Given Matrix is:"")
for m in tran_matrix:
print(m)"
2622,Add between 2 numbers without using arithmetic operators,"
'''Write a Python
program to add between 2 numbers without using arithmetic operators.
or Write a program to add between 2 numbers without using
arithmetic operators using Python '''
print(""Enter first number:"")
num1=int(input())
print(""Enter second number:"")
num2=int(input())
while num2 != 0:
carry= num1 & num2
num1= num1 ^ num2
num2=carry << 1
print(""Addition of two number is "",num1)
"
2623,Python Program to Find the Number of Nodes in a Binary Tree,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def count_nodes(node):
if node is None:
return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('count')
print('quit')
while True:
print('inorder traversal of binary tree: ', end='')
if btree is not None:
btree.inorder()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'count':
print('Number of nodes in tree: {}'.format(count_nodes(btree)))
elif operation == 'quit':
break"
2624,"Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.
:","Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[-5:]
printList()
"
2625,Print even numbers in given range using recursion,"def even(num1,num2): if num1>num2: return print(num1,end="" "") return even(num1+2,num2)num1=2print(""Enter your Limit:"")num2=int(input())print(""All Even number given range are:"")even(num1,num2)"
2626,Python Program to Find All Connected Components using DFS in an Undirected Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def add_undirected_edge(self, v1_key, v2_key, weight=1):
""""""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight.""""""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)
def does_undirected_edge_exist(self, v1_key, v2_key):
""""""Return True if there is an undirected edge between v1_key and v2_key.""""""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def label_all_reachable(vertex, component, label):
""""""Set component[v] = label for all v in the component containing vertex.""""""
label_all_reachable_helper(vertex, set(), component, label)
def label_all_reachable_helper(vertex, visited, component, label):
""""""Set component[v] = label for all v in the component containing
vertex. Uses set visited to keep track of nodes alread visited.""""""
visited.add(vertex)
component[vertex] = label
for dest in vertex.get_neighbours():
if dest not in visited:
label_all_reachable_helper(dest, visited, component, label)
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex ')
print('add edge ')
print('components')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_undirected_edge_exist(src, dest):
g.add_undirected_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'components':
component = dict.fromkeys(g, None)
label = 1
for v in g:
if component[v] is None:
label_all_reachable(v, component, label)
label += 1
max_label = label
for label in range(1, max_label):
print('Component {}:'.format(label),
[v.get_key() for v in component if component[v] == label])
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2627,Program to find the normal and trace of a matrix,"import math
# 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()])
# Calculate sum of the diagonals element
# and Calculate sum of all the element
trace=0
sum=0
for i in range(0, row_size):
for j in range(0, col_size):
if i==j:
trace += matrix[i][j]
sum+=matrix[i][j]
normal=math.sqrt(sum)
# Display the normal and trace of the matrix
print(""Normal Of the Matrix is: "",normal)
print(""Trace Of the Matrix is: "",trace)"
2628,Check Armstrong number using recursion,"sum=0def check_ArmstrongNumber(num): global sum if (num!=0): sum+=pow(num%10,3) check_ArmstrongNumber(num//10) return sumnum=int(input(""Enter a number:""))if (check_ArmstrongNumber(num) == num): print(""It is an Armstrong Number."")else: print(""It is not an Armstrong Number."")"
2629,Python Program to Interchange the two Adjacent Nodes given a circular Linked List,"class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current
def get_prev_node(self, ref_node):
if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
def append(self, data):
self.insert_at_end(Node(data))
def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break
def interchange(llist, n):
current = llist.get_node(n)
current2 = current.next
if current2.next != current:
before = llist.get_prev_node(current)
after = current2.next
before.next = current2
current2.next = current
current.next = after
if llist.head == current:
llist.head = current2
elif llist.head == current2:
llist.head = current
a_cllist = CircularLinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_cllist.append(int(data))
n = int(input('The nodes at indices n and n+1 will be interchanged.'
' Please enter n: '))
interchange(a_cllist, n)
print('The new list: ')
a_cllist.display()"
2630,Print the frequency of all numbers in an array,"
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
for i in range(0, size):
if(arr[i]>=max):
max=arr[i]
for i in range(0,max+1):
freq.append(0)
for i in range(0, size):
freq[arr[i]]+=1
for i in range(0, max+1):
if(freq[i]!=0):
print(""occurs "",i,"" "",freq[i],"" times"")"
2631,Find the sum of Even numbers using recursion,"def SumEven(num1,num2): if num1>num2: return 0 return num1+SumEven(num1+2,num2)num1=2print(""Enter your Limit:"")num2=int(input())print(""Sum of all Even numbers in the given range is:"",SumEven(num1,num2))"
2632,Find the sum of odd numbers using recursion,"def SumOdd(num1,num2): if num1>num2: return 0 return num1+SumOdd(num1+2,num2)num1=1print(""Enter your Limit:"")num2=int(input())print(""Sum of all odd numbers in the given range is:"",SumOdd(num1,num2))"
2633, Program to print the Inverted V Star Pattern,"
row_size=int(input(""Enter the row size:""))
print_control_x=row_size
print_control_y=row_size
for out in range(1,row_size+1):
for in1 in range(1,row_size*2+1):
if in1==print_control_x or in1==print_control_y:
print(""*"",end="""")
else:
print("" "", end="""")
print_control_x-=1
print_control_y+=1
print(""\r"")
"
2634,Program to check the given number is a palindrome or not,"
'''Write
a Python program to check the given number is a palindrome or not. or
Write a program to check the
given number is a palindrome or not
using Python '''
num=int(input(""Enter a number:""))
num1=num
num2=0
while(num!=0):
rem=num%10
num=int(num/10)
num2=num2*10+rem
if(num1==num2):
print(""It is Palindrome"")
else:
print(""It is not Palindrome"") "
2635,Python Program to Read a Linked List in Reverse,"class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beg(self, new_node):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
node = Node(data)
a_llist.insert_at_beg(node)
print('The linked list: ', end = '')
a_llist.display()"
2636,Program to Find subtraction of two matrices,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Subtraction of two matrices
sub_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sub_matrix[i][j]=matrix[i][j]-matrix1[i][j]
# display the Subtraction of two matrices
print(""Subtraction of the two Matrices is:"")
for m in sub_matrix:
print(m)"
2637,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""]
"
2638,"Program to convert Days into years, months and Weeks","days=int(input(""Enter Day:""))
years =(int) (days / 365)
weeks =(int) (days / 7)
months =(int) (days / 30)
print(""Days to Years:"",years)
print(""Days to Weeks:"",weeks)
print(""Days to Months:"",months)"
2639,Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple,"def last(n):
return n[-1]
def sort(tuples):
return sorted(tuples, key=last)
a=input(""Enter a list of tuples:"")
print(""Sorted:"")
print(sort(a))"
2640, Python Program to Implement Radix Sort ,"def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return ((alist[index]//(base**digit)) % base)
return key
largest = max(alist)
exp = 0
while base**exp <= largest:
alist = counting_sort(alist, base - 1, key_factory(exp, base))
exp = exp + 1
return alist
def counting_sort(alist, largest, key):
c = [0]*(largest + 1)
for i in range(len(alist)):
c[key(alist, i)] = c[key(alist, i)] + 1
# Find the last index for each element
c[0] = c[0] - 1 # to decrement each element for zero-based indexing
for i in range(1, largest + 1):
c[i] = c[i] + c[i - 1]
result = [None]*len(alist)
for i in range(len(alist) - 1, -1, -1):
result[c[key(alist, i)]] = alist[i]
c[key(alist, i)] = c[key(alist, i)] - 1
return result
alist = input('Enter the list of (nonnegative) numbers: ').split()
alist = [int(x) for x in alist]
sorted_list = radix_sort(alist)
print('Sorted list: ', end='')
print(sorted_list)"
2641,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))"
2642,Program to check whether a matrix is sparse or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
count_zero=0
#Count number of zeros present in the given Matrix
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]==0:
count_zero+=1
#check if zeros present in the given Matrix>(row*column)/2
if count_zero>(row_size*col_size)//2:
print(""Given Matrix is a sparse Matrix."")
else:
print(""Given Matrix is not a sparse Matrix."")"
2643,Python Program to Find the Largest Number in a List,"a=[]
n=int(input(""Enter number of elements:""))
for i in range(1,n+1):
b=int(input(""Enter element:""))
a.append(b)
a.sort()
print(""Largest element is:"",a[n-1])"
2644,Program to Find the smallest of three numbers,"
print(""Enter 3 numbers:"")
num1=int(input())
num2=int(input())
num3=int(input())
print(""The smallest number is "",min(num1,num2,num3))
"
2645,"Python Program to Print Numbers in a Range (1,upper) Without Using any Loops","def printno(upper):
if(upper>0):
printno(upper-1)
print(upper)
upper=int(input(""Enter upper limit: ""))
printno(upper)"
2646,Program to print inverted right triangle star pattern,"
print(""Enter the row size:"")
row_size=int(input())
for out in range(row_size+1):
for j in range(row_size,out,-1):
print(""*"",end="""")
print(""\r"")
"
2647, Python Program to Display the Nodes of a Linked List in Reverse without using Recursion,"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_reversed(self):
end_node = None
while end_node != self.head:
current = self.head
while current.next != end_node:
current = current.next
print(current.data, end = ' ')
end_node = current
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The reversed linked list: ', end = '')
a_llist.display_reversed()"
2648,Convert a decimal number to hexadecimal using recursion,"str3=""""def DecimalToHexadecimal(n): global str3 if(n!=0): rem = n % 16 if (rem < 10): str3 += (chr)(rem + 48) # 48 Ascii = 0 else: str3 += (chr)(rem + 55) #55 Ascii = 7 DecimalToHexadecimal(n // 16) return str3n=int(input(""Enter the Decimal Value:""))str=DecimalToHexadecimal(n)print(""Hexadecimal Value of Decimal number is:"",''.join(reversed(str)))"
2649,Program to check whether number is Spy Number or Not,"
num=int(input(""Enter a number:""))
sum=0
mult=1
while num!=0:
rem = num % 10
sum += rem
mult *= rem
num //= 10
if sum==mult:
print(""It is a spy Number."")
else:
print(""It is not a spy Number."")"
2650,Find the maximum 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 maximum element of the given 2d array
max=-sys.maxsize-1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]>=max:
max=matrix[i][j]
# Display the largest element of the given matrix
print(""The Maximum element of the Given 2d array is: "",max)"
2651,Python Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String,"string=raw_input(""Enter string:"")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print(""The number of lowercase characters is:"")
print(count1)
print(""The number of uppercase characters is:"")
print(count2)"
2652,Program to print square star pattern,"
print(""Enter the row and column size:"");
row_size=int(input())
for out in range(0,row_size):
for i in range(0,row_size):
print(""*"")
print(""\r"")
"
2653, Program to print the Inverted Half Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
for out in range(row_size,0,-1):
for in1 in range(row_size,out,-1):
print("" "",end="""")
for in2 in range(1, out+1):
print(in2,end="""")
print(""\r"")
"
2654,Count distinct elements in an array,"
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
for i in range(0, size):
if(arr[i]>=max):
max=arr[i]
for i in range(0,max+1):
freq.append(0)
for i in range(0, size):
freq[arr[i]]+=1
count=0
for i in range(0, max+1):
if freq[i] == 1:
count+=1
print(""Numbers of distinct elements are "",count)"
2655,Sort names in alphabetical order,"
size=int(input(""Enter number of names:""))
print(""Enter "",size,"" names:"")
str=[]
for i in range(size):
ele=input()
str.append(ele)
for i in range(size):
for j in range(i+1,size):
if (str[i]>str[j])>0:
temp=str[i]
str[i]=str[j]
str[j]=temp
print(""After sorting names are:"")
for i in range(size):
print(str[i])"
2656,"Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.
:","Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[:5]
printList()
"
2657,Python Program to Count the Number of Occurrences of an Element in the Linked List using Recursion,"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 count(self, key):
return self.count_helper(self.head, key)
def count_helper(self, current, key):
if current is None:
return 0
if current.data == key:
return 1 + self.count_helper(current.next, key)
else:
return self.count_helper(current.next, key)
a_llist = LinkedList()
for data in [7, 3, 7, 4, 7, 11, 4, 0, 3, 7]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()
key = int(input('Enter data item: '))
count = a_llist.count(key)
print('{0} occurs {1} time(s) in the list.'.format(key, count))"
2658,"
7.2
Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
:","
class Rectangle(object):
def __init__(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
aRectangle = Rectangle(2,10)
print aRectangle.area()
"
2659,Program to Find nth Disarium Number,"
import math
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num1=num
c1 = 0
num2 = num
while num1 != 0:
num1 //= 10
c1 += 1
num1 = num
sum = 0
while num1 != 0:
rem = num1 % 10
sum += math.pow(rem, c1)
num1 //= 10
c1 -= 1
if sum == num2:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Sunny number is "",letest)"
2660,Python Program to Select the ith Largest Element from a List in Expected Linear Time,"def select(alist, start, end, i):
""""""Find ith largest element in alist[start... end-1].""""""
if end - start <= 1:
return alist[start]
pivot = partition(alist, start, end)
# number of elements in alist[pivot... end - 1]
k = end - pivot
if i < k:
return select(alist, pivot + 1, end, i)
elif i > k:
return select(alist, start, pivot, i - k)
return alist[pivot]
def partition(alist, start, end):
pivot = alist[start]
i = start + 1
j = end - 1
while True:
while (i <= j and alist[i] <= pivot):
i = i + 1
while (i <= j and alist[j] >= pivot):
j = j - 1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
i = int(input('The ith smallest element will be found. Enter i: '))
ith_smallest_item = select(alist, 0, len(alist), i)
print('Result: {}.'.format(ith_smallest_item))"
2661,Program to Find the multiplication of two matrices,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
sum=0
# Compute Multiplication of two matrices
mul_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
for k in range(row_size):
sum+=matrix[i][j]*matrix1[i][j]
mul_matrix[i][j]=sum
# display the Multiplication of two matrices
print(""Multiplication of the two Matrices is:"")
for m in mul_matrix:
print(m)"
2662,Check whether a given number is a strong number or not,"
'''Write
a Python program to check whether a given number is a strong number or
not. or
Write a program to check whether
a given number is a strong number or not
using Python '''
num=int(input(""Enter a number:""))
num2=num
sum=0
while(num!=0):
fact=1
rem=num%10
num=int(num/10)
for i in range(1,rem+1):
fact=fact*i
sum=sum+fact
if sum==num2:
print(""It is a Strong Number"")
else:
print(""It is not a Strong Number"")
"
2663, Program to print the Solid Inverted Half 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 p in range(row_size,abs(out),-1):
print(""*"",end="""")
print(""\r"")"
2664,Program to find the sum of series 1+X+X^2/2!+X^3/3!...+X^N/N!,"
print(""Enter the range of number:"")
n=int(input())
print(""Enter the value of x:"")
x=int(input())
sum=1.0
i=1
while(i<=n):
fact=1
for j in range(1,i+1):
fact*=j
sum+=pow(x,i)/fact
i+=1
print(""The sum of the series = "",sum)"
2665,Program to Find the nth Automorphic number,"
rangenumber=int(input(""Enter an Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num1 = num
sqr = num1 * num1
flag = 0
while num1>0:
if num1%10 != sqr%10:
flag = -1
break
num1 = num1 // 10
sqr = sqr // 10
if flag==0:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Automorphic number is "",letest)"
2666, Input a string through the keyboard and Print the same,"
arr=[]
size = int(input(""Enter the size of the array: ""))
for i in range(0,size):
word = (input())
arr.append(word)
for i in range(0,size):
print(arr[i],end="""")"
2667,Python Program to Solve 0-1 Knapsack Problem using Dynamic Programming with Memoization,"def knapsack(value, weight, capacity):
""""""Return the maximum value of items that doesn't exceed capacity.
value[i] is the value of item i and weight[i] is the weight of item i
for 1 <= i <= n where n is the number of items.
capacity is the maximum weight.
""""""
n = len(value) - 1
# m[i][w] will store the maximum value that can be attained with a maximum
# capacity of w and using only the first i items
m = [[-1]*(capacity + 1) for _ in range(n + 1)]
return knapsack_helper(value, weight, m, n, capacity)
def knapsack_helper(value, weight, m, i, w):
""""""Return maximum value of first i items attainable with weight <= w.
m[i][w] will store the maximum value that can be attained with a maximum
capacity of w and using only the first i items
This function fills m as smaller subproblems needed to compute m[i][w] are
solved.
value[i] is the value of item i and weight[i] is the weight of item i
for 1 <= i <= n where n is the number of items.
""""""
if m[i][w] >= 0:
return m[i][w]
if i == 0:
q = 0
elif weight[i] <= w:
q = max(knapsack_helper(value, weight,
m, i - 1 , w - weight[i])
+ value[i],
knapsack_helper(value, weight,
m, i - 1 , w))
else:
q = knapsack_helper(value, weight,
m, i - 1 , w)
m[i][w] = q
return q
n = int(input('Enter number of items: '))
value = input('Enter the values of the {} item(s) in order: '
.format(n)).split()
value = [int(v) for v in value]
value.insert(0, None) # so that the value of the ith item is at value[i]
weight = input('Enter the positive weights of the {} item(s) in order: '
.format(n)).split()
weight = [int(w) for w in weight]
weight.insert(0, None) # so that the weight of the ith item is at weight[i]
capacity = int(input('Enter maximum weight: '))
ans = knapsack(value, weight, capacity)
print('The maximum value of items that can be carried:', ans)"
2668,Linear Search Program in C | C++ | Java | Python ,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
search_elm=int(input(""Enter the search element: ""))
found=0
for i in range(size):
if arr[i]==search_elm:
found=1
if found==1:
print(""Search element is found."")
else:
print(""Search element is not found."")
"
2669,Sort array in descending order using recursion,"def swap_Element(arr,i,j): temp = arr[i] arr[i] = arr[j] arr[j] = tempdef Decreasing_sort_element(arr,n): if(n>0): for i in range(0,n): if (arr[i] <= arr[n - 1]): swap_Element(arr, i, n - 1) Decreasing_sort_element(arr, n - 1)def printArr(arr,n): for i in range(0, n): print(arr[i],end="" "")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)Decreasing_sort_element(arr,n)print(""After Decreasing order sort Array Elements are:"")printArr(arr, n)"
2670,Python Program to Reverse a Stack using Recursion,"class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def display(self):
for data in reversed(self.items):
print(data)
def insert_at_bottom(s, data):
if s.is_empty():
s.push(data)
else:
popped = s.pop()
insert_at_bottom(s, data)
s.push(popped)
def reverse_stack(s):
if not s.is_empty():
popped = s.pop()
reverse_stack(s)
insert_at_bottom(s, popped)
s = Stack()
data_list = input('Please enter the elements to push: ').split()
for data in data_list:
s.push(int(data))
print('The stack:')
s.display()
reverse_stack(s)
print('After reversing:')
s.display()"
2671,Program to print Fibonacci series in Python | C | C++ | Java,"
print(""Enter the range of number(Limit):"")
n=int(input())
i=1
a=0
b=1
c=a+b
while(i<=n):
print(c,end="" "")
c = a + b
a = b
b = c
i+=1"
2672,Program to Find the sum of a lower triangular matrix,"# 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()])
#Calculate sum of lower triangular matrix element
sum=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i= '0' and str[i] <= '9':
n_count+=1
elif str[i] >=chr(0) and str[i] <= chr(47) or str[i] >= chr(58) and str[i] <=chr(64) or str[i] >=chr(91) and str[i] <= chr(96) or str[i] >= chr(123) and str[i] <= chr(127):
s_count+=1
print(""Number of digits: "",n_count)
print(""Number of vowels: "", v_count)
print(""Number of special character: "",s_count)
print(""Number of consonants: "",len(str) - n_count - v_count - s_count)"
2675,Python Program to Implement Binary Search without Recursion,"def binary_search(alist, key):
""""""Search key in alist[start... end - 1].""""""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1
alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = binary_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))"
2676,Python Program to Compute Prime Factors of an Integer,"
n=int(input(""Enter an integer:""))
print(""Factors are:"")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i=i+1"
2677,Print the Inverted Pant's Shape Star Pattern,"row_size=int(input(""Enter the row size:""))for out in range(1,row_size+1): for inn in range(1,row_size*2): if inn<=out or inn>=row_size*2-out: print(""*"",end="""") else: print("" "", end="""") print(""\r"")"
2678,Program to Print the Hollow Half Pyramid Star Pattern,"row_size=int(input(""Enter the row size:""))print_control_x=row_size//2+1for out in range(1,row_size+1): for inn in range(1,row_size+1): if inn==1 or out==inn or out==row_size: print(""*"",end="""") else: print("" "", end="""") print(""\r"")"
2679,Program to find the transpose of a matrix,"# 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 transpose of two matrices
tran_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0,row_size):
for j in range(0,col_size):
tran_matrix[i][j]=matrix[j][i]
# display transpose of the matrix
print(""Transpose of the Given Matrix is:"")
for m in tran_matrix:
print(m)"
2680,Print only consonants in a string,"
str=input(""Enter the String:"")
print(""All the consonants in the string are:"")
for i in range(len(str)):
if str[i] == 'a' or str[i] == 'A' or str[i] == 'e' or str[i] == 'E' or str[i] == 'i'or str[i] == 'I' or str[i] == 'o' or str[i] == 'O' or str[i] == 'u' or str[i] == 'U':
continue
else:
print(str[i],end="" "")"
2681,Multiply two numbers without using multiplication(*) operator,"
num1=int(input(""Enter the First numbers :""))
num2=int(input(""Enter the Second number:""))
sum=0
for i in range(1,num1+1):
sum=sum+num2
print(""The multiplication of "",num1,"" and "",num2,"" is "",sum)
"
2682,Python Program for Depth First Binary Tree Search without using Recursion,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def preorder_depth_first(self):
s = Stack()
s.push(self)
while (not s.is_empty()):
node = s.pop()
print(node.key, end=' ')
if node.right is not None:
s.push(node.right)
if node.left is not None:
s.push(node.left)
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
btree = BinaryTree()
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('dfs')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'dfs':
print('pre-order dfs traversal: ', end='')
if btree is not None:
btree.preorder_depth_first()
print()
elif operation == 'quit':
break"
2683,Print prime numbers from 1 to n using recursion,"def CheckPrime(i,num): if num==i: return 0 else: if(num%i==0): return 1 else: return CheckPrime(i+1,num)n=int(input(""Enter your Number:""))print(""Prime Number Between 1 to n are: "")for i in range(2,n+1): if(CheckPrime(2,i)==0): print(i,end="" "")"
2684,Python Program to Detect if Two Strings are Anagrams,"s1=raw_input(""Enter first string:"")
s2=raw_input(""Enter second string:"")
if(sorted(s1)==sorted(s2)):
print(""The strings are anagrams."")
else:
print(""The strings aren't anagrams."")"
2685,Convert Lowercase to Uppercase using the inbuilt function,"
str=input(""Enter the String(Lower case):"")
print(""Upper case String is:"", str.upper())"
2686,Find the sum of all elements in a 2D Array,"# 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()])
# Calculate sum of given matrix Elements
sum=0
for i in range(0,row_size):
for j in range(0,col_size):
sum+=matrix[i][j]
# Display The Sum Of Given Matrix Elements
print(""Sum of the Given Matrix Elements is: "",sum)"
2687,"You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
:","Solutions:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split("","")))
print sorted(l, key=itemgetter(0,1,2))
"
2688,Python Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically,"print(""Enter a hyphen separated sequence of words:"")
lst=[n for n in raw_input().split('-')]
lst.sort()
print(""Sorted:"")
print('-'.join(lst))"
2689,Python Program to Calculate the Number of Digits and Letters in a String,"string=raw_input(""Enter string:"")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print(""The number of digits is:"")
print(count1)
print(""The number of characters is:"")
print(count2)"
2690,Program to print the Full Pyramid Star Pattern,"
row_size=int(input(""Enter the row size:""))
star_print=1
for out in range(0,row_size):
for inn in range(row_size-1,out,-1):
print("" "",end="""")
for p in range(0,star_print):
print(""*"",end="""")
star_print+=2
print(""\r"")"
2691,Python Program to Find the Area of a Rectangle Using Classes,"class rectangle():
def __init__(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
return self.breadth*self.length
a=int(input(""Enter length of rectangle: ""))
b=int(input(""Enter breadth of rectangle: ""))
obj=rectangle(a,b)
print(""Area of rectangle:"",obj.area())
print()"
2692,Python Program to Find the Length of the Linked List without using Recursion,"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 length(self):
current = self.head
length = 0
while current:
length = length + 1
current = current.next
return length
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))
print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')"
2693,Convert alternate characters to capital letters,"
str=input(""Enter the String:"")
j=0
newStr=""""
for i in range(len(str)):
if j%2==1:
if str[i]>='A' and str[i]<='Z' :
ch=chr(ord(str[i])+32)
newStr=newStr+ch
else:
newStr=newStr+str[i]
else:
if str[i] >= 'a' and str[i] <= 'z':
ch=chr(ord(str[i])-32)
newStr=newStr+ch
else:
newStr=newStr+str[i]
if str[i]==' ':
continue
j=j+1
print(""After converting Your String is :"", newStr)"
2694,Binary Search Program in C | C++ | Java | Python ,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
search_elm=int(input(""Enter the search element: ""))
found=0
lowerBound = 0
upperBound = size-1
while lowerBound<=upperBound and not found:
mid = (lowerBound + upperBound ) // 2
if arr[mid]==search_elm:
found=1
else:
if arr[mid] < search_elm:
lowerBound = mid + 1
else:
upperBound = mid - 1
if found==1:
print(""Search element is found."")
else:
print(""Search element is not found."")
"
2695,Python Program to Implement Depth-First Search on a Graph using Recursion,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def display_dfs(v):
""""""Display DFS traversal starting at vertex v.""""""
display_dfs_helper(v, set())
def display_dfs_helper(v, visited):
""""""Display DFS traversal starting at vertex v. Uses set visited to keep
track of already visited nodes.""""""
visited.add(v)
print(v.get_key(), end=' ')
for dest in v.get_neighbours():
if dest not in visited:
display_dfs_helper(dest, visited)
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('dfs ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'dfs':
key = int(do[1])
print('Depth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_dfs(vertex)
print()
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2696,"Define a function which can compute the sum of two numbers.
:","Solution
def SumFunction(number1, number2):
return number1+number2
print SumFunction(1,2)
"
2697,Print all permutations of a string using recursion,"import java.util.Scanner;public class AnagramString { static void rotate(char str[],int n) { int j,size=str.length; int p=size-n; char temp=str[p]; for(j=p+1;j= 0 and arr[i] > temp): arr[ i +1] = arr[ i] i=i-1 arr[i+1] = temparr=[]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)print(""Before Sorting Array Element are: "",arr)InsertionSort(arr, n)print(""After Sorting Array Elements are:"",arr)"
2702,"A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡Â
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.","import math
pos = [0,0]
while True:
s = raw_input()
if not s:
break
movement = s.split("" "")
direction = movement[0]
steps = int(movement[1])
if direction==""UP"":
pos[0]+=steps
elif direction==""DOWN"":
pos[0]-=steps
elif direction==""LEFT"":
pos[1]-=steps
elif direction==""RIGHT"":
pos[1]+=steps
else:
pass
print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
"
2703,Python Program to Sort using a Binary Search Tree,"class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key <= node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
class BSTree:
def __init__(self):
self.root = None
def inorder(self):
if self.root is not None:
self.root.inorder()
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
bstree = BSTree()
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
for x in alist:
bstree.add(x)
print('Sorted list: ', end='')
bstree.inorder()"
2704,"
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.
:","
def removeDuplicate( li ):
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.append(item)
return newli
li=[12,24,35,24,88,120,155,88,120,155]
print removeDuplicate(li)
"
2705,Check whether a given number is positive or negative,"num=int(input(""Enter a number:""))
if(num<0):
print(""The number is negative"")
elif(num>0):
print(""The number is positive"")
else:
print(""The number is neither negative nor positive"")"
2706,Python Program to Create a Linked List & Display the Elements in the 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 is not None:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()"
2707,Check whether a given number is Friendly pair or not,"
'''Write
a Python program to check whether a given number is Friendly pair or
not. or
Write a program to check whether
a given number is Friendly pair or not
using Python '''
print(""Enter two numbers:"")
num1=int(input())
num2=int(input())
sum1=0
sum2=0
for i in range(1,num1):
if(num1%i==0):
sum1=sum1+i
for i in range(1,num2):
if(num2%i==0):
sum2=sum2+i
if num1/num2==sum1/sum2:
print(""It is a Friendly Pair"")
else:
print(""It is not a Friendly Pair"")
"
2708,Find median of two sorted arrays of different sizes,"def Find_median(arr,arr2,size,size2): m_size = size + size2 merge_arr = [0]*m_size i=0 k=0 j=0 while k 1:
print(n, end=' ')
if (n % 2):
# n is odd
n = 3*n + 1
else:
# n is even
n = n//2
print(1, end='')
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)"
2711,"
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
","
n=int(raw_input())
sum=0.0
for i in range(1,n+1):
sum += float(float(i)/(i+1))
print sum
"
2712,"Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1,¡ÂY-1.","input_str = raw_input()
dimensions=[int(x) for x in input_str.split(',')]
rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
for row in range(rowNum):
for col in range(colNum):
multilist[row][col]= row*col
print multilist
"
2713,Check whether a year is leap year or not,"
year=int(input(""Enter a Year:""))
if ((year % 100 == 0 and year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)):
print(""It is a Leap Year"")
else:
print(""It is not a Leap Year"")"
2714, Program to Print the Pant's Shape Star Pattern,"
row_size=int(input(""Enter the row size:""))
print_control_x=row_size
print_control_y=row_size
for out in range(1,row_size+1):
for inn in range(1,row_size*2):
if inn>print_control_x and inn 0 and arr[inn -1] >= temp:
arr[inn] = arr[inn -1]
inn-=1
arr[inn] = temp
print(""\nAfter Sorting Array Element are: "",arr)
"
2728,Remove element from an array by index,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)pos=int(input(""Enter the position of the Element:""))print(""Before deleting array elements are:"")for i in range(0,size): print(arr[i],end="" "")arr.pop(pos)print(""\nAfter Deleting Array Element are:"")print(arr)"
2729,Print the Alphabet Inverted Half Pyramid Pattern,"
print(""Enter the row and column size:"")
row_size=input()
for out in range(ord(row_size),ord('A')-1,-1):
for i in range(ord(row_size)-1,out-1,-1):
print("" "",end="""")
for p in range(ord('A'), out+1):
print(chr(out),end="""")
print(""\r"")
"
2730,Find out all Trimorphic numbers present within a given range,"
print(""Enter a range:"")
range1=int(input())
range2=int(input())
print(""Trimorphic numbers between "",range1,"" and "",range2,"" are: "")
for i in range(range1,range2+1):
flag = 0
num=i
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(i,end="" "")"
2731,Check strong number using recursion,"def Factorial(num): if num<=0: return 1 else: return num*Factorial(num-1)sum=0def check_StrongNumber(num): global sum if (num>0): fact = 1 rem = num % 10 check_StrongNumber(num // 10) fact = Factorial(rem) sum+=fact return sumnum=int(input(""Enter a number:""))if (check_StrongNumber(num) == num): print(""It is a strong Number."")else: print(""It is not a strong Number."")"
2732,Copy one string to another using recursion,"def Copy_String(str, str1,i): str1[i]=str[i] if (str[i] == '\0'): return Copy_String(str, str1, i + 1)str=input(""Enter your String:"")str+='\0'str1=[0]*(len(str))Copy_String(str, str1,0)print(""Copy Done..."")print(""Copy string is:"","""".join(str1))"
2733,Program to concatenate two String,"
str=input(""Enter the 1st String:"")
str2=input(""Enter the 2nd String:"")
print(""After concatenate string is:"")
print(str+"" ""+str2)"
2734,Program to Find the sum of series 3+33+333.....+N,"n=int(input(""Enter the range of number:""))sum=0p=3for i in range(1,n+1): sum += p p=(p*10)+3print(""The sum of the series = "",sum)"
2735,Find missing numbers in an array,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)sum=0for i in range(0,size): sum += arr[i]size2=size+1miss=int((size2*(size2+1))/2)print(""Missing Number is: "",abs(miss-sum))"
2736,"Enter marks of five subjects and calculate total, average, and percentage","print(""Enter marks of 5 subjects out of 100:"")
sub1=float(input(""Enter sub1 marks:""))
sub2=float(input(""Enter sub2 marks:""))
sub3=float(input(""Enter sub3 marks:""))
sub4=float(input(""Enter sub4 marks:""))
sub5=float(input(""Enter sub5 marks:""))
total_marks=sub1+sub2+sub3+sub4+sub5;
avg=total_marks/5.0;
percentage=total_marks/500*100;
print(""Total Marks:"",total_marks)
print(""Average:"",avg)
print(""Percentage:"",percentage,""%"")"
2737,Program to Find the sum of series 3+33+333.....+N,"n=int(input(""Enter the range of number:""))sum=0p=3for i in range(1,n+1): sum += p p=(p*10)+3print(""The sum of the series = "",sum)"
2738,"
Write a special comment to indicate a Python source code file is in unicode.
:","
# -*- coding: utf-8 -*-
"
2739,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)
"
2740,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."")"
2741,Print mirrored right triangle Alphabet pattern,"
print(""Enter the row and column size:"");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),out+1):
print(chr(i),end="" "")
print(""\r"")
"
2742,Program to print the Solid Diamond Alphabet Pattern,"row_size=int(input(""Enter the row size:""))x=0for out in range(row_size,-(row_size+1),-1): for inn in range(1,abs(out)+1): print("" "",end="""") for p in range(row_size,abs(out)-1,-1): print((chr)(x+65),end="" "") if out > 0: x +=1 else: x -=1 print(""\r"")"
2743,"Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
:","Solution
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print squaredNumbers
"
2744,"
Please write a program to print the running time of execution of ""1+1"" for 100 times.
:","
from timeit import Timer
t = Timer(""for i in range(100):1+1"")
print t.timeit()
"
2745,Convert Temperature from degree Celsius to Fahrenheit ,"celsius=float(input(""Enter degree in celsius: ""))
fahrenheit=(celsius*(9/5))+32
print(""Degree in Fahrenheit is"",fahrenheit)"
2746,Python Program to Remove All Tuples in a List of Tuples with the USN Outside the Given Range,"y=[('a','12CS039'),('b','12CS320'),('c','12CS055'),('d','12CS100')]
low=int(input(""Enter lower roll number (starting with 12CS):""))
up=int(input(""Enter upper roll number (starting with 12CS):""))
l='12CS0'+str(low)
u='12CS'+str(up)
p=[x for x in y if x[1]>l and x[1]len2:
print s1
elif len2>len1:
print s2
else:
print s1
print s2
printValue(""one"",""three"")
"
2750,Python Program to Remove the Given Key from a Dictionary,"d = {'a':1,'b':2,'c':3,'d':4}
print(""Initial dictionary"")
print(d)
key=raw_input(""Enter the key to delete(a-d):"")
if key in d:
del d[key]
else:
print(""Key not found!"")
exit(0)
print(""Updated dictionary"")
print(d)"
2751,Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character,"test_string=raw_input(""Enter string:"")
l=test_string.split()
d={}
for word in l:
if(word[0] not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,"":"",v)"
2752,Python Program to Implement a Stack using Linked List,"class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped
a_stack = Stack()
while True:
print('push ')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
a_stack.push(int(do[1]))
elif operation == 'pop':
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))
elif operation == 'quit':
break"
2753,Python Program to Print Odd Numbers Within a Given Range,"
lower=int(input(""Enter the lower limit for the range:""))
upper=int(input(""Enter the upper limit for the range:""))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)"
2754,"Sort an array of 0s, 1s and 2s","arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)for i in range(0,size): for j in range(i+1, size): if arr[i]>=arr[j]: temp = arr[i] arr[i] = arr[j] arr[j] = tempprint(""After segregate 0s, 1s and 2s in an Array, Array is:"",arr)"
2755,Python Program to Find the Largest value in a Tree using Inorder Traversal,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder_largest(self):
# largest will be a single element list
# this is a workaround to reference an integer
largest = []
self.inorder_largest_helper(largest)
return largest[0]
def inorder_largest_helper(self, largest):
if self.left is not None:
self.left.inorder_largest_helper(largest)
if largest == []:
largest.append(self.key)
elif largest[0] < self.key:
largest[0] = self.key
if self.right is not None:
self.right.inorder_largest_helper(largest)
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('largest')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'largest':
if btree is None:
print('Tree is empty.')
else:
print('Largest element: {}'.format(btree.inorder_largest()))
elif operation == 'quit':
break"
2756,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)"
2757,Python Program to Count the Number of Digits in a Number,"n=int(input(""Enter number:""))
count=0
while(n>0):
count=count+1
n=n//10
print(""The number of digits in the number are:"",count)"
2758, Program to print the Full Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
np=1
for out in range(0,row_size):
for in1 in range(row_size-1,out,-1):
print("" "",end="""")
for in2 in range(np,0,-1):
print(in2,end="""")
np+=2
print(""\r"")
"
2759,Python Program to Implement Counting Sort,"def counting_sort(alist, largest):
c = [0]*(largest + 1)
for i in range(len(alist)):
c[alist[i]] = c[alist[i]] + 1
# Find the last index for each element
c[0] = c[0] - 1 # to decrement each element for zero-based indexing
for i in range(1, largest + 1):
c[i] = c[i] + c[i - 1]
result = [None]*len(alist)
# Though it is not required here,
# it becomes necessary to reverse the list
# when this function needs to be a stable sort
for x in reversed(alist):
result[c[x]] = x
c[x] = c[x] - 1
return result
alist = input('Enter the list of (nonnegative) numbers: ').split()
alist = [int(x) for x in alist]
k = max(alist)
sorted_list = counting_sort(alist, k)
print('Sorted list: ', end='')
print(sorted_list)"
2760,Find the Generic root of a number,"
'''Write a Python
program to Find the Generic root of a number.''
print(""Enter a number:"")
num = int(input())
while num > 10:
sum = 0
while num:
r=num % 10
num= num / 10
sum+= r
if sum > 10:
num = sum
else:
break
print(""Generic root of the number is "", int(sum))
"
2761,Python Program to Find the Fibonacci Series Using Recursion,"def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input(""Enter number of terms:""))
print(""Fibonacci sequence:"")
for i in range(n):
print(fibonacci(i))"
2762,Python Program to Print all the Paths from the Root to the Leaf in a Tree,"class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def print_all_paths_to_leaf(self):
self.print_all_paths_to_leaf_helper([])
def print_all_paths_to_leaf_helper(self, path_till_now):
path_till_now.append(self.key)
if self.children == []:
for key in path_till_now:
print(key, end=' ')
print()
else:
for child in self.children:
child.print_all_paths_to_leaf_helper(path_till_now[:])
tree = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('paths')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)
elif operation == 'paths':
if tree is None:
print('Tree is empty.')
else:
tree.print_all_paths_to_leaf()
elif operation == 'quit':
break"
2763,Python Program to Find the Second Largest Number in a List Using Bubble Sort,"a=[]
n=int(input(""Enter number of elements:""))
for i in range(1,n+1):
b=int(input(""Enter element:""))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print('Second largest number is:',a[n-2])"
2764,Python Program to Solve n-Queen Problem without Recursion,"class QueenChessBoard:
def __init__(self, size):
# board has dimensions size x size
self.size = size
# columns[r] is a number c if a queen is placed at row r and column c.
# columns[r] is out of range if no queen is place in row r.
# Thus after all queens are placed, they will be at positions
# (columns[0], 0), (columns[1], 1), ... (columns[size - 1], size - 1)
self.columns = []
def place_in_next_row(self, column):
self.columns.append(column)
def remove_in_current_row(self):
return self.columns.pop()
def is_this_column_safe_in_next_row(self, column):
# index of next row
row = len(self.columns)
# check column
for queen_column in self.columns:
if column == queen_column:
return False
# check diagonal
for queen_row, queen_column in enumerate(self.columns):
if queen_column - queen_row == column - row:
return False
# check other diagonal
for queen_row, queen_column in enumerate(self.columns):
if ((self.size - queen_column) - queen_row
== (self.size - column) - row):
return False
return True
def display(self):
for row in range(self.size):
for column in range(self.size):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()
def solve_queen(size):
""""""Display a chessboard for each possible configuration of placing n queens
on an n x n chessboard and print the number of such configurations.""""""
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
column = 0
# iterate over rows of board
while True:
# place queen in next row
while column < size:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row += 1
column = 0
break
else:
column += 1
# if could not find column to place in or if board is full
if (column == size or row == size):
# if board is full, we have a solution
if row == size:
board.display()
print()
number_of_solutions += 1
# small optimization:
# In a board that already has queens placed in all rows except
# the last, we know there can only be at most one position in
# the last row where a queen can be placed. In this case, there
# is a valid position in the last row. Thus we can backtrack two
# times to reach the second last row.
board.remove_in_current_row()
row -= 1
# now backtrack
try:
prev_column = board.remove_in_current_row()
except IndexError:
# all queens removed
# thus no more possible configurations
break
# try previous row again
row -= 1
# start checking at column = (1 + value of column in previous row)
column = 1 + prev_column
print('Number of solutions:', number_of_solutions)
n = int(input('Enter n: '))
solve_queen(n)"
2765,Check whether number is Sunny Number or Not.,"
import math
num=int(input(""Enter a number:""))
root=math.sqrt(num+1)
if int(root)==root:
print(""It is a Sunny Number."")
else:
print(""It is Not a Sunny Number."")"
2766,Count number of zeros in a number using recursion,"count=0def count_digit(num): global count if (num >0): if(num%10==0): count +=1 count_digit(num // 10) return countn=int(input(""Enter a number:""))print(""The number of Zeros in the Given number is:"",count_digit(n))"
2767,Python Program to Build Binary Tree if Inorder or Postorder Traversal as Input,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def postorder(self):
if self.left is not None:
self.left.postorder()
if self.right is not None:
self.right.postorder()
print(self.key, end=' ')
def construct_btree(postord, inord):
if postord == [] or inord == []:
return None
key = postord[-1]
node = BinaryTree(key)
index = inord.index(key)
node.left = construct_btree(postord[:index], inord[:index])
node.right = construct_btree(postord[index:-1], inord[index + 1:])
return node
postord = input('Input post-order traversal: ').split()
postord = [int(x) for x in postord]
inord = input('Input in-order traversal: ').split()
inord = [int(x) for x in inord]
btree = construct_btree(postord, inord)
print('Binary tree constructed.')
print('Verifying:')
print('Post-order traversal: ', end='')
btree.postorder()
print()
print('In-order traversal: ', end='')
btree.inorder()
print()"
2768,Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm,"def find_max_subarray(alist, start, end):
""""""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end.""""""
max_ending_at_i = max_seen_so_far = alist[start]
max_left_at_i = max_left_so_far = start
# max_right_at_i is always i + 1
max_right_so_far = start + 1
for i in range(start + 1, end):
if max_ending_at_i > 0:
max_ending_at_i += alist[i]
else:
max_ending_at_i = alist[i]
max_left_at_i = i
if max_ending_at_i > max_seen_so_far:
max_seen_so_far = max_ending_at_i
max_left_so_far = max_left_at_i
max_right_so_far = i + 1
return max_left_so_far, max_right_so_far, max_seen_so_far
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))"
2769,Python Program to Calculate the Number of Words and the Number of Characters Present in a String,"string=raw_input(""Enter string:"")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print(""Number of words in the string:"")
print(word)
print(""Number of characters in the string:"")
print(char)"
2770,Program to calculate the area and perimeter of a rectangle,"length=int(input(""Enter length of a rectangle :""))
breadth=int(input(""Enter breadth of a rectangle :""))
area=length*breadth
perimeter=2*(length+breadth)
print(""Area ="",area)
print(""Perimeter ="",perimeter)"
2771,Python Program to Determine Whether a Given Number is Even or Odd Recursively,"def check(n):
if (n < 2):
return (n % 2 == 0)
return (check(n - 2))
n=int(input(""Enter number:""))
if(check(n)==True):
print(""Number is even!"")
else:
print(""Number is odd!"")"
2772,Python Program to Count the Occurrences of Each Word in a Given String Sentence,"string=raw_input(""Enter string:"")
word=raw_input(""Enter word:"")
a=[]
count=0
a=string.split("" "")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print(""Count of the word is:"")
print(count)"
2773,Write a program to calculate simple Interest,"principle=float(input(""Enter a principle:""))
rate=float(input(""Enter a rate:""))
time=float(input(""Enter a time(year):""))
simple_interest=(principle*rate*time)/100;
print(""Simple Interest:"",simple_interest)"
2774,Python Program to Implement Johnson’s Algorithm,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def set_weight(self, dest, weight):
""""""Set weight of edge from this vertex to dest.""""""
self.points_to[dest] = weight
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def johnson(g):
""""""Return distance where distance[u][v] is the min distance from u to v.
distance[u][v] is the shortest distance from vertex u to v.
g is a Graph object which can have negative edge weights.
""""""
# add new vertex q
g.add_vertex('q')
# let q point to all other vertices in g with zero-weight edges
for v in g:
g.add_edge('q', v.get_key(), 0)
# compute shortest distance from vertex q to all other vertices
bell_dist = bellman_ford(g, g.get_vertex('q'))
# set weight(u, v) = weight(u, v) + bell_dist(u) - bell_dist(v) for each
# edge (u, v)
for v in g:
for n in v.get_neighbours():
w = v.get_weight(n)
v.set_weight(n, w + bell_dist[v] - bell_dist[n])
# remove vertex q
# This implementation of the graph stores edge (u, v) in Vertex object u
# Since no other vertex points back to q, we do not need to worry about
# removing edges pointing to q from other vertices.
del g.vertices['q']
# distance[u][v] will hold smallest distance from vertex u to v
distance = {}
# run dijkstra's algorithm on each source vertex
for v in g:
distance[v] = dijkstra(g, v)
# correct distances
for v in g:
for w in g:
distance[v][w] += bell_dist[w] - bell_dist[v]
# correct weights in original graph
for v in g:
for n in v.get_neighbours():
w = v.get_weight(n)
v.set_weight(n, w + bell_dist[n] - bell_dist[v])
return distance
def bellman_ford(g, source):
""""""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
g is a Graph object which can have negative edge weights.
source is a Vertex object in g.
""""""
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
for _ in range(len(g) - 1):
for v in g:
for n in v.get_neighbours():
distance[n] = min(distance[n], distance[v] + v.get_weight(n))
return distance
def dijkstra(g, source):
""""""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
g is a Graph object.
source is a Vertex object in g.
""""""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
while unvisited != set():
# find vertex with minimum distance
closest = min(unvisited, key=lambda v: distance[v])
# mark as visited
unvisited.remove(closest)
# update distances
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance
return distance
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('johnson')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')
elif operation == 'johnson':
distance = johnson(g)
print('Shortest distances:')
for start in g:
for end in g:
print('{} to {}'.format(start.get_key(), end.get_key()), end=' ')
print('distance {}'.format(distance[start][end]))
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2775,Python Program to Flatten a List without using Recursion,"a=[[1,[[2]],[[[3]]]],[[4],5]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print(flatten(a))"
2776,Python Program to Implement Binomial Heap,"class BinomialTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0
def add_at_end(self, t):
self.children.append(t)
self.order = self.order + 1
class BinomialHeap:
def __init__(self):
self.trees = []
def extract_min(self):
if self.trees == []:
return None
smallest_node = self.trees[0]
for tree in self.trees:
if tree.key < smallest_node.key:
smallest_node = tree
self.trees.remove(smallest_node)
h = BinomialHeap()
h.trees = smallest_node.children
self.merge(h)
return smallest_node.key
def get_min(self):
if self.trees == []:
return None
least = self.trees[0].key
for tree in self.trees:
if tree.key < least:
least = tree.key
return least
def combine_roots(self, h):
self.trees.extend(h.trees)
self.trees.sort(key=lambda tree: tree.order)
def merge(self, h):
self.combine_roots(h)
if self.trees == []:
return
i = 0
while i < len(self.trees) - 1:
current = self.trees[i]
after = self.trees[i + 1]
if current.order == after.order:
if (i + 1 < len(self.trees) - 1
and self.trees[i + 2].order == after.order):
after_after = self.trees[i + 2]
if after.key < after_after.key:
after.add_at_end(after_after)
del self.trees[i + 2]
else:
after_after.add_at_end(after)
del self.trees[i + 1]
else:
if current.key < after.key:
current.add_at_end(after)
del self.trees[i + 1]
else:
after.add_at_end(current)
del self.trees[i]
i = i + 1
def insert(self, key):
g = BinomialHeap()
g.trees.append(BinomialTree(key))
self.merge(g)
bheap = BinomialHeap()
print('Menu')
print('insert ')
print('min get')
print('min extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'min':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Minimum value: {}'.format(bheap.get_min()))
elif suboperation == 'extract':
print('Minimum value removed: {}'.format(bheap.extract_min()))
elif operation == 'quit':
break"
2777,Program to find the sum of an upper triangular matrix,"# 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()])
#Calculate sum of Upper triangular matrix element
sum=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i>j:
sum += matrix[i][j]
# display the sum of the Upper triangular matrix element
print(""Sum of Upper Triangular Matrix Elements is: "",sum)"
2778, Find out all Perfect numbers present within a given range,"
'''Write a Python
program to find out all Perfect numbers present within a given range.
or Write a program to find out all Perfect numbers present
within a given range using Python '''
print(""Enter a range:"")
range1=int(input())
range2=int(input())
print(""Perfect numbers between "",range1,"" and "",range2,"" are: "")
for j in range(range1,range2+1):
sum=0
num=j
for i in range(1,j):
if(j%i==0):
sum=sum+i
if sum==num:
print(j,end="" "")
"
2779,"Python Program to Read a Number n And Print the Series ""1+2+…..+n= ""","n=int(input(""Enter a number: ""))
a=[]
for i in range(1,n+1):
print(i,sep="" "",end="" "")
if(i=max:
max=matrix[i][j]
# Display the largest element of the given matrix
print(""The Maximum element of the Given 2d array is: "",max)"
2781,Python Program to Solve Matrix-Chain Multiplication using Dynamic Programming with Memoization,"def matrix_product(p):
""""""Return m and s.
m[i][j] is the minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i].
""""""
length = len(p) # len(p) = number of matrices + 1
# m[i][j] is the minimum number of multiplications needed to compute the
# product of matrices A(i), A(i+1), ..., A(j)
# s[i][j] is the matrix after which the product is split in the minimum
# number of multiplications needed
m = [[-1]*length for _ in range(length)]
s = [[-1]*length for _ in range(length)]
matrix_product_helper(p, 1, length - 1, m, s)
return m, s
def matrix_product_helper(p, start, end, m, s):
""""""Return minimum number of scalar multiplications needed to compute the
product of matrices A(start), A(start + 1), ..., A(end).
The minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j) is stored in m[i][j].
The index of the matrix after which the above product is split in an optimal
parenthesization is stored in s[i][j].
p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i].
""""""
if m[start][end] >= 0:
return m[start][end]
if start == end:
q = 0
else:
q = float('inf')
for k in range(start, end):
temp = matrix_product_helper(p, start, k, m, s) \
+ matrix_product_helper(p, k + 1, end, m, s) \
+ p[start - 1]*p[k]*p[end]
if q > temp:
q = temp
s[start][end] = k
m[start][end] = q
return q
def print_parenthesization(s, start, end):
""""""Print the optimal parenthesization of the matrix product A(start) x
A(start + 1) x ... x A(end).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
""""""
if start == end:
print('A[{}]'.format(start), end='')
return
k = s[start][end]
print('(', end='')
print_parenthesization(s, start, k)
print_parenthesization(s, k + 1, end)
print(')', end='')
n = int(input('Enter number of matrices: '))
p = []
for i in range(n):
temp = int(input('Enter number of rows in matrix {}: '.format(i + 1)))
p.append(temp)
temp = int(input('Enter number of columns in matrix {}: '.format(n)))
p.append(temp)
m, s = matrix_product(p)
print('The number of scalar multiplications needed:', m[1][n])
print('Optimal parenthesization: ', end='')
print_parenthesization(s, 1, n)"
2782,Program to Find nth Armstrong Number ,"
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num2 = num
num1 = num
sum = 0
while num1 != 0:
rem = num1 % 10
num1 = num1 // 10
sum = sum + rem * rem * rem
if sum == num2:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Armstrong Number is "",latest)"
2783,Python Program to Form a New String where the First Character and the Last Character have been Exchanged,"def change(string):
return string[-1:] + string[1:-1] + string[:1]
string=raw_input(""Enter string:"")
print(""Modified string:"")
print(change(string))"
2784, Program to print the Half Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
for out in range(1,row_size+1):
for i in range(row_size+1,out,-1):
print(out,end="""")
print(""\r"")
"
2785,Convert Octal to decimal using recursion,"decimal=0sem=0def OctalToDecimal(n): global sem,decimal if(n!=0): decimal+=(n%10)*pow(8,sem) sem+=1 OctalToDecimal(n // 10) return decimaln=int(input(""Enter the Octal Value:""))print(""Decimal Value of Octal number is:"",OctalToDecimal(n))"
2786,Program to check whether a matrix is symmetric or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
if row_size!=col_size:
print(""Given Matrix is not a Square Matrix."")
else:
#compute the transpose matrix
tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0, row_size):
for j in range(0, col_size):
tran_matrix[i][j] = matrix[j][i]
# check given matrix elements and transpose
# matrix elements are same or not.
flag=0
for i in range(0, row_size):
for j in range(0, col_size):
if matrix[i][j] != tran_matrix[i][j]:
flag=1
break
if flag==1:
print(""Given Matrix is not a symmetric Matrix."")
else:
print(""Given Matrix is a symmetric Matrix."")"
2787,Python Program to Remove Duplicates from 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 get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
def remove_duplicates(llist):
current1 = llist.head
while current1:
data = current1.data
current2 = current1.next
while current2:
if current2.data == data:
llist.remove(current2)
current2 = current2.next
current1 = current1.next
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))
remove_duplicates(a_llist)
print('The list with duplicates removed: ')
a_llist.display()"
2788,Python Program to Find the Smallest Divisor of an Integer,"
n=int(input(""Enter an integer:""))
a=[]
for i in range(2,n+1):
if(n%i==0):
a.append(i)
a.sort()
print(""Smallest divisor is:"",a[0])"
2789,Print the Hollow Half Pyramid Number Pattern,"row_size=int(input(""Enter the row size:""))print_control_x=row_size//2+1for out in range(1,row_size+1): for inn in range(1,row_size+1): if inn==1 or out==inn or out==row_size: print(out,end="""") else: print("" "", end="""") print(""\r"")"
2790,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)"
2791,Program to check two matrix are equal or not,"# Get size of 1st matrix
row_size=int(input(""Enter the row Size Of the 1st Matrix:""))
col_size=int(input(""Enter the columns Size Of the 1st Matrix:""))
# Get size of 2nd matrix
row_size1=int(input(""Enter the row Size Of the 1st Matrix:""))
col_size1=int(input(""Enter the columns Size Of the 2nd Matrix:""))
matrix=[]
# Taking input of the 1st matrix
print(""Enter the 1st Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the 2nd Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compare two matrices
point=0
if row_size==row_size1 and col_size==col_size1:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != matrix1[i][j]:
point=1
break
else:
print(""Two matrices are not equal."")
exit(0)
if point==1:
print(""Two matrices are not equal."")
else:
print(""Two matrices are equal."")"
2792,Separate even and odd numbers in an array,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""\nOdd numbers are:"")
for i in range(0,size):
if (arr[i] % 2 != 0):
print(arr[i],end="" "")
print(""\nEven numbers are:"")
for i in range(0,size):
if (arr[i] % 2 == 0):
print(arr[i],end="" "")"
2793,Find the sum of n natural numbers using recursion,"def SumOfNaturalNumber(n): if n>0: return n+SumOfNaturalNumber(n-1) else: return nn=int(input(""Enter the N Number:""))print(""Sum of N Natural Number Using Recursion is:"",SumOfNaturalNumber(n))"
2794,Python Program for Depth First Binary Tree Search using Recursion,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def depth_first(self):
print('entering {}...'.format(self.key))
if self.left is not None:
self.left.depth_first()
print('at {}...'.format(self.key))
if self.right is not None:
self.right.depth_first()
print('leaving {}...'.format(self.key))
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('dfs')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'dfs':
print('depth-first search traversal:')
if btree is not None:
btree.depth_first()
print()
elif operation == 'quit':
break"
2795,Python Program to Check If Two Numbers are Amicable Numbers,"x=int(input('Enter number 1: '))
y=int(input('Enter number 2: '))
sum1=0
sum2=0
for i in range(1,x):
if x%i==0:
sum1+=i
for j in range(1,y):
if y%j==0:
sum2+=j
if(sum1==y and sum2==x):
print('Amicable!')
else:
print('Not Amicable!')"
2796,Decimal to Octal conversion using recursion,"sem=1octal=0def DecimalToOctal(n): global sem,octal if(n!=0): octal = octal + (n % 8) * sem sem = sem * 10 DecimalToOctal(n // 8) return octaln=int(input(""Enter the Decimal Value:""))print(""Octal Value of Decimal number is: "",DecimalToOctal(n))"
2797,Program to find the normal and trace of a matrix,"import math
# 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()])
# Calculate sum of the diagonals element
# and Calculate sum of all the element
trace=0
sum=0
for i in range(0, row_size):
for j in range(0, col_size):
if i==j:
trace += matrix[i][j]
sum+=matrix[i][j]
normal=math.sqrt(sum)
# Display the normal and trace of the matrix
print(""Normal Of the Matrix is: "",normal)
print(""Trace Of the Matrix is: "",trace)"
2798,Write a program to print the alphabet pattern,"
print(""Enter the row and column size:"");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),ord(row_size)+1):
print(chr(i),end="" "")
print(""\r"")
"
2799,Program to check whether a matrix is sparse or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
count_zero=0
#Count number of zeros present in the given Matrix
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]==0:
count_zero+=1
#check if zeros present in the given Matrix>(row*column)/2
if count_zero>(row_size*col_size)//2:
print(""Given Matrix is a sparse Matrix."")
else:
print(""Given Matrix is not a sparse Matrix."")"
2800,"
Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
:","
import random
print random.choice([i for i in range(11) if i%2==0])
"
2801,Program to Find the nth Palindrome Number,"
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num2=0
num1 = num
while num1 != 0:
rem = num1 % 10
num1 //= 10
num2 = num2 * 10 + rem
if num==num2:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Palindrome Number is "",letest)"
2802,Program to print the right triangle Alphabet pattern,"
print(""Enter the row and column size:"");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),out+1):
print(chr(i),end="" "")
print(""\r"")
"
2803,Python Program to Find the GCD of Two Numbers Using Recursion,"def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input(""Enter first number:""))
b=int(input(""Enter second number:""))
GCD=gcd(a,b)
print(""GCD is: "")
print(GCD)"
2804,Python Program to Find Transitive Closure of a Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def transitive_closure(g):
""""""Return dictionary reachable.
reachable[u][v] = True iff there is a path from vertex u to v.
g is a Graph object which can have negative edge weights.
""""""
reachable = {v:dict.fromkeys(g, False) for v in g}
for v in g:
for n in v.get_neighbours():
reachable[v][n] = True
for v in g:
reachable[v][v] = True
for p in g:
for v in g:
for w in g:
if reachable[v][p] and reachable[p][w]:
reachable[v][w] = True
return reachable
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('transitive-closure')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'transitive-closure':
reachable = transitive_closure(g)
print('All pairs (u, v) such that there is a path from u to v: ')
for start in g:
for end in g:
if reachable[start][end]:
print('{}, {}'.format(start.get_key(), end.get_key()))
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2805,Program to find addition of two matrices ,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Addition of two matrices
sum_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sum_matrix[i][j]=matrix[i][j]+matrix1[i][j]
# display the sum of two matrices
print(""Sum of the two Matrices is:"")
for m in sum_matrix:
print(m)"
2806,Remove all uppercase characters in the String ,"
str=input(""Enter the String:"")
str2 = []
i = 0
while i < len(str):
ch = str[i]
if not ch.isupper():
str2.append(ch)
i += 1
Final_String = ''.join(str2)
print(""After removing uppercase letter string is:"",Final_String)"
2807,Decimal to Octal conversion using recursion,"sem=1octal=0def DecimalToOctal(n): global sem,octal if(n!=0): octal = octal + (n % 8) * sem sem = sem * 10 DecimalToOctal(n // 8) return octaln=int(input(""Enter the Decimal Value:""))print(""Octal Value of Decimal number is: "",DecimalToOctal(n))"
2808,Check whether a given number is positive or negative,"num=int(input(""Enter a number:""))
if(num<0):
print(""The number is negative"")
elif(num>0):
print(""The number is positive"")
else:
print(""The number is neither negative nor positive"")"
2809,Python Program to Find the Sum of Elements in a List Recursively,"def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input(""Enter the number of elements for list:""))
a=[]
for i in range(0,n):
element=int(input(""Enter element:""))
a.append(element)
print(""The list is:"")
print(a)
print(""Sum of items in list:"")
b=sum_arr(a,n)
print(b)"
2810,Python Program to Solve Matrix-Chain Multiplication using Dynamic Programming with Bottom-Up Approach,"def matrix_product(p):
""""""Return m and s.
m[i][j] is the minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i].
""""""
length = len(p) # len(p) = number of matrices + 1
# m[i][j] is the minimum number of multiplications needed to compute the
# product of matrices A(i), A(i+1), ..., A(j)
# s[i][j] is the matrix after which the product is split in the minimum
# number of multiplications needed
m = [[-1]*length for _ in range(length)]
s = [[-1]*length for _ in range(length)]
for i in range(1, length):
m[i][i] = 0
for chain_length in range(2, length):
for start in range(1, length - chain_length + 1):
end = start + chain_length - 1
q = float('inf')
for k in range(start, end):
temp = m[start][k] + m[k + 1][end] + p[start - 1]*p[k]*p[end]
if temp < q:
q = temp
s[start][end] = k
m[start][end] = q
return m, s
def print_parenthesization(s, start, end):
""""""Print the optimal parenthesization of the matrix product A(start) x
A(start + 1) x ... x A(end).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
""""""
if start == end:
print('A[{}]'.format(start), end='')
return
k = s[start][end]
print('(', end='')
print_parenthesization(s, start, k)
print_parenthesization(s, k + 1, end)
print(')', end='')
n = int(input('Enter number of matrices: '))
p = []
for i in range(n):
temp = int(input('Enter number of rows in matrix {}: '.format(i + 1)))
p.append(temp)
temp = int(input('Enter number of columns in matrix {}: '.format(n)))
p.append(temp)
m, s = matrix_product(p)
print('The number of scalar multiplications needed:', m[1][n])
print('Optimal parenthesization: ', end='')
print_parenthesization(s, 1, n)"
2811,Python Program to Implement Binomial Tree,"class BinomialTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0
def add_at_end(self, t):
self.children.append(t)
self.order = self.order + 1
trees = []
print('Menu')
print('create ')
print('combine ')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'create':
key = int(do[1])
btree = BinomialTree(key)
trees.append(btree)
print('Binomial tree created.')
elif operation == 'combine':
index1 = int(do[1])
index2 = int(do[2])
if trees[index1].order == trees[index2].order:
trees[index1].add_at_end(trees[index2])
del trees[index2]
print('Binomial trees combined.')
else:
print('Orders of the trees need to be the same.')
elif operation == 'quit':
break
print('{:>8}{:>12}{:>8}'.format('Index', 'Root key', 'Order'))
for index, t in enumerate(trees):
print('{:8d}{:12d}{:8d}'.format(index, t.key, t.order))"
2812,"Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
:","l=[]
for i in range(2000, 3201):
if (i%7==0) and (i%5!=0):
l.append(str(i))
print ','.join(l)
"
2813,Python Program to Find the Smallest Set of Unit-Length Closed Intervals that Contains All Points using Greedy Algorithm,"def smallest_unit_length_intervals(points):
""""""Return smallest set with unit-length intervals that includes all points.
A smallest set containing closed intervals is returned such that each point
is included in some interval.
The intervals are in the form of tuples (a, b).
points is a list of points on the x-axis.
""""""
points.sort()
smallest_set = set()
end_of_last_interval = float('-inf')
for p in points:
if end_of_last_interval <= p:
interval = (p, p + 1)
smallest_set.add(interval)
end_of_last_interval = p + 1
return smallest_set
points = input('Enter the points: ').split()
points = [float(p) for p in points]
ans = smallest_unit_length_intervals(points)
print('A smallest-size set containing unit-length intervals '
'that contain all of these points is', ans)"
2814,Write a program to print the pattern,"
print(""Enter the row and column size:"");
row_size=int(input())
for out in range(1,row_size+1):
for i in range(0,row_size):
print(out,end="""")
print(""\r"")"
2815,Python Program to Solve 0-1 Knapsack Problem using Dynamic Programming with Bottom-Up Approach,"def knapsack(value, weight, capacity):
""""""Return the maximum value of items that doesn't exceed capacity.
value[i] is the value of item i and weight[i] is the weight of item i
for 1 <= i <= n where n is the number of items.
capacity is the maximum weight.
""""""
n = len(value) - 1
# m[i][w] will store the maximum value that can be attained with a maximum
# capacity of w and using only the first i items
m = [[-1]*(capacity + 1) for _ in range(n + 1)]
for w in range(capacity + 1):
m[0][w] = 0
for i in range(1, n + 1):
for w in range(capacity + 1):
if weight[i] > w:
m[i][w] = m[i - 1][w]
else:
m[i][w] = max(m[i - 1][w - weight[i]] + value[i],
m[i - 1][w])
return m[n][capacity]
n = int(input('Enter number of items: '))
value = input('Enter the values of the {} item(s) in order: '
.format(n)).split()
value = [int(v) for v in value]
value.insert(0, None) # so that the value of the ith item is at value[i]
weight = input('Enter the positive weights of the {} item(s) in order: '
.format(n)).split()
weight = [int(w) for w in weight]
weight.insert(0, None) # so that the weight of the ith item is at weight[i]
capacity = int(input('Enter maximum weight: '))
ans = knapsack(value, weight, capacity)
print('The maximum value of items that can be carried:', ans)"
2816,"
Please write a program which prints all permutations of [1,2,3]
:","
import itertools
print list(itertools.permutations([1,2,3]))
"
2817,Program to convert octal to decimal,"print(""Enter the octal number: "");
octal=int(input());
decimal = 0
sem = 0
while(octal!= 0):
decimal=decimal+(octal%10)*pow(8,sem)
sem+=1
octal=octal// 10
print(""Decimal number is: "",decimal)
"
2818,Python Program to Demonstrate Circular Single Linked List,"class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def get_node(self, index):
if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current
def get_prev_node(self, ref_node):
if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.head = new_node
def remove(self, node):
if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)
prev_node.next = node.next
if self.head == node:
self.head = node.next
def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break
a_cllist = CircularLinkedList()
print('Menu')
print('insert after ')
print('insert before ')
print('insert at beg')
print('insert at end')
print('remove ')
print('quit')
while True:
print('The list: ', end = '')
a_cllist.display()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cllist.insert_at_beg(new_node)
elif position == 'end':
a_cllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cllist.remove(node)
elif operation == 'quit':
break"
2819,Python Program to Reverse a Given Number,"
n=int(input(""Enter number: ""))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print(""Reverse of the number:"",rev)"
2820,Odd Even Sort Program in Python | Java | C | C++,"
size=int(input(""Enter the size of the array:""));
arr=[]
print(""Enter the element of the array:"");
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Before Sorting Array Element are: "",arr)
for out in range(0,size):
for inn in range(0, size-1,+2):
if inn != size-1:
if arr[ inn] > arr[inn +1]:
temp = arr[inn]
arr[inn]=arr[inn +1]
arr[inn +1]=temp
for inn in range(1, size - 1, +2):
if inn != size-1:
if arr[ inn] > arr[inn +1]:
temp = arr[inn]
arr[inn]=arr[inn +1]
arr[inn +1]=temp
print(""\nAfter Sorting Array Element are: "",arr)"
2821,Program to compute the area and perimeter of Heptagon,"
import math
print(""Enter the length of the side:"")
a=int(input())
area=3.634*pow(a,2)
perimeter=(7*a)
print(""Area of the Heptagon = "",area)
print(""Perimeter of the Heptagon= "",perimeter)
"
2822,"
By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].
:","
li = [12,24,35,70,88,120,155]
li = [x for x in li if x%5!=0 and x%7!=0]
print li
"
2823,Python Program to Find Nth Node in the Inorder Traversal of a Tree,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder_nth(self, n):
return self.inorder_nth_helper(n, [])
def inorder_nth_helper(self, n, inord):
if self.left is not None:
temp = self.left.inorder_nth_helper(n, inord)
if temp is not None:
return temp
inord.append(self)
if n == len(inord):
return self
if self.right is not None:
temp = self.right.inorder_nth_helper(n, inord)
if temp is not None:
return temp
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('inorder ')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'inorder':
if btree is not None:
index = int(do[1].strip().lower())
node = btree.inorder_nth(index)
if node is not None:
print('nth term of inorder traversal: {}'.format(node.key))
else:
print('index exceeds maximum possible index.')
else:
print('Tree is empty.')
elif operation == 'quit':
break"
2824,"A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.","Solutions:
import re
value = []
items=[x for x in raw_input().split(',')]
for p in items:
if len(p)<6 or len(p)>12:
continue
else:
pass
if not re.search(""[a-z]"",p):
continue
elif not re.search(""[0-9]"",p):
continue
elif not re.search(""[A-Z]"",p):
continue
elif not re.search(""[$#@]"",p):
continue
elif re.search(""\s"",p):
continue
else:
pass
value.append(p)
print "","".join(value)
"
2825,Python Program to Accept Three Digits and Print all Possible Combinations from the Digits,"
a=int(input(""Enter first number:""))
b=int(input(""Enter second number:""))
c=int(input(""Enter third number:""))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])"
2826,"
Define a class Person and its two child classes: Male and Female. All classes have a method ""getGender"" which can print ""Male"" for Male class and ""Female"" for Female class.
:","
class Person(object):
def getGender( self ):
return ""Unknown""
class Male( Person ):
def getGender( self ):
return ""Male""
class Female( Person ):
def getGender( self ):
return ""Female""
aMale = Male()
aFemale= Female()
print aMale.getGender()
print aFemale.getGender()
"
2827,Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10,"l=int(input(""Enter lower range: ""))
u=int(input(""Enter upper range: ""))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10]
print(a)"
2828,Program to convert kilometers into miles and meters,"kilo_meter=int(input(""Enter Kilo Meter: ""))
miles=kilo_meter/1.609;
meter=kilo_meter*1000;
print(""Kilo Meter to Miles:"",miles)
print(""Kilo Meter to Meter:"",meter)"
2829,Python Program to Find the Product of two Numbers Using Recursion,"def product(a,b):
if(a self.get(i)):
largest = l
else:
largest = i
if (m <= self.size() - 1 and self.get(m) > self.get(largest)):
largest = m
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)
def swap(self, i, j):
self.items[i], self.items[j] = self.items[j], self.items[i]
def insert(self, key):
index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p
theap = TernaryHeap()
print('Menu (this assumes no duplicate keys)')
print('insert ')
print('max get')
print('max extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
theap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(theap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(theap.extract_max()))
elif operation == 'quit':
break"
2831,"
Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
","import re
s = raw_input()
print re.findall(""\d+"",s)
"
2832,Program to check whether a matrix is a scalar or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
# check except Diagonal all elements are 0 or not
# and check all diagonal elements are same or not
point=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i!=j and matrix[i][j]!=0:
point=1
break
if i==j and matrix[i][j]!=matrix[i][j]:
point = 1
break
if point==1:
print(""Given Matrix is not a Scaler Matrix."")
else:
print(""Given Matrix is a Scaler Matrix."")"
2833,Python Program to Check whether a Tree is a Binary Search Tree,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def is_bst_p(self):
if self.left is not None:
if self.key < self.left.key:
return False
elif not self.left.is_bst_p():
return False
if self.right is not None:
if self.key > self.right.key:
return False
elif not self.right.is_bst_p():
return False
return True
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('bst')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'bst':
if btree is not None:
if btree.is_bst_p():
print('Tree is a binary search tree.')
else:
print('Tree is not a binary search tree.')
else:
print('Tree is empty.')
elif operation == 'quit':
break"
2834,Find out all palindrome numbers present within a given range.,"
'''Write
a Python program to find out all palindrome numbers present within a
given range. or Write a program to find out all
palindrome numbers present within a given range using Python '''
print(""Enter a range in numbers(num1-num2):"")
range1=int(input())
range2=int(input())
print(range1,"" to "",range2,"" palindrome numbers are "");
for i in range(range1,range2+1):
num1=i
num2=0
while(num1!=0):
rem=num1%10
num1=int(num1/10)
num2=num2*10+rem
if(i==num2):
print(i,end="" "")
"
2835,Reverse words in a given string,"str=input(""Enter Your String:"")sub_str=str.split("" "")print(""After reversing words in a given string is:"")for out in range(len(sub_str)-1,-1,-1): print(sub_str[out],end="" "")"
2836,Python Program to Check String is Palindrome using Stack,"class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
s = Stack()
text = input('Please enter the string: ')
for character in text:
s.push(character)
reversed_text = ''
while not s.is_empty():
reversed_text = reversed_text + s.pop()
if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')"
2837,Check if one array is a subset of another array or not ,"
arr=[]
arr2=[]
size = int(input(""Enter the size of the 1st array: ""))
size2 = int(input(""Enter the size of the 2nd array: ""))
print(""Enter the Element of the 1st array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the Element of the 2nd array:"")
for i in range(0,size2):
num2 = int(input())
arr2.append(num2)
count=0
for i in range(0, size):
for j in range(0, size2):
if arr[i] == arr2[j]:
count+=1
if count==size2:
print(""Array two is a subset of array one."")
else:
print(""Array two is not a subset of array one."")"
2838,Python Program to Find All Nodes Reachable from a Node using BFS in a Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def find_all_reachable_nodes(vertex):
""""""Return set containing all vertices reachable from vertex.""""""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)
return visited
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('reachable ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'reachable':
key = int(do[1])
vertex = g.get_vertex(key)
reachable = find_all_reachable_nodes(vertex)
print('All nodes reachable from {}:'.format(key),
[v.get_key() for v in reachable])
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2839, Find the 2nd smallest element in the array,"
import sys
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
min=sys.maxsize
sec_min=sys.maxsize
for j in range(0,size):
if (arr[j] <= min):
sec_min=min
min = arr[j]
elif(arr[i] <= sec_min):
sec_min = arr[j]
print(""The 2nd smallest element of array: "",sec_min)"
2840,Python Program to Search for an Element in the Linked List using Recursion,"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 is not None:
print(current.data, end = ' ')
current = current.next
def find_index(self, key):
return self.find_index_helper(key, 0, self.head)
def find_index_helper(self, key, start, node):
if node is None:
return -1
if node.data == key:
return start
else:
return self.find_index_helper(key, start + 1, node.next)
a_llist = LinkedList()
for data in [3, 5, 0, 10, 7]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()
key = int(input('What data item would you like to search for? '))
index = a_llist.find_index(key)
if index == -1:
print(str(key) + ' was not found.')
else:
print(str(key) + ' is at index ' + str(index) + '.')"
2841,Python Program to Add Corresponding Positioned Elements of 2 Linked Lists,"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 is not None:
print(current.data, end = ' ')
current = current.next
def add_linked_lists(llist1, llist2):
sum_llist = LinkedList()
current1 = llist1.head
current2 = llist2.head
while (current1 and current2):
sum = current1.data + current2.data
sum_llist.append(sum)
current1 = current1.next
current2 = current2.next
if current1 is None:
while current2:
sum_llist.append(current2.data)
current2 = current2.next
else:
while current1:
sum_llist.append(current1.data)
current1 = current1.next
return sum_llist
llist1 = LinkedList()
llist2 = LinkedList()
data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))
data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))
sum_llist = add_linked_lists(llist1, llist2)
print('The sum linked list: ', end = '')
sum_llist.display()"
2842,Python Program to Append the Contents of One File to Another File,"name1 = input(""Enter file to be read from: "")
name2 = input(""Enter file to be appended to: "")
fin = open(name1, ""r"")
data2 = fin.read()
fin.close()
fout = open(name2, ""a"")
fout.write(data2)
fout.close()"
2843,"
Please write a program which accepts a string from console and print the characters that have even indexes.
","
s=raw_input()
s = s[::2]
print s
"
2844,Print odd numbers in given range using recursion,"def odd(num1,num2): if num1>num2: return print(num1,end="" "") return odd(num1+2,num2)num1=1print(""Enter your Limit:"")num2=int(input())print(""All odd number given range are:"")odd(num1,num2)"
2845,Bubble Sort Program in Python | Java | C | C++,"
size=int(input(""Enter the size of the array:""));
arr=[]
print(""Enter the element of the array:"");
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Before Sorting Array Element are: "",arr)
for out in range(size-1,0,-1):
for inn in range(out):
if arr[inn] > arr[inn +1]:
temp=arr[inn]
arr[inn]=arr[inn +1]
arr[inn +1]=temp
print(""\nAfter Sorting Array Element are: "",arr)"
2846,Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.,"lines = []
while True:
s = raw_input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print sentence
"
2847,Python Program to Implement Cocktail Shaker Sort,"def cocktail_shaker_sort(alist):
def swap(i, j):
alist[i], alist[j] = alist[j], alist[i]
upper = len(alist) - 1
lower = 0
no_swap = False
while (not no_swap and upper - lower > 1):
no_swap = True
for j in range(lower, upper):
if alist[j + 1] < alist[j]:
swap(j + 1, j)
no_swap = False
upper = upper - 1
for j in range(upper, lower, -1):
if alist[j - 1] > alist[j]:
swap(j - 1, j)
no_swap = False
lower = lower + 1
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
cocktail_shaker_sort(alist)
print('Sorted list: ', end='')
print(alist)"
2848,Program to find addition of two matrices ,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Addition of two matrices
sum_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sum_matrix[i][j]=matrix[i][j]+matrix1[i][j]
# display the sum of two matrices
print(""Sum of the two Matrices is:"")
for m in sum_matrix:
print(m)"
2849,Find mean and median of unsorted array,"def Find_mean(arr,size): sum=0 for i in range(0, size): sum+=arr[i] mean=sum/size print(""Mean = "",mean)def Find_median(arr,size): arr.sort() if size%2==1: median=arr[size//2] print(""\nMedian= "",median) else: median = (arr[size // 2] + (arr[(size // 2) - 1])) / 2.0 print(""\nMedian= "", median)arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)Find_mean(arr,size)Find_median(arr,size)"
2850,Python Program that Displays which Letters are in the First String but not in the Second,"s1=raw_input(""Enter first string:"")
s2=raw_input(""Enter second string:"")
a=list(set(s1)-set(s2))
print(""The letters are:"")
for i in a:
print(i)"
2851,Python Program to Implement Binary Search with Recursion,"def binary_search(alist, start, end, key):
""""""Search key in alist[start... end - 1].""""""
if not start < end:
return -1
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid
alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = binary_search(alist, 0, len(alist), key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))"
2852,Python Program to Detect the Cycle in 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 get_node(self, index):
current = self.head
for i in range(index):
current = current.next
if current is None:
return None
return current
def has_cycle(llist):
slow = llist.head
fast = llist.head
while (fast != None and fast.next != None):
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
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))
length = len(data_list)
if length != 0:
values = '0-' + str(length - 1)
last_ptr = input('Enter the index [' + values + '] of the node'
' to which you want the last node to point'
' (enter nothing to make it point to None): ').strip()
if last_ptr == '':
last_ptr = None
else:
last_ptr = a_llist.get_node(int(last_ptr))
a_llist.last_node.next = last_ptr
if has_cycle(a_llist):
print('The linked list has a cycle.')
else:
print('The linked list does not have a cycle.')"
2853,"
Please write a program to compress and decompress the string ""hello world!hello world!hello world!hello world!"".
:","
import zlib
s = 'hello world!hello world!hello world!hello world!'
t = zlib.compress(s)
print t
print zlib.decompress(t)
"
2854,Python Program to Interchange two Elements of the List without touching the Key Field,"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 get_node(self, index):
current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def interchange(llist, n, m):
node1 = llist.get_node(n)
node2 = llist.get_node(m)
prev_node1 = llist.get_prev_node(node1)
prev_node2 = llist.get_prev_node(node2)
if prev_node1 is not None:
prev_node1.next = node2
else:
llist.head = node2
if prev_node2 is not None:
prev_node2.next = node1
else:
llist.head = node1
temp = node2.next
node2.next = node1.next
node1.next = temp
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))
ans = input('Please enter the two indices of the two elements that'
' you want to exchange: ').split()
n = int(ans[0])
m = int(ans[1])
interchange(a_llist, n, m)
print('The new list: ')
a_llist.display()"
2855,Write a program to print the pattern,"
print(""Enter the row and column size:"")
row_size=int(input())
for out in range(row_size,0,-1):
for i in range(row_size,0,-1):
print(i,end="""")
print(""\r"")
"
2856,Print Strong numbers in a given range(1 to n),"
print(""Enter a range:"")
range1=int(input())
range2=int(input())
print(""Strong numbers between "",range1,"" and "",range2,"" are: "")
for i in range(range1,range2+1):
num2=i
num1=i
sum=0
while(num1!=0):
fact=1
rem=num1%10
num1=int(num1/10)
for j in range(1,rem+1):
fact=fact*j
sum=sum+fact
if sum==num2:
print(i,end="" "")
"
2857,Program to convert Hexadecimal To Octal,"
import math
hex=input(""Enter Hexadecimal Number:"")
value=0
decimal=0
j=len(hex)
j-=1
for i in range(0,len(hex)):
if hex[i]>='0' and hex[i]<='9' :
value=(int)(hex[i])
if hex[i]=='A' or hex[i]=='a':
value=10
if hex[i] == 'B' or hex[i] == 'b':
value=11
if hex[i] == 'C' or hex[i] == 'c':
value=12
if hex[i] == 'D' or hex[i] == 'd':
value=13
if hex[i] == 'E' or hex[i] == 'e':
value=14
if hex[i] == 'F' or hex[i] == 'f':
value=15
decimal=decimal+(int)(value*math.pow(16,j))
j-=1
sem=1
octal=0
while(decimal !=0):
octal=octal+(decimal%8)*sem
decimal=decimal//8
sem=int(sem*10)
print(""Octal Number is:"",octal)"
2858,Count the number of odd and even digits,"print(""Enter the number:"")
num=int(input())
odd=0
even=0
while(num!=0):
rem=num%10
if(rem%2==1):
odd+=1
else:
even+=1
num//=10
print(""Number of even digits = "",even)
print(""Number of odd digits = "",odd) "
2859,Python Program to Solve Interval Scheduling Problem using Greedy Algorithm,"def interval_scheduling(stimes, ftimes):
""""""Return largest set of mutually compatible activities.
This will return a maximum-set subset of activities (numbered from 0 to n -
1) that are mutually compatible. Two activities are mutually compatible if
the start time of one activity is not less then the finish time of the other.
stimes[i] is the start time of activity i.
ftimes[i] is the finish time of activity i.
""""""
# index = [0, 1, 2, ..., n - 1] for n items
index = list(range(len(stimes)))
# sort according to finish times
index.sort(key=lambda i: ftimes[i])
maximal_set = set()
prev_finish_time = 0
for i in index:
if stimes[i] >= prev_finish_time:
maximal_set.add(i)
prev_finish_time = ftimes[i]
return maximal_set
n = int(input('Enter number of activities: '))
stimes = input('Enter the start time of the {} activities in order: '
.format(n)).split()
stimes = [int(st) for st in stimes]
ftimes = input('Enter the finish times of the {} activities in order: '
.format(n)).split()
ftimes = [int(ft) for ft in ftimes]
ans = interval_scheduling(stimes, ftimes)
print('A maximum-size subset of activities that are mutually compatible is', ans)"
2860,Python Program to Print all the Prime Numbers within a Given Range,"r=int(input(""Enter upper limit: ""))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)"
2861,Find the maximum 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 maximum element of the given 2d array
max=-sys.maxsize-1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]>=max:
max=matrix[i][j]
# Display the largest element of the given matrix
print(""The Maximum element of the Given 2d array is: "",max)"
2862,Find the index of an element in an array,"arr=[]temp=0pos=0index=0size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)print(""Enter the search element:"")ele=int(input())print(""Array elements are:"")for i in range(0,size): print(arr[i],end="" "")for i in range(0,size): if arr[i] == ele: temp = 1 index=iif temp==1: print(""\nIndex of Search Element "",ele,"" is "",index)else: print(""\nElement not found...."")"
2863, Program to print the Half Pyramid Number Pattern,"
row_size=int(input(""Enter the row size:""))
for out in range(row_size+1):
for i in range(out):
print(out,end="""")
print(""\r"")
"
2864,Program to check whether a matrix is symmetric or not,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
if row_size!=col_size:
print(""Given Matrix is not a Square Matrix."")
else:
#compute the transpose matrix
tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)]
for i in range(0, row_size):
for j in range(0, col_size):
tran_matrix[i][j] = matrix[j][i]
# check given matrix elements and transpose
# matrix elements are same or not.
flag=0
for i in range(0, row_size):
for j in range(0, col_size):
if matrix[i][j] != tran_matrix[i][j]:
flag=1
break
if flag==1:
print(""Given Matrix is not a symmetric Matrix."")
else:
print(""Given Matrix is a symmetric Matrix."")"
2865,Python Program to Implement Quicksort,"def quicksort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
p = partition(alist, start, end)
quicksort(alist, start, p)
quicksort(alist, p + 1, end)
def partition(alist, start, end):
pivot = alist[start]
i = start + 1
j = end - 1
while True:
while (i <= j and alist[i] <= pivot):
i = i + 1
while (i <= j and alist[j] >= pivot):
j = j - 1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
quicksort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)"
2866,Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary,"test_string=raw_input(""Enter string:"")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))"
2867,Program to Find the sum of a lower triangular matrix,"# 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()])
#Calculate sum of lower triangular matrix element
sum=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def replace_node_of_parent(self, new_node):
if self.parent is not None:
if new_node is not None:
new_node.parent = self.parent
if self.parent.left == self:
self.parent.left = new_node
elif self.parent.right == self:
self.parent.right = new_node
else:
self.key = new_node.key
self.left = new_node.left
self.right = new_node.right
if new_node.left is not None:
new_node.left.parent = self
if new_node.right is not None:
new_node.right.parent = self
def find_min(self):
current = self
while current.left is not None:
current = current.left
return current
def remove(self):
if (self.left is not None and self.right is not None):
successor = self.right.find_min()
self.key = successor.key
successor.remove()
elif self.left is not None:
self.replace_node_of_parent(self.left)
elif self.right is not None:
self.replace_node_of_parent(self.right)
else:
self.replace_node_of_parent(None)
def search(self, key):
if self.key > key:
if self.left is not None:
return self.left.search(key)
else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key)
else:
return None
return self
class BSTree:
def __init__(self):
self.root = None
def inorder(self):
if self.root is not None:
self.root.inorder()
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
def remove(self, key):
to_remove = self.search(key)
if (self.root == to_remove
and self.root.left is None and self.root.right is None):
self.root = None
else:
to_remove.remove()
def search(self, key):
if self.root is not None:
return self.root.search(key)
bstree = BSTree()
print('Menu (this assumes no duplicate keys)')
print('add ')
print('remove ')
print('inorder')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
elif operation == 'remove':
key = int(do[1])
bstree.remove(key)
elif operation == 'inorder':
print('Inorder traversal: ', end='')
bstree.inorder()
print()
elif operation == 'quit':
break"
2874,Program to print a to z in c using ascii value,"
print(""Printing a-z using ASCII"")
for i in range(97,123):
print(chr(i),end="" "")"
2875,Python Program to Implement Tower of Hanoi,"def hanoi(disks, source, auxiliary, target):
if disks == 1:
print('Move disk 1 from peg {} to peg {}.'.format(source, target))
return
hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from peg {} to peg {}.'.format(disks, source, target))
hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter number of disks: '))
hanoi(disks, 'A', 'B', 'C')"
2876,Division Two Numbers Operator without using Division(/) operator,"
num1=int(input(""Enter first number:""))
num2=int(input(""Enter second number:""))
div=0
while num1>=num2:
num1=num1-num2
div+=1
print(""Division of two number is "",div)
"
2877,Python Program to Convert a given Singly Linked List to a Circular 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 convert_to_circular(llist):
if llist.last_node:
llist.last_node.next = llist.head
def print_last_node_points_to(llist):
last = llist.last_node
if last is None:
print('List is empty.')
return
if last.next is None:
print('Last node points to None.')
else:
print('Last node points to element with data {}.'.format(last.next.data))
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))
print_last_node_points_to(a_llist)
print('Converting linked list to a circular linked list...')
convert_to_circular(a_llist)
print_last_node_points_to(a_llist)"
2878,Python Program to Find the Sum of Digits in a Number,"
n=int(input(""Enter a number:""))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print(""The total sum of digits is:"",tot)"
2879,Python Program that Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File,"fname = input(""Enter file name: "")
l=input(""Enter letter to be searched:"")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print(""Occurrences of the letter:"")
print(k)"
2880,Write a program to calculate Amicable pairs,"
'''Write a Python
program to Calculate Amicable pairs. or Write a
program to Calculate Amicable pairs using Python '''
print(""Enter the two number:"")
num1=int(input())
num2=int(input())
sum1=0;
sum2=0;
for i in range(1,num1):
if num1%i==0:
sum1+=i
for i in range(1,num2):
if num2%i==0:
sum2+=i
if sum1==num2:
if sum2==num1:
print(""This is an amicable pair."")
else:
print(""This is not an amicable pair."")
"
2881,Python Program to Display all the Nodes in a Linked List using Recursion,"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):
self.display_helper(self.head)
def display_helper(self, current):
if current is None:
return
print(current.data, end = ' ')
self.display_helper(current.next)
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()"
2882,Sort the elements of an array in ascending order,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Before sorting array elements are:"")
for i in range(0,size):
print(arr[i],end="" "")
for i in range(0,size):
for j in range(i+1, size):
if arr[i] >= arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print(""\nAfter sorting array elements are:"")
for i in range(0, size):
print(arr[i],end="" "")"
2883,Print array in reverse order using recursion,"def ReverseArray(arr,n): if(n>0): i=n-1 print(arr[i], end="" "") ReverseArray(arr, i)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)print(""After reversing Array Element Are:"")ReverseArray(arr,n)"
2884, Read a String with spaces,"
str=input(""Enter the String:"")
print(""Your Enter String is:"", str)"
2885,Python Program to Create a Mirror Copy of a Tree and Display using BFS Traversal,"class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def mirror_copy(self):
mirror = BinaryTree(self.key)
if self.right is not None:
mirror.left = self.right.mirror_copy()
if self.left is not None:
mirror.right = self.left.mirror_copy()
return mirror
def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
if popped.left is not None:
queue.append(popped.left)
if popped.right is not None:
queue.append(popped.right)
print(popped.key, end=' ')
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('mirror')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'mirror':
if btree is not None:
print('Creating mirror copy...')
mirror = btree.mirror_copy()
print('BFS traversal of original tree: ')
btree.bfs()
print()
print('BFS traversal of mirror: ')
mirror.bfs()
print()
elif operation == 'quit':
break"
2886,Program to Find sum of N Natural Numbers,"#Take input number of natural number
n=int(input(""Enter the N value:""))#Calculate the sum of the n natural number
sum=0
for i in range(1,n+1):
sum=sum+i#display the sum of the n natural number
print(""The sum of n natural numbers is "", sum)
"
2887,"
Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
:","
import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
if li[mid]==element:
index = mid
elif li[mid]>element:
top = mid-1
else:
bottom = mid+1
return index
li=[2,5,7,9,11,17,222]
print bin_search(li,11)
print bin_search(li,12)
"
2888,Write a program to swap three numbers ,"num1=int(input(""Enter 1st number:""))
num2=int(input(""Enter 2nd number:""))
num3=int(input(""Enter 3rd number:""))
num1=num1+num2+num3
num2=num1-num2-num3
num3=num1-num2-num3
num1=num1-num2-num3
print(""***After swapping***"")
print(""Number 1: "",num1)
print(""Number 2: "",num2)
print(""Number 3: "",num3)"
2889,Python Program to Check if a Number is a Prime Number,"a=int(input(""Enter number: ""))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(""Number is prime"")
else:
print(""Number isn't prime"")"
2890, Program to Print Cross Sign (╳ ) Number Pattern,"row_size=int(input(""Enter the row size:""))print_control_x=row_size//2+1for out in range(1,row_size+1): for inn in range(1,row_size+1): if inn==out or inn+out==row_size+1: print(out,end="""") else: print("" "", end="""") print(""\r"")"
2891,Python Program to Implement Stack Using Two Queues,"class Stack:
def __init__(self):
self.queue1 = Queue()
self.queue2 = Queue()
def is_empty(self):
return self.queue2.is_empty()
def push(self, data):
self.queue1.enqueue(data)
while not self.queue2.is_empty():
x = self.queue2.dequeue()
self.queue1.enqueue(x)
self.queue1, self.queue2 = self.queue2, self.queue1
def pop(self):
return self.queue2.dequeue()
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
s = Stack()
print('Menu')
print('push ')
print('pop')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break"
2892,Python Program to Print Middle most Node of 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 print_middle(llist):
current = llist.head
length = 0
while current:
current = current.next
length = length + 1
current = llist.head
for i in range((length - 1)//2):
current = current.next
if current:
if length % 2 == 0:
print('The two middle elements are {} and {}.'
.format(current.data, current.next.data))
else:
print('The middle element is {}.'.format(current.data))
else:
print('The list is empty.')
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))
print_middle(a_llist)"
2893,"
By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].
:","
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print li
"
2894,Python Program to Print the Alternate Nodes in a Linked List without using Recursion,"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 alternate(self):
current = self.head
while current:
print(current.data, end = ' ')
if current.next is not None:
current = current.next.next
else:
break
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))
print('The alternate nodes of the linked list: ', end = '')
a_llist.alternate()"
2895,"Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
:","
class Circle(object):
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
aCircle = Circle(2)
print aCircle.area()
"
2896,Count number of the words in a String,"
str1=input(""Enter the String:"")
str2=len(str1.split())
print(""Word present in a string are "",str(str2))"
2897,Write a program to print the alphabet pattern,"
print(""Enter the row and column size:"");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),ord(row_size)+1):
print(chr(i),end="" "")
print(""\r"")
"
2898,Convert decimal to binary using recursion,"def DecimalToBinary(n): if n==0: return 0 else: return (n% 2 + 10 * DecimalToBinary(n // 2))n=int(input(""Enter the Decimal Value:""))print(""Binary Value of Decimal number is:"",DecimalToBinary(n))"
2899,Python Program to Calculate the Length of a String Without Using a Library Function,"string=raw_input(""Enter string:"")
count=0
for i in string:
count=count+1
print(""Length of the string is:"")
print(count)"
2900,Program to Calculate the surface area and volume of a Cylinder,"
import math
PI=3.14
r=int(input(""Enter the radius of the cylinder:""))
h=int(input(""Enter the height of the cylinder:""))
surface_area=(2*PI*r*h)+(2*PI*math.pow(r,2))
volume=PI*math.pow(r,2)*h
print(""Surface Area of the cylinder = "",surface_area)
print(""Volume of the cylinder = "",volume)"
2901,Program to Find nth Sunny Number,"
import math
rangenumber=int(input(""Enter a Nth Number:""))
c = 0
letest = 0
num = 1
while c != rangenumber:
num1=num
root = math.sqrt(num1 + 1)
if int(root) == root:
c+=1
letest = num
num = num + 1
print(rangenumber,""th Sunny number is "",letest)"
2902,Program to find the sum of series 1+2+3..+N,"
print(""Enter the range of number:"")
n=int(input())
sum=0
for i in range(1,n+1):
sum+=i
print(""The sum of the series = "",sum) "
2903,Python Program to Find the Intersection of Two Lists,"def intersection(a, b):
return list(set(a) & set(b))
def main():
alist=[]
blist=[]
n1=int(input(""Enter number of elements for list1:""))
n2=int(input(""Enter number of elements for list2:""))
print(""For list1:"")
for x in range(0,n1):
element=int(input(""Enter element"" + str(x+1) + "":""))
alist.append(element)
print(""For list2:"")
for x in range(0,n2):
element=int(input(""Enter element"" + str(x+1) + "":""))
blist.append(element)
print(""The intersection is :"")
print(intersection(alist, blist))
main()"
2904,Program to swap two numbers using third variable,"num1=int(input(""Enter 1st number:""))
num2=int(input(""Enter 2nd number:""))
temp=num1
num1=num2
num2=temp
print(""***After swapping***"")
print(""Number 1: "",num1)
print(""Number 2: "",num2)"
2905,Print Abundant numbers in a given range(1 to n),"
print(""Enter a range"")
range1=int(input())
range2=int(input())
print(""Abundant numbers between "",range1,"" and "",range2,"" are: "")
for j in range(range1,range2+1):
sum=0
for i in range(1,j):
if(j%i==0):
sum=sum+i
if sum>j:
print(j,end="" "")
"
2906,Segregate 0s and 1s in an array,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array(only 0s and 1s):"")for i in range(0,size): num = int(input()) arr.append(num)c=0for i in range(0,size): if arr[i]==0: c+=1for i in range(0,c): arr[i]=0for i in range(c,size): arr[i]=1print(""After segregate 0s and 1s in an Array, Array is:"")print(arr)"
2907,Write a program to print the alphabet pattern,"
print(""Enter the row and column size:"")
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),ord(row_size)+1):
print(chr(out),end="""")
print(""\r"")
"
2908,Python Program to Take in the Marks of 5 Subjects and Display the Grade,"
sub1=int(input(""Enter marks of the first subject: ""))
sub2=int(input(""Enter marks of the second subject: ""))
sub3=int(input(""Enter marks of the third subject: ""))
sub4=int(input(""Enter marks of the fourth subject: ""))
sub5=int(input(""Enter marks of the fifth subject: ""))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print(""Grade: A"")
elif(avg>=80&avg<90):
print(""Grade: B"")
elif(avg>=70&avg<80):
print(""Grade: C"")
elif(avg>=60&avg<70):
print(""Grade: D"")
else:
print(""Grade: F"")"
2909,Python Program to Create a Class in which One Method Accepts a String from the User and Another Prints it,"class print1():
def __init__(self):
self.string=""""
def get(self):
self.string=input(""Enter string: "")
def put(self):
print(""String is:"")
print(self.string)
obj=print1()
obj.get()
obj.put()"
2910,Python Program to Implement Binary Insertion Sort,"def binary_insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
pos = binary_search(alist, temp, 0, i) + 1
for k in range(i, pos, -1):
alist[k] = alist[k - 1]
alist[pos] = temp
def binary_search(alist, key, start, end):
'''If key is in the list at index p, then return p.
If there are multiple such keys in the list, then return the index of any one.
If key is not in the list and a < key < b where a and b are elements in the list, then return the index of a.
If key is not in the list and key < a where a is the first element in the list, then return -1.
Only elements with indexes start to end - 1 inclusive are considered.
'''
if end - start <= 1:
if key < alist[start]:
return start - 1
else:
return start
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, key, mid, end)
elif alist[mid] > key:
return binary_search(alist, key, start, mid)
else:
return mid
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
binary_insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)"
2911,Print array elements using recursion,"def PrintArray(arr,i,n): if(i>=n): return print(arr[i],end="" "") PrintArray(arr,i+1,n)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)print(""Array Element Are:"")PrintArray(arr,0,n)"
2912,Python Program to Find Element Occurring Odd Number of Times in a List,"def find_odd_occurring(alist):
""""""Return the element that occurs odd number of times in alist.
alist is a list in which all elements except one element occurs an even
number of times.
""""""
ans = 0
for element in alist:
ans ^= element
return ans
alist = input('Enter the list: ').split()
alist = [int(i) for i in alist]
ans = find_odd_occurring(alist)
print('The element that occurs odd number of times:', ans)"
2913,Binary search Program using recursion ,"def binary_search(arr, start, end, Search_ele): if(start>end): return -1 mid=(int)((start+end)/2) if(arr[mid]==Search_ele): return mid if (Search_ele < arr[mid]): return (binary_search(arr, start, mid - 1, Search_ele)) else: return (binary_search(arr, mid + 1, end, Search_ele))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)Search_ele=int(input(""Enter the search element:""))pos=binary_search(arr, 0, n, Search_ele)if (pos== -1): print(Search_ele,"" not found in array"")else: print(Search_ele,"" found at "",""arr["",pos,""]"")"
2914,Python Program to find the factorial of a number without recursion,"n=int(input(""Enter number:""))
fact=1
while(n>0):
fact=fact*n
n=n-1
print(""Factorial of the number is: "")
print(fact)"
2915,Program to Check whether two strings are same or not,"
str=input(""Enter the 1st String:"")
str2=input(""Enter the 2nd String:"")
count = 0
if len(str) != len(str2):
print(""Strings are not the same."")
else:
for i in range(0,len(str)):
if str[i] == str2[i]:
count=1
break
if count!=1:
print(""Input strings are not the same."")
else:
print(""Input strings are the same."")"
2916,Program to Find subtraction of two matrices,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Subtraction of two matrices
sub_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sub_matrix[i][j]=matrix[i][j]-matrix1[i][j]
# display the Subtraction of two matrices
print(""Subtraction of the two Matrices is:"")
for m in sub_matrix:
print(m)"
2917,Python Program to Flatten a Nested List using Recursion,"def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
s=[[1,2],[3,4]]
print(""Flattened list is: "",flatten(s))"
2918,Python Program to Implement Breadth-First Search on a Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def display_bfs(vertex):
""""""Display BFS Traversal starting at vertex.""""""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
print(current.get_key(), end=' ')
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('bfs ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'bfs':
key = int(do[1])
print('Breadth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_bfs(vertex)
print()
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2919,Python Program to Print a Topological Sorting of a Directed Acyclic Graph using DFS,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def get_topological_sorting(graph):
""""""Return a topological sorting of the DAG. Return None if graph is not a DAG.""""""
tlist = []
visited = set()
on_stack = set()
for v in graph:
if v not in visited:
if not get_topological_sorting_helper(v, visited, on_stack, tlist):
return None
return tlist
def get_topological_sorting_helper(v, visited, on_stack, tlist):
""""""Perform DFS traversal starting at vertex v and store a topological
sorting of the DAG in tlist. Return False if it is found that the graph is
not a DAG. Uses set visited to keep track of already visited nodes.""""""
if v in on_stack:
# graph has cycles and is therefore not a DAG.
return False
on_stack.add(v)
for dest in v.get_neighbours():
if dest not in visited:
if not get_topological_sorting_helper(dest, visited, on_stack, tlist):
return False
on_stack.remove(v)
visited.add(v)
tlist.insert(0, v.get_key()) # prepend node key to tlist
return True
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('topological')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'topological':
tlist = get_topological_sorting(g)
if tlist is not None:
print('Topological Sorting: ', end='')
print(tlist)
else:
print('Graph is not a DAG.')
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2920,Find the maximum occurring character in given string,"str=input(""Enter Your String:"")max=-1arr=[0]*256for i in range(len(str)): if str[i]==' ': continue num=ord(str[i]) arr[num]+=1ch=' 'for i in range(len(str)): if arr[ord(str[i])] != 0: if arr[ord(str[i])] >= max: max = arr[ord(str[i])] ch=str[i]print(""The Maximum occurring character in a string is "",ch)"
2921,Python Program to Find if Undirected Graph contains Cycle using BFS,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def add_undirected_edge(self, v1_key, v2_key, weight=1):
""""""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight.""""""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)
def does_undirected_edge_exist(self, v1_key, v2_key):
""""""Return True if there is an undirected edge between v1_key and v2_key.""""""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def is_cycle_present(vertex, visited):
""""""Return True if cycle is present in component containing vertex and put
all vertices in component in set visited.""""""
parent = {vertex: None}
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
parent[dest] = current
q.enqueue(dest)
else:
if parent[current] is not dest:
return True
return False
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex ')
print('add edge ')
print('cycle')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_undirected_edge_exist(v1, v2):
g.add_undirected_edge(v1, v2)
else:
print('Edge already exists.')
elif operation == 'cycle':
present = False
visited = set()
for v in g:
if v not in visited:
if is_cycle_present(v, visited):
present = True
break
if present:
print('Cycle present.')
else:
print('Cycle not present.')
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2922,Insert an element into an array at a specified position,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""Enter the element:"")
ele=int(input())
print(""Enter the position:"")
pos=int(input())
print(""Before inserting array elements are:"")
for i in range(0,size):
print(arr[i],end="" "")
arr.insert(pos-1,ele)
print(""\nAfter inserting array elements are:"")
print(arr)"
2923,Find the square of a number accept from user,"num=int(input(""Enter a number:"")) print(""Square of the number:"",num*num) "
2924,Separate positive and negative numbers in an array,"
arr=[]
size = int(input(""Enter the size of the array: ""))
print(""Enter the Element of the array:"")
for i in range(0,size):
num = int(input())
arr.append(num)
print(""\nPositive numbers are:"")
for i in range(0,size):
if(arr[i]>0):
print(arr[i],end="" "")
print(""\nNegative numbers are:"")
for i in range(0,size):
if(arr[i]<0):
print(arr[i],end="" "")"
2925,Count repeated characters in a string,"
str=input(""Enter the String:"")
arr=[0]*256
for i in range(len(str)):
if str[i]==' ':
continue
num=ord(str[i])
arr[num]+=1
print(""Repeated character in a string are:"")
for i in range(256):
if arr[i]>1:
print((chr)(i),"" occurs "",arr[i],"" times"")"
2926,Python Program to Find the first Common Element between the 2 given Linked Lists,"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 first_common(llist1, llist2):
current1 = llist1.head
while current1:
data = current1.data
current2 = llist2.head
while current2:
if data == current2.data:
return data
current2 = current2.next
current1 = current1.next
return None
llist1 = LinkedList()
llist2 = LinkedList()
data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))
data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))
common = first_common(llist1, llist2)
if common:
print('The element that appears first in the first linked list that'
' is common to both is {}.'.format(common))
else:
print('The two lists have no common elements.')"
2927,Python Program to Find All Connected Components using BFS in an Undirected Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def add_undirected_edge(self, v1_key, v2_key, weight=1):
""""""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight.""""""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)
def does_undirected_edge_exist(self, v1_key, v2_key):
""""""Return True if there is an undirected edge between v1_key and v2_key.""""""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def label_all_reachable(vertex, component, label):
""""""Set component[v] = label for all v in the component containing vertex.""""""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
component[current] = label
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex ')
print('add edge ')
print('components')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_undirected_edge_exist(src, dest):
g.add_undirected_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'components':
component = dict.fromkeys(g, None)
label = 1
for v in g:
if component[v] is None:
label_all_reachable(v, component, label)
label += 1
max_label = label
for label in range(1, max_label):
component_vertices = [v.get_key() for v in component
if component[v] == label]
print('Component {}:'.format(label), component_vertices)
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2928,Program to find the sum of series 1^1+2^2+3^3...+N^N,"
import math
print(""Enter the range of number:"")
n=int(input())
sum=0
for i in range(1,n+1):
sum+=pow(i,i)
print(""The sum of the series = "",sum)"
2929,Program to Find square of a 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 square of the matrix
for i in range(0,row_size):
for j in range(0,col_size):
matrix[i][j]=pow(matrix[i][j],2)
# display square of the matrix
print(""Square of the Matrix elements are:"")
for m in matrix:
print(m)"
2930,Python Program to Count Number of Lowercase Characters in a String,"string=raw_input(""Enter string:"")
count=0
for i in string:
if(i.islower()):
count=count+1
print(""The number of lowercase characters is:"")
print(count)"
2931,Capitalize the first and last letter of every word in a string,"
ch=input(""Enter the String:"")
j=0
str=list(ch)
str+='\0'
for i in range(len(str)):
if i==0 or str[i-1]==' ':
str[i]=str[i].upper()
elif str[i]==' ' or str[i]=='\0':
str[i-1] = str[i-1].upper()
print(""Your String is:"", """".join(str))"
2932,"
By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
:","
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
print array
"
2933,Find the largest digit in a number,"
print(""Enter the Number :"")
num=int(input())
Largest=0;
while (num > 0):
reminder=num%10
if Largest= max):
sec_max=max
max = arr[j]
elif(arr[i] >= sec_max):
sec_max = arr[j]
print(""The 2nd largest element of array: "",sec_max)"
2935,Print all the Even numbers from 1 to n,"
n=int(input(""Enter the n value:""))
print(""Printing even numbers between 1 to "",n)
for i in range(1,n+1):
if i%2==0:
print(i)
"
2936,Python Program to Implement Queue,"class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
q = Queue()
while True:
print('enqueue ')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'quit':
break"
2937,Find the sum of all diagonal elements of a matrix,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
sum=0
#Calculate sum of the diagonals element
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i==j:
sum+=matrix[i][j]
# Display the sum of diagonals Element
print(""Sum of diagonals Element is: "",sum)"
2938,Program to Find subtraction of two matrices,"# 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 1st matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
matrix1=[]
# Taking input of the 2nd matrix
print(""Enter the Matrix Element:"")
for i in range(row_size):
matrix1.append([int(j) for j in input().split()])
# Compute Subtraction of two matrices
sub_matrix=[[0 for i in range(col_size)] for i in range(row_size)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
sub_matrix[i][j]=matrix[i][j]-matrix1[i][j]
# display the Subtraction of two matrices
print(""Subtraction of the two Matrices is:"")
for m in sub_matrix:
print(m)"
2939,"Define a function that can convert a integer into a string and print it in console.
:","Solution
def printValue(n):
print str(n)
printValue(3)
"
2940,Program to compute the area of Trapezoid,"
print(""Enter the value of base:"")
a=int(input())
b=int(input())
h=int(input(""Enter the value of height:""))
area=((a+b)*h)/2.0
print(""Area of the Trapezoid = "",area)
"
2941,Find GCD of two numbers using recursion,"def gcd(num1,num2): if num2==0: return num1 else: return gcd(num2,num1%num2)print(""Enter the two Number:"")num1=int(input())num2=int(input())print(""Gcd of Given Numbers Using Recursion is:"",gcd(num1,num2))"
2942,Python Program to Implement Depth First Search Traversal using Post Order,"class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def postorder(self):
for child in self.children:
child.postorder()
print(self.key, end=' ')
tree = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('dfs')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)
elif operation == 'dfs':
print('Post-order traversal: ', end='')
tree.postorder()
print()
elif operation == 'quit':
break"
2943,Program to find the sum of series 1^1+2^2+3^3...+N^N,"
import math
print(""Enter the range of number:"")
n=int(input())
sum=0
for i in range(1,n+1):
sum+=pow(i,i)
print(""The sum of the series = "",sum)"
2944,Print the average marks obtained by a student in five tests,"arr=[]sum=0avg=0.0print(""Enter the five test Marks:"")for i in range(0,5): mark = int(input()) sum+=mark arr.append(mark)avg=sum/5.0print(""Average of five tests marks is: "",avg)"
2945,Python Program to Find All Nodes Reachable from a Node using DFS in a Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def find_all_reachable_nodes(v):
""""""Return set containing all vertices reachable from vertex.""""""
reachable = set()
find_all_reachable_nodes_helper(v, reachable)
return reachable
def find_all_reachable_nodes_helper(v, visited):
""""""Add all vertices visited by DFS traversal starting at v to the set visited.""""""
visited.add(v)
for dest in v.get_neighbours():
if dest not in visited:
find_all_reachable_nodes_helper(dest, visited)
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('reachable ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'reachable':
key = int(do[1])
vertex = g.get_vertex(key)
reachable = find_all_reachable_nodes(vertex)
print('All nodes reachable from {}:'.format(key),
[v.get_key() for v in reachable])
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2946,"Program to print series 0,6,10,17,22,30,36...N","
print(""Enter the range of number(Limit):"")
n=int(input())
i=1
a=0
b=6
k=10
p=11
while(i<=n):
if (i % 2 == 0):
print(b,end="" "")
b += p
p += 2
else:
print(a,end="" "")
a += k
k += 2
i+=1"
2947,Program to print square pattern of numbers,"
print(""Enter the row and column size:"");
row_size=int(input())
for out in range(1,row_size+1):
for i in range(1,row_size+1):
print(i,end="""")
print(""\r"")
"
2948,Program to display a lower triangular matrix,"# 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()])
#Display Lower triangular matrix
print(""Lower Triangular Matrix is:\n"")
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i')
print('add edge ')
print('dfs ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'dfs':
key = int(do[1])
print('Depth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_dfs(vertex)
print()
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2950,"
Please generate a random float where the value is between 5 and 95 using Python math module.
:","
import random
print random.random()*100-5
"
2951,Python Program to Check whether a Singly Linked List is a Palindrome,"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 get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def is_palindrome(llist):
start = llist.head
end = llist.last_node
while (start != end and end.next != start):
if start.data != end.data:
return False
start = start.next
end = llist.get_prev_node(end)
return True
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))
if is_palindrome(a_llist):
print('The linked list is palindromic.')
else:
print('The linked list is not palindromic.')"
2952,Program to find sum of series 1+4+9+16+25+.....+N,"
import math
print(""Enter the range of number(Limit):"")
n=int(input())
i=1
while(i<=n):
sum += pow(i, 2)
i+=1
print(""The sum of the series = "",sum)"
2953,Program to Find the sum of series 9+99+999.....+N,"n=int(input(""Enter the range of number:""))sum=0p=9for i in range(1,n+1): sum += p p=(p*10)+9print(""The sum of the series = "",sum)"
2954,Python Program to Read Two Numbers and Print Their Quotient and Remainder,"
a=int(input(""Enter the first number: ""))
b=int(input(""Enter the second number: ""))
quotient=a//b
remainder=a%b
print(""Quotient is:"",quotient)
print(""Remainder is:"",remainder)"
2955,Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + ….. + 1/N,"n=int(input(""Enter the number of terms: ""))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print(""The sum of series is"",round(sum1,2))"
2956, Program to print the Solid Inverted Half Diamond Number Pattern,"row_size=int(input(""Enter the row size:""))for out in range(row_size,-(row_size+1),-1): for in1 in range(1,abs(out)+1): print("" "",end="""") for p in range(abs(out),row_size+1): print(p,end="""") print(""\r"")"
2957,Remove duplicate characters from a given string,"str=input(""Enter Your String:"")arr=[0]*256for i in range(len(str)): if str[i]!=' ': num=ord(str[i]) arr[num]+=1print(""After Removing Duplicate character from a given string is:"")for i in range(len(str)): if str[i]!=' ': if arr[ord(str[i])] !=0: print(str[i],end="""") arr[ord(str[i])]=0 else: print(str[i], end="""")"
2958,Find lexicographic rank of a given string,"def Find_Factorial(len1): fact = 1 for i in range(1, len1+1): fact = fact * i return factdef Find_Lexicographic_Rank(str,len1): rank = 1 for inn in range(0, len1): count=0 for out in range(inn+1, len1+1): if str[inn] > str[out]: count+=1 rank+=count*Find_Factorial(len1-inn) return rankstr=input(""Enter Your String:"")print(""Lexicographic Rank of given String is: "",Find_Lexicographic_Rank(str,len(str)-1))"
2959,Python Program to Count the Number of Occurrences of an Element in the Linked List without using Recursion,"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 count(self, key):
current = self.head
count = 0
while current:
if current.data == key:
count = count + 1
current = current.next
return count
a_llist = LinkedList()
for data in [5, 1, 3, 5, 5, 15, 4, 9, 2]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()
key = int(input('Enter data item: '))
count = a_llist.count(key)
print('{0} occurs {1} time(s) in the list.'.format(key, count))"
2960,Find out all Automorphic numbers present within a given range,"
'''Write a Python
program to find out all Automorphic numbers present within a given
range. or Write a program to find out all Automorphic numbers
present within a given range using Python '''
print(""Enter a range:"")
range1=int(input())
range2=int(input())
print(""Perfect numbers between "",range1,"" and "",range2,"" are: "")
for i in range(range1,range2+1):
num=i
sqr=num*num
flag=0
while num!=0:
if(num%10 != sqr%10):
flag=-1
break
num=int(num/10)
sqr=int(sqr/10)
if(flag==0):
print(i,end="" "")
"
2961,Program to display a lower triangular matrix,"# 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()])
#Display Lower triangular matrix
print(""Lower Triangular Matrix is:\n"")
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i= '0' and str[inn] <= '9': count+=1if count==len(str): print(""String contains only digits."")else: print(""String does not contain only digits."")"
2963,Program to Calculate the surface area and volume of a Cone,"
import math
PI=3.14
r=int(input(""Enter the radius of the cone:""))
h=int(input(""Enter the height of the cone:""))
surface_area=(PI*r)*(r+math.sqrt(math.pow(h,2)+math.pow(r,2)))
volume=PI*math.pow(r,2)*(h/3.0)
print(""Surface Area of the cone= "",surface_area)
print(""Volume of the cone = "",volume)
"
2964,"
Define a custom exception class which takes a string message as attribute.
:","
class MyError(Exception):
""""""My own exception class
Attributes:
msg -- explanation of the error
""""""
def __init__(self, msg):
self.msg = msg
error = MyError(""something wrong"")
"
2965,Python Program to Replace all Occurrences of ‘a’ with $ in a String,"string=input(""Enter string:"")
string=string.replace('a','$')
string=string.replace('A','$')
print(""Modified string:"")
print(string)"
2966,Find the LCM of two numbers using recursion,"def gcd(num1,num2): if num2==0: return num1 else: return gcd(num2,num1%num2)def lcm(num1,num2): return (num1 * num2) // gcd(num1, num2)print(""Enter the two Number:"")num1=int(input())num2=int(input())print(""Lcm of Given Numbers Using Recursion is:"",lcm(num1,num2))"
2967,Python Program to Remove the Duplicate Items from a List,"a=[]
n= int(input(""Enter the number of elements in list:""))
for x in range(0,n):
element=int(input(""Enter element"" + str(x+1) + "":""))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print(""Non-duplicate items:"")
print(unique)"
2968,Check if given number is palindrome using recursion,"rev = 0def Num_reverse(num): global rev if num!=0: rem=num%10 rev=(rev*10)+rem Num_reverse(num//10) return revnum=int(input(""Enter your Number:""))if(Num_reverse(num)==num): print(num,"" is a Palindrome Number."")else: print(num,"" is not a Palindrome Number."")"
2969,Move all zeros to the Start of an Array,"arr=[]size = int(input(""Enter the size of the array: ""))print(""Enter the Element of the array:"")for i in range(0,size): num = int(input()) arr.append(num)c=size-1for i in range(size-1,-1,-1): if arr[i]!=0: arr[c]=arr[i] c-=1for i in range(c,-1,-1): arr[c]=0 c-=1print(""After Move all zeros to Start, Array is:"")print(arr)"
2970,"
Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
:","
import random
print random.sample(range(100), 5)
"
2971,Count how many consonants present in a String,"
str=input(""Enter the String:"")
count=0
for i in range(len(str)):
if str[i] == 'a' or str[i] == 'A' or str[i] == 'e' or str[i] == 'E' or str[i] == 'i'or str[i] == 'I' or str[i] == 'o' or str[i] == 'O' or str[i] == 'u' or str[i] == 'U' or str[i]==' ':
continue
else:
count+=1
if count==0:
print(""No consonants are present in the string."")
else:
print(""Numbers of consonants present in the string are "",count)"
2972,Python Program to Print DFS Numbering of a Graph,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def dfs(v, pre, post):
""""""Display DFS traversal starting at vertex v. Stores pre and post times in
dictionaries pre and post.""""""
dfs_helper(v, set(), pre, post, [0])
def dfs_helper(v, visited, pre, post, time):
""""""Display DFS traversal starting at vertex v. Uses set visited to keep
track of already visited nodes, dictionaries pre and post to store
discovered and finished times and the one-element list time to keep track of
current time.""""""
visited.add(v)
time[0] = time[0] + 1
pre[v] = time[0]
print('Visiting {}... discovered time = {}'.format(v.get_key(), time[0]))
for dest in v.get_neighbours():
if dest not in visited:
dfs_helper(dest, visited, pre, post, time)
time[0] = time[0] + 1
post[v] = time[0]
print('Leaving {}... finished time = {}'.format(v.get_key(), time[0]))
g = Graph()
print('Menu')
print('add vertex ')
print('add edge ')
print('dfs ')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'dfs':
key = int(do[1])
print('Depth-first Traversal: ')
vertex = g.get_vertex(key)
pre = dict()
post = dict()
dfs(vertex, pre, post)
print()
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break"
2973,Linear search Program using recursion ,"temp=0def Linear_search(arr,Search_ele,n): global temp if(n>0): i=n-1 if(arr[i]==Search_ele): temp=1 Linear_search(arr, Search_ele, i) return temparr=[]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)Search_ele=int(input(""Enter the search element:""))if(Linear_search(arr,Search_ele,n)==1): print(""Element found...."")else: print(""Element not found...."")"
2974,Python Program to Implement Dijkstra’s Shortest Path Algorithm,"class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def add_vertex(self, key):
""""""Add a vertex with the given key to the graph.""""""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
""""""Return vertex object with the corresponding key.""""""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
""""""Add edge from src_key to dest_key with given weight.""""""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
""""""Return True if there is an edge from src_key to dest_key.""""""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
""""""Return key corresponding to this vertex object.""""""
return self.key
def add_neighbour(self, dest, weight):
""""""Make this vertex point to dest with given edge weight.""""""
self.points_to[dest] = weight
def get_neighbours(self):
""""""Return all vertices pointed to by this vertex.""""""
return self.points_to.keys()
def get_weight(self, dest):
""""""Get weight of edge from this vertex to dest.""""""
return self.points_to[dest]
def does_it_point_to(self, dest):
""""""Return True if this vertex points to dest.""""""
return dest in self.points_to
def dijkstra(g, source):
""""""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
g is a Graph object.
source is a Vertex object in g.
""""""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
while unvisited != set():
# find vertex with minimum distance
closest = min(unvisited, key=lambda v: distance[v])
# mark as visited
unvisited.remove(closest)
# update distances
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance
return distance
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex ')
print('add edge ')
print('shortest