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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

Lacie Tillie """""" 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

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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" soup = BeautifulSoup(html_doc, 'html.parser') print(""href of the first tag:"") print(soup.find('a').attrs['href']) " 238,Write a Python program to convert an integer to binary keep leading zeros. ,"x = 12 print(format(x, '08b')) print(format(x, '010b')) " 239,Write a Python program to reverse strings in a given list of string values using lambda. ,"def reverse_strings_list(string_list): result = list(map(lambda x: """".join(reversed(x)), 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)) " 240,Write a NumPy program to count the frequency of unique values in NumPy array. ,"import numpy as np a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] ) print(""Original array:"") print(a) unique_elements, counts_elements = np.unique(a, return_counts=True) print(""Frequency of unique values of the said array:"") print(np.asarray((unique_elements, counts_elements))) " 241,"Write a NumPy program to calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to a given array. ","import numpy as np x = np.array([1, 3, 5, 7, 0]) print(""Original array: "") print(x) r1 = np.ediff1d(x, to_begin=[0, 0], to_end=[200]) r2 = np.insert(np.append(np.diff(x), 200), 0, [0, 0]) assert np.array_equiv(r1, r2) print(""Difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to the said array:"") print(r2) " 242,Write a Python program to calculate the area of the sector. ,"def sectorarea(): pi=22/7 radius = float(input('Radius of Circle: ')) angle = float(input('angle measure: ')) if angle >= 360: print(""Angle is not possible"") return sur_area = (pi*radius**2) * (angle/360) print(""Sector Area: "", sur_area) sectorarea() " 243,"Write a NumPy program to print the full NumPy array, without truncation. ","import numpy as np import sys nums = np.arange(2000) np.set_printoptions(threshold=sys.maxsize) print(nums) " 244,Write a Python program to extract all the text 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(""Text from the said page:"") print(soup.get_text()) " 245,Write a Python program to convert given a dictionary to a list of tuples. ,"def test(d): return list(d.items()) d = {'Red': 1, 'Green': 3, 'White': 5, 'Black': 2, 'Pink': 4} print(""Original Dictionary:"") print(d) print(""\nConvert the said dictionary to a list of tuples:"") print(test(d)) " 246,Write a Pandas program to select rows by filtering on one or more column(s) in a multi-index 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], 'tcode': ['t1', 't2', 't3', 't4', 't5', 't6']}) print(""Original DataFrame:"") print(df) print(""\nCreate MultiIndex on 'tcode' and 'school_code':"") df = df.set_index(['tcode', 'school_code']) print(df) print(""\nSelect rows(s) from 'tcode' column:"") print(df.query(""tcode == 't2'"")) print(""\nSelect rows(s) from 'school_code' column:"") print(df.query(""school_code == 's001'"")) print(""\nSelect rows(s) from 'tcode' and 'scode' columns:"") print(df.query((""tcode == 't1'"") and (""school_code == 's001'""))) " 247,Write a Python program to find smallest and largest word in a given string. ,"def smallest_largest_words(str1): word = """"; all_words = []; str1 = str1 + "" ""; for i in range(0, len(str1)): if(str1[i] != ' '): word = word + str1[i]; else: all_words.append(word); word = """"; small = large = all_words[0]; #Find smallest and largest word in the str1 for k in range(0, len(all_words)): if(len(small) > len(all_words[k])): small = all_words[k]; if(len(large) < len(all_words[k])): large = all_words[k]; return small,large; str1 = ""Write a Java program to sort an array of given integers using Quick sort Algorithm.""; print(""Original Strings:\n"",str1) small, large = smallest_largest_words(str1) print(""Smallest word: "" + small); print(""Largest word: "" + large); " 248,Write a Python program to find the length of a given dictionary values. ,"def test(dictt): result = {} for val in dictt.values(): result[val] = len(val) return result color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'} print(""\nOriginal Dictionary:"") print(color_dict) print(""Length of dictionary values:"") 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(""Length of dictionary values:"") print(test(color_dict)) " 249,"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) " 250,Write a Pandas program to extract words starting with capital 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 Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.', '17 West Livingston Court'] }) print(""Original DataFrame:"") print(df) def find_capital_word(str1): result = re.findall(r'\b[A-Z]\w+', str1) return result df['caps_word_in']=df['address'].apply(lambda cw : find_capital_word(cw)) print(""\nExtract words starting with capital words from the sentences':"") print(df) " 251,Write a Python program to join one or more path components together and split a given path in directory and file. ,"import os path = r'g:\\testpath\\a.txt' print(""Original path:"") print(path) print(""\nDir and file name of the said path:"") print(os.path.split(path)) print(""\nJoin one or more path components together:"") print(os.path.join(r'g:\\testpath\\','a.txt')) " 252,"Write a Python program to randomize the order of the values of an list, returning a new list. ","from copy import deepcopy from random import randint def shuffle_list(lst): temp_lst = deepcopy(lst) m = len(temp_lst) while (m): m -= 1 i = randint(0, m) temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst nums = [1, 2, 3, 4, 5, 6] print(""Original list: "",nums) print(""\nShuffle the elements of the said list:"") print(shuffle_list(nums)) " 253,Write a Python program to count the same pair in three given lists. ,"def count_same_pair(nums1, nums2, nums3): result = sum(m == n == o for m, n, o in zip(nums1, nums2, nums3)) return result nums1 = [1,2,3,4,5,6,7,8] nums2 = [2,2,3,1,2,6,7,9] nums3 = [2,1,3,1,2,6,7,9] print(""Original lists:"") print(nums1) print(nums2) print(nums3) print(""\nNumber of same pair of the said three given lists:"") print(count_same_pair(nums1, nums2, nums3)) " 254,Write a Pandas program to create a Pivot table with multiple indexes from the data set of titanic.csv. ,"import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = pd.pivot_table(df, index = [""sex"",""age""], aggfunc=np.sum) print(result) " 255,Write a Python program to get the volume of a sphere with radius 6.," pi = 3.1415926535897931 r= 6.0 V= 4.0/3.0*pi* r**3 print('The volume of the sphere is: ',V) " 256,"Write a Python program to traverse a given list in reverse order, also print the elements with original index. ","color = [""red"", ""green"", ""white"", ""black""] print(""Original list:"") print(color) print(""\nTraverse the said list in reverse order:"") for i in reversed(color): print(i) print(""\nTraverse the said list in reverse order with original index:"") for i, el in reversed(list(enumerate(color))): print(i, el) " 257,"Write a NumPy program to create an array of zeros and three column types (integer, float, character). ","import numpy as np x = np.zeros((3,), dtype=('i4,f4,a40')) new_data = [(1, 2., ""Albert Einstein""), (2, 2., ""Edmond Halley""), (3, 3., ""Gertrude B. Elion"")] x[:] = new_data print(x) " 258,Write a NumPy program to stack 1-D arrays as row wise. ,"import numpy as np print(""\nOriginal arrays:"") x = np.array((1,2,3)) y = np.array((2,3,4)) print(""Array-1"") print(x) print(""Array-2"") print(y) new_array = np.row_stack((x, y)) print(""\nStack 1-D arrays as rows wise:"") print(new_array) " 259,Write a Pandas program to add 100 days with reporting date of unidentified flying object (UFO). ,"import pandas as pd from datetime import timedelta df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print(""Original Dataframe:"") print(df.head()) print(""\nAdd 100 days with reporting date:"") df['New_doc_dt'] = df['Date_time'] + timedelta(days=180) print(df) " 260,Write a NumPy program to compute numerical negative value for all elements in a given array. ,"import numpy as np x = np.array([0, 1, -1]) print(""Original array: "") print(x) r1 = np.negative(x) r2 = -x assert np.array_equal(r1, r2) print(""Numerical negative value for all elements of the said array:"") print(r1) " 261,Write a Python program to sort each sublist of strings in a given list of lists using lambda. ,"def sort_sublists(input_list): result = [sorted(x, key = lambda x:x[0]) for x in 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)) " 262,Write a Python program to generate the combinations of n distinct objects taken from the elements of a given list. ,"def combination(n, n_list): if n<=0: yield [] return for i in range(len(n_list)): c_num = n_list[i:i+1] for a_num in combination(n-1, n_list[i+1:]): yield c_num + a_num n_list = [1,2,3,4,5,6,7,8,9] print(""Original list:"") print(n_list) n = 2 result = combination(n, n_list) print(""\nCombinations of"",n,""distinct objects:"") for e in result: print(e) " 263,Write a Python program to find all index positions of the maximum and minimum values in a given list of numbers. ,"def position_max_min(nums): max_val = max(nums) min_val = min(nums) max_result = [i for i, j in enumerate(nums) if j == max_val] min_result = [i for i, j in enumerate(nums) if j == min_val] return max_result,min_result nums = [12,33,23,10,67,89,45,667,23,12,11,10,54] print(""Original list:"") print(nums) result = position_max_min(nums) print(""\nIndex positions of the maximum value of the said list:"") print(result[0]) print(""\nIndex positions of the minimum value of the said list:"") print(result[1]) " 264,Write a NumPy program to get the powers of an array values element-wise. ,"import numpy as np x = np.arange(7) print(""Original array"") print(x) print(""First array elements raised to powers from second array, element-wise:"") print(np.power(x, 3)) " 265,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) " 266,Write a NumPy program to create display every element of a NumPy array. ,"import numpy as np x = np.arange(12).reshape(3, 4) for x in np.nditer(x): print(x,end=' ') print() " 267,Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees where hire_date> 01-01-07. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') df[df['hire_date'] >='20070101'] " 268,Write a NumPy program to create a 2d array with 1 on the border and 0 inside. ,"import numpy as np x = np.ones((5,5)) print(""Original array:"") print(x) print(""1 on the border and 0 inside in the array"") x[1:-1,1:-1] = 0 print(x) " 269,Write a NumPy program to get the n largest values of an array. ,"import numpy as np x = np.arange(10) print(""Original array:"") print(x) np.random.shuffle(x) n = 1 print (x[np.argsort(x)[-n:]]) " 270,Write a Python program to find numbers within a given range where every number is divisible by every digit it contains. ,"def divisible_by_digits(start_num, end_num): return [n for n in range(start_num, end_num+1) \ if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))] print(divisible_by_digits(1,22)) " 271,Write a Python program to extract h1 tag from example.com. ,"from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://en.wikipedia.org/wiki/Main_Page') bs = BeautifulSoup(html, ""html.parser"") titles = bs.find_all(['h1', 'h2','h3','h4','h5','h6']) print('List all the header tags :', *titles, sep='\n\n') " 272,Write a Python program to remove a specified item using the index from an array. ,"from array import * array_num = array('i', [1, 3, 5, 7, 9]) print(""Original array: ""+str(array_num)) print(""Remove the third item form the array:"") array_num.pop(2) print(""New array: ""+str(array_num)) " 273,Write a Python program to sort a given list of lists by length and value using lambda. ,"def sort_sublists(input_list): result = sorted(input_list, key=lambda l: (len(l), l)) return result 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)) " 274,Write a Python program to find the index position of the largest value smaller than a given number in a sorted list using Binary Search (bisect). ,"from bisect import bisect_left def Binary_Search(l, x): i = bisect_left(l, x) if i: return (i-1) else: return -1 nums = [1, 2, 3, 4, 8, 8, 10, 12] x = 5 num_position = Binary_Search(nums, x) if num_position == -1: print(""Not found..!"") else: print(""Largest value smaller than "", x, "" is at index "", num_position ) " 275,Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed. ,"import numpy as np result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) print(""\nCopy of a matrix with the elements below the k-th diagonal zeroed:"") print(result) " 276,"Write a Python program which iterates the integers from 1 to 50. For multiples of three print ""Fizz"" instead of the number and for the multiples of five print ""Buzz"". For numbers which are multiples of both three and five print ""FizzBuzz"".","for fizzbuzz in range(51): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print(""fizzbuzz"") continue elif fizzbuzz % 3 == 0: print(""fizz"") continue elif fizzbuzz % 5 == 0: print(""buzz"") continue print(fizzbuzz) " 277,"Write a Python program to get a list with n elements removed from the left, right. ","def drop_left_right(a, n = 1): return a[n:], a[:-n] nums = [1, 2, 3] print(""Original list elements:"") print(nums) result = drop_left_right(nums) print(""Remove 1 element from left of the said list:"") print(result[0]) print(""Remove 1 element from right of the said list:"") print(result[1]) nums = [1, 2, 3, 4] print(""\nOriginal list elements:"") print(nums) result = drop_left_right(nums,2) print(""Remove 2 elements from left of the said list:"") print(result[0]) print(""Remove 2 elements from right of the said list:"") print(result[1]) nums = [1, 2, 3, 4, 5, 6] print(""\nOriginal list elements:"") print(nums) result = drop_left_right(nums) print(""Remove 7 elements from left of the said list:"") print(result[0]) print(""Remove 7 elements from right of the said list:"") print(result[1]) " 278,Write a Python program to list the tables of given SQLite database file. ,"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 two tables 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);"") cursorObj.execute(""CREATE TABLE temp_agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);"") print(""List of tables:"") cursorObj.execute(""SELECT name FROM sqlite_master WHERE type='table';"") print(cursorObj.fetchall()) conn.commit() sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print(""\nThe SQLite connection is closed."") " 279,"Write a Python program to split values into two groups, based on the result of the given filter list. ","def bifurcate(colors, filter): return [ [x for x, flag in zip(colors, filter) if flag], [x for x, flag in zip(colors, filter) if not flag] ] print(bifurcate(['red', 'green', 'blue', 'pink'], [True, True, False, True])) " 280,Write a Python program to store a given dictionary in a json file. ,"d = {""students"":[{""firstName"": ""Nikki"", ""lastName"": ""Roysden""}, {""firstName"": ""Mervin"", ""lastName"": ""Friedland""}, {""firstName"": ""Aron "", ""lastName"": ""Wilkins""}], ""teachers"":[{""firstName"": ""Amberly"", ""lastName"": ""Calico""}, {""firstName"": ""Regine"", ""lastName"": ""Agtarap""}]} print(""Original dictionary:"") print(d) print(type(d)) import json with open(""dictionary"", ""w"") as f: json.dump(d, f, indent = 4, sort_keys = True) print(""\nJson file to dictionary:"") with open('dictionary') as f: data = json.load(f) print(data) " 281,Write a Python program to add two objects if both objects are an integer type. ,"def add_numbers(a, b): if not (isinstance(a, int) and isinstance(b, int)): return ""Inputs must be integers!"" return a + b print(add_numbers(10, 20)) print(add_numbers(10, 20.23)) print(add_numbers('5', 6)) print(add_numbers('5', '6')) " 282,Write a Python program to count the number of items 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 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(""Number of items of the Doubly linked list:"",items.count) " 283,Write a Pandas program to combine the columns of two potentially differently-indexed DataFrames into a single result DataFrame. ,"import pandas as pd data1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K2']) data2 = pd.DataFrame({'C': ['C0', 'C2', 'C3'], 'D': ['D0', 'D2', 'D3']}, index=['K0', 'K2', 'K3']) print(""Original DataFrames:"") print(data1) print(""--------------------"") print(data2) print(""\nMerged Data (Joining on index):"") result = data1.join(data2) print(result) " 284,Write a Python program to count number of items in a dictionary value that is a list. ,"dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} ctr = sum(map(len, dict.values())) print(ctr) " 285,Write a Python program to find the elements of a given list of strings that contain specific substring using lambda. ,"def find_substring(str1, sub_str): result = list(filter(lambda x: sub_str in x, str1)) return result colors = [""red"", ""black"", ""white"", ""green"", ""orange""] print(""Original list:"") print(colors) sub_str = ""ack"" print(""\nSubstring to search:"") print(sub_str) print(""Elements of the said list that contain specific substring:"") print(find_substring(colors, sub_str)) sub_str = ""abc"" print(""\nSubstring to search:"") print(sub_str) print(""Elements of the said list that contain specific substring:"") print(find_substring(colors, sub_str)) " 286,Write a Pandas program to generate holidays between two dates using the US federal holiday calendar. ,"import pandas as pd from pandas.tseries.holiday import * sdt = datetime(2021, 1, 1) edt = datetime(2030, 12, 31) print(""Holidays between 2021-01-01 and 2030-12-31 using the US federal holiday calendar."") cal = USFederalHolidayCalendar() for dt in cal.holidays(start=sdt, end=edt): print (dt) " 287,Write a NumPy program to get all 2D diagonals of a 3D NumPy array. ,"import numpy as np np_array = np.arange(3*4*5).reshape(3,4,5) print(""Original Numpy array:"") print(np_array) print(""Type: "",type(np_array)) result = np.diagonal(np_array, axis1=1, axis2=2) print(""\n2D diagonals: "") print(result) print(""Type: "",type(result)) " 288,Write a Python program to solve the Fibonacci sequence using recursion. ,"def fibonacci(n): if n == 1 or n == 2: return 1 else: return (fibonacci(n - 1) + (fibonacci(n - 2))) print(fibonacci(7)) " 289,Write a NumPy program to access an array by column. ,"import numpy as np x= np.arange(9).reshape(3,3) print(""Original array elements:"") print(x) print(""Access an array by column:"") print(""First column:"") print(x[:,0]) print(""Second column:"") print(x[:,1]) print(""Third column:"") print(x[:,2]) " 290,Write a Python program to get the sum of a non-negative integer. ,"def sumDigits(n): if n == 0: return 0 else: return n % 10 + sumDigits(int(n / 10)) print(sumDigits(345)) print(sumDigits(45)) " 291,Write a NumPy program to create and display every element of a NumPy array in Fortran order. ,"import numpy as np x = np.arange(12).reshape(3, 4) print(""Elements of the array in Fortan array:"") for x in np.nditer(x, order=""F""): print(x,end=' ') print(""\n"") " 292,Write a Python program to check whether a specified list is sorted or not. ,"def is_sort_list(nums): result = all(nums[i] <= nums[i+1] for i in range(len(nums)-1)) return result nums1 = [1,2,4,6,8,10,12,14,16,17] print (""Original list:"") print(nums1) print(""\nIs the said list is sorted!"") print(is_sort_list(nums1)) nums2 = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2] print (""\nOriginal list:"") print(nums1) print(""\nIs the said list is sorted!"") print(is_sort_list(nums2)) " 293,Write a NumPy program to create a 3x3 identity matrix. ,"import numpy as np array_2D=np.identity(3) print('3x3 matrix:') print(array_2D) " 294,"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')) " 295,Write a Python program to remove the first occurrence of a specified element from an array. ,"from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) print(""Original array: ""+str(array_num)) print(""Remove the first occurrence of 3 from the said array:"") array_num.remove(3) print(""New array: ""+str(array_num)) " 296,Write a Pandas program to extract word mention someone in tweets using @ 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_at_word(text): word=re.findall(r'(?<[email protected])\w+',text) return "" "".join(word) df['at_word']=df['tweets'].apply(lambda x: find_at_word(x)) print(""\Extracting @word from dataframe columns:"") print(df) " 297,Write a Python program to calculate the sum of the positive and negative numbers of a given list of numbers using lambda function. ,"nums = [2, 4, -6, -9, 11, -12, 14, -5, 17] print(""Original list:"",nums) total_negative_nums = list(filter(lambda nums:nums<0,nums)) total_positive_nums = list(filter(lambda nums:nums>0,nums)) print(""Sum of the positive numbers: "",sum(total_negative_nums)) print(""Sum of the negative numbers: "",sum(total_positive_nums)) " 298,"Write a Pandas program to split the following dataframe into groups, group by month and year based on order date and find the total purchase amount year wise, month wise. ","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-2013','08-17-2013','10-09-2013','07-27-2014','10-09-2012','10-10-2012','10-10-2012','06-17-2014','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(""\nYear wise Month wise purchase amount:"") result = df.groupby([df['ord_date'].dt.year, df['ord_date'].dt.month]).agg({'purch_amt':sum}) print(result) " 299,Write a Python code to create a program for Bitonic Sort. ,"#License: https://bit.ly/2InTS3W # 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 = int(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 funcion 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 = int(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 = [] print(""How many numbers u want to enter?""); n = int(input()) print(""Input the numbers:""); for i in range(n): a.append(int(input())) up = 1 sort(a, n, up) print(""\n\nSorted array is:"") for i in range(n): print(""%d"" % a[i]) " 300,Write a Python program to get the cumulative sum of the elements of a given list. ,"from itertools import accumulate def cumsum(lst): return list(accumulate(lst)) nums = [1,2,3,4] print(""Original list elements:"") print(nums) print(""Cumulative sum of the elements of the said list:"") print(cumsum(nums)) nums = [-1,-2,-3,4] print(""\nOriginal list elements:"") print(nums) print(""Cumulative sum of the elements of the said list:"") print(cumsum(nums)) " 301,Write a NumPy program to create an array which looks like below array. ,"import numpy as np x = np.tri(4, 3, -1) print(x) " 302,Write a Python program to extract common index elements from more than one given list. ,"def extract_index_ele(l1, l2, l3): result = [] for m, n, o in zip(l1, l2, l3): if (m == n == o): result.append(m) return result nums1 = [1, 1, 3, 4, 5, 6, 7] nums2 = [0, 1, 2, 3, 4, 5, 7] nums3 = [0, 1, 2, 3, 4, 5, 7] print(""Original lists:"") print(nums1) print(nums2) print(nums3) print(""\nCommon index elements of the said lists:"") print(extract_index_ele(nums1, nums2, nums3)) " 303,Write a Pandas program to check if a specified value exists in single and multiple column index 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 = ['t1', 't2', 't3', 't4', 't5', 't6']) print(""Original DataFrame with single index:"") print(df) print(""\nCheck a value is exist in single column index dataframe:"") print('t1' in df.index) print('t11' in df.index) print(""\nCreate MultiIndex using columns 't_id', ‘school_code’ and 'class':"") 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], 't_id': ['t1', 't2', 't3', 't4', 't5', 't6']}) df1 = df.set_index(['t_id', 'school_code', 'class']) print(df1) print(""\nCheck a value is exist in multiple columns index dataframe:"") print('t4' in df1.index.levels[0]) print('t4' in df1.index.levels[1]) print('t4' in df1.index.levels[2]) " 304,Write a Python program to count the elements in a list until an element is a tuple. ,"num = [10,20,30,(10,20),40] ctr = 0 for n in num: if isinstance(n, tuple): break ctr += 1 print(ctr) " 305,"Write a Pandas program to create a stacked 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']] plt.figure(figsize=(25,25)) df2.plot.hist(stacked=True, bins=20) 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() " 306,Write a Python program to add a number to each element in a given list of numbers. ,"def add_val_to_list(lst, add_val): result = lst result = [x+add_val for x in result] return result nums = [3,8,9,4,5,0,5,0,3] print(""Original lists:"") print(nums) add_val = 3 print(""\nAdd"",add_val,""to each element in the said list:"") print(add_val_to_list(nums, add_val)) nums = [3.2,8,9.9,4.2,5,0.1,5,3.11,0] print(""\nOriginal lists:"") print(nums) add_val = .51 print(""\nAdd"",add_val,""to each element in the said list:"") print(add_val_to_list(nums, add_val)) " 307,Write a Python program to create a multidimensional list (lists of lists) with zeros. ,"nums = [] for i in range(3): nums.append([]) for j in range(2): nums[i].append(0) print(""Multidimensional list:"") print(nums) " 308,Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series. ,"import pandas as pd import numpy as np num_series = pd.Series(np.random.randint(1, 10, 9)) print(""Original Series:"") print(num_series) result = np.argwhere(num_series % 5==0) print(""Positions of numbers that are multiples of 5:"") print(result) " 309,Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2. ,"def substring_copy(str, n): flen = 2 if flen > len(str): flen = len(str) substr = str[:flen] result = """" for i in range(n): result = result + substr return result print(substring_copy('abcdef', 2)) print(substring_copy('p', 3)); " 310,"Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice). ","import numpy as np nums = np.array([70, 50, 20, 30, -11, 60, 50, 40]) print(""Original array:"") print(nums) print(""\nAfter partitioning on 4 the position:"") print(np.partition(nums, 4)) " 311,"Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise, sales man wise where Manager = ""Douglas"". ","import pandas as pd df = pd.read_excel('E:\SaleData.xlsx') table = pd.pivot_table(df,index=[""Region"",""Manager"",""SalesMan""], values=""Sale_amt"") print(table.query('Manager == [""Douglas""]')) " 312,Write a Python program to check whether a specified list is sorted or not using lambda. ,"def is_sort_list(nums, key=lambda x: x): for i, e in enumerate(nums[1:]): if key(e) < key(nums[i]): return False return True nums1 = [1,2,4,6,8,10,12,14,16,17] print (""Original list:"") print(nums1) print(""\nIs the said list is sorted!"") print(is_sort_list(nums1)) nums2 = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2] print (""\nOriginal list:"") print(nums1) print(""\nIs the said list is sorted!"") print(is_sort_list(nums2)) " 313,Write a Python program to rotate a Deque Object specified number (positive) of times. ,"import collections # declare an empty deque object dq_object = collections.deque() # Add elements to the deque - left to right dq_object.append(2) dq_object.append(4) dq_object.append(6) dq_object.append(8) dq_object.append(10) print(""Deque before rotation:"") print(dq_object) # Rotate once in positive direction dq_object.rotate() print(""\nDeque after 1 positive rotation:"") print(dq_object) # Rotate twice in positive direction dq_object.rotate(2) print(""\nDeque after 2 positive rotations:"") print(dq_object) " 314,"Write a Python code to send a request to a web page and stop waiting for a response after a given number of seconds. In the event of times out of request, raise Timeout exception. ","import requests print(""timeout = 0.001"") try: r = requests.get('https://github.com/', timeout = 0.001) print(r.text) except requests.exceptions.RequestException as e: print(e) print(""\ntimeout = 1.0"") try: r = requests.get('https://github.com/', timeout = 1.0) print(""Connected....!"") except requests.exceptions.RequestException as e: print(e) " 315,Write a Python program to create a doubly linked list and print nodes from current position to first node. ,"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 print_backward(self): current = self.tail while current: print(current.data) current = current.prev 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(""Print Items in the Doubly linked backwards:"") items.print_backward() " 316,Write a Pandas program to convert a specified character column in title case 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(""\nTitle cases:"") df['company_code_title_cases'] = list(map(lambda x: x.title(), df['company_code'])) print(df) " 317,Write a Pandas program to convert given series into a dataframe with its index as another column on the dataframe. ,"import numpy as np import pandas as pd char_list = list('ABCDEFGHIJKLMNOP') num_arra = np.arange(8) num_dict = dict(zip(char_list, num_arra)) num_ser = pd.Series(num_dict) df = num_ser.to_frame().reset_index() print(df.head()) " 318,Write a NumPy program to make all the elements of a given string to a numeric string of 5 digits with zeros on its left. ,"import numpy as np x = np.array(['2', '11', '234', '1234', '12345'], dtype=np.str) print(""\nOriginal Array:"") print(x) r = np.char.zfill(x, 5) print(""\nNumeric string of 5 digits with zeros:"") print(r) " 319,Write a Python program to create a list with the unique values filtered out. ,"from collections import Counter def filter_unique(lst): return [item for item, count in Counter(lst).items() if count > 1] print(filter_unique([1, 2, 2, 3, 4, 4, 5])) " 320,Write a Python program to set a random seed and get a random number between 0 and 1. Use random.random. ,"import random print(""Set a random seed and get a random number between 0 and 1:"") random.seed(0) new_random_value = random.random() print(new_random_value) random.seed(1) new_random_value = random.random() print(new_random_value) random.seed(2) new_random_value = random.random() print(new_random_value) " 321,"Create an array (a) of shape 3, 4, 8 (K=3, J=4, I=8). tidx is an array of the same length as a.shape[1], i.e. contains J = 4 elements where each index denotes which element of K should be chosen.","import numpy as np a = np.random.randint(0, 10, (3, 4, 8)) print(""Original array and shape:"") print(a) print(a.shape) print(""--------------------------------"") tidx = np.random.randint(0, 3, 4) print(""tidex: "",tidx) print(""Result:"") print(a[tidx, np.arange(len(tidx)),:]) " 322,"Write a Pandas program to split a given dataset, group by one column and apply an aggregate function to few columns and another aggregate function to the rest of the columns of the dataframe. ","import pandas as pd pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001], '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], 'sale_feb':[250.5, 170.65, 15.26, 110.5, 598.5, 1400.6, 2760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_mar':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_apr':[150.5, 270.65, 95.26, 210.5, 948.5, 2400.6, 760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_may':[130.5, 270.65, 65.26, 310.5, 948.5, 2400.6, 760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_jun':[150.5, 270.65, 45.26, 110.5, 948.5, 3400.6, 5760, 983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_jul':[950.5, 270.65, 65.26, 210.5, 948.5, 2400.6, 5760, 983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_aug':[150.5, 70.65, 65.26, 110.5, 948.5, 400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_sep':[150.5, 270.65, 65.26, 110.5, 948.5, 200.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_oct':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_nov':[150.5, 270.65, 95.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'sale_dec':[150.5, 70.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6] }) print(""Original Orders DataFrame:"") print(df) print(""\Result after group on salesman_id and apply different aggregate functions:"") df = df.groupby('salesman_id').agg(lambda x : x.sum() if x.name in ['sale_jan','sale_feb','sale_mar'] else x.mean()) print(df) " 323,Write a NumPy program (using NumPy) to sum of all the multiples of 3 or 5 below 100. ,"import numpy as np x = np.arange(1, 100) # find multiple of 3 or 5 n= x[(x % 3 == 0) | (x % 5 == 0)] print(n[:1000]) # print sum the numbers print(n.sum()) " 324,"Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and find details where ""Labor Hours"" > 20000. ","import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df[df[""Labor_Hours""] > 20000].head() " 325,Write a Python program to iterate a given list cyclically on specific index position. ,"def cyclically_iteration(lst,spec_index): result = [] length = len(lst) for i in range(length): element_index = spec_index % length result.append(lst[element_index]) spec_index += 1 return result chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] print(""Original list:"") print(chars) spec_index = 3 print(""\nIterate the said list cyclically on specific index position"",spec_index,"":"") print(cyclically_iteration(chars,spec_index)) spec_index = 5 print(""\nIterate the said list cyclically on specific index position"",spec_index,"":"") print(cyclically_iteration(chars,spec_index)) " 326,Write a Pandas program to interpolate the missing values using the Linear Interpolation method 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(""\nInterpolate the missing values using the Linear Interpolation method (purch_amt):"") df['purch_amt'].interpolate(method='linear', direction = 'forward', inplace=True) print(df) " 327,Write a Python program to read a random line from a file. ,"import random def random_line(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(random_line('test.txt')) " 328,Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder. ,"area = 1256.66 volume = 1254.725 decimals = 2 print(""The area of the rectangle is {0:.{1}f}cm\u00b2"".format(area, decimals)) decimals = 3 print(""The volume of the cylinder is {0:.{1}f}cm\u00b3"".format(volume, decimals)) " 329,Write a NumPy program compare two given arrays. ,"import numpy as np a = np.array([1, 2]) b = np.array([4, 5]) print(""Array a: "",a) print(""Array b: "",b) print(""a > b"") print(np.greater(a, b)) print(""a >= b"") print(np.greater_equal(a, b)) print(""a < b"") print(np.less(a, b)) print(""a <= b"") print(np.less_equal(a, b)) " 330,Write a Pandas program to split the following given dataframe into groups based on school code and call a specific group with the name of the group. ,"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 = student_data.groupby(['school_code']) print(""Call school code 's001':"") print(grouped.get_group('s001')) print(""\nCall school code 's004':"") print(grouped.get_group('s004')) " 331,Write a Python program to compute the sum of digits of each number of a given list of positive integers. ,"from itertools import chain def sum_of_digits(nums): return sum(int(y) for y in (chain(*[str(x) for x in nums]))) 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,70] print(""\nOriginal tuple: "") print(nums) print(""Sum of digits of each number of the said list of integers:"") print(sum_of_digits(nums)) " 332,Write a Python program to assess if a file is closed or not. ," f = open('abc.txt','r') print(f.closed) f.close() print(f.closed) " 333,Write a Python program to interleave two given list into another list randomly. ,"import random def randomly_interleave(nums1, nums2): result = [x.pop(0) for x in random.sample([nums1]*len(nums1) + [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)) " 334,"Given variables x=30 and y=20, write a Python program to print ""30+20=50"". ","x = 30 y = 20 print(""\n%d+%d=%d"" % (x, y, x+y)) print() " 335,Write a Python program to find the characters in a list of strings which occur more than and less than a given number. ,"from collections import Counter from itertools import chain def max_aggregate(list_str, N): temp = (set(sub) for sub in list_str) counts = Counter(chain.from_iterable(temp)) gt_N = [chr for chr, count in counts.items() if count > N] lt_N = [chr for chr, count in counts.items() if count < N] return gt_N, lt_N list_str = ['abcd', 'iabhef', 'dsalsdf', 'sdfsas', 'jlkdfgd'] print(""Original list:"") print(list_str) N = 3 result = max_aggregate(list_str, N) print(""\nCharacters of the said list of strings which occur more than:"",N) print(result[0]) print(""\nCharacters of the said list of strings which occur less than:"",N) print(result[1]) " 336,Write a NumPy program to add two zeros to the beginning of each element of a given array of string values. ,"import numpy as np nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str) print(""Original array:"") print(nums) print(""\nAdd two zeros to the beginning of each element of the said array:"") print(np.char.add('00', nums)) print(""\nAlternate method:"") print(np.char.rjust(nums, 6, fillchar='0')) " 337,Write a NumPy program to count the occurrence of a specified item in a given NumPy array. ,"import numpy as np nums = np.array([10, 20, 20, 20, 20, 0, 20, 30, 30, 30, 0, 0, 20, 20, 0]) print(""Original array:"") print(nums) print(np.count_nonzero(nums == 10)) print(np.count_nonzero(nums == 20)) print(np.count_nonzero(nums == 30)) print(np.count_nonzero(nums == 0)) " 338,Write a Python program to sort a given positive number in descending/ascending order. ,"def test_dsc(n): return int(''.join(sorted(str(n), reverse = True))) def test_asc(n): return int(''.join(sorted(list(str(n))))[::1]) n = 134543 print(""Original Number: "",n); print(""Descending order of the said number: "", test_dsc(n)); print(""Ascending order of the said number: "", test_asc(n)); n = 43750973 print(""\nOriginal Number: "",n); print(""Descending order of the said number: "", test_dsc(n)); print(""Ascending order of the said number: "", test_asc(n)); " 339,Write a Python program to check whether a string contains all letters of the alphabet. ,"import string alphabet = set(string.ascii_lowercase) input_string = 'The quick brown fox jumps over the lazy dog' print(set(input_string.lower()) >= alphabet) input_string = 'The quick brown fox jumps over the lazy cat' print(set(input_string.lower()) >= alphabet) " 340,Write a Python program to delete a specific item from a given doubly linked list. ,"class Node(object): # Singly linked node def __init__(self, value=None, next=None, prev=None): self.value = value 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, value): # Append an item new_item = Node(value, 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.value current = current.next yield item_val def print_foward(self): for node in self.iter(): print(node) def search_item(self, val): for node in self.iter(): if val == node: return True return False def delete(self, value): # Delete a specific item current = self.head node_deleted = False if current is None: node_deleted = False elif current.value == value: self.head = current.next self.head.prev = None node_deleted = True elif self.tail.value == value: self.tail = self.tail.prev self.tail.next = None node_deleted = True else: while current: if current.value == value: current.prev.next = current.next current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: 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() items.delete(""Java"") items.delete(""Python"") print(""\nList after deleting two items:"") items.print_foward() " 341,Write a NumPy program to convert a list and tuple into arrays. ,"import numpy as np my_list = [1, 2, 3, 4, 5, 6, 7, 8] print(""List to array: "") print(np.asarray(my_list)) my_tuple = ([8, 4, 6], [1, 2, 3]) print(""Tuple to array: "") print(np.asarray(my_tuple)) " 342,Write a Pandas program to create a plot of distribution of UFO (unidentified flying object) observation time. ,"import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r'ufo.csv') df['duration_sec'] = (df['length_of_encounter_seconds'].astype(float))/60 s = df[""duration_sec""].quantile(0.95) temp = df['duration_sec'] temp = temp.sort_values() temp = temp[temp < s] plt.figure(figsize=(10, 8)) sns.distplot(temp) plt.xlabel('Duration(min)', fontsize=20) plt.ylabel(""Frequency"", fontsize=15) plt.xticks(fontsize=12) plt.title(""-Distribution of UFO obervation time-"", fontsize=20) plt.show() " 343,"Write a NumPy program to find the union of two arrays. Union will return the unique, sorted array of values that are in either of the two 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 sorted array of values that are in either of the two input arrays:"") print(np.union1d(array1, array2)) " 344,Write a Python program to sum all the items in a dictionary. ,"my_dict = {'data1':100,'data2':-54,'data3':247} print(sum(my_dict.values())) " 345,"Write a Python program to find the ration of positive numbers, negative numbers and zeroes in an array of integers. ","from array import array def plusMinus(nums): n = len(nums) n1 = n2 = n3 = 0 for x in nums: if x > 0: n1 += 1 elif x < 0: n2 += 1 else: n3 += 1 return round(n1/n,2), round(n2/n,2), round(n3/n,2) nums = array('i', [0, 1, 2, -1, -5, 6, 0, -3, -2, 3, 4, 6, 8]) print(""Original array:"",nums) nums_arr = list(map(int, nums)) result = plusMinus(nums_arr) print(""Ratio of positive numbers, negative numbers and zeroes:"") print(result) nums = array('i', [2, 1, 2, -1, -5, 6, 4, -3, -2, 3, 4, 6, 8]) print(""\nOriginal array:"",nums) nums_arr = list(map(int, nums)) result = plusMinus(nums_arr) print(""Ratio of positive numbers, negative numbers and zeroes:"") print(result) " 346,Write a Python program to sort a list of elements using the selection sort algorithm. ,"def selectionSort(nlist): for fillslot in range(len(nlist)-1,0,-1): maxpos=0 for location in range(1,fillslot+1): if nlist[location]>nlist[maxpos]: maxpos = location temp = nlist[fillslot] nlist[fillslot] = nlist[maxpos] nlist[maxpos] = temp nlist = [14,46,43,27,57,41,45,21,70] selectionSort(nlist) print(nlist) " 347,Write a Python program to interleave multiple lists of the same length. ,"def interleave_multiple_lists(list1,list2,list3): result = [el for pair in zip(list1, list2, list3) for el in pair] return result list1 = [1,2,3,4,5,6,7] list2 = [10,20,30,40,50,60,70] list3 = [100,200,300,400,500,600,700] print(""Original list:"") print(""list1:"",list1) print(""list2:"",list2) print(""list3:"",list3) print(""\nInterleave multiple lists:"") print(interleave_multiple_lists(list1,list2,list3)) " 348,"Write a Python program to combines two or more dictionaries, creating a list of values for each key. ","from collections import defaultdict def test(*dicts): result = defaultdict(list) for el in dicts: for key in el: result[key].append(el[key]) return dict(result) d1 = {'w': 50, 'x': 100, 'y': 'Green', 'z': 400} d2 = {'x': 300, 'y': 'Red', 'z': 600} print(""Original dictionaries:"") print(d1) print(d2) print(""\nCombined dictionaries, creating a list of values for each key:"") print(test(d1, d2)) " 349,Write a Pandas program to drop a index level from a multi-level column index of a dataframe. ,"import pandas as pd cols = pd.MultiIndex.from_tuples([(""a"", ""x""), (""a"", ""y""), (""a"", ""z"")]) print(""\nConstruct a Dataframe using the said MultiIndex levels: "") df = pd.DataFrame([[1,2,3], [3,4,5], [5,6,7]], columns=cols) print(df) #Levels are 0-indexed beginning from the top. print(""\nRemove the top level index:"") df.columns = df.columns.droplevel(0) print(df) df = pd.DataFrame([[1,2,3], [3,4,5], [5,6,7]], columns=cols) print(""\nOriginal dataframe:"") print(df) print(""\nRemove the index next to top level:"") df.columns = df.columns.droplevel(1) print(df) " 350,Write a Pandas program to get all the sighting days of the unidentified flying object (ufo) between 1950-10-10 and 1960-10-10. ,"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 days of the unidentified flying object (ufo) between 1949-10-10 and 1960-10-10:"") selected_period = df[(df['Date_time'] >= '1950-01-01 00:00:00') & (df['Date_time'] <= '1960-12-31 23:59:59')] print(selected_period) " 351,Write a Python program to make an iterator that drops elements from the iterable as soon as an element is a positive number. ,"import itertools as it def drop_while(nums): return it.dropwhile(lambda x : x < 0, nums) nums = [-1,-2,-3,4,-10,2,0,5,12] print(""Original list: "",nums) result = drop_while(nums) print(""Drops elements from the iterable when a positive number arises \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(""Drops elements from the iterable when a positive number arises \n"",list(result)) " 352,Write a Python program to remove empty lists from a given list of lists. ,"list1 = [[], [], [], 'Red', 'Green', [1,2], 'Blue', [], []] print(""Original list:"") print(list1) print(""\nAfter deleting the empty lists from the said lists of lists"") list2 = [x for x in list1 if x] print(list2) " 353,Write a Python program to sort a list of elements using Cocktail shaker sort. ,"def cocktail_shaker_sort(nums): for i in range(len(nums)-1, 0, -1): is_swapped = False for j in range(i, 0, -1): if nums[j] < nums[j-1]: nums[j], nums[j-1] = nums[j-1], nums[j] is_swapped = True for j in range(i): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] is_swapped = True if not is_swapped: return nums num1 = input('Input comma separated numbers:\n').strip() nums = [int(item) for item in num1.split(',')] print(cocktail_shaker_sort(nums)) " 354,"Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length. ","def check_string(s): messg = [] if not any(x.isupper() for x in s): messg.append('String must have 1 upper case character.') if not any(x.islower() for x in s): messg.append('String must have 1 lower case character.') if not any(x.isdigit() for x in s): messg.append('String must have 1 number.') if len(s) < 8: messg.append('String length should be atleast 8.') if not messg: messg.append('Valid string.') return messg s = input(""Input the string: "") print(check_string(s)) " 355,"Write a NumPy program to extract first, third and fifth elements of the third and fifth rows from a given (6x6) array. ","import numpy as np arra_data = np.arange(0,36).reshape((6, 6)) print(""Original array:"") print(arra_data) print(""\nExtracted data: First, third and fifth elements of the third and fifth rows"") print(arra_data[2::2, ::2]) " 356,Write a Python program to check if a given function is a generator or not. Use types.GeneratorType(),"import types def a(x): yield x def b(x): return x def add(x, y): return x + y print(isinstance(a(456), types.GeneratorType)) print(isinstance(b(823), types.GeneratorType)) print(isinstance(add(8,2), types.GeneratorType)) " 357,Write a Python program to find the string similarity between two given strings. ,"import difflib def string_similarity(str1, str2): result = difflib.SequenceMatcher(a=str1.lower(), b=str2.lower()) return result.ratio() str1 = 'Python Exercises' str2 = 'Python Exercises' print(""Original string:"") print(str1) print(str2) print(""Similarity between two said strings:"") print(string_similarity(str1,str2)) str1 = 'Python Exercises' str2 = 'Python Exercise' print(""\nOriginal string:"") print(str1) print(str2) print(""Similarity between two said strings:"") print(string_similarity(str1,str2)) str1 = 'Python Exercises' str2 = 'Python Ex.' print(""\nOriginal string:"") print(str1) print(str2) print(""Similarity between two said strings:"") print(string_similarity(str1,str2)) str1 = 'Python Exercises' str2 = 'Python' print(""\nOriginal string:"") print(str1) print(str2) print(""Similarity between two said strings:"") print(string_similarity(str1,str2)) str1 = 'Python Exercises' str1 = 'Java Exercises' print(""\nOriginal string:"") print(str1) print(str2) print(""Similarity between two said strings:"") print(string_similarity(str1,str2)) " 358,Write a Python program to convert a pair of values into a sorted unique array. ,"L = [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1, 2), (3, 4), (3, 4), (7, 8), (9, 10)] print(""Original List: "", L) print(""Sorted Unique Data:"",sorted(set().union(*L))) " 359,"Write a NumPy program to calculate cumulative sum of the elements along a given axis, sum over rows for each of the 3 columns and sum over columns for each of the 2 rows of a given 3x3 array. ","import numpy as np x = np.array([[1,2,3], [4,5,6]]) print(""Original array: "") print(x) print(""Cumulative sum of the elements along a given axis:"") r = np.cumsum(x) print(r) print(""\nSum over rows for each of the 3 columns:"") r = np.cumsum(x,axis=0) print(r) print(""\nSum over columns for each of the 2 rows:"") r = np.cumsum(x,axis=1) print(r) " 360,Write a Python program to check multiple keys exists in a dictionary. ,"student = { 'name': 'Alex', 'class': 'V', 'roll_id': '2' } print(student.keys() >= {'class', 'name'}) print(student.keys() >= {'name', 'Alex'}) print(student.keys() >= {'roll_id', 'name'}) " 361,Write a Python program to create two strings from a given string. Create the first string using those character which occurs only once and create the second string which consists of multi-time occurring characters in the said string. ,"from collections import Counter def generateStrings(input): str_char_ctr = Counter(input) part1 = [ key for (key,count) in str_char_ctr.items() if count==1] part2 = [ key for (key,count) in str_char_ctr.items() if count>1] part1.sort() part2.sort() return part1,part2 input = ""aabbcceffgh"" s1, s2 = generateStrings(input) print(''.join(s1)) print(''.join(s2)) " 362,Write a Pandas program to check whether only lower case or upper case is present in a given column of a DataFrame. ,"import pandas as pd df = pd.DataFrame({ 'company_code': ['ABCD','EFGF', 'hhhh', 'abcd', 'EAWQaaa'], '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 lower (company_code)?"") df['company_code_ul_cases'] = list(map(lambda x: x.islower(), df['company_code'])) print(df) print(""\nIs Upper (company_code)?"") df['company_code_ul_cases'] = list(map(lambda x: x.isupper(), df['company_code'])) print(df) " 363,"Write a Python program to find the minimum, maximum value for each tuple position in a given list of tuples. ","def max_min_list_tuples(nums): zip(*nums) result1 = map(max, zip(*nums)) result2 = map(min, zip(*nums)) return list(result1), list(result2) nums = [(2,3),(2,4),(0,6),(7,1)] print(""Original list:"") print(nums) result = max_min_list_tuples(nums) print(""\nMaximum value for each tuple position in the said list of tuples:"") print(result[0]) print(""\nMinimum value for each tuple position in the said list of tuples:"") print(result[1]) " 364,Write a Python program to convert a given list of strings into list of lists. ,"def strings_to_listOflists(colors): result = [list(word) for word in colors] return result colors = [""Red"", ""Maroon"", ""Yellow"", ""Olive""] print('Original list of strings:') print(colors) print(""\nConvert the said list of strings into list of lists:"") print(strings_to_listOflists(colors)) " 365,Write a Pandas program to print a DataFrame without 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 = [1, 2, 3, 4, 5, 6]) print(""Original DataFrame with single index:"") print(df) print(""\nDataFrame without index:"") print(df.to_string(index=False)) " 366,Write a Python program to display some information about the OS where the script is running. ,"import platform as pl os_profile = [ 'architecture', 'linux_distribution', 'mac_ver', 'machine', 'node', 'platform', 'processor', 'python_build', 'python_compiler', 'python_version', 'release', 'system', 'uname', 'version', ] for key in os_profile: if hasattr(pl, key): print(key + "": "" + str(getattr(pl, key)())) " 367,Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard pattern. ,"import numpy as np x = np.ones((3,3)) print(""Checkerboard pattern:"") x = np.zeros((8,8),dtype=int) x[1::2,::2] = 1 x[::2,1::2] = 1 print(x) " 368,"Write a Python program to filter the height and width of students, which are stored in a dictionary. ","def filter_data(students): result = {k: s for k, s in students.items() if s[0] >=6.0 and s[1] >=70} 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)) " 369,Write a NumPy program to find the nearest value from a given value in an array. ,"import numpy as np x = np.random.uniform(1, 12, 5) v = 4 n = x.flat[np.abs(x - v).argmin()] print(n) " 370,Write a NumPy program to create a two-dimensional array of specified format. ,"import numpy as np print(""Create an array of shape (15,10):"") print(""Command-1"") print(np.arange(1, 151).reshape(15, 10)) print(""\nCommand-2"") print(np.arange(1, 151).reshape(-1, 10)) print(""\nCommand-3"") print(np.arange(1, 151).reshape(15, -1)) " 371,"Write a NumPy program to create an array of 4,5 shape and to reverse the rows of the said array. After reversing 1st row will be 4th and 4th will be 1st, 2nd row will be 3rd row and 3rd row will be 2nd row. ","import numpy as np array_nums = np.arange(20).reshape(4,5) print(""Original array:"") print(array_nums) print(""\nAfter reversing:"") array_nums[:] = array_nums[3::-1] print(array_nums) " 372,"Write a Python program to select a random element from a list, set, dictionary (value) and a file from a directory. Use random.choice()","import random import os print(""Select a random element from a list:"") elements = [1, 2, 3, 4, 5] print(random.choice(elements)) print(random.choice(elements)) print(random.choice(elements)) print(""\nSelect a random element from a set:"") elements = set([1, 2, 3, 4, 5]) # convert to tuple because sets are invalid inputs print(random.choice(tuple(elements))) print(random.choice(tuple(elements))) print(random.choice(tuple(elements))) print(""\nSelect a random value from a dictionary:"") d = {""a"": 1, ""b"": 2, ""c"": 3, ""d"": 4, ""e"": 5} key = random.choice(list(d)) print(d[key]) key = random.choice(list(d)) print(d[key]) key = random.choice(list(d)) print(d[key]) print(""\nSelect a random file from a directory.:"") print(random.choice(os.listdir(""/""))) " 373,Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array. ,"import numpy as np arra=np.ones((1,8,8)) print(""Original array:"") print(arra) result = np.triu(arra, k=1) print(""\nResult:"") print(result) " 374,Write a Python program to create a key-value list pairings in a given dictionary. ,"from itertools import product def test(dictt): result = [dict(zip(dictt, sub)) for sub in product(*dictt.values())] return result students = {1: ['Jean Castro'], 2: ['Lula Powell'], 3: ['Brian Howell'], 4: ['Lynne Foster'], 5: ['Zachary Simon']} print(""\nOriginal dictionary:"") print(students) print(""\nA key-value list pairings of the said dictionary:"") print(test(students)) " 375,"Write a Python program to generate a random alphabetical character, alphabetical string and alphabetical string of a fixed length. Use random.choice()","import random import string print(""Generate a random alphabetical character:"") print(random.choice(string.ascii_letters)) print(""\nGenerate a random alphabetical string:"") max_length = 255 str1 = """" for i in range(random.randint(1, max_length)): str1 += random.choice(string.ascii_letters) print(str1) print(""\nGenerate a random alphabetical string of a fixed length:"") str1 = """" for i in range(10): str1 += random.choice(string.ascii_letters) print(str1) " 376,"Write a NumPy program to calculate cumulative product of the elements along a given axis, sum over rows for each of the 3 columns and product over columns for each of the 2 rows of a given 3x3 array. ","import numpy as np x = np.array([[1,2,3], [4,5,6]]) print(""Original array: "") print(x) print(""Cumulative product of the elements along a given axis:"") r = np.cumprod(x) print(r) print(""\nProduct over rows for each of the 3 columns:"") r = np.cumprod(x,axis=0) print(r) print(""\nProduct over columns for each of the 2 rows:"") r = np.cumprod(x,axis=1) print(r) " 377,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) " 378,"Write a Pandas program to create a new DataFrame based on existing series, using specified argument and override the existing columns names. ","import pandas as pd s1 = pd.Series([0, 1, 2, 3], name='col1') s2 = pd.Series([0, 1, 2, 3]) s3 = pd.Series([0, 1, 4, 5], name='col3') df = pd.concat([s1, s2, s3], axis=1, keys=['column1', 'column2', 'column3']) print(df) " 379,Write a Python program to create all possible permutations from a given collection of distinct numbers.,"def permute(nums): result_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) result_perms = new_perms return result_perms my_nums = [1,2,3] print(""Original Cofllection: "",my_nums) print(""Collection of distinct numbers:\n"",permute(my_nums)) " 380,Write a Python program to find the maximum and minimum values in a given list of tuples using lambda function. ,"def max_min_list_tuples(class_students): return_max = max(class_students,key=lambda item:item[1])[1] return_min = min(class_students,key=lambda item:item[1])[1] return return_max, return_min class_students = [('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)] 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)) " 381,Write a Python program to append items from inerrable to the end of the array. ,"from array import * array_num = array('i', [1, 3, 5, 7, 9]) print(""Original array: ""+str(array_num)) array_num.extend(array_num) print(""Extended array: ""+str(array_num)) " 382,Write a Python function that takes a list of words and return the longest word and the length of the longest one. ,"def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][0], word_len[-1][1] result = find_longest_word([""PHP"", ""Exercises"", ""Backend""]) print(""\nLongest word: "",result[1]) print(""Length of the longest word: "",result[0]) " 383,"Write a Python program to configure the rounding to round to the nearest - with ties going towards 0, with ties going away from 0. Use decimal.ROUND_HALF_DOWN, decimal.ROUND_HALF_UP","import decimal print(""Configure the rounding to round to the nearest, with ties going towards 0:"") decimal.getcontext().prec = 1 decimal.getcontext().rounding = decimal.ROUND_HALF_DOWN print(decimal.Decimal(10) / decimal.Decimal(4)) print(""\nConfigure the rounding to round to the nearest, with ties going away from 0:"") decimal.getcontext().prec = 1 decimal.getcontext().rounding = decimal.ROUND_HALF_UP print(decimal.Decimal(10) / decimal.Decimal(4)) " 384,Write a Python program to access only unique key value of a Python object. ,"import json python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}' print(""Original Python object:"") print(python_obj) json_obj = json.loads(python_obj) print(""\nUnique Key in a JSON object:"") print(json_obj) " 385,Write a NumPy program to read a CSV data file and store records in an array. ,"from numpy import genfromtxt csv_data = genfromtxt('fdata.csv', dtype=['S10','float32','float32','float32','float32'], delimiter="","") print(csv_data) " 386,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight dataframe's specific 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_cols(s): color = 'grey' return 'background-color: %s' % color print(""\nHighlight specific columns:"") df.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']]) " 387,Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. ,"def string_test(s): 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 (""Original String : "", s) print (""No. of Upper case characters : "", d[""UPPER_CASE""]) print (""No. of Lower case Characters : "", d[""LOWER_CASE""]) string_test('The quick Brown Fox') " 388,Write a Python program to create a list containing the power of said number in bases raised to the corresponding number in the index using Python map. ,"bases_num = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(""Base numbers abd index: "") print(bases_num) print(index) result = list(map(pow, bases_num, index)) print(""\nPower of said number in bases raised to the corresponding number in the index:"") print(result) " 389,Write a Pandas program to extract year between 1800 to 2200 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'], 'year': ['year 1800','year 1700','year 2300', 'year 1900', 'year 2200'] }) print(""Original DataFrame:"") print(df) def find_year(text): #line=re.findall(r""\b(18[0][0]|2[0-2][00])\b"",text) result = re.findall(r""\b(18[0-9]{2}|19[0-8][0-9]|199[0-9]|2[01][0-9]{2}|2200)\b"",text) return result df['year_range']=df['year'].apply(lambda x: find_year(x)) print(""\Extracting year between 1800 to 2200:"") print(df) " 390,Write a Pandas program to extract the day name from a specified date. Add 2 days and 1 business day with the specified date. ,"import pandas as pd newday = pd.Timestamp('2020-02-07') print(""First date:"") print(newday) print(""\nThe day name of the said date:"") print(newday.day_name()) print(""\nAdd 2 days with the said date:"") newday1 = newday + pd.Timedelta('2 day') print(newday1.day_name()) print(""\nNext business day:"") nbday = newday + pd.offsets.BDay() print(nbday.day_name()) " 391,Write a Python program to read the current line from a given CSV file. Use csv.reader,"import csv f = open(""employees.csv"", newline='') csv_reader = csv.reader(f) print(next(csv_reader)) print(next(csv_reader)) print(next(csv_reader)) " 392,Write a Python program to read a square matrix from console and print the sum of matrix primary diagonal. Accept the size of the square matrix and elements for each column separated with a space (for every row) as input from the user. ,"size = int(input(""Input the size of the matrix: "")) matrix = [[0] * size for row in range(0, size)] for x in range(0, size): line = list(map(int, input().split())) for y in range(0, size): matrix[x][y] = line[y] matrix_sum_diagonal = sum(matrix[size - i - 1][size - i - 1] for i in range(size)) print(""Sum of matrix primary diagonal:"") print(matrix_sum_diagonal) " 393,Write a Pandas program to import sheet2 data from a given excel data (employee.xlsx ) into a Pandas dataframe. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx',sheet_name=1) print(df) " 394,"Write a NumPy program to convert a given array into bytes, and load it as array. ","import numpy as np import os a = np.array([1, 2, 3, 4, 5, 6]) print(""Original array:"") print(a) a_bytes = a.tostring() a2 = np.fromstring(a_bytes, dtype=a.dtype) print(""After loading, content of the text file:"") print(a2) print(np.array_equal(a, a2)) " 395,Write a Pandas program to create a monthly time period and display the list of names in the current local scope. ,"import pandas as pd mtp = pd.Period('2021-11','M') print(""Monthly time perid: "",mtp) print(""\nList of names in the current local scope:"") print(dir(mtp)) " 396,"Write a NumPy program to sort an along the first, last axis of an array. ","import numpy as np a = np.array([[4, 6],[2, 1]]) print(""Original array: "") print(a) print(""Sort along the first axis: "") x = np.sort(a, axis=0) print(x) print(""Sort along the last axis: "") y = np.sort(x, axis=1) print(y) " 397,"Write a NumPy program to move the specified axis backwards, until it lies in a given position. ","import numpy as np x = np.ones((2,3,4,5)) print(np.rollaxis(x, 3, 1).shape) " 398,"Write a NumPy program to check whether each element of a given array starts with ""P"". ","import numpy as np x1 = np.array(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str) print(""\nOriginal Array:"") print(x1) print(""Test if each element of the said array starts with 'P':"") r = np.char.startswith(x1, ""P"") print(r) " 399,Write a Pandas program to construct a DataFrame 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 Dataframe using the said MultiIndex levels: "") df = pd.DataFrame(np.random.randn(8, 5), index=sales_index) print(df) " 400,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the entire row in Yellow where a specific column value is greater than 0.5. ","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 - table style:"") def highlight_greaterthan(x): if x.C > .5: return ['background-color: yellow']*5 else: return ['background-color: white']*5 df.style.apply(highlight_greaterthan, axis=1) " 401,"a href=""python-conditional-exercise-15.php"" target=""_blank"">Click me to see the sample solution","import re p= input(""Input your password"") x = True while x: if (len(p)<6 or len(p)>12): break elif not re.search(""[a-z]"",p): break elif not re.search(""[0-9]"",p): break elif not re.search(""[A-Z]"",p): break elif not re.search(""[$#@]"",p): break elif re.search(""\s"",p): break else: print(""Valid Password"") x=False break if x: print(""Not a Valid Password"") " 402,"Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array. ","import numpy as np X = np.array([1, 7, 13, 105]) print(""Original array:"") print(X) print(""Size of the memory occupied by the said array:"") print(""%d bytes"" % (X.size * X.itemsize)) " 403,Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. ,"a = int(input(""Input an integer : "")) n1 = int( ""%s"" % a ) n2 = int( ""%s%s"" % (a,a) ) n3 = int( ""%s%s%s"" % (a,a,a) ) print (n1+n2+n3) " 404,"Write a Python program to find a tuple, the smallest second index value from a list of tuples. ","x = [(4, 1), (1, 2), (6, 0)] print(min(x, key=lambda n: (n[1], -n[0]))) " 405,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in table style. ","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:"") # Set CSS properties for th elements in dataframe th_props = [ ('font-size', '12px'), ('text-align', 'center'), ('font-weight', 'bold'), ('color', '#6d6d6d'), ('background-color', '#f7ffff') ] # Set CSS properties for td elements in dataframe td_props = [ ('font-size', '12px') ] # Set table styles styles = [ dict(selector=""th"", props=th_props), dict(selector=""td"", props=td_props) ] (df.style .set_table_styles(styles)) " 406,Write a NumPy program to convert Pandas dataframe to NumPy array with headers. ,"import numpy as np import pandas as pd np_array = np.random.rand(12,3) print(""Original Numpy array:"") print(np_array) print(""Type: "",type(np_array)) df = pd.DataFrame(np.random.rand(12,3),columns=['A','B','C']) print(""\nPanda's DataFrame: "") print(df) print(""Type: "",type(df)) " 407,Write a NumPy program to calculate 2p 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(""\n2^p for all the elements of the said array:"") r1 = np.exp2(x) r2 = 2 ** x assert np.allclose(r1, r2) print(r1) " 408,"Create a dataframe of ten rows, four columns with random values. Write a Pandas program to set dataframe background Color black and font color yellow. ","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(""\nBackground:black - fontcolor:yelow"") df.style.set_properties(**{'background-color': 'black', 'color': 'yellow'}) " 409,Write a NumPy program to extract first and third elements of the first 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: First and third elements of the first and third rows "") print(arra_data[::2, ::2]) " 410,"Write a Python program to sum of three given integers. However, if two values are equal sum will be zero. ","def sum(x, y, z): if x == y or y == z or x==z: sum = 0 else: sum = x + y + z return sum print(sum(2, 1, 2)) print(sum(3, 2, 2)) print(sum(2, 2, 2)) print(sum(1, 2, 3)) " 411,Write a Pandas program to sort a MultiIndex of a DataFrame. Also sort on various levels of index. ,"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(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(""\nSort on MultiIndex DataFrame:"") df1 = df.sort_index() print(""\nSort on Index level=0 of the DataFrame:"") df2 = df.sort_index(level=0) print(df2) print(""\nSort on Index level=1 of the DataFrame:"") df2 = df.sort_index(level=1) print(df2) print(""\nPass a level name to sort the DataFrame:"") df3 = df.sort_index(level=""city"") print(df3) " 412,"Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array. ","import numpy as np x = np.array([[0,1],[2,3]]) print(""Original array:"") print(x) print(""Sum of all elements:"") print(np.sum(x)) print(""Sum of each column:"") print(np.sum(x, axis=0)) print(""Sum of each row:"") print(np.sum(x, axis=1)) " 413,"Write a Python program to extract specified number of elements from a given list, which follows each other continuously. ","from itertools import groupby def extract_elements(nums, n): result = [i for i, j in groupby(nums) if len(list(j)) == n] return result nums1 = [1, 1, 3, 4, 4, 5, 6, 7] n = 2 print(""Original list:"") print(nums1) print(""Extract 2 number of elements from the said list which follows each other continuously:"") print(extract_elements(nums1, n)) nums2 = [0, 1, 2, 3, 4, 4, 4, 4, 5, 7] n = 4 print(""Original lists:"") print(nums2) print(""Extract 4 number of elements from the said list which follows each other continuously:"") print(extract_elements(nums2, n)) " 414,Write a Python program to sort a given list of tuples on specified element. ,"def sort_on_specific_item(lst, n): result = sorted((lst), key=lambda x: x[n]) return result items = [('item2', 10, 10.12), ('item3', 15, 25.10), ('item1', 11, 24.50),('item4', 12, 22.50)] print(""Original list of tuples:"") print(items) print(""\nSort on 1st element of the tuple of the said list:"") n = 0 print(sort_on_specific_item(items, n)) print(""\nSort on 2nd element of the tuple of the said list:"") n = 1 print(sort_on_specific_item(items, n)) print(""\nSort on 3rd element of the tuple of the said list:"") n = 2 print(sort_on_specific_item(items, n)) " 415,Write a NumPy program to move axes of an array to new positions. Other axes remain in their original order. ,"import numpy as np x = np.zeros((2, 3, 4)) print(np.moveaxis(x, 0, -1).shape) print(np.moveaxis(x, -1, 0).shape) " 416,Write a Python program to scramble the letters of string in a given list. ,"from random import shuffle def shuffle_word(text_list): text_list = list(text_list) shuffle(text_list) return ''.join(text_list) text_list = ['Python', 'list', 'exercises', 'practice', 'solution'] print(""Original list:"") print(text_list) print(""\nAfter scrambling the letters of the strings of the said list:"") result = [shuffle_word(word) for word in text_list] print(result) " 417,Write a Python program to get the most frequent element in a given list of numbers. ,"def most_frequent(nums): return max(set(nums), key = nums.count) print(most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2])) 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(""Item with maximum frequency of the said list:"") print(most_frequent(nums)) nums = [1, 2, 3, 1, 2, 3, 2, 1, 4, 3, 3] print (""\nOriginal list:"") print(nums) print(""Item with maximum frequency of the said list:"") print(most_frequent(nums)) " 418,"Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors. ","def smallest_multiple(n): if (n<=2): return n i = n * 2 factors = [number for number in range(n, 1, -1) if number * 2 > n] print(factors) while True: for a in factors: if i % a != 0: i += n break if (a == factors[-1] and i % a == 0): return i print(smallest_multiple(13)) print(smallest_multiple(11)) print(smallest_multiple(2)) print(smallest_multiple(1)) " 419,Write a NumPy program to copy data from a given array to another array. ,"import numpy as np x = np.array([24, 27, 30, 29, 18, 14]) print(""Original array:"") print(x) y = np.empty_like (x) y[:] = x print(""\nCopy of the said array:"") print(y) " 420,Write a Pandas program to split a dataset to group by two columns and then sort the aggregated results within the groups. ,"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) df_agg = df.groupby(['customer_id','salesman_id']).agg({'purch_amt':sum}) result = df_agg['purch_amt'].groupby(level=0, group_keys=False) print(""\nGroup on 'customer_id', 'salesman_id' and then sort sum of purch_amt within the groups:"") print(result.nlargest()) " 421,Write a Python program to find the indexes of all None items in a given list. ,"def relative_order(lst): result = [i for i in range(len(lst)) if lst[i] == None] return result nums = [1, None, 5, 4,None, 0, None, None] print(""Original list:"") print(nums) print(""\nIndexes of all None items of the list:"") print(relative_order(nums)) " 422,Write a Python program to split a given multiline string into a list of lines. ,"def split_lines(s): return s.split('\n') print(""Original string:"") print(""This\nis a\nmultiline\nstring.\n"") print(""Split the said multiline string into a list of lines:"") print(split_lines('This\nis a\nmultiline\nstring.\n')) " 423,Write a Python program to write a Python list of lists to a csv file. After writing the CSV file read the CSV file and display the content. ,"import csv data = [[10,'a1', 1], [12,'a2', 3], [14, 'a3', 5], [16, 'a4', 7], [18, 'a5', 9]] with open(""temp.csv"", ""w"", newline="""") as f: writer = csv.writer(f) writer.writerows(data) with open('temp.csv', newline='') as csvfile: data = csv.reader(csvfile, delimiter=' ') for row in data: print(', '.join(row)) " 424,"Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length using lambda. ","def check_string(str1): messg = [ lambda str1: any(x.isupper() for x in str1) or 'String must have 1 upper case character.', lambda str1: any(x.islower() for x in str1) or 'String must have 1 lower case character.', lambda str1: any(x.isdigit() for x in str1) or 'String must have 1 number.', lambda str1: len(str1) >= 7 or 'String length should be atleast 8.',] result = [x for x in [i(str1) for i in messg] if x != True] if not result: result.append('Valid string.') return result s = input(""Input the string: "") print(check_string(s)) " 425,Write a Python program to run an operating system command using the os module. ,"import os if os.name == ""nt"": command = ""dir"" else: command = ""ls -l"" os.system(command) " 426,"Write a Pandas program to create a subtotal of ""Labor Hours"" against MSHA ID from the given excel data (coalpublic2013.xlsx ). ","import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df_sub=df[[""MSHA ID"",""Labor_Hours""]].groupby('MSHA ID').sum() df_sub " 427,Write a Python program to count the number of rows 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));"") print(""Number of records before inserting rows:"") cursor = cursorObj.execute('select * from salesman;') print(len(cursor.fetchall())) # 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() print(""\nNumber of records after inserting rows:"") cursor = cursorObj.execute('select * from salesman;') print(len(cursor.fetchall())) sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print(""\nThe SQLite connection is closed."") " 428,Write a Python program to count the frequency of consecutive duplicate elements in a given list of numbers. ,"def count_dups(nums): element = [] freque = [] if not nums: return element running_count = 1 for i in range(len(nums)-1): if nums[i] == nums[i+1]: running_count += 1 else: freque.append(running_count) element.append(nums[i]) running_count = 1 freque.append(running_count) element.append(nums[i+1]) return element,freque nums = [1,2,2,2,4,4,4,5,5,5,5] print(""Original lists:"") print(nums) print(""\nConsecutive duplicate elements and their frequency:"") print(count_dups(nums)) " 429,Write a NumPy program to convert a given vector of integers to a matrix of binary representation. ,"import numpy as np nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15]) print(""Original vector:"") print(nums) bin_nums = ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) print(""\nBinary representation of the said vector:"") print(bin_nums[:,::-1]) " 430,Write a NumPy program to create an empty and a full array. ,"import numpy as np # Create an empty array x = np.empty((3,4)) print(x) # Create a full array y = np.full((3,3),6) print(y) " 431,Write a Python program to find all the h2 tags and list the first four 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('h2')[0:4]) " 432,Write a Pandas program to check whether only proper case or title case is present in a given column of a DataFrame. ,"import pandas as pd df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'Hhhh', 'abcd', 'EAWQaaa'], '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 proper case or title case?"") df['company_code_is_title'] = list(map(lambda x: x.istitle(), df['company_code'])) print(df) " 433,"Write a Pandas program to calculate one, two, three business day(s) from a specified date. Also find the next business month end from a specific date. ","import pandas as pd from pandas.tseries.offsets import * import datetime from datetime import datetime, date dt = datetime(2020, 1, 4) print(""Specified date:"") print(dt) print(""\nOne business day from the said date:"") obday = dt + BusinessDay() print(obday) print(""\nTwo business days from the said date:"") tbday = dt + 2 * BusinessDay() print(tbday) print(""\nThree business days from the said date:"") thbday = dt + 3 * BusinessDay() print(thbday) print(""\nNext business month end from the said date:"") nbday = dt + BMonthEnd() print(nbday) " 434,"Write a Pandas program to filter those records where WHO region contains ""Ea"" substring 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()) # Remove NA / NaN values new_w_a_con = w_a_con.dropna() print(""\nMatch if a given column has a particular sub string:"") print(new_w_a_con[new_w_a_con[""WHO region""].str.contains(""Ea"")]) " 435,Write a Python program to extract single key-value pair of a dictionary in variables. ,"d = {'Red': 'Green'} (c1, c2), = d.items() print(c1) print(c2) " 436,Write a Python program to test whether a passed letter is a vowel or not. ,"def is_vowel(char): all_vowels = 'aeiou' return char in all_vowels print(is_vowel('c')) print(is_vowel('e')) " 437,Write a Python program to generate groups of five consecutive numbers in a list. ,"l = [[5*i + j for j in range(1,6)] for i in range(5)] print(l) " 438,rite a Python program to get the unique enumeration values. ,"import enum class Countries(enum.Enum): Afghanistan = 93 Albania = 355 Algeria = 213 Andorra = 376 Angola = 244 India = 355 USA = 213 for result in Countries: print('{:15} = {}'.format(result.name, result.value)) " 439,Write a Python program to find the class wise roll number from a tuple-of-tuples. ,"from collections import defaultdict classes = ( ('V', 1), ('VI', 1), ('V', 2), ('VI', 2), ('VI', 3), ('VII', 1), ) class_rollno = defaultdict(list) for class_name, roll_id in classes: class_rollno[class_name].append(roll_id) print(class_rollno) " 440,"Write a Python program to generate a list, containing the Fibonacci sequence, up until the nth term. ","def fibonacci_nums(n): if n <= 0: return [0] sequence = [0, 1] while len(sequence) <= n: next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2] sequence.append(next_value) return sequence print(""First 7 Fibonacci numbers:"") print(fibonacci_nums(7)) print(""\nFirst 15 Fibonacci numbers:"") print(fibonacci_nums(15)) print(""\nFirst 50 Fibonacci numbers:"") print(fibonacci_nums(50)) " 441,Write a python program to find the next previous palindrome of a specified number. ,"def Previous_Palindrome(num): for x in range(num-1,0,-1): if str(x) == str(x)[::-1]: return x print(Previous_Palindrome(99)); print(Previous_Palindrome(1221)); " 442,Write a Python program to convert true to 1 and false to 0. ,"x = 'true' x = int(x == 'true') print(x) x = 'abcd' x = int(x == 'true') print(x) " 443,Write a Python program to remove specific words from a given list using lambda. ,"def remove_words(list1, remove_words): result = list(filter(lambda word: word not in remove_words, list1)) return result colors = ['orange', 'red', 'green', 'blue', 'white', 'black'] remove_colors = ['orange','black'] 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)) " 444,"Write a NumPy program to create a 12x12x4 array with random values and extract any array of shape(6,6,3) from the said array. ","import numpy as np nums = np.random.random((8,8,3)) print(""Original array:"") print(nums) print(""\nExtract array of shape (6,6,3) from the said array:"") new_nums = nums[:6, :6, :] print(new_nums) " 445,Write a Pandas program to check the equality of two given series. ,"import pandas as pd nums1 = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]) nums2 = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]) print(""Original Series:"") print(nums1) print(nums2) print(""Check 2 series are equal or not?"") print(nums1 == nums2) " 446,Write a NumPy program to compute the factor of a given array by Singular Value Decomposition. ,"import numpy as np a = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float32) print(""Original array:"") print(a) U, s, V = np.linalg.svd(a, full_matrices=False) q, r = np.linalg.qr(a) print(""Factor of a given array by Singular Value Decomposition:"") print(""U=\n"", U, ""\ns=\n"", s, ""\nV=\n"", V) " 447,"Write a Pandas program to extract a single row, rows and a specific value from a MultiIndex levels 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(""\nExtract a single row from the said dataframe:"") print(df.loc[('sale2', 'city2')]) print(""\nExtract a single row from the said dataframe:"") print(df.loc[('sale2', 'city2')]) print(""\nExtract number of rows from the said dataframe:"") print(df.loc['sale1']) print(""\nExtract number of rows from the said dataframe:"") print(df.loc['sale3']) print(""\nExtract a single value from the said dataframe:"") print(df.loc[('sale1', 'city2'), 1]) print(""\nExtract a single value from the said dataframe:"") print(df.loc[('sale4', 'city1'), 4]) " 448,Write a Pandas program to calculate the total number of missing values in a 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(""\nTotal number of missing values of the said DataFrame:"") result = df.isna().sum().sum() print(result) " 449,Write a Python program to sum all amicable numbers from 1 to specified numbers. ,"def amicable_numbers_sum(limit): if not isinstance(limit, int): return ""Input is not an integer!"" if limit < 1: return ""Input must be bigger than 0!"" amicables = set() for num in range(2, limit+1): if num in amicables: continue sum_fact = sum([fact for fact in range(1, num) if num % fact == 0]) sum_fact2 = sum([fact for fact in range(1, sum_fact) if sum_fact % fact == 0]) if num == sum_fact2 and num != sum_fact: amicables.add(num) amicables.add(sum_fact2) return sum(amicables) print(amicable_numbers_sum(9999)) print(amicable_numbers_sum(999)) print(amicable_numbers_sum(99)) " 450,Write a Python program to remove newline characters from a file. ,"def remove_newlines(fname): flist = open(fname).readlines() return [s.rstrip('\n') for s in flist] print(remove_newlines(""test.txt"")) " 451,Write a NumPy program to find the most frequent value in an array. ,"import numpy as np x = np.random.randint(0, 10, 40) print(""Original array:"") print(x) print(""Most frequent value in the above array:"") print(np.bincount(x).argmax()) " 452,Write a Python program to find all lower and upper mixed case combinations of a given string. ,"import itertools def combination(str1): result = map(''.join, itertools.product(*((c.lower(), c.upper()) for c in str1))) return list(result) st =""abc"" print(""Original string:"") print(st) print(""All lower and upper mixed case combinations of the said string:"") print(combination(st)) st =""w3r"" print(""\nOriginal string:"") print(st) print(""All lower and upper mixed case combinations of the said string:"") print(combination(st)) st =""Python"" print(""\nOriginal string:"") print(st) print(""All lower and upper mixed case combinations of the said string:"") print(combination(st)) " 453,Write a Pandas program to extract items at given positions of a given series. ,"import pandas as pd num_series = pd.Series(list('2390238923902390239023')) element_pos = [0, 2, 6, 11, 21] print(""Original Series:"") print(num_series) result = num_series.take(element_pos) print(""\nExtract items at given positions of the said series:"") print(result) " 454,"Write a Python program to find the nested lists elements, which are present in another list using lambda. ","def intersection_nested_lists(l1, l2): result = [list(filter(lambda x: x in l1, sublist)) for sublist 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)) " 455,Write a NumPy program to extract all the elements of the first and fourth 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 first and fourth columns "") print(arra_data[:, [0,3]]) " 456,Write a Python program to check whether it follows the sequence given in the patterns array. ,"def is_samePatterns(colors, patterns): if len(colors) != len(patterns): return False sdict = {} pset = set() sset = set() for i in range(len(patterns)): pset.add(patterns[i]) sset.add(colors[i]) if patterns[i] not in sdict.keys(): sdict[patterns[i]] = [] keys = sdict[patterns[i]] keys.append(colors[i]) sdict[patterns[i]] = keys if len(pset) != len(sset): return False for values in sdict.values(): for i in range(len(values) - 1): if values[i] != values[i+1]: return False return True print(is_samePatterns([""red"", ""green"", ""green""], [""a"", ""b"", ""b""])) print(is_samePatterns([""red"", ""green"", ""greenn""], [""a"", ""b"", ""b""])) " 457,"Write a Python program to create a dictionary of keys x, y, and z where each key has as value a list from 11-20, 21-30, and 31-40 respectively. Access the fifth value of each key from the dictionary. ","from pprint import pprint dict_nums = dict(x=list(range(11, 20)), y=list(range(21, 30)), z=list(range(31, 40))) pprint(dict_nums) print(dict_nums[""x""][4]) print(dict_nums[""y""][4]) print(dict_nums[""z""][4]) for k,v in dict_nums.items(): print(k, ""has value"", v) " 458,Write a Pandas program to create a yearly time period from a specified year and display the properties of this period. ,"import pandas as pd ytp = pd.Period('2020','A-DEC') print(""Yearly time perid:"",ytp) print(""\nAll the properties of the said period:"") print(dir(ytp)) " 459,Write a Python program to set the indentation of the first line. ,"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. ''' text1 = textwrap.dedent(sample_text).strip() print() print(textwrap.fill(text1, initial_indent='', subsequent_indent=' ' * 4, width=80, )) print() " 460,Write a NumPy program to reverse an array (first element becomes last). ,"import numpy as np import numpy as np x = np.arange(12, 38) print(""Original array:"") print(x) print(""Reverse array:"") x = x[::-1] print(x) " 461,Write a Python program to display the examination schedule. (extract the date from exam_st_date). ,"exam_st_date = (11,12,2014) print( ""The examination will start from : %i / %i / %i""%exam_st_date) " 462,Write a Python program to count number of non-empty substrings of a given string. ,"def number_of_substrings(str): str_len = len(str); return int(str_len * (str_len + 1) / 2); str1 = input(""Input a string: "") print(""Number of substrings:"") print(number_of_substrings(str1)) " 463,Write a Pandas program to change the order of index of a given series. ,"import pandas as pd s = pd.Series(data = [1,2,3,4,5], index = ['A', 'B', 'C','D','E']) print(""Original Data Series:"") print(s) s = s.reindex(index = ['B','A','C','D','E']) print(""Data Series after changing the order of index:"") print(s) " 464,Write a NumPy program to compute the cross product of two given vectors. ,"import numpy as np p = [[1, 0], [0, 1]] q = [[1, 2], [3, 4]] print(""original matrix:"") print(p) print(q) result1 = np.cross(p, q) result2 = np.cross(q, p) print(""cross product of the said two vectors(p, q):"") print(result1) print(""cross product of the said two vectors(q, p):"") print(result2) " 465,Write a Python program to remove None value from a given list. ,"def remove_none(nums): result = [x for x in nums if x is not None] return 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)) " 466,Write a Python program to print a nested lists (each list on a new line) using the print() function. ,"colors = [['Red'], ['Green'], ['Black']] print('\n'.join([str(lst) for lst in colors])) " 467,Write a Python program to search a specific item in a given doubly linked list and return true if the item is found otherwise return false. ,"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 search_item(self, val): for node in self.iter(): if val == node: return True return False 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(""\n"") if items.search_item('SQL'): print(""True"") else: print(""False"") if items.search_item('C+'): print(""True"") else: print(""False"") " 468,Write a NumPy program to convert (in sequence depth wise (along third axis)) two 1-D arrays into a 2-D array. ,"import numpy as np a = np.array([[10],[20],[30]]) b = np.array([[40],[50],[60]]) c = np.dstack((a, b)) print(c) " 469,Write a Pandas program to check whether two given words present in a 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': ['9910 Surrey Ave.','92 N. Bishop Ave.','9910 Golden Star Ave.', '102 Dunbar St.', '17 West Livingston Court'] }) print(""Original DataFrame:"") print(df) def test_and_cond(text): result = re.findall(r'(?=.*Ave.)(?=.*9910).*', text) return "" "".join(result) df['check_two_words']=df['address'].apply(lambda x : test_and_cond(x)) print(""\nPresent two words!"") print(df) " 470,Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module. ,"from collections import defaultdict def grouping_dictionary(l): d = defaultdict(list) for k, v in l: d[k].append(v) return d 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)) " 471,"Write a NumPy program to test element-wise for complex number, real number of a given array. Also test whether a given number is a scalar type or not. ","import numpy as np a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j]) print(""Original array"") print(a) print(""Checking for complex number:"") print(np.iscomplex(a)) print(""Checking for real number:"") print(np.isreal(a)) print(""Checking for scalar type:"") print(np.isscalar(3.1)) print(np.isscalar([3.1])) " 472,Write a Pandas program to create a time series object with a time zone. ,"import pandas as pd print(""Timezone: Europe/Berlin:"") print(""Using pytz:"") date_pytz = pd.Timestamp('2019-01-01', tz = 'Europe/Berlin') print(date_pytz.tz) print(""Using dateutil:"") date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/Europe/Berlin') print(date_util.tz) print(""\nUS/Pacific:"") print(""Using pytz:"") date_pytz = pd.Timestamp('2019-01-01', tz = 'US/Pacific') print(date_pytz.tz) print(""Using dateutil:"") date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/US/Pacific') print(date_util.tz) " 473,Write a NumPy program to check whether a Numpy array contains a specified row. ,"import numpy as np num = np.arange(20) arr1 = np.reshape(num, [4, 5]) print(""Original array:"") print(arr1) print([0, 1, 2, 3, 4] in arr1.tolist()) print([0, 1, 2, 3, 5] in arr1.tolist()) print([15, 16, 17, 18, 19] in arr1.tolist()) " 474,Write a NumPy program to check whether the NumPy array is empty or not. ,"import numpy as np x = np.array([2, 3]) y = np.array([]) # size 2, array is not empty print(x.size) # size 0, array is empty print(y.size) " 475,Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). ,"items = input(""Input comma separated sequence of words"") words = [word for word in items.split("","")] print("","".join(sorted(list(set(words))))) " 476,Write a Python program to set a new value of an 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 def __setitem__(self, index, value): if index > self.count - 1: raise Exception(""Index out of range."") current = self.tail for n in range(index): current = current.next current.data = value 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(""Modify items by index:"") items[1] = ""SQL"" print(""New value: "",items[1]) items[4] = ""Perl"" print(""New value: "",items[4]) " 477,Write a Python program to update a specific column value of a given table and select all rows before and after updating the said 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 commission .15 to .45 where id is 5003:"") sql_update_query = """"""Update salesman set commission = .45 where salesman_id = 5003"""""" 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."") " 478,Write a Python program to find the k,"class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def kth_smallest(root, k): stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if k == 0: break root = root.right return root.val root = TreeNode(8) root.left = TreeNode(5) root.right = TreeNode(14) root.left.left = TreeNode(4) root.left.right = TreeNode(6) root.left.right.left = TreeNode(8) root.left.right.right = TreeNode(7) root.right.right = TreeNode(24) root.right.right.left = TreeNode(22) print(kth_smallest(root, 2)) print(kth_smallest(root, 3)) " 479,Write a Pandas program to count year-country wise frequency of 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()) df['Year'] = df['Date_time'].apply(lambda x: ""%d"" % (x.year)) result = df.groupby(['Year', 'country']).size() print(""\nCountry-year wise frequency of reporting dates of UFO:"") print(result) " 480,Write a Python program to create an iterator that returns consecutive keys and groups from an iterable. ,"import itertools as it print(""Iterate over characters of a string and display\nconsecutive keys and groups from the iterable:"") str1 = 'AAAAJJJJHHHHNWWWEERRRSSSOOIIU' data_groupby = it.groupby(str1) for key, group in data_groupby: print('Key:', key) print('Group:', list(group)) print(""\nIterate over elements of a list and display\nconsecutive keys and groups from the iterable:"") str1 = 'AAAAJJJJHHHHNWWWEERRRSSSOOIIU' str1 = [1,2,2,3,4,4,5,5,5,6,6,7,7,7,8] data_groupby = it.groupby(str1) for key, group in data_groupby: print('Key:', key) print('Group:', list(group)) " 481,Write a Python program to remove all the elements of a given deque object. ,"import collections odd_nums = (1,3,5,7,9) odd_deque = collections.deque(odd_nums) print(""Original Deque object with odd numbers:"") print(odd_deque) print(""Deque length: %d""%(len(odd_deque))) odd_deque.clear() print(""Deque object after removing all numbers-"") print(odd_deque) print(""Deque length:%d""%(len(odd_deque))) " 482,"Write a NumPy program to create an array of 4,5 shape and swap column1 with column4. ","import numpy as np array_nums = np.arange(20).reshape(4,5) print(""Original array:"") print(array_nums) print(""\nAfter swapping column1 with column4:"") array_nums[:,[0,3]] = array_nums[:,[3,0]] print(array_nums) " 483,Write a Pandas program to create a TimeSeries to display all the Sundays of given year. ,"import pandas as pd result = pd.Series(pd.date_range('2020-01-01', periods=52, freq='W-SUN')) print(""All Sundays of 2019:"") print(result) " 484,Write a Python function that takes a list and returns a new list with unique elements of the first list. ,"def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x print(unique_list([1,2,3,3,3,3,4,5])) " 485,Write a Python program to write a Python dictionary to a csv file. After writing the CSV file read the CSV file and display the content. ,"import csv csv_columns = ['id','Column1', 'Column2', 'Column3', 'Column4', 'Column5'] dict_data = {'id':['1', '2', '3'], 'Column1':[33, 25, 56], 'Column2':[35, 30, 30], 'Column3':[21, 40, 55], 'Column4':[71, 25, 55], 'Column5':[10, 10, 40], } csv_file = ""temp.csv"" try: with open(csv_file, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(dict_data) except IOError: print(""I/O error"") data = csv.DictReader(open(csv_file)) print(""CSV file as a dictionary:\n"") for row in data: print(row) " 486,"Write a Python program to find the indices of elements of a given list, greater than a specified value. ","def test(lst, value): result = [i for i,val in enumerate(lst) if val > value] return result nums = [1234, 1522, 1984, 19372, 1000, 2342, 7626] print(""\nOriginal list:"") print(nums) val = 3000 print(""Indices of elements of the said list, greater than"",val) print(test(nums,val)) nums = [1234, 1522, 1984, 19372, 1000, 2342, 7626] print(""\nOriginal list:"") print(nums) val = 20000 print(""Indices of elements of the said list, greater than"",val) print(test(nums,val)) " 487,Write a NumPy program to test whether each element of a 1-D array is also present in a second array. ,"import numpy as np array1 = np.array([0, 10, 20, 40, 60]) print(""Array1: "",array1) array2 = [0, 40] print(""Array2: "",array2) print(""Compare each element of array1 and array2"") print(np.in1d(array1, array2)) " 488,"Write a Python program to determine the largest and smallest integers, longs, floats. ","import sys print(""Float value information: "",sys.float_info) print(""\nInteger value information: "",sys.int_info) print(""\nMaximum size of an integer: "",sys.maxsize) " 489,Write a Pandas program to extract numbers greater than 940 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.1111','920 N. Bishop Ave.','9910 Golden Star St.', '1025 Dunbar St.', '1700 West Livingston Court'] }) print(""Original DataFrame:"") print(df) def test_num_great(text): result = re.findall(r'95[5-9]|9[6-9]\d|[1-9]\d{3,}',text) return "" "".join(result) df['num_great']=df['address'].apply(lambda x : test_num_great(x)) print(""\nNumber greater than 940:"") print(df) " 490,"Write a Python program to print a long text, convert the string to a list and print all the words and their frequencies. ","string_words = '''United States Declaration of Independence From Wikipedia, the free encyclopedia The United States Declaration of Independence is the statement adopted by the Second Continental Congress meeting at the Pennsylvania State House (Independence Hall) in Philadelphia on July 4, 1776, which announced that the thirteen American colonies, then at war with the Kingdom of Great Britain, regarded themselves as thirteen independent sovereign states, no longer under British rule. These states would found a new nation – the United States of America. John Adams was a leader in pushing for independence, which was passed on July 2 with no opposing vote cast. A committee of five had already drafted the formal declaration, to be ready when Congress voted on independence. John Adams persuaded the committee to select Thomas Jefferson to compose the original draft of the document, which Congress would edit to produce the final version. The Declaration was ultimately a formal explanation of why Congress had voted on July 2 to declare independence from Great Britain, more than a year after the outbreak of the American Revolutionary War. The next day, Adams wrote to his wife Abigail: ""The Second Day of July 1776, will be the most memorable Epocha, in the History of America."" But Independence Day is actually celebrated on July 4, the date that the Declaration of Independence was approved. After ratifying the text on July 4, Congress issued the Declaration of Independence in several forms. It was initially published as the printed Dunlap broadside that was widely distributed and read to the public. The source copy used for this printing has been lost, and may have been a copy in Thomas Jefferson's hand.[5] Jefferson's original draft, complete with changes made by John Adams and Benjamin Franklin, and Jefferson's notes of changes made by Congress, are preserved at the Library of Congress. The best-known version of the Declaration is a signed copy that is displayed at the National Archives in Washington, D.C., and which is popularly regarded as the official document. This engrossed copy was ordered by Congress on July 19 and signed primarily on August 2. The sources and interpretation of the Declaration have been the subject of much scholarly inquiry. The Declaration justified the independence of the United States by listing colonial grievances against King George III, and by asserting certain natural and legal rights, including a right of revolution. Having served its original purpose in announcing independence, references to the text of the Declaration were few in the following years. Abraham Lincoln made it the centerpiece of his rhetoric (as in the Gettysburg Address of 1863) and his policies. Since then, it has become a well-known statement on human rights, particularly its second sentence: We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. This has been called ""one of the best-known sentences in the English language"", containing ""the most potent and consequential words in American history"". The passage came to represent a moral standard to which the United States should strive. This view was notably promoted by Abraham Lincoln, who considered the Declaration to be the foundation of his political philosophy and argued that it is a statement of principles through which the United States Constitution should be interpreted. The U.S. Declaration of Independence inspired many other similar documents in other countries, the first being the 1789 Declaration of Flanders issued during the Brabant Revolution in the Austrian Netherlands (modern-day Belgium). It also served as the primary model for numerous declarations of independence across Europe and Latin America, as well as Africa (Liberia) and Oceania (New Zealand) during the first half of the 19th century.''' word_list = string_words.split() word_freq = [word_list.count(n) for n in word_list] print(""String:\n {} \n"".format(string_words)) print(""List:\n {} \n"".format(str(word_list))) print(""Pairs (Words and Frequencies:\n {}"".format(str(list(zip(word_list, word_freq))))) " 491,Write a Pandas program to extract numbers less than 100 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': ['72 Surrey Ave.11','92 N. Bishop Ave.','9910 Golden Star St.', '102 Dunbar St.', '17 West Livingston Court'] }) print(""Original DataFrame:"") print(df) def test_num_less(n): nums = [] for i in n.split(): result = re.findall(r'\b(0*(?:[1-9][0-9]?|100))\b',i) nums.append(result) all_num=["","".join(x) for x in nums if x != []] return "" "".join(all_num) df['num_less'] = df['address'].apply(lambda x : test_num_less(x)) print(""\nNumber less than 100:"") print(df) " 492,Write a Pandas program to split the following dataframe into groups and count unique values of 'value' column. ,"import pandas as pd df = pd.DataFrame({ 'id': [1, 1, 2, 3, 3, 4, 4, 4], 'value': ['a', 'a', 'b', None, 'a', 'a', None, 'b'] }) print(""Original DataFrame:"") print(df) print(""Count unique values:"") print (df.groupby('value')['id'].nunique()) " 493,"Write a Python program to compute the sum of elements of a given array of integers, use map() function. ","from array import array def array_sum(nums_arr): sum_n = 0 for n in nums_arr: sum_n += n return sum_n nums = array('i', [1, 2, 3, 4, 5, -15]) print(""Original array:"",nums) nums_arr = list(map(int, nums)) result = array_sum(nums_arr) print(""Sum of all elements of the said array:"") print(result) " 494,Write a Python program to convert a given string into a list of words. ,"str1 = ""The quick brown fox jumps over the lazy dog."" print(str1.split(' ')) str1 = ""The-quick-brown-fox-jumps-over-the-lazy-dog."" print(str1.split('-')) " 495,Write a Python program to display a given decimal value in scientific notation. Use decimal.Decimal,"import decimal #Source: https://bit.ly/2SfZEtL def format_e(n): a = '%E' % n return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1] print(""Original decimal value: ""+ ""40800000000.00000000000000"") print(""Scientific notation of the said decimal value:"") print(format_e(decimal.Decimal('40800000000.00000000000000'))) print(""\nOriginal decimal value: ""+ ""40000000000.00000000000000"") print(""Scientific notation of the said decimal value:"") print(format_e(decimal.Decimal('40000000000.00000000000000'))) print(""\nOriginal decimal value: ""+ ""40812300000.00000000000000"") print(""Scientific notation of the said decimal value:"") print(format_e(decimal.Decimal('40812300000.00000000000000'))) " 496,Write a Python program to create a list by concatenating a given list which range goes from 1 to n. ,"my_list = ['p', 'q'] n = 4 new_list = ['{}{}'.format(x, y) for y in range(1, n+1) for x in my_list] print(new_list) " 497,Write a Python program to find the index of an item in a specified list. ,"num =[10, 30, 4, -6] print(num.index(30)) " 498,Write a Pandas program to generate time series combining day and intraday offsets intervals. ,"import pandas as pd dateset1 = pd.date_range('2029-01-01 00:00:00', periods=20, freq='3h10min') print(""Time series with frequency 3h10min:"") print(dateset1) dateset2 = pd.date_range('2029-01-01 00:00:00', periods=20, freq='1D10min20U') print(""\nTime series with frequency 1 day 10 minutes and 20 microseconds:"") print(dateset2) " 499,Write a Python program to print the following integers with zeros on the left of specified width. ,"x = 3 y = 123 print(""\nOriginal Number: "", x) print(""Formatted Number(left padding, width 2): ""+""{:0>2d}"".format(x)); print(""Original Number: "", y) print(""Formatted Number(left padding, width 6): ""+""{:0>6d}"".format(y)); print() " 500,Write a Python program to extract characters from various text files and puts them into a list. ,"import glob char_list = [] files_list = glob.glob(""*.txt"") for file_elem in files_list: with open(file_elem, ""r"") as f: char_list.append(f.read()) print(char_list) " 501,Write a Python program to add two given lists using map and lambda. ,"nums1 = [1, 2, 3] nums2 = [4, 5, 6] print(""Original list:"") print(nums1) print(nums2) result = map(lambda x, y: x + y, nums1, nums2) print(""\nResult: after adding two list"") print(list(result)) " 502,Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included). ,"def printValues(): l = list() for i in range(1,21): l.append(i**2) print(l[:5]) print(l[-5:]) printValues() " 503,Write a NumPy program to extract all the rows from a given array 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'], ['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) char='E' result = student[np.char.startswith(student[:,2], char)] print(""\nStudent name starting with"",char,"":"") print(result) char='1' result = student[np.char.startswith(student[:,0], char)] print(""\nStudent id starting with"",char,"":"") print(result) " 504,Write a Python program to square the elements of a list using map() function. ,"def square_num(n): return n * n nums = [4, 5, 2, 9] print(""Original List: "",nums) result = map(square_num, nums) print(""Square the elements of the said list using map():"") print(list(result)) " 505,Write a Python program to read a file line by line and store it into a list. ,"def file_read(fname): with open(fname) as f: #Content_list is the list that contains the read lines. content_list = f.readlines() print(content_list) file_read(\'test.txt\') " 506,Write a Python program to read a file line by line store it into an array. ,"def file_read(fname): content_array = [] with open(fname) as f: #Content_list is the list that contains the read lines. for line in f: content_array.append(line) print(content_array) file_read('test.txt') " 507,Write a Python program that takes a text file as input and returns the number of words of a given text file. ,"def count_words(filepath): with open(filepath) as f: data = f.read() data.replace("","", "" "") return len(data.split("" "")) print(count_words(""words.txt"")) " 508,Write a Python program for nth Catalan Number. ,"def catalan_number(num): if num <=1: return 1 res_num = 0 for i in range(num): res_num += catalan_number(i) * catalan_number(num-i-1) return res_num for n in range(10): print(catalan_number(n)) " 509,Write a Python program to get the total length of all values of a given dictionary with string values. ,"def test(dictt): result = sum((len(values) for values in dictt.values())) return result color = {'#FF0000':'Red', '#800000':'Maroon', '#FFFF00':'Yellow', '#808000':'Olive'} print(""\nOriginal dictionary:"") print(color) print(""\nTotal length of all values of the said dictionary with string values:"") print(test(color)) " 510,Write a Pandas program to convert 1,"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], 't_id': ['t1', 't2', 't3', 't4', 't5', 't6']}) print(""Original DataFrame:"") print(df) print(""\nMultiIndex using columns 't_id', ‘school_code’ and 'class':"") df1 = df.set_index(['t_id', 'school_code', 'class']) print(df1) print(""\nConvert 1st and 3rd levels in the index frame into columns:"") df2 = df1.reset_index(level=['t_id', 'class']) print(df2) " 511,Write a Python program to access a function inside a function. ,"def test(a): def add(b): nonlocal a a += 1 return a+b return add func= test(4) print(func(4)) " 512,Write a Python program to filter a list of integers using Lambda. ,"nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(""Original list of integers:"") print(nums) print(""\nEven numbers from the said list:"") even_nums = list(filter(lambda x: x%2 == 0, nums)) print(even_nums) print(""\nOdd numbers from the said list:"") odd_nums = list(filter(lambda x: x%2 != 0, nums)) print(odd_nums) " 513,"Write a Pandas program to find out the 'WHO region, 'Country', 'Beverage Types' in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' from the world alcohol consumption dataset. ","import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print(""World alcohol consumption sample data:"") print(w_a_con.head()) print(""\nThe world alcohol consumption details ('WHO region','Country','Beverage Types') \nin the year ‘1986’ or ‘1989’ where WHO region is ‘Americas’ or 'Europe':"") print(w_a_con[((w_a_con['Year']==1985) | (w_a_con['Year']==1989)) & ((w_a_con['WHO region']=='Americas') | (w_a_con['WHO region']=='Europe'))][['WHO region','Country','Beverage Types']].head(10)) " 514,Write a Python program to construct a Decimal from a float and a Decimal from a string. Also represent the Decimal value as a tuple. Use decimal.Decimal,"import decimal print(""Construct a Decimal from a float:"") pi_val = decimal.Decimal(3.14159) print(pi_val) print(pi_val.as_tuple()) print(""\nConstruct a Decimal from a string:"") num_str = decimal.Decimal(""123.25"") print(num_str) print(num_str.as_tuple()) " 515,Write a Python program to remove all duplicate elements from a given array and returns a new array. ,"import array as arr def test(nums): return sorted(set(nums),key=nums.index) array_num = arr.array('i', [1, 3, 5, 1, 3, 7, 9]) print(""Original array:"") for i in range(len(array_num)): print(array_num[i], end=' ') print(""\nAfter removing duplicate elements from the said array:"") result = arr.array('i', test(array_num)) for i in range(len(result)): print(result[i], end=' ') array_num = arr.array('i', [2, 4, 2, 6, 4, 8]) print(""\nOriginal array:"") for i in range(len(array_num)): print(array_num[i], end=' ') print(""\nAfter removing duplicate elements from the said array:"") result = arr.array('i', test(array_num)) for i in range(len(result)): print(result[i], end=' ') " 516,Write a Pandas program to find and replace the missing values in a given DataFrame which do not have any valuable information. ,"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,""--"",70010,70003,70012,np.nan,70013], 'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,""?"",12.43,2480.4,250.45, 3045.6], 'ord_date': ['?','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,""--"",3002,3001,3001], 'salesman_id':[5002,5003,""?"",5001,np.nan,5002,5001,""?"",5003,5002,5003,""--""]}) print(""Original Orders DataFrame:"") print(df) print(""\nReplace the missing values with NaN:"") result = df.replace({""?"": np.nan, ""--"": np.nan}) print(result) " 517,Write a Python program to find the index of the last element in the given list that satisfies the provided testing function. ,"def find_last_index(lst, fn): return len(lst) - 1 - next(i for i, x in enumerate(lst[::-1]) if fn(x)) print(find_last_index([1, 2, 3, 4], lambda n: n % 2 == 1)) " 518,Write a Python program to iterate over all pairs of consecutive items in a given list. ,"def pairwise(l1): temp = [] for i in range(len(l1) - 1): current_element, next_element = l1[i], l1[i + 1] x = (current_element, next_element) temp.append(x) return temp l1 = [1,1,2,3,3,4,4,5] print(""Original lists:"") print(l1) print(""\nIterate over all pairs of consecutive items of the said list:"") print(pairwise(l1)) " 519,Write a Python program to create a list with the non-unique values filtered out. ,"from collections import Counter def filter_non_unique(lst): return [item for item, count in Counter(lst).items() if count == 1] print(filter_non_unique([1, 2, 2, 3, 4, 4, 5])) " 520,Write a Python program to find the second smallest number in a list. ,"def second_smallest(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[1] print(second_smallest([1, 2, -8, -2, 0, -2])) print(second_smallest([1, 1, 0, 0, 2, -2, -2])) print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2])) print(second_smallest([2,2])) print(second_smallest([2])) " 521,"Write a Python program to create a deque and append few elements to the left and right, then remove some elements from the left, right sides and reverse the deque. ","import collections # Create a deque deque_colors = collections.deque([""Red"",""Green"",""White""]) print(deque_colors) # Append to the left print(""\nAdding to the left: "") deque_colors.appendleft(""Pink"") print(deque_colors) # Append to the right print(""\nAdding to the right: "") deque_colors.append(""Orange"") print(deque_colors) # Remove from the right print(""\nRemoving from the right: "") deque_colors.pop() print(deque_colors) # Remove from the left print(""\nRemoving from the left: "") deque_colors.popleft() print(deque_colors) # Reverse the dequeue print(""\nReversing the deque: "") deque_colors.reverse() print(deque_colors) " 522,Write a Python program to count float number in a given mixed list using lambda. ,"def count_integer(list1): ert = list(map(lambda i: isinstance(i, float), list1)) result = len([e for e in ert if e]) return result list1 = [1, 'abcd', 3.12, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22] print(""Original list:"") print(list1) print(""\nNumber of floats in the said mixed list:"") print(count_integer(list1)) " 523,Write a NumPy program to compute the histogram of nums against the bins. ,"import numpy as np import matplotlib.pyplot as plt nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1]) bins = np.array([0, 1, 2, 3]) print(""nums: "",nums) print(""bins: "",bins) print(""Result:"", np.histogram(nums, bins)) plt.hist(nums, bins=bins) plt.show() " 524,Write a Python program to extract numbers from a given string. ,"def test(str1): result = [int(str1) for str1 in str1.split() if str1.isdigit()] return result str1 = ""red 12 black 45 green"" print(""Original string:"", str1) print(""Extract numbers from the said string:"") print(test(str1)) " 525,Write a Pandas program to partition each of the passengers into four categories based on their age. ,"import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = pd.cut(df['age'], [0, 10, 30, 60, 80]) print(result) " 526,"Write a NumPy program to fetch all items from a given array of 4,5 shape which are either greater than 6 and a multiple of 3. ","import numpy as np array_nums1 = np.arange(20).reshape(4,5) print(""Original arrays:"") print(array_nums1) result = array_nums1[(array_nums1>6) & (array_nums1%3==0)] print(""\nItems greater than 6 and a multiple of 3 of the said array:"") print(result) " 527,Write a Python program to find smallest window that contains all characters of a given string. ,"from collections import defaultdict def find_sub_string(str): str_len = len(str) # Count all distinct characters. dist_count_char = len(set([x for x in str])) ctr, start_pos, start_pos_index, min_len = 0, 0, -1, 9999999999 curr_count = defaultdict(lambda: 0) for i in range(str_len): curr_count[str[i]] += 1 if curr_count[str[i]] == 1: ctr += 1 if ctr == dist_count_char: while curr_count[str[start_pos]] > 1: if curr_count[str[start_pos]] > 1: curr_count[str[start_pos]] -= 1 start_pos += 1 len_window = i - start_pos + 1 if min_len > len_window: min_len = len_window start_pos_index = start_pos return str[start_pos_index: start_pos_index + min_len] str1 = ""asdaewsqgtwwsa"" print(""Original Strings:\n"",str1) print(""\nSmallest window that contains all characters of the said string:"") print(find_sub_string(str1)) " 528,Write a Python program to find the years where 25th of December be a Sunday between 2000 and 2150. ,"'''Days of the week''' # Source:https://bit.ly/30NoXF8 from datetime import date from itertools import islice # xmasIsSunday :: Int -> Bool def xmasIsSunday(y): '''True if Dec 25 in the given year is a Sunday.''' return 6 == date(y, 12, 25).weekday() # main :: IO () def main(): '''Years between 2000 and 2150 with 25 December on a Sunday''' xs = list(filter( xmasIsSunday, enumFromTo(2000)(2150) )) total = len(xs) print( fTable(main.__doc__ + ':\n\n' + '(Total ' + str(total) + ')\n')( lambda i: str(1 + i) )(str)(index(xs))( enumFromTo(0)(total - 1) ) ) # GENERIC ------------------------------------------------- # enumFromTo :: (Int, Int) -> [Int] def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: list(range(m, 1 + n)) # index (!!) :: [a] -> Int -> a def index(xs): '''Item at given (zero-based) index.''' return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, ""__getitem__"") ) else next(islice(xs, n, None)) ) # unlines :: [String] -> String def unlines(xs): '''A single string formed by the intercalation of a list of strings with the newline character. ''' return '\n'.join(xs) # FORMATTING --------------------------------------------- # fTable :: String -> (a -> String) -> # (b -> String) -> (a -> b) -> [a] -> String def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) # MAIN -- if __name__ == '__main__': main() " 529,Write a Python program to accept a filename from the user and print the extension of that. ,"filename = input(""Input the Filename: "") f_extns = filename.split(""."") print (""The extension of the file is : "" + repr(f_extns[-1])) " 530,Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it. ,"import numpy as np import os x = np.arange(10) y = np.arange(11, 20) print(""Original arrays:"") print(x) print(y) np.savez('temp_arra.npz', x=x, y=y) print(""Load arrays from the 'temp_arra.npz' file:"") with np.load('temp_arra.npz') as data: x2 = data['x'] y2 = data['y'] print(x2) print(y2) " 531,Write a Python program to swap two sublists in a given list. ,"nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print(""Original list:"") print(nums) nums[6:10], nums[1:3] = nums[1:3], nums[6:10] print(""\nSwap two sublists of the said list:"") print(nums) nums[1:3], nums[4:6] = nums[4:6], nums[1:3] print(""\nSwap two sublists of the said list:"") print(nums) " 532,Write a Pandas program to convert a specified character column in upper/lower cases 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] }) df1 = 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(""\nUpper cases in comapny_code:"") df['upper_company_code'] = list(map(lambda x: x.upper(), df['company_code'])) print(df) print(""\nLower cases in comapny_code:"") df1['lower_company_code'] = list(map(lambda x: x.lower(), df1['company_code'])) print(df1) " 533,Write a NumPy program to stack 1-D arrays as columns wise. ,"import numpy as np print(""\nOriginal arrays:"") x = np.array((1,2,3)) y = np.array((2,3,4)) print(""Array-1"") print(x) print(""Array-2"") print(y) new_array = np.column_stack((x, y)) print(""\nStack 1-D arrays as columns wise:"") print(new_array) " 534,Write a NumPy program to get the lower-triangular L in the Cholesky decomposition of a given array. ,"import numpy as np a = np.array([[4, 12, -16], [12, 37, -53], [-16, -53, 98]], dtype=np.int32) print(""Original array:"") print(a) L = np.linalg.cholesky(a) print(""Lower-trianglular L in the Cholesky decomposition of the said array:"") print(L) " 535,Write a Python program to get the unique values in a given list of lists. ,"def unique_values_in_list_of_lists(lst): result = set(x for l in lst for x in l) return list(result) nums = [[1,2,3,5], [2,3,5,4], [0,5,4,1], [3,7,2,1], [1,2,1,2]] print(""Original list:"") print(nums) print(""Unique values of the said list of lists:"") print(unique_values_in_list_of_lists(nums)) chars = [['h','g','l','k'], ['a','b','d','e','c'], ['j','i','y'], ['n','b','v','c'], ['x','z']] print(""\nOriginal list:"") print(chars) print(""Unique values of the said list of lists:"") print(unique_values_in_list_of_lists(chars)) " 536,Write a NumPy program to compute the condition number of a given matrix. ,"import numpy as np m = np.array([[1,2],[3,4]]) print(""Original matrix:"") print(m) result = np.linalg.cond(m) print(""Condition number of the said matrix:"") print(result) " 537,"Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary. ","import itertools d ={'1':['a','b'], '2':['c','d']} for combo in itertools.product(*[d[k] for k in sorted(d.keys())]): print(''.join(combo)) " 538,Write a Pandas program to filter the specified columns and records by range 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(""\nFiltering records by label or index:"") print(w_a_con.loc[0:4, [""WHO region"", ""Beverage Types""]]) " 539,Write a NumPy program to create a new array which is the average of every consecutive triplet of elements of a given array. ,"import numpy as np arr1 = np.array([1,2,3, 2,4,6, 1,2,12, 0,-12,6]) print(""Original array:"") print(arr1) result = np.mean(arr1.reshape(-1, 3), axis=1) print(""Average of every consecutive triplet of elements of the said array:"") print(result) " 540,"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) " 541,Write a Pandas program to get the length of the integer 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 sale_amount:"") df['sale_amount_length'] = df['sale_amount'].map(str).apply(len) print(df) " 542,"Write a Python program to get information about the file pertaining to the file mode. Print the information - ID of device containing file, inode number, protection, number of hard links, user ID of owner, group ID of owner, total size (in bytes), time of last access, time of last modification and time of last status change. ","import os path = 'e:\\testpath\\p.txt' fd = os.open(path, os.O_RDWR) info = os.fstat(fd) print (f""ID of device containing file: {info.st_dev}"") print (f""Inode number: {info.st_ino}"") print (f""Protection: {info.st_mode}"") print (f""Number of hard links: {info.st_nlink}"") print (f""User ID of owner: {info.st_uid}"") print (f""Group ID of owner: {info.st_gid}"") print (f""Total size, in bytes: {info.st_size}"") print (f""Time of last access: {info.st_atime}"") print (f""Time of last modification: {info.st_mtime }"") print (f""Time of last status change: {info.st_ctime }"") os.close( fd) " 543,Write a Python program to create a flat list of all the values in a flat dictionary. ,"def test(flat_dict): return list(flat_dict.values()) students = { 'Theodore': 19, 'Roxanne': 20, 'Mathew': 21, 'Betty': 20 } print(""\nOriginal dictionary elements:"") print(students) print(""\nCreate a flat list of all the values of the said flat dictionary:"") print(test(students)) " 544,rite a Python program to find numbers between 100 and 400 (both included) where each digit of a number is an even number. The numbers obtained should be printed in a comma-separated sequence.,"items = [] for i in range(100, 401): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0): items.append(s) print( "","".join(items)) " 545,Write a Python program to sort a list of dictionaries using Lambda. ,"models = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'Mi Max', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}] print(""Original list of dictionaries :"") print(models) sorted_models = sorted(models, key = lambda x: x['color']) print(""\nSorting the List of dictionaries :"") print(sorted_models) " 546,Write a NumPy program to normalize a 3x3 random matrix. ,"import numpy as np x= np.random.random((3,3)) print(""Original Array:"") print(x) xmax, xmin = x.max(), x.min() x = (x - xmin)/(xmax - xmin) print(""After normalization:"") print(x) " 547,Write a NumPy program to get the qr factorization of a given array. ,"import numpy as np a = np.array([[4, 12, -14], [12, 37, -53], [-14, -53, 98]], dtype=np.int32) print(""Original array:"") print(a) q, r = np.linalg.qr(a) print(""qr factorization of the said array:"") print( ""q=\n"", q, ""\nr=\n"", r) " 548,Write a Python program to print all permutations with given repetition number of characters of a given string. ,"from itertools import product def all_repeat(str1, rno): chars = list(str1) results = [] for c in product(chars, repeat = rno): results.append(c) return results print(all_repeat('xyz', 3)) print(all_repeat('xyz', 2)) print(all_repeat('abcd', 4)) " 549,Write a Python program to test if a variable is a list or tuple or a set. ,"#x = ['a', 'b', 'c', 'd'] #x = {'a', 'b', 'c', 'd'} x = ('tuple', False, 3.2, 1) if type(x) is list: print('x is a list') elif type(x) is set: print('x is a set') elif type(x) is tuple: print('x is a tuple') else: print('Neither a list or a set or a tuple.') " 550,Write a Python program to get all possible combinations of the elements of a given list using itertools module. ,"import itertools def combinations_list(list1): temp = [] for i in range(0,len(list1)+1): temp.append(list(itertools.combinations(list1,i))) return temp colors = ['orange', 'red', 'green', 'blue'] print(""Original list:"") print(colors) print(""\nAll possible combinations of the said list’s elements:"") print(combinations_list(colors)) " 551,Write a Pandas program to replace NaNs with a single constant value in specified columns in a 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(""\nReplace NaNs with a single constant value:"") result = df['ord_no'].fillna(0, inplace=False) print(result) " 552,Write a Python program to count the occurrences of the items in a given list using lambda. ,"def count_occurrences(nums): result = dict(map(lambda el : (el, list(nums).count(el)), nums)) return result nums = [3,4,5,8,0,3,8,5,0,3,1,5,2,3,4,2] print(""Original list:"") print(nums) print(""\nCount the occurrences of the items in the said list:"") print(count_occurrences(nums)) " 553,Write a NumPy program to generate an array of 15 random numbers from a standard normal distribution. ,"import numpy as np rand_num = np.random.normal(0,1,15) print(""15 random numbers from a standard normal distribution:"") print(rand_num) " 554,Write a Python program to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0). ,"def sum_series(n): if n < 1: return 0 else: return n + sum_series(n - 2) print(sum_series(6)) print(sum_series(10)) " 555,"Write a Pandas program to create a horizontal 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.barh(stacked=True) plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020 to 30-04-2020', fontsize=12, color='black') plt.show() " 556,Write a Pandas program to create a dataframe indexing by date and time. ,"import pandas as pd print(""Create a dataframe, indexing by date and time:"") dt_range = pd.date_range(start ='2020-05-12 07:10:10', freq ='S', periods = 10) df_dt = pd.DataFrame({""Sale_amt"":[100, 110, 117, 150, 112, 99, 129, 135, 140, 150]}, index = dt_range) print(df_dt) " 557,Write a Pandas program to create a time series object that has time indexed data. Also select the dates of same year and select the dates between certain dates. ,"import pandas as pd index = pd.DatetimeIndex(['2011-09-02', '2012-08-04', '2015-09-03', '2010-08-04', '2015-03-03', '2011-08-04', '2015-04-03', '2012-08-04']) s_dates = pd.Series([0, 1, 2, 3, 4, 5, 6, 7], index=index) print(""Time series object with indexed data:"") print(s_dates) print(""\nDates of same year:"") print(s_dates['2015']) print(""\nDates between 2012-01-01 and 2012-12-31"") print(s_dates['2012-01-01':'2012-12-31']) " 558,Write a NumPy program to remove the leading 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) lstripped_char = np.char.lstrip(x) print(""\nRemove the leading whitespaces : "", lstripped_char) " 559,Write a Python program to split a list into different variables. ,"color = [(""Black"", ""#000000"", ""rgb(0, 0, 0)""), (""Red"", ""#FF0000"", ""rgb(255, 0, 0)""), (""Yellow"", ""#FFFF00"", ""rgb(255, 255, 0)"")] var1, var2, var3 = color print(var1) print(var2) print(var3) " 560,Write a Python program to find the first two elements of a given list whose sum is equal to a given value. Use itertools module to solve the problem. ,"import itertools as it def sum_pairs_list(nums, n): for num2, num1 in list(it.combinations(nums[::-1], 2))[::-1]: if num2 + num1 == n: return [num1, num2] nums = [1,2,3,4,5,6,7] n = 10 print(""Original list:"",nums,"": Given value:"",n) print(""Sum of pair equal to "",n,""="",sum_pairs_list(nums,n)) nums = [1,2,-3,-4,-5,6,-7] n = -6 print(""Original list:"",nums,"": Given value:"",n) print(""Sum of pair equal to "",n,""="",sum_pairs_list(nums,n)) " 561,"Write a Pandas program to create an index labels by using 64-bit integers, using floating-point numbers in a given dataframe. ","import pandas as pd print(""Create an Int64Index:"") df_i64 = 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=[1, 2, 3, 4, 5, 6]) print(df_i64) print(""\nView the Index:"") print(df_i64.index) print(""\nFloating-point labels using Float64Index:"") df_f64 = 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=[.1, .2, .3, .4, .5, .6]) print(df_f64) print(""\nView the Index:"") print(df_f64.index) " 562,Write a NumPy program to convert a NumPy array into Python list structure. ,"import numpy as np x= np.arange(6).reshape(3, 2) print(""Original array elements:"") print(x) print(""Array to list:"") print(x.tolist()) " 563,Write a Python program to copy of a deque object and verify the shallow copying process. ,"import collections tup1 = (1,3,5,7,9) dq1 = collections.deque(tup1) dq2 = dq1.copy() print(""Content of dq1:"") print(dq1) print(""dq2 id:"") print(id(dq1)) print(""\nContent of dq2:"") print(dq2) print(""dq2 id:"") print(id(dq2)) print(""\nChecking the first element of dq1 and dq2 are shallow copies:"") print(id(dq1[0])) print(id(dq2[0])) " 564,Write a Python program to create an instance of an OrderedDict using a given dictionary. Sort the dictionary during the creation and print the members of the dictionary in reverse order. ,"from collections import OrderedDict dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376, 'Angola': 244} new_dict = OrderedDict(dict.items()) for key in new_dict: print (key, new_dict[key]) print(""\nIn reverse order:"") for key in reversed(new_dict): print (key, new_dict[key]) " 565,"Write a Python program to retrieve the HTML code of the title, its text, and the HTML code of its parent. ","import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print(""title"") print(soup.title) print(""title text"") print(soup.title.text) print(""Parent content of the title:"") print(soup.title.parent) " 566,Write a Python program to shuffle and print a specified list. ,"from random import shuffle color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] shuffle(color) print(color) " 567,Write a NumPy program to swap columns in a given array. ,"import numpy as np my_array = np.arange(12).reshape(3, 4) print(""Original array:"") print(my_array) my_array[:,[0, 1]] = my_array[:,[1, 0]] print(""\nAfter swapping arrays:"") print(my_array) " 568,Write a Pandas program to find out the alcohol consumption details in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' from the world alcohol consumption dataset. ,"import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print(""World alcohol consumption sample data:"") print(w_a_con.head()) print(""\nThe world alcohol consumption details in the year ‘1986’ or ‘1989’ where WHO region is ‘Americas’ or 'Europe':"") print(w_a_con[((w_a_con['Year']==1985) | (w_a_con['Year']==1989)) & ((w_a_con['WHO region']=='Americas') | (w_a_con['WHO region']=='Europe'))].head(10)) " 569,Write a NumPy program to remove a specific column from a given array. ,"import numpy as np nums = np.random.random((7, 5)) print(""Original array:"") print(nums) print(""\nDelete the first column of the said array:"") print(np.delete(nums, [0], axis=1)) print(""\nDelete the last column of the said array:"") print(np.delete(nums, [4], axis=1)) " 570,Write a Pandas program convert the first and last character of each word to upper case in each word of a given series. ,"import pandas as pd series1 = pd.Series(['php', 'python', 'java', 'c#']) print(""Original Series:"") print(series1) result = series1.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper()) print(""\nFirst and last character of each word to upper case:"") print(result) " 571,"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')) " 572,Write a NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10. ,"import numpy as np x = np.random.randint(0, 11, 5) print(""Vector of length 5 filled with arbitrary integers from 0 to 10:"") print(x) " 573,Write a Pandas program to insert a column in the sixth position of the said excel sheet and fill it with NaN values. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df.insert(3, ""column1"", np.nan) print(df.head) " 574,Write a Pandas program to sort a given Series. ,"import pandas as pd s = pd.Series(['100', '200', 'python', '300.12', '400']) print(""Original Data Series:"") print(s) new_s = pd.Series(s).sort_values() print(new_s) " 575,Write a Python program to add two positive integers without using the '+' operator. ,"def add_without_plus_operator(a, b): while b != 0: data = a & b a = a ^ b b = data << 1 return a print(add_without_plus_operator(2, 10)) print(add_without_plus_operator(-20, 10)) print(add_without_plus_operator(-10, -20)) " 576,Write a Pandas program to create a plot to present the number of unidentified flying object (UFO) reports per year. ,"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(""\nPlot to present the number unidentified flying objects (ufo) found year wise:"") df[""Year""] = df.Date_time.dt.year df.Year.value_counts().sort_index().plot(x=""Year"") " 577,Write a Python program to sort a list of elements using Comb sort. ,"def comb_sort(nums): shrink_fact = 1.3 gaps = len(nums) swapped = True i = 0 while gaps > 1 or swapped: gaps = int(float(gaps) / shrink_fact) swapped = False i = 0 while gaps + i < len(nums): if nums[i] > nums[i+gaps]: nums[i], nums[i+gaps] = nums[i+gaps], nums[i] swapped = True i += 1 return nums num1 = input('Input comma separated numbers:\n').strip() nums = [int(item) for item in num1.split(',')] print(comb_sort(nums)) " 578,Write a Python program to find maximum difference pair in a given list. ,"from itertools import combinations from heapq import nlargest def test(lst): result = nlargest(1, combinations(lst, 2), key=lambda sub: abs(sub[0] - sub[1])) return result marks = [32,14,90,10,22,42,31] print(""\nOriginal list:"") print(marks) print(""\nFind maximum difference pair of the said list:"") print(test(marks)) " 579,Write a Python program to move the specified number of elements to the end of the given list. ,"def move_end(nums, offset): return nums[offset:] + nums[:offset] print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 3)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -3)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 8)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -8)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 7)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -7)) " 580,Write a Python program to insert an element at the beginning of a given OrderedDictionary. ,"from collections import OrderedDict color_orderdict = OrderedDict([('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')]) print(""Original OrderedDict:"") print(color_orderdict) print(""Insert an element at the beginning of the said OrderedDict:"") color_orderdict.update({'color4':'Orange'}) color_orderdict.move_to_end('color4', last = False) print(""\nUpdated OrderedDict:"") print(color_orderdict) " 581,Write a Python program to print the following floating numbers upto 2 decimal places. ,"x = 3.1415926 y = 12.9999 print(""\nOriginal Number: "", x) print(""Formatted Number: ""+""{:.2f}"".format(x)); print(""Original Number: "", y) print(""Formatted Number: ""+""{:.2f}"".format(y)); print() " 582,Write a Python program to extract every first or specified element from a given two-dimensional list. ,"def specified_element(nums, N): result = [i[N] for i in nums] return result nums = [ [1,2,3,2], [4,5,6,2], [7,1,9,5], ] print(""Original list of lists:"") print(nums) N = 0 print(""\nExtract every first element from the said given two dimensional list:"") print(specified_element(nums, N)) N = 2 print(""\nExtract every third element from the said given two dimensional list:"") print(specified_element(nums, N)) " 583,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()) " 584,Write a Python program to iterate over dictionaries using for loops. ,"d = {'Red': 1, 'Green': 2, 'Blue': 3} for color_key, value in d.items(): print(color_key, 'corresponds to ', d[color_key]) " 585,Write a Python program to sort unsorted numbers using Stooge sort. ,"#Ref.https://bit.ly/3pk7iPH def stooge_sort(arr): stooge(arr, 0, len(arr) - 1) return arr def stooge(arr, i, h): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) lst = [4, 3, 5, 1, 2] print(""\nOriginal list:"") print(lst) print(""After applying Stooge sort the said list becomes:"") print(stooge_sort(lst)) lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print(""\nOriginal list:"") print(lst) print(""After applying Stooge sort the said list becomes:"") print(stooge_sort(lst)) lst = [1.1, 1, 0, -1, -1.1, .1] print(""\nOriginal list:"") print(lst) print(""After applying Stooge sort the said list becomes:"") print(stooge_sort(lst)) " 586,Write a Python program to rearrange positive and negative numbers in a given array using Lambda. ,"array_nums = [-1, 2, -3, 5, 7, 8, 9, -10] print(""Original arrays:"") print(array_nums) result = sorted(array_nums, key = lambda i: 0 if i == 0 else -1 / i) print(""\nRearrange positive and negative numbers of the said array:"") print(result) " 587,Write a Python program to perform an action if a condition is true. ,"n=1 if n == 1: print(""\nFirst day of a Month!"") print() " 588,Write a Python program to find the maximum length of a substring in a given string where all the characters of the substring are same. Use itertools module to solve the problem. ,"import itertools def max_sub_string(str1): return max(len(list(x)) for _, x in itertools.groupby(str1)) str1 = ""aaabbccddeeeee"" print(""Original string:"",str1) print(""Maximum length of a substring with unique characters of the said string:"") print(max_sub_string(str1)) str1 = ""c++ exercises"" print(""\nOriginal string:"",str1) print(""Maximum length of a substring with unique characters of the said string:"") print(max_sub_string(str1)) " 589,Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees where hire_date between two specific month and year. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') result = df[(df['hire_date'] >='Jan-2005') & (df['hire_date'] <= 'Dec-2006')].head() result " 590,Write a Python program to find the list of words that are longer than n from a given list of words. ,"def long_words(n, str): word_len = [] txt = str.split("" "") for x in txt: if len(x) > n: word_len.append(x) return word_len print(long_words(3, ""The quick brown fox jumps over the lazy dog"")) " 591,"Write a Python program to generate 26 text files named A.txt, B.txt, and so on up to Z.txt. ","import string, os if not os.path.exists(""letters""): os.makedirs(""letters"") for letter in string.ascii_uppercase: with open(letter + "".txt"", ""w"") as f: f.writelines(letter) " 592,Write a NumPy program to split a given text into lines and split the single line into array values. ,"import numpy as np student = """"""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 text:"") print(student) text_lines = student.splitlines() text_lines = [r.split('\t') for r in text_lines] result = np.array(text_lines, dtype=np.str) print(""\nArray from the said text:"") print(result) " 593,Write a Numpy program to test whether numpy array is faster than Python list or not. ,"import time import numpy as np SIZE = 200000 list1 = range(SIZE) list2 = range(SIZE) arra1 = np.arange(SIZE) arra2 = np.arange(SIZE) start_list = time.time() result=[(x,y) for x,y in zip(list1,list2)] print(""Time to aggregates elements from each of the iterables:"") print(""List:"") print((time.time()-start_list)*1000) start_array = time.time() result = arra1 + arra2 print(""NumPy array:"") print((time.time()-start_array)*1000) " 594,Write a Python program to insert an element in a given list after every nth position. ,"def insert_elemnt_nth(lst, ele, n): result = [] for st_idx in range(0, len(lst), n): result.extend(lst[st_idx:st_idx+n]) result.append(ele) result.pop() return result nums = [1,2,3,4,5,6,7,8,9,0] print(""Original list:"") print(nums) i_ele = 'a' i_ele_pos = 2 print(""\nInsert"",i_ele,""in the said list after"",i_ele_pos,""nd element:"") print(insert_elemnt_nth(nums, i_ele, i_ele_pos)) i_ele = 'b' i_ele_pos = 4 print(""\nInsert"",i_ele,""in the said list after"",i_ele_pos,""th element:"") print(insert_elemnt_nth(nums, i_ele, i_ele_pos)) " 595,"Write a NumPy program to create one-dimensional array of single, two and three digit numbers. ","import numpy as np nums = np.arange(1, 21) print(""One-dimensional array of single digit numbers:"") print(nums) nums = np.arange(10, 21) print(""\nOne-dimensional array of two digit numbers:"") print(nums) nums = np.arange(100, 201) print(""\nOne-dimensional array of three digit numbers:"") print(nums) " 596,Write a NumPy program to create an array of all the even integers from 30 to 70. ,"import numpy as np array=np.arange(30,71,2) print(""Array of all the even integers from 30 to 70"") print(array) " 597,"Write a Python program to get the symmetric difference between two iterables, without filtering out duplicate values. ","def symmetric_difference(x, y): (_x, _y) = (set(x), set(y)) return [item for item in x if item not in _y] + [item for item in y if item not in _x] print(symmetric_difference([10, 20, 30], [10, 20, 40])) " 598,Write a Python program to create a file and write some text and rename the file name. ,"import glob import os with open('a.txt', 'w') as f: f.write('Python program to create a symbolic link and read it to decide the original file pointed by the link.') print('\nInitial file/dir name:', os.listdir()) with open('a.txt', 'r') as f: print('\nContents of a.txt:', repr(f.read())) os.rename('a.txt', 'b.txt') print('\nAfter renaming initial file/dir name:', os.listdir()) with open('b.txt', 'r') as f: print('\nContents of b.txt:', repr(f.read())) " 599,Write a Python program to convert a given string to snake case. ,"from re import sub def snake_case(s): return '-'.join( sub(r""(\s|_|-)+"","" "", sub(r""[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+"", lambda mo: ' ' + mo.group(0).lower(), s)).split()) print(snake_case('JavaScript')) print(snake_case('GDScript')) print(snake_case('BTW...what *do* you call that naming style? snake_case? ')) " 600,"Write a NumPy program to find rows of a given array of shape (8,3) that contain elements of each row of another given array of shape (2,2). ","import numpy as np nums1 = np.random.randint(0,6,(6,4)) nums2 = np.random.randint(0,6,(2,3)) print(""Original arrays:"") print(nums1) print(""\n"",nums2) temp = (nums1[..., np.newaxis, np.newaxis] == nums2) rows = (temp.sum(axis=(1,2,3)) >= nums2.shape[1]).nonzero()[0] print(""\nRows of a given array that contain elements of each row of another given array:"") print(rows) " 601,Write a Python program to find a triplet in an array such that the sum is closest to a given number. Return the sum of the three integers. ,"#Source: https://bit.ly/2SRefdb from bisect import bisect, bisect_left class Solution: def threeSumClosest(self, nums, target): """""" :type nums: List[int] :type target: int :rtype: int """""" nums = sorted(nums) # Let top[i] be the sum of largest i numbers. top = [ 0, nums[-1], nums[-1] + nums[-2] ] min_diff = float('inf') three_sum = 0 # Find range of the least number in curr_n (0, 1, 2 or 3) # numbers that sum up to curr_target, then find range of # 2nd least number and so on by recursion. def closest(curr_target, curr_n, lo=0): if curr_n == 0: nonlocal min_diff, three_sum if abs(curr_target) < min_diff: min_diff = abs(curr_target) three_sum = target - curr_target return next_n = curr_n - 1 max_i = len(nums) - curr_n max_i = bisect( nums, curr_target // curr_n, lo, max_i) min_i = bisect_left( nums, curr_target - top[next_n], lo, max_i) - 1 min_i = max(min_i, lo) for i in range(min_i, max_i + 1): if min_diff == 0: return if i == min_i or nums[i] != nums[i - 1]: next_target = curr_target - nums[i] closest(next_target, next_n, i + 1) closest(target, 3) return three_sum s = Solution() nums = [1, 2, 3, 4, 5, -6] target = 14 result = s.threeSumClosest(nums, target) print(""\nArray values & target value:"",nums,""&"",target) print(""Sum of the integers closest to target:"", result) nums = [1, 2, 3, 4, -5, -6] target = 5 result = s.threeSumClosest(nums, target) print(""\nArray values & target value:"",nums,""&"",target) print(""Sum of the integers closest to target:"", result) " 602,Write a Python program to display the first and last colors from the following list. ,"color_list = [""Red"",""Green"",""White"" ,""Black""] print( ""%s %s""%(color_list[0],color_list[-1])) " 603,"Write a Pandas program to create a plot of Open, High, Low, Close, Adjusted Closing prices and 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') stock_data.plot(subplots = True, figsize = (8, 8)); plt.legend(loc = 'best') plt.suptitle('Open,High,Low,Close,Adj Close prices & Volume of Alphabet Inc., From 01-04-2020 to 30-09-2020', fontsize=12, color='black') plt.show() " 604,Write a Python program to delete a node with the given key in a given Binary search tree (BST). ,"# Definition: Binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def delete_Node(root, key): # if root doesn't exist, just return it if not root: return root # Find the node in the left subtree if key value is less than root value if root.val > key: root.left = delete_Node(root.left, key) # Find the node in right subtree if key value is greater than root value, elif root.val < key: root.right= delete_Node(root.right, key) # Delete the node if root.value == key else: # If there is no right children delete the node and new root would be root.left if not root.right: return root.left # If there is no left children delete the node and new root would be root.right if not root.left: return root.right # If both left and right children exist in the node replace its value with # the minmimum value in the right subtree. Now delete that minimum node # in the right subtree temp_val = root.right mini_val = temp_val.val while temp_val.left: temp_val = temp_val.left mini_val = temp_val.val # Delete the minimum node in right subtree root.right = deleteNode(root.right,root.val) return root def preOrder(node): if not node: return print(node.val) preOrder(node.left) preOrder(node.right) root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(6) root.left.left = TreeNode(2) root.left.right = TreeNode(4) root.left.right.left = TreeNode(7) print(""Original node:"") print(preOrder(root)) result = delete_Node(root, 4) print(""After deleting specified node:"") print(preOrder(result)) " 605,"Write a Python program to generate the running maximum, minimum value of the elements of an iterable. ","from itertools import accumulate def running_max_product(iters): return accumulate(iters, max) #List result = running_max_product([1,3,2,7,9,8,10,11,12,14,11,12,7]) print(""Running maximum value of a list:"") for i in result: print(i) #Tuple result = running_max_product((1,3,3,7,9,8,10,9,8,14,11,15,7)) print(""Running maximum value of a Tuple:"") for i in result: print(i) def running_min_product(iters): return accumulate(iters, min) #List result = running_min_product([3,2,7,9,8,10,11,12,1,14,11,12,7]) print(""Running minimum value of a list:"") for i in result: print(i) #Tuple result = running_min_product((1,3,3,7,9,8,10,9,8,0,11,15,7)) print(""Running minimum value of a Tuple:"") for i in result: print(i) " 606,Write a Pandas program to get the items which are not common of two given series. ,"import pandas as pd import numpy as np 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 a given series not present in another given series:"") sr11 = pd.Series(np.union1d(sr1, sr2)) sr22 = pd.Series(np.intersect1d(sr1, sr2)) result = sr11[~sr11.isin(sr22)] print(result) " 607,"Write a Pandas program to filter all columns where all entries present, check which rows and columns has a NaN and finally drop rows with any NaNs 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 all columns which all entries present:"") print(w_a_con.loc[:, w_a_con.notnull().all()]) print(""\nRows and columns has a NaN:"") print(w_a_con.loc[:,w_a_con.isnull().any()]) print(""\nDrop rows with any NaNs:"") print(w_a_con.dropna(how='any')) " 608,Write a Pandas program to compute the Euclidean distance between two given series. ,"import pandas as pd import numpy as np x = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = pd.Series([11, 8, 7, 5, 6, 5, 3, 4, 7, 1]) print(""Original series:"") print(x) print(y) print(""\nEuclidean distance between two said series:"") print(np.linalg.norm(x-y)) " 609,Write a Pandas program to convert year and day of year into a single datetime column of a dataframe.,"import pandas as pd data = {\ ""year"": [2002, 2003, 2015, 2018], ""day_of_the_year"": [250, 365, 1, 140] } df = pd.DataFrame(data) print(""Original DataFrame:"") print(df) df[""combined""] = df[""year""]*1000 + df[""day_of_the_year""] df[""date""] = pd.to_datetime(df[""combined""], format = ""%Y%j"") print(""\nNew DataFrame:"") print(df) " 610,Write a Python program to sort unsorted numbers using non-parallelized implementation of odd-even transposition sort. ,"def odd_even_transposition(arr_nums: list) -> list: arr_size = len(arr_nums) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr_nums[i + 1] < arr_nums[i]: arr_nums[i], arr_nums[i + 1] = arr_nums[i + 1], arr_nums[i] return arr_nums 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) " 611,Write a NumPy program to replace a specific character with another in a given array of string values. ,"import numpy as np str1 = np.array([['Python-NumPy-Exercises'], ['-Python-']]) print(""Original array of string values:"") print(str1) print(""\nReplace '-' with '=' character in the said array of string values:"") print(np.char.strip(np.char.replace(str1, '-', '=='))) print(""\nReplace '-' with ' ' character in the said array of string values:"") print(np.char.strip(np.char.replace(str1, '-', ' '))) " 612,Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components. ,"def hex_to_rgb(hex): return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)) print(hex_to_rgb('FFA501')) print(hex_to_rgb('FFFFFF')) print(hex_to_rgb('000000')) print(hex_to_rgb('FF0000')) print(hex_to_rgb('000080')) print(hex_to_rgb('C0C0C0')) " 613,Write a Python program to convert a given list of tuples to a list of strings using map function. ,"def tuples_to_list_string(lst): result = list(map(' '.join, lst)) return result colors = [('red', 'pink'), ('white', 'black'), ('orange', 'green')] print(""Original list of tuples:"") print(colors) print(""\nConvert the said list of tuples to a list of strings:"") print(tuples_to_list_string(colors)) names = [('Sheridan','Gentry'), ('Laila','Mckee'), ('Ahsan','Rivas'), ('Conna','Gonzalez')] print(""\nOriginal list of tuples:"") print(names) print(""\nConvert the said list of tuples to a list of strings:"") print(tuples_to_list_string(names)) " 614,Write a Python program to check if the elements of the first list are contained in the second one regardless of order. ,"def is_contained_in(l1, l2): for x in set(l1): if l1.count(x) > l2.count(x): return False return True print(is_contained_in([1, 2], [2, 4, 1])) print(is_contained_in([1], [2, 4, 1])) print(is_contained_in([1, 1], [4, 2, 1])) print(is_contained_in([1, 1], [3, 2, 4, 1, 5, 1])) " 615,Write a Python program to create a histogram from a given list of integers. ,"def histogram( items ): for n in items: output = '' times = n while( times > 0 ): output += '*' times = times - 1 print(output) histogram([2, 3, 6, 5]) " 616,Write a Python program that prints each item and its corresponding type from the following list.,"datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {""class"":'V', ""section"":'A'}] for item in datalist: print (""Type of "",item, "" is "", type(item)) " 617,Write a Python program to find the index of the first element in the given list that satisfies the provided testing function. ,"def find_index(nums, fn): return next(i for i, x in enumerate(nums) if fn(x)) print(find_index([1, 2, 3, 4], lambda n: n % 2 == 1)) " 618,Write a Python program to sort a given dictionary by key. ,"color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print(""%s: %s"" % (key, color_dict[key])) " 619,Write a Python program to chose specified number of colours from three different colours and generate the unique combinations. ,"from itertools import combinations def unique_combinations_colors(list_data, n): return ["" and "".join(items) for items in combinations(list_data, r=n)] colors = [""Red"",""Green"",""Blue""] print(""Original List: "",colors) n=1 print(""\nn = 1"") print(list(unique_combinations_colors(colors, n))) n=2 print(""\nn = 2"") print(list(unique_combinations_colors(colors, n))) n=3 print(""\nn = 3"") print(list(unique_combinations_colors(colors, n))) " 620,Write a Pandas program to Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. ,"import pandas as pd df1 = pd.DataFrame({'A': [None, 0, None], 'B': [3, 4, 5]}) df2 = pd.DataFrame({'A': [1, 1, 3], 'B': [3, None, 3]}) df1.combine_first(df2) print(""Original DataFrames:"") print(df1) print(""--------------------"") print(df2) print(""\nMerge two dataframes with different columns:"") result = df1.combine_first(df2) print(result) " 621,Write a NumPy program to multiply a matrix by another matrix of complex numbers and create a new matrix of complex numbers. ,"import numpy as np x = np.array([1+2j,3+4j]) print(""First array:"") print(x) y = np.array([5+6j,7+8j]) print(""Second array:"") print(y) z = np.vdot(x, y) print(""Product of above two arrays:"") print(z) " 622,Write a Python program to add two strings as they are numbers (Positive integer values). Return a message if the numbers are string. ,"def test(n1, n2): n1, n2 = '0' + n1, '0' + n2 if (n1.isnumeric() and n2.isnumeric()): return str(int(n1) + int(n2)) else: return 'Error in input!' print(test(""10"", ""32"")) print(test(""10"", ""22.6"")) print(test(""100"", ""-200"")) " 623,Write a Python program to insert spaces between words starting with capital letters. ,"import re def capital_words_spaces(str1): return re.sub(r""(\w)([A-Z])"", r""\1 \2"", str1) print(capital_words_spaces(""Python"")) print(capital_words_spaces(""PythonExercises"")) print(capital_words_spaces(""PythonExercisesPracticeSolution"")) " 624,Write a Python program to print the following floating numbers upto 2 decimal places with a sign. ,"x = 3.1415926 y = -12.9999 print(""\nOriginal Number: "", x) print(""Formatted Number with sign: ""+""{:+.2f}"".format(x)); print(""Original Number: "", y) print(""Formatted Number with sign: ""+""{:+.2f}"".format(y)); print() " 625,Write a Python program to initialize and fills a list with the specified value. ,"def initialize_list_with_values(n, val = 0): return [val for x in range(n)] print(initialize_list_with_values(7)) print(initialize_list_with_values(8,3)) print(initialize_list_with_values(5,-2)) print(initialize_list_with_values(5, 3.2)) " 626,Write a Python program to convert a given array elements to a height balanced Binary Search Tree (BST). ,"class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def array_to_bst(array_nums): if not array_nums: return None mid_num = len(array_nums)//2 node = TreeNode(array_nums[mid_num]) node.left = array_to_bst(array_nums[:mid_num]) node.right = array_to_bst(array_nums[mid_num+1:]) return node def preOrder(node): if not node: return print(node.val) preOrder(node.left) preOrder(node.right) array_nums = [1,2,3,4,5,6,7] print(""Original array:"") print(array_nums) result = array_to_bst(array_nums) print(""\nArray to a height balanced BST:"") print(preOrder(result)) " 627,Write a Pandas program to merge two given datasets using multiple join keys. ,"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:"") merged_data = pd.merge(data1, data2, on=['key1', 'key2']) print(merged_data) " 628,Write a Python program to create a deep copy of a given list. Use copy.copy,"import copy nums_x = [1, [2, 3, 4]] print(""Original list: "", 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 list:"") nums_x[1][1] = 10 print(nums_x) print(""\nCopy of the second list (Deep copy):"") print(nums_y) nums = [[1, 2, 3], [4, 5, 6]] deep_copy = copy.deepcopy(nums) print(""\nOriginal list:"") print(nums) print(""\nDeep copy of the said list:"") print(deep_copy) print(""\nChange the value of some elements of the original list:"") nums[0][2] = 55 nums[1][1] = 77 print(""\nOriginal list:"") print(nums) print(""\nSecond list (Deep copy):"") print(deep_copy) " 629,Write a NumPy program to get the memory usage by NumPy arrays. ,"import numpy as np from sys import getsizeof x = [0] * 1024 y = np.array(x) print(getsizeof(x)) " 630,Write a Python program to find the first tag with a given attribute value in an 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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" 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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

Lacie Tillie """""" 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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" 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 = ""

SomebadHTML Code

"" print(""Original string:"") print(str1) soup = BeautifulSoup(""

SomebadHTML Code

"", ""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"" % (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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" 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

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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" soup = BeautifulSoup(html_doc, 'html.parser') print(""Text of the first tag:"") print(soup.find('a').text) " 1521,Write a Python program to combine two dictionary adding values for common keys. ,"from collections import Counter d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} d = Counter(d1) + Counter(d2) print(d) " 1522,Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and to sort the records by the hire_date column. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') result = df.sort_values('hire_date') result " 1523,Write a NumPy program to create a one dimensional array of forty pseudo-randomly generated values. Select random numbers from a uniform distribution between 0 and 1. ,"import numpy as np np.random.seed(10) print(np.random.rand(40)) " 1524,Write a NumPy program to convert numpy dtypes to native python types. ,"import numpy as np print(""numpy.float32 to python float"") x = np.float32(0) print(type(x)) pyval = x.item() print(type(pyval)) " 1525,Write a Python program to get the every nth element in a given list. ,"def every_nth(nums, nth): return nums[nth - 1::nth] print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6)) " 1526,Write a NumPy program to find the number of weekdays in March 2017. ,"import numpy as np print(""Number of weekdays in March 2017:"") print(np.busday_count('2017-03', '2017-04')) " 1527,Write a Python program to sort a given mixed list of integers and strings. Numbers must be sorted before strings. ,"def sort_mixed_list(mixed_list): int_part = sorted([i for i in mixed_list if type(i) is int]) str_part = sorted([i for i in mixed_list if type(i) is str]) return int_part + str_part 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)) " 1528,Write a Python program to reverse a string. ,"def reverse_string(str1): return ''.join(reversed(str1)) print() print(reverse_string(""abcdef"")) print(reverse_string(""Python Exercises."")) print() " 1529,Write a Python program to insert an element before each element of a list. ,"color = ['Red', 'Green', 'Black'] print(""Original List: "",color) color = [v for elt in color for v in ('c', elt)] print(""Original List: "",color) " 1530,Write a NumPy program to get the row numbers in given array where at least one item is larger than a specified value. ,"import numpy as np num = np.arange(36) arr1 = np.reshape(num, [4, 9]) print(""Original array:"") print(arr1) result = np.where(np.any(arr1>10, axis=1)) print(""\nRow numbers where at least one item is larger than 10:"") print(result) " 1531,Write a NumPy program to get the indices of the sorted elements of a given array. ,"import numpy as np student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]) print(""Original array:"") print(student_id) i = np.argsort(student_id) print(""Indices of the sorted elements of a given array:"") print(i) " 1532,Write a Python program to remove all strings from a given list of tuples. ,"def test(list1): result = [tuple(v for v in i if not isinstance(v, str)) for i in list1] return list(result) marks = [(100, 'Math'), (80, 'Math'), (90, 'Math'), (88, 'Science', 89), (90, 'Science', 92)] print(""\nOriginal list:"") print(marks) print(""\nRemove all strings from the said list of tuples:"") print(test(marks)) " 1533,Write a Python program to sort Counter by value. ,"from collections import Counter x = Counter({'Math':81, 'Physics':83, 'Chemistry':87}) print(x.most_common()) " 1534,Write a Python program to remove the parenthesis area in a string. ,"import re items = [""example (.com)"", ""w3resource"", ""github (.com)"", ""stackoverflow (.com)""] for item in items: print(re.sub(r"" ?\([^)]+\)"", """", item)) " 1535,Write a NumPy program to compute the median of flattened given array. ,"import numpy as np x = np.arange(12).reshape((2, 6)) print(""\nOriginal array:"") print(x) r1 = np.median(x) print(""\nMedian of said array:"") print(r1) " 1536,Write a Python program to convert a given Bytearray to Hexadecimal string. ,"def bytearray_to_hexadecimal(list_val): result = ''.join('{:02x}'.format(x) for x in list_val) return(result) list_val = [111, 12, 45, 67, 109] print(""Original Bytearray :"") print(list_val) print(""\nHexadecimal string:"") print(bytearray_to_hexadecimal(list_val)) " 1537,Write a Python program to calculate the maximum and minimum sum of a sublist in a given list of lists. ,"def max_min_sublist(lst): max_result = (max(lst, key=sum)) min_result = (min(lst, key=sum)) return max_result,min_result nums = [[1,2,3,5], [2,3,5,4], [0,5,4,1], [3,7,2,1], [1,2,1,2]] print(""Original list:"") print(nums) result = max_min_sublist(nums) print(""\nMaximum sum of sub list of the said list of lists:"") print(result[0]) print(""\nMinimum sum of sub list of the said list of lists:"") print(result[1]) " 1538,"Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20. ","def sum(x, y): sum = x + y if sum in range(15, 20): return 20 else: return sum print(sum(10, 6)) print(sum(10, 2)) print(sum(10, 12)) " 1539,Write a Python program to convert a given decimal number to binary list. ,"def decimal_to_binary_list(n): result = [int(x) for x in list('{0:0b}'.format(n))] return result n = 8 print(""Original Number:"",n) print(""Decimal number ("",n,"") to binary list:"") print(decimal_to_binary_list(n)) n = 45 print(""\nOriginal Number:"",n) print(""Decimal number ("",n,"") to binary list:"") print(decimal_to_binary_list(n)) n = 100 print(""\nOriginal Number:"",n) print(""Decimal number ("",n,"") to binary list:"") print(decimal_to_binary_list(n)) " 1540,Write a Pandas program to compare the elements of the two Pandas Series. ,"import pandas as pd ds1 = pd.Series([2, 4, 6, 8, 10]) ds2 = pd.Series([1, 3, 5, 7, 10]) print(""Series1:"") print(ds1) print(""Series2:"") print(ds2) print(""Compare the elements of the said Series:"") print(""Equals:"") print(ds1 == ds2) print(""Greater than:"") print(ds1 > ds2) print(""Less than:"") print(ds1 < ds2) " 1541,Write a NumPy program to calculate the Frobenius norm and the condition number of a given array. ,"import numpy as np a = np.arange(1, 10).reshape((3, 3)) print(""Original array:"") print(a) print(""Frobenius norm and the condition number:"") print(np.linalg.norm(a, 'fro')) print(np.linalg.cond(a, 'fro')) " 1542,Write a Python program to generate all possible permutations of n different objects. ,"import itertools def permutations_all(l): for values in itertools.permutations(l): print(values) permutations_all([1]) print(""\n"") permutations_all([1,2]) print(""\n"") permutations_all([1,2,3]) " 1543,"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)) " 1544,Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15. ,"import numpy as np x = np.arange(21) print(""Original vector:"") print(x) print(""After changing the sign of the numbers in the range from 9 to 15:"") x[(x >= 9) & (x <= 15)] *= -1 print(x) " 1545,Write a NumPy program to create an array using scientific notation numbers. Set the precision value to 6 and print the array. ,"import numpy as np nums = np.array([1.2e-7, 1.5e-6, 1.7e-5]) print(""Original arrays:"") print(nums) print(""Set the precision value to 10:"") np.set_printoptions(suppress=True, precision=10) print(nums) " 1546,Write a Pandas program to manipulate and convert date times with timezone information. ,"import pandas as pd dtt = pd.date_range('2018-01-01', periods=3, freq='H') dtt = dtt.tz_localize('UTC') print(dtt) print(""\nFrom UTC to America/Los_Angeles:"") dtt = dtt.tz_convert('America/Los_Angeles') print(dtt) " 1547,Write a Python program to print the even numbers from a given list. ,"def is_even_num(l): enum = [] for n in l: if n % 2 == 0: enum.append(n) return enum print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) " 1548,Write a Pandas program to split the following dataframe into groups based on first column and set other column values into a list of values. ,"import pandas as pd df = pd.DataFrame( {'X' : [10, 10, 10, 20, 30, 30, 10], 'Y' : [10, 15, 11, 20, 21, 12, 14], 'Z' : [22, 20, 18, 20, 13, 10, 0]}) print(""Original DataFrame:"") print(df) result= df.groupby('X').aggregate(lambda tdf: tdf.unique().tolist()) print(result) " 1549,Write a Python program to sort one list based on another list containing the desired indexes. ,"def sort_by_indexes(lst, indexes, reverse=False): return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \ x[0], reverse=reverse)] l1 = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk'] l2 = [3, 2, 6, 4, 1, 5] print(sort_by_indexes(l1, l2)) print(sort_by_indexes(l1, l2, True)) " 1550,Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. ,"d=dict() for x in range(1,16): d[x]=x**2 print(d) " 1551,Write a Python program to check if a given value is a method of a user-defined class. Use types.MethodType(),"import types class C: def x(): return 1 def y(): return 1 def b(): return 2 print(isinstance(C().x, types.MethodType)) print(isinstance(C().y, types.MethodType)) print(isinstance(b, types.MethodType)) print(isinstance(max, types.MethodType)) print(isinstance(abs, types.MethodType)) " 1552,"Write a Python program to generate and print a list except for the first 5 elements, 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[5:]) printValues() " 1553,Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees of a specified year. ,"import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') df2 = df.set_index(['hire_date']) result = df2[""2005""] result " 1554,Write a Python program to rotate a Deque Object specified number (negative) of times. ,"import collections # declare an empty deque object dq_object = collections.deque() # Add elements to the deque - left to right dq_object.append(2) dq_object.append(4) dq_object.append(6) dq_object.append(8) dq_object.append(10) print(""Deque before rotation:"") print(dq_object) # Rotate once in negative direction dq_object.rotate(-1) print(""\nDeque after 1 negative rotation:"") print(dq_object) # Rotate twice in negative direction dq_object.rotate(-2) print(""\nDeque after 2 negative rotations:"") print(dq_object) " 1555,"Write a NumPy program to generate inner, outer, and cross products of matrices and vectors. ","import numpy as np x = np.array([1, 4, 0], float) y = np.array([2, 2, 1], float) print(""Matrices and vectors."") print(""x:"") print(x) print(""y:"") print(y) print(""Inner product of x and y:"") print(np.inner(x, y)) print(""Outer product of x and y:"") print(np.outer(x, y)) print(""Cross product of x and y:"") print(np.cross(x, y)) " 1556,Write a NumPy program to create a 1-D array going from 0 to 50 and an array from 10 to 50. ,"import numpy as np x = np.arange(50) print(""Array from 0 to 50:"") print(x) x = np.arange(10, 50) print(""Array from 10 to 50:"") print(x) " 1557,Write a Python program to split an iterable and generate iterables specified number of times. ,"import itertools as it def tee_data(iter, n): return it.tee(iter, n) #List result = tee_data(['A','B','C','D'], 5) print(""Generate iterables specified number of times:"") for i in result: print(list(i)) #String result = tee_data(""Python itertools"", 4) print(""\nGenerate iterables specified number of times:"") for i in result: print(list(i)) " 1558,"Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data. ","import numpy as np student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]) student_height = np.array([40., 42., 45., 41., 38., 40., 42.0]) #Sort by studen_id then by student_height indices = np.lexsort((student_id, student_height)) print(""Sorted indices:"") print(indices) print(""Sorted data:"") for n in indices: print(student_id[n], student_height[n]) " 1559,Write a Python program to get the smallest number from a list. ,"def smallest_num_in_list( list ): min = list[ 0 ] for a in list: if a < min: min = a return min print(smallest_num_in_list([1, 2, -8, 0])) " 1560,Write a Python program to sort a list of elements using Cycle sort. ,"# License: https://bit.ly/2V5W81t def cycleSort(vector): ""Sort a vector in place and return the number of writes."" writes = 0 # Loop through the vector to find cycles to rotate. for cycleStart, item in enumerate(vector): # Find where to put the item. pos = cycleStart for item2 in vector[cycleStart + 1:]: if item2 < 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 == vector[pos]: pos += 1 vector[pos], item = item, vector[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for item2 in vector[cycleStart + 1:]: if item2 < item: pos += 1 # Put the item there or right after any duplicates. while item == vector[pos]: pos += 1 vector[pos], item = item, vector[pos] writes += 1 return writes if __name__ == '__main__': x = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6] xcopy = x[::] writes = cycleSort(xcopy) if xcopy != sorted(x): print('Wrong order!') else: print('%r\nIs correctly sorted using cycleSort to' '\n%r\nUsing %i writes.' % (x, xcopy, writes)) " 1561,Write a NumPy program to extract all the elements of the first 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 row"") print(arra_data[0]) " 1562,Write a Pandas program to create a histogram to visualize daily return distribution of Alphabet Inc. stock price between two specific dates. ,"import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(""alphabet_stock_data.csv"") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-9-30') df['Date'] = pd.to_datetime(df['Date']) new_df = (df['Date']>= start_date) & (df['Date']<= end_date) df1 = df.loc[new_df] df2 = df1[['Date', 'Adj Close']] df3 = df2.set_index('Date') daily_changes = df3.pct_change(periods=1) sns.distplot(daily_changes['Adj Close'].dropna(),bins=100,color='purple') plt.suptitle('Daily % return of Alphabet Inc. stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black') plt.grid(True) plt.show() " 1563,Write a Python program to find tag(s) directly 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.

Learn HTML from w3resource.com

Learn CSS from w3resource.com

"""""" 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.

    Learn HTML from w3resource.com

    Learn CSS from w3resource.com

    """""" 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                                                                                                                                                                                                    
    NameClass
    Vinayak12
    Ishita10
        " 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 + "">(.*?)"" 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 ') 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) g.add_edge(dest, src, weight) else: print('Edge already exists.')   elif operation == 'shortest': key = int(do[1]) source = g.get_vertex(key) distance = dijkstra(g, source) print('Distances from {}: '.format(key)) for v in distance: print('Distance to {}: {}'.format(v.get_key(), distance[v])) 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" 2975,"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) " 2976,Find the length of the string without using the inbuilt function," str=input(""Enter the String:"") len=0 while str[len:]:     len+=1 print(""Your Enter String is:"", len)" 2977,"Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). :","Solution evenNumbers = filter(lambda x: x%2==0, range(1,21)) print evenNumbers " 2978,"Define a function that can accept two strings as input and concatenate them and then print it in console. :","Solution def printValue(s1,s2): print s1+s2 printValue(""3"",""4"") #34 " 2979,Binary to Decimal conversion using recursion,"def BinaryToDecimal(n):    if n==0:        return 0    else:        return (n% 10 + 2* BinaryToDecimal(n // 10))n=int(input(""Enter the Binary Value:""))print(""Decimal Value of Binary number is:"",BinaryToDecimal(n))" 2980,Python Program to Convert Binary to Gray Code,"def binary_to_gray(n): """"""Convert Binary to Gray codeword and return it."""""" n = int(n, 2) # convert to int n ^= (n >> 1)   # bin(n) returns n's binary representation with a '0b' prefixed # the slice operation is to remove the prefix return bin(n)[2:]     g = input('Enter binary number: ') b = binary_to_gray(g) print('Gray codeword:', b)" 2981,Program to convert octal to binary ,"print(""Enter octal number: "") octal=int(input()) decimal = 0 i = 0 binary = 0 while (octal != 0):       decimal = decimal + (octal % 10) * pow (8, i)       i+=1       octal = octal // 10 i = 1 while (decimal != 0):       binary = binary + (decimal % 2) * i       decimal = decimal // 2       i = i * 10 print (""Binary number is: "", binary) " 2982,Program to print series 2 4 7 12 21 ...N,"n=int(input(""Enter the range of number(Limit):""))i=0pr=2print(""2 "",end="""")while i=1:    print(""1 "",end="""")if n>=2:    print(""2 "",end="""")if n>=3:    print(""5 "",end="""")a=1b=2c=5while i<=n:    d = a + b + c    a = b    b = c    c = d    print(d,end="" "")    i+=1" 2987,Python Program to Find the Power of a Number Using Recursion,"def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) base=int(input(""Enter base: "")) exp=int(input(""Enter exponential value: "")) print(""Result:"",power(base,exp))" 2988,Python Program to Check if Expression is correctly Parenthesized,"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() exp = input('Please enter the expression: ')   for c in exp: if c == '(': s.push(1) elif c == ')': if s.is_empty(): is_balanced = False break s.pop() else: if s.is_empty(): is_balanced = True else: is_balanced = False   if is_balanced: print('Expression is correctly parenthesized.') else: print('Expression is not correctly parenthesized.')" 2989,Count how many vowels 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':         count+=1 if count==0:         print(""No vowels are present in the string."") else:     print(""Numbers of vowels present in the string are "",count)" 2990,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))" 2991,Python Program to Find the Largest Element in a Doubly Linked List,"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 append(self, data): self.insert_at_end(Node(data))   def insert_at_end(self, new_node): if self.last is None: self.last = new_node self.first = new_node else: new_node.prev = self.last self.last.next = new_node self.last = new_node     def find_largest(dllist): if dllist.first is None: return None largest = dllist.first.data current = dllist.first.next while current: if current.data > largest: largest = current.data current = current.next return largest     a_dllist = DoublyLinkedList()   data_list = input('Please enter the elements in the doubly linked list: ').split() for data in data_list: a_dllist.append(int(data))   largest = find_largest(a_dllist) if largest: print('The largest element is {}.'.format(largest)) else: print('The list is empty.')" 2992,Python Program to Find if Undirected 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 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     def is_cycle_present(v, visited): """"""Return True if cycle is present in component containing vertex and put all vertices in component in set visited."""""" parent = {v: None} return is_cycle_present_helper(v, visited, parent)     def is_cycle_present_helper(v, visited, parent): """"""Return True if cycle is present in component containing vertex and put all vertices in component in set visited. Uses dictionary parent to keep track of parents of nodes in the DFS tree."""""" visited.add(v) for dest in v.get_neighbours(): if dest not in visited: parent[dest] = v if is_cycle_present_helper(dest, visited, parent): return True else: if parent[v] 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" 2993,Program to Find nth Spy Number ," rangenumber=int(input(""Enter a Nth Number:"")) c = 0 letest = 0 num = 1 while c != rangenumber:     sum = 0     mult = 1     num1=num     while num1 != 0:         rem = num1 % 10         sum += rem         mult *= rem         num1 //= 10     if sum == mult:             c+=1             letest = num     num = num + 1 print(rangenumber,""th Spy number is "",letest)" 2994,Find out how many 1 and 0 in a given number.," '''Write a Python program to find out all How many 1 and 0 in a given number. or Write a program to find out all How many 1 and 0 in a given the number using Python ''' print(""Enter a number:"") num=int(input()) c1=0 c0=0 while int(num):     r=num%10     num=int(num/10)     if r==1:         c1=c1+1     if r==0:         c0=c0+1 print(""The total number of zero's are "",c0) print(""The total number of one's are "",c1) " 2995,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."")" 2996,Find the Longest word in a string,"str=input(""Enter Your String:"")sub_str=str.split("" "")maxInd=0max=0max = len(sub_str[0])for inn in range(0,len(sub_str)):    len1 = len(sub_str[inn])    if len1 > max:        max=len1        maxInd=innprint(""Longest Substring(Word) is "",sub_str[maxInd])" 2997,Python Program to Convert Gray Code to Binary,"def gray_to_binary(n): """"""Convert Gray codeword to binary and return it."""""" n = int(n, 2) # convert to int   mask = n while mask != 0: mask >>= 1 n ^= mask   # bin(n) returns n's binary representation with a '0b' prefixed # the slice operation is to remove the prefix return bin(n)[2:]     g = input('Enter Gray codeword: ') b = gray_to_binary(g) print('In binary:', b)" 2998,Python Program to Implement a 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() 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': 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" 2999,Python Program to solve Maximum Subarray Problem using Divide and Conquer,"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."""""" # base case if start == end - 1: return start, end, alist[start] else: mid = (start + end)//2 left_start, left_end, left_max = find_max_subarray(alist, start, mid) right_start, right_end, right_max = find_max_subarray(alist, mid, end) cross_start, cross_end, cross_max = find_max_crossing_subarray(alist, start, mid, end) if (left_max > right_max and left_max > cross_max): return left_start, left_end, left_max elif (right_max > left_max and right_max > cross_max): return right_start, right_end, right_max else: return cross_start, cross_end, cross_max   def find_max_crossing_subarray(alist, start, mid, end): """"""Returns (l, r, m) such that alist[l:r] is the maximum subarray within alist with start <= l < mid <= r < end with sum m. The arguments start, mid, end must satisfy start <= mid <= end."""""" sum_left = float('-inf') sum_temp = 0 cross_start = mid for i in range(mid - 1, start - 1, -1): sum_temp = sum_temp + alist[i] if sum_temp > sum_left: sum_left = sum_temp cross_start = i   sum_right = float('-inf') sum_temp = 0 cross_end = mid + 1 for i in range(mid, end): sum_temp = sum_temp + alist[i] if sum_temp > sum_right: sum_right = sum_temp cross_end = i + 1 return cross_start, cross_end, sum_left + sum_right   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))" 3000,Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.,"items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) " 3001,Program to calculate the LCM of two numbers," '''Write a Python program to calculate the LCM of two numbers. or     Write a program to calculate the LCM of two numbers using Python ''' print(""Enter two number to find L.C.M:"") num1=int(input()) num2=int(input()) n1=num1 n2=num2 while(num1!=num2):    if (num1 > num2):       num1 = num1 - num2    else:       num2= num2 - num1 lcm=int((n1*n2)/num1) print(""L.C.M is"",lcm) " 3002,Count inversions 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)count=0print(""All the inversions are:"")for i in range(0,size-1):    for j in range(i+1, size):        if arr[i]>arr[j]:            print(""("",arr[i],"","",arr[j],"")"")            count+=1if count==0:     print(""(0)"")elif count==0:     print(""\nNumber of Inversions is "",count)else:    print(""\nNumber of Inversions are "",count)" 3003,"Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).","n=int(input(""Enter a number:"")) d={x:x*x for x in range(1,n+1)} print(d)" 3004,Python Program to Reverse a String without using Recursion,"a=str(input(""Enter a string: "")) print(""Reverse of the string is: "") print(a[::-1])" 3005,Python Program to Count all Paths in a Grid with Holes using Dynamic Programming with Bottom-Up Approach,"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)]   if (0, 0) in holes: paths[0][0] = 0 else: paths[0][0] = 1   for x in range(1, n + 1): if (x, 0) in holes: paths[x][0] = 0 else: paths[x][0] = paths[x - 1][0]   for y in range(1, m + 1): if (0, y) in holes: paths[0][y] = 0 else: paths[0][y] = paths[0][y - 1]   for x in range(1, n + 1): for y in range(1, m + 1): if (x, y) in holes: paths[x][y] = 0 else: paths[x][y] = paths[x - 1][y] + paths[x][y - 1]   return paths[n][m]     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))" 3006,Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches,"  cm=int(input(""Enter the height in centimeters:"")) inches=0.394*cm feet=0.0328*cm print(""The length in inches"",round(inches,2)) print(""The length in feet"",round(feet,2))" 3007," Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. :"," import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) " 3008,Python Program to Read the Contents of a File,"a=str(input(""Enter the name of the file with .txt extension:"")) file2=open(a,'r') line=file2.readline() while(line!=""""): print(line) line=file2.readline() file2.close()" 3009," Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. "," def EvenGenerator(n): i=0 while i<=n: if i%2==0: yield i i+=1 n=int(raw_input()) values = [] for i in EvenGenerator(n): values.append(str(i)) print "","".join(values) " 3010,"Define a function that can receive two integral numbers in string form and compute their sum and then print it in console. :","Solution def printValue(s1,s2): print int(s1)+int(s2) printValue(""3"",""4"") #7 " 3011," By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. :"," li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] print li " 3012,Print the Full Inverted Pyramid Alphabet Pattern,"row_size=int(input(""Enter the row size:""))np=row_size*2-1for out in range(row_size-1,-1,-1):    for inn in range(row_size,out,-1):        print("" "",end="""")    for p in range(0,np):        print((chr)(out+65),end="""")    np-=2    print(""\r"")" 3013," Please write a program which accepts basic mathematic expression from console and print the evaluation result. "," expression = raw_input() print eval(expression) " 3014,Print vowels in a string," str=input(""Enter the String:"") 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':         print(str[i],end="" "")" 3015,Python Program to Merge Two Lists and Sort it,"a=[] c=[] n1=int(input(""Enter number of elements:"")) for i in range(1,n1+1): b=int(input(""Enter element:"")) a.append(b) n2=int(input(""Enter number of elements:"")) for i in range(1,n2+1): d=int(input(""Enter element:"")) c.append(d) new=a+c new.sort() print(""Sorted list is:"",new)" 3016,Max sum contiguous subarray,"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)Maximum_Sum=0for i in range(0,size):    for j in range(i, size):        sum=0        for p in range(i, j):            sum+=arr[p]        if sum>=Maximum_Sum:             Maximum_Sum=sumprint(""Maximum sum of Contiguous Subarray is "",Maximum_Sum)" 3017,Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers without using Recursion,"a=[] l=int(input(""Enter lower limit: "")) u=int(input(""Enter upper limit: "")) a=[x for x in range(l,u+1) if x%2!=0 and str(x)==str(x)[::-1]] print(""The numbers are: "",a)" 3018,Program to Print Cube Number series 1 8 27 64...N," print(""Enter the range of number(Limit):"") n=int(input()) i=1 while(i<=n):     print(i*i*i,end="" "")     i+=1" 3019,Python Program to Implement Merge Sort,"def merge_sort(alist, start, end): '''Sorts the list from indexes start to end - 1 inclusive.''' if end - start > 1: mid = (start + end)//2 merge_sort(alist, start, mid) merge_sort(alist, mid, end) merge_list(alist, start, mid, end)   def merge_list(alist, start, mid, end): left = alist[start:mid] right = alist[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): alist[k] = left[i] i = i + 1 else: alist[k] = right[j] j = j + 1 k = k + 1 if start + i < mid: while k < end: alist[k] = left[i] i = i + 1 k = k + 1 else: while k < end: alist[k] = right[j] j = j + 1 k = k + 1     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] merge_sort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist)" 3020,Program to reverse a string without using the reverse function," str=input(""Enter the String:"") print(""After Reversing String is :"") for i in range(len(str)-1,-1,-1):     print(str[i],end="""")" 3021,"Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). :","Solution squaredNumbers = map(lambda x: x**2, range(1,21)) print squaredNumbers " 3022,Program to find the sum of series 1^2+2^2+3^2...+N^2," print(""Enter the range of number:"") n=int(input()) sum=0 for i in range(1,n+1):     sum+=i*i print(""The sum of the series = "",sum)" 3023,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)" 3024,Program to Find the Biggest of three numbers," print(""Enter 3 numbers:"") num1=int(input()) num2=int(input()) num3=int(input()) print(""The biggest number is "",max(num1,num2,num3)) " 3025,Python Program to Form an Integer that has the Number of Digits at Ten's Place and the Least Significant Digit of the Entered Integer at One's Place,"  n=int(input(""Enter the number:"")) tmp=n k=0 while(n>0): k=k+1 n=n//10 b=str(tmp) c=str(k) d=c+b[k-1] print(""The new number formed:"",int(d))" 3026,"Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). :","Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li printList() " 3027,Multiply two numbers using recursion,"def Multiplication(num1,num2):    if num1 pivot: j = j - 1   if i >= j: return j   swap(alist, i, j)   def swap(alist, i, j): alist[i], alist[j] = alist[j], alist[i]   def heapsort(alist, start, end): build_max_heap(alist, start, end) for i in range(end - 1, start, -1): swap(alist, start, i) max_heapify(alist, index=0, start=start, end=i)   def build_max_heap(alist, start, end): def parent(i): return (i - 1)//2 length = end - start index = parent(length - 1) while index >= 0: max_heapify(alist, index, start, end) index = index - 1   def max_heapify(alist, index, start, end): def left(i): return 2*i + 1 def right(i): return 2*i + 2   size = end - start l = left(index) r = right(index) if (l < size and alist[start + l] > alist[start + index]): largest = l else: largest = index if (r < size and alist[start + r] > alist[start + largest]): largest = r if largest != index: swap(alist, start + largest, start + index) max_heapify(alist, largest, start, end)     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] introsort(alist) print('Sorted list: ', end='') print(alist)" 3035,Python Program to Search the Number of Times a Particular Number Occurs 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) k=0 num=int(input(""Enter the number to be counted:"")) for j in a: if(j==num): k=k+1 print(""Number of times"",num,""appears is"",k)" 3036,Print perfect square numbers in a given range," import math print(""Enter range:"") range1=int(input()) range2=int(input()) print(""Perfect squares between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     sqr=math.sqrt(i)     if sqr-math.floor(sqr)==0:         print(i,end="" "")  " 3037,Find maximum and minimum elements in array using recursion,"import sysdef FindMax(arr,n):    if n == 1:        return arr[0]    return max(arr[n - 1], FindMax(arr, n - 1))def FindMin(arr,n):    if n==1:        return arr[0]    return min(arr[n-1], FindMin(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)print(""Maximum Element of the array is: "",FindMax(arr,len(arr)))print(""Minimum Element of the array is: "",FindMin(arr,len(arr)))" 3038,Write a program to print the alphabet 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),ord('A')-1,-1):         print(chr(i),end="" "")     print(""\r"") " 3039,Capitalize First letter of each word in String," str=input(""Enter the String:"") j=0 newStr="""" for i in range(len(str)):     if i==0 or str[i-1]==' ':         ch=str[i].upper()         newStr+=ch     else:         newStr = newStr + str[i] print(""Your String is:"", newStr)" 3040,Python Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List,"import math print(""Enter the coefficients of the form ax^3 + bx^2 + cx + d"") lst=[] for i in range(0,4): a=int(input(""Enter coefficient:"")) lst.append(a) x=int(input(""Enter the value of x:"")) sum1=0 j=3 for i in range(0,3): while(j>0): sum1=sum1+(lst[i]*math.pow(x,j)) break j=j-1 sum1=sum1+lst[3] print(""The value of the polynomial is:"",sum1)" 3041,"Write a program which accepts a string as input to print ""Yes"" if the string is ""yes"" or ""YES"" or ""Yes"", otherwise print ""No"". :","Solution s= raw_input() if s==""yes"" or s==""YES"" or s==""Yes"": print ""Yes"" else: print ""No"" " 3042,Convert Uppercase to Lowercase using string function," str=input(""Enter the String(Upper case):"") print(""Lower case String is:"", str.lower())" 3043,Program to print inverted pyramid star pattern," print(""Enter the row size:"") row_size=int(input()) for out in range(row_size+1):     for j in range(out):         print("" "",end="""")     for p in range(row_size,out,-1):         print(""* "",end="""")     print(""\r"")" 3044,Python Program to Find the Sum of All 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 sum_nodes(node): if node is None: return 0 return node.key + sum_nodes(node.left) + sum_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('sum') 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 == 'sum': print('Sum of nodes in tree: {}'.format(sum_nodes(btree)))   elif operation == 'quit': break" 3045,Find sum of even numbers using recursion in an array,"sum=0def SumOfEvenElement(arr,n):    global sum    if(n>0):        i=n-1        if(arr[i]%2==0):            sum=sum+arr[i]        SumOfEvenElement(arr,i)    return sumarr=[]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(""Sum of even Element is:"",SumOfEvenElement(arr,n))" 3046," Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. :"," s = raw_input() u = unicode( s ,""utf-8"") print u " 3047,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= 'A' and str[i] <= 'Z':         ch = str[i]         break     else:         continue print(""First capital letter in a given String is: "", ch)" 3055,Convert Lowercase to Uppercase without using the inbuilt function," str=input(""Enter the String(Lower case):"") i=0 ch='' #convert capital letter string to small letter string while len(str)>i:     if str[i]>='a' and str[i]<='z' :         ch+=chr(ord(str[i])-32)     else:         ch += chr(ord(str[i]))     i+=1 print(""Lower case String is:"", ch)" 3056,Find out all Pronic numbers present within a given range," import math print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Pronic numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     flag = 0     for j in range(0, i + 1):         if j * (j + 1) == i:             flag = 1             break     if flag == 1:         print(i,end="" "")" 3057,Python Program to Display the Nodes of a Linked List in Reverse 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): self.display_reversed_helper(self.head)   def display_reversed_helper(self, current): if current is None: return   self.display_reversed_helper(current.next) print(current.data, end = ' ')   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()" 3058,Python Program to Check if a String is a Palindrome or Not,"string=raw_input(""Enter string:"") if(string==string[::-1]): print(""The string is a palindrome"") else: print(""The string isn't a palindrome"")" 3059,Find out all Evil numbers present within a given range," print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Evil numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     one_c = 0     num=i     while num != 0:         if num % 2 == 1:             one_c += 1         num //= 2     if one_c % 2 == 0:         print(i,end="" "")" 3060,Program to Find Nth Abundant Number," rangenumber=int(input(""Enter a Nth Number:"")) c = 0 letest = 0 num = 1 while c != rangenumber:     num1 = num     sum = 0     for i in range(1, num1):         if num1 % i == 0:             sum = sum + i     if sum>num:         c+=1         letest = num     num = num + 1 print(rangenumber,""th Abundant number is "",letest)" 3061,Python Program to Implement Dequeue,"class Dequeue: def __init__(self): self.items = []   def is_empty(self): return self.items == []   def append(self, data): self.items.append(data)   def append_left(self, data): self.items.insert(0, data)   def pop(self): return self.items.pop()   def pop_left(self): return self.items.pop(0)     q = Dequeue() print('Menu') print('append ') print('appendleft ') print('pop') print('popleft') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'append': q.append(int(do[1])) elif operation == 'appendleft': q.append_left(int(do[1])) elif operation == 'pop': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from right: ', q.pop()) elif operation == 'popleft': if q.is_empty(): print('Dequeue is empty.') else: print('Popped value from left: ', q.pop_left()) elif operation == 'quit': break" 3062,Check a given number is an Automorphic number or not," '''Write a Python program to check whether a given number is An Automorphic number or not. or Write a program to check whether a given number is An Automorphic number or not using Python ''' num=int(input(""Enter a number:"")) 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(""It is an Automorphic Number"") else:    print(""It is not an Automorphic Number"") " 3063,Merging two unsorted arrays of different lengths,"def Merge_Array(arr,arr2,size,size2):    m_size = size + size2    merge_arr = [0]*m_size    i=0    k=0    j=0    while k after ') print('insert before ') print('insert at beg') print('insert at end') print('remove ') print('quit')   while True: print('The list: ', end = '') a_cdllist.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_cdllist.insert_at_beg(new_node) elif position == 'end': a_cdllist.insert_at_end(new_node) else: index = int(position) ref_node = a_cdllist.get_node(index) if ref_node is None: print('No such index.') continue if suboperation == 'after': a_cdllist.insert_after(ref_node, new_node) elif suboperation == 'before': a_cdllist.insert_before(ref_node, new_node)   elif operation == 'remove': index = int(do[1]) node = a_cdllist.get_node(index) if node is None: print('No such index.') continue a_cdllist.remove(node)   elif operation == 'quit': break" 3068,Python Program to Copy the Contents of One File into Another,"with open(""test.txt"") as f: with open(""out.txt"", ""w"") as f1: for line in f: f1.write(line)" 3069,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)  " 3070,Write a program to sum of all digits of a number.," '''Write a Python program to the sum of all digits of a number. or     Write a program to the sum of all digits of a number using Python ''' n=int(input(""Enter a number:"")) sum=0 while n>0:    rem=n%10    sum=sum+rem    n=int(n/10) print(""The sum of digits of number is:"", sum)  " 3071,Python Program to Find the Sum of the Series: 1 + x^2/2 + x^3/3 + … x^n/n,"n=int(input(""Enter the number of terms:"")) x=int(input(""Enter the value of x:"")) sum1=1 for i in range(2,n+1): sum1=sum1+((x**i)/i) print(""The sum of series is"",round(sum1,2))" 3072,Program to Calculate the surface area and volume of a Cuboid ," l=int(input(""Enter the length of the cuboid:"")) h=int(input(""Enter the height of the cuboid:"")) w=int(input(""Enter the weight of the cuboid:"")) surface_area=2*((l*w)+(l*h)+(h*w)) volume=l*w*h print(""Surface Area of the cuboid = "",surface_area) print(""Volume of the cuboid = "",volume) " 3073,Find frequency of 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(""Frequency of character in a string are:"") for i in range(256):     if arr[i]!=0:         print((chr)(i),"" occurs "",arr[i],"" times"")" 3074,Program to Find the sum of series 1/1!+1/2!+1/3!.....+1/N!,"n=int(input(""Enter the range of number:""))sum=0.0fact=1for i in range(1,n+1):    fact *= i    sum+=1.0/factprint(""The sum of the series = "",sum)" 3075,Find reverse of a number using recursion," def reverse(num):     if num<10:       print(num)       return     else:         print(num % 10,end="""")         reverse(int(num / 10)) print(""Enter your number:"") num=int(input()) print(""Reverse of the input number is:"") reverse(num)  " 3076,Python Program that Displays which Letters are in the Two Strings but not in Both,"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)" 3077,Program to Find the sum of series 1/2+2/3+3/4.....+(N-1)/N,"n=int(input(""Enter the range of number:""))sum=0.0for i in range(1,n+1):    sum += i / (i + 1)print(""The sum of the series = "",sum)" 3078,Python Program to Find the Sum of Sine Series,"import math def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i pi=22/7 y=x*(pi/180) sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign return sine x=int(input(""Enter the value of x in degrees:"")) n=int(input(""Enter the number of terms:"")) print(round(sin(x,n),2))" 3079,Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number,"l_range=int(input(""Enter the lower range:"")) u_range=int(input(""Enter the upper range:"")) a=[(x,x**2) for x in range(l_range,u_range+1)] print(a)" 3080,Python Program to Clear the Rightmost Set Bit of a Number,"def clear_rightmost_set_bit(n): """"""Clear rightmost set bit of n and return it."""""" return n & (n - 1)     n = int(input('Enter a number: ')) ans = clear_rightmost_set_bit(n) print('n with its rightmost set bit cleared equals:', ans)" 3081,Print a string using an array," import array arr=array.array('u', ['c','s','i','n','f','o','3','6','0','.','c','o','m']) len=len(arr) for i in range(0,len):     print(arr[i],end="""")" 3082,Check whether a given number is a Harshad number or not," '''Write a Python program to check whether a given number is a Harshad number or not. or Write a program to check whether a given number is a Harshad number or not using Python ''' num=int(input(""Enter a number:"")) num2=num sum=0 while num!=0:   rem=num%10   num=int(num/10)   sum=sum+rem if(num2%sum==0):    print(""It is a Harshad Number"") else: print(""It is not a Harshad Number"")  " 3083,delete an element from 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 element to be deleted:"") ele=int(input()) print(""Before deleting array elements are:"") for i in range(0,size):     print(arr[i],end="" "") for i in range(0,size):     if arr[i] == ele:             pos = i             temp = 1 if temp==1:     arr.pop(pos) print(""\nAfter deleting array elements are:"") print(arr)" 3084," Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions. Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function :","print abs.__doc__ print int.__doc__ print raw_input.__doc__ def square(num): '''Return the square value of the input number. The input number must be integer. ''' return num ** 2 print square(2) print square.__doc__ " 3085,Python Program to Implement Binary Heap,"class BinaryHeap: def __init__(self): self.items = []   def size(self): return len(self.items)   def parent(self, i): return (i - 1)//2   def left(self, i): return 2*i + 1   def right(self, i): return 2*i + 2   def get(self, i): return self.items[i]   def get_max(self): if self.size() == 0: return None return self.items[0]   def extract_max(self): if self.size() == 0: return None largest = self.get_max() self.items[0] = self.items[-1] del self.items[-1] self.max_heapify(0) return largest   def max_heapify(self, i): l = self.left(i) r = self.right(i) if (l <= self.size() - 1 and self.get(l) > self.get(i)): largest = l else: largest = i 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     bheap = BinaryHeap()   print('Menu') 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]) bheap.insert(data) elif operation == 'max': suboperation = do[1].strip().lower() if suboperation == 'get': print('Maximum value: {}'.format(bheap.get_max())) elif suboperation == 'extract': print('Maximum value removed: {}'.format(bheap.extract_max()))   elif operation == 'quit': break" 3086,Program to Find the sum of series 2+4+6+8.....+N,"n=int(input(""Enter the range of number:""))sum=0i=0while i<=n:    sum+=i    i+=2print(""The sum of the series = "",sum)" 3087,Python Program to Find the LCM of Two Numbers Using Recursion,"def lcm(a,b): lcm.multiple=lcm.multiple+b if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)): return lcm.multiple; else: lcm(a, b) return lcm.multiple lcm.multiple=0 a=int(input(""Enter first number:"")) b=int(input(""Enter second number:"")) if(a>b): LCM=lcm(b,a) else: LCM=lcm(a,b) print(LCM)" 3088,Program to read and display a Matrix,"# Get size of matrixrow_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 matrixprint(""Enter the Matrix Element:"")for i in range(row_size):    matrix.append([int(j) for j in input().split()])# display the Matrixprint(""Given Matrix is:"")for m in matrix:    print(m)" 3089,Find the type of the array," arr=[] odd_type=0 even_type=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(""Array elements are:"") for i in range(0,size):     print(arr[i],end="" "") for i in range(0,size):     if arr[i] % 2 == 0:         even_type +=1     else:         odd_type +=1 if even_type==size:         print(""\nEven type array"") elif odd_type==size:         print(""\nodd type array"") else:         print(""\nMixed array"")" 3090,Find out all Harshad numbers present within a given range," '''Write a Python program to find out all Harshad numbers present within a given range. or Write a program to find out all Harshad numbers present within a given range using Python ''' print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Harshad numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     num2=i     num=i     sum=0     while num!=0:         rem=num%10         num=int(num/10)         sum=sum+rem     if(num2%sum==0):         print(i,end="" "") " 3091,Find length of string using recursion,"def StringLength(str, i):    if (str[i] == '\0'):        return 0    else:        return (1 + StringLength(str, i + 1))str=input(""Enter your String:"")str+='\0'print(""Length of the String is: "",StringLength(str,0))" 3092,"Program to print series 1,-2,6,-15,31...N","n=int(input(""Enter the range of number(Limit):""))i=1pr=1while i<=n:    if(i%2==0):        print(-1*pr,end="" "")    else:        print(pr, end="" "")    pr+=pow(i,2)    i+=1" 3093,Program to compute the area and perimeter of Pentagon," import math print(""Enter the length of the side:"") a=int(input()) area=(math.sqrt(5*(5+2*math.sqrt(5)))*pow(a,2))/4.0 perimeter=(5*a) print(""Area of the Pentagon = "",area) print(""Perimeter of the Pentagon = "",perimeter) " 3094,Python Program to Find the Sum of Cosine Series,"import math def cosine(x,n): cosx = 1 sign = -1 for i in range(2, n, 2): pi=22/7 y=x*(pi/180) cosx = cosx + (sign*(y**i))/math.factorial(i) sign = -sign return cosx x=int(input(""Enter the value of x in degrees:"")) n=int(input(""Enter the number of terms:"")) print(round(cosine(x,n),2))" 3095,Find the 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 for j in range(0,size):     if (arr[j] <= min):         min = arr[j] print(""The smallest element of array: "",min)" 3096,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)" 3097," Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? Hint:"," def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2*i+4*j==numlegs: return i,j return ns,ns numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions " 3098,Write a program to print the alphabet 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),ord('A')-1,-1):         print(chr(i),end="" "")     print(""\r"") " 3099,Check whether a given number is an Abundant number or not," '''Write a Python program to check whether a given number is an Abundant number or not. or Write a program to check whether a given number is an Abundant number or not using Python ''' num=int(input(""Enter a number:"")) sum=0 for i in range(1,num):    if(num%i==0):       sum=sum+i if sum>num:    print(""It is an Abundant Number"") else:    print(""It is not an Abundant Number"") " 3100,Program to Find sum of series 1-2+3-4+5...+N,"n=int(input(""Enter the range of number:""))sum=0for i in range(1,n+1):    if i % 2 == 0:        sum -= i    else:        sum += iprint(""The sum of the series = "",sum)" 3101,Python Program to Read a List of Words and Return the Length of the Longest One,"a=[] n= int(input(""Enter the number of elements in list:"")) for x in range(0,n): element=input(""Enter element"" + str(x+1) + "":"") a.append(element) max1=len(a[0]) temp=a[0] for i in a: if(len(i)>max1): max1=len(i) temp=i print(""The word with the longest length is:"") print(temp)" 3102,Print Average of Numbers in array at even position ," arr=[] cout=0 sum=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) for j in range(1, size+1):     if (j % 2 == 0):         sum += arr[j]         cout+=1 avg = (sum / cout) print(""Average of Numbers in array at even position is "", avg)" 3103,Print First 50 natural numbers using recursion,"def PrintNaturalNumber(n):    if(n<=50):        print(n,end="" "")        PrintNaturalNumber(n + 1)n=1print(""First 50 Natural Numbers are:"")PrintNaturalNumber(n)" 3104,Check whether number is Disarium Number or Not," import math num=int(input(""Enter a number:"")) num1 = num c=0 while num1!=0:     num1 //= 10     c+=1 num1=num sum=0 while num1!=0:     rem = num1 % 10     sum += math.pow(rem, c)     num1 //= 10     c-=1 if sum==num:     print(""It is a Disarium Number."") else:    print(""It is Not a Disarium Number."")" 3105,"Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. :","def putNumbers(n): i = 0 while ij: sum += matrix[i][j] # display the sum of the Upper triangular matrix element print(""Sum of Upper Triangular Matrix Elements is: "",sum)" 3109,Python Program to Check if a Number is an Armstrong Number,"  n=int(input(""Enter any number: "")) a=list(map(int,str(n))) b=list(map(lambda x:x**3,a)) if(sum(b)==n): print(""The number is an armstrong number. "") else: print(""The number isn't an arsmtrong number. "")" 3110,Python Program to Find the Fibonacci Series without Using Recursion,"a=int(input(""Enter the first number of the series "")) b=int(input(""Enter the second number of the series "")) n=int(input(""Enter the number of terms needed "")) print(a,b,end="" "") while(n-2): c=a+b a=b b=c print(c,end="" "") n=n-1" 3111,Python Program to Read a String from the User and Append it into a File,"fname = input(""Enter file name: "") file3=open(fname,""a"") c=input(""Enter string to append: \n""); file3.write(""\n"") file3.write(c) file3.close() print(""Contents of appended file:""); file4=open(fname,'r') line1=file4.readline() while(line1!=""""): print(line1) line1=file4.readline() file4.close()" 3112,Remove all lowercase characters in the string," str=input(""Enter the String:"") str2 = [] i = 0 while i < len(str):     ch = str[i]     if not ch.islower():         str2.append(ch)     i += 1 Final_String = ''.join(str2) print(""After removing lowercase letter string is:"",Final_String)" 3113,Print prime numbers in a given range(1 to n)," import math print(""Enter a range to find all prime numbers within that range:"") range1=int(input()) range2=int(input()) print(""Prime numbers between "",range1,"" and "",range2,"" are: "") for j in range(range1,range2+1):       count=0 for i in range(2,int(math.sqrt(j))+1):       if j%i==0:         count+=1 if count==0:  print(j,end="" "") " 3114,Python Program to Check Common Letters in Two Input Strings,"s1=raw_input(""Enter first string:"") s2=raw_input(""Enter second string:"") a=list(set(s1)&set(s2)) print(""The common letters are:"") for i in a: print(i)" 3115,Python Program to Print Nth Node from the last 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 length_llist(llist): length = 0 current = llist.head while current: current = current.next length = length + 1 return length     def return_n_from_last(llist, n): l = length_llist(llist) current = llist.head for i in range(l - n): current = current.next return current.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))   n = int(input('The nth element from the end will be printed. Please enter n: ')) value = return_n_from_last(a_llist, n)   print('The nth element from the end: {}'.format(value))" 3116,"Program to convert seconds to hour, minute and seconds"," t_sec=int(input(""Enter the total Second:"")) hour=(int)(t_sec/3600) t_sec=(int)(t_sec%3600) mint=(int)(t_sec/60) sec=(int)(t_sec%60) print(""Hours="",hour,""\nMinutes="",mint,""\nSecond="",sec)" 3117,Python Program to Display the Nodes of a Tree using BFS Traversal,"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 bfs(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('bfs') 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 == 'bfs': if tree is None: print('Tree is empty.') else: print('BFS traversal: ', end='') tree.bfs() print()   elif operation == 'quit': break" 3118,Check given string is palindrome or not," str=input(""Enter the String:"") count = 0 j=len(str)-1 for i in range(len(str)):     if str[i]==str[j]:         count+=1     j-=1 if count==len(str):     print(""Input string is palindrome"") else:     print(""Input string is not palindrome"")" 3119,Python Program to Implement Stack using One Queue,"class Stack: def __init__(self): self.q = Queue()   def is_empty(self): return self.q.is_empty()   def push(self, data): self.q.enqueue(data)   def pop(self): for _ in range(self.q.get_size() - 1): dequeued = self.q.dequeue() self.q.enqueue(dequeued) return self.q.dequeue()     class Queue: def __init__(self): self.items = [] self.size = 0   def is_empty(self): return self.items == []   def enqueue(self, data): self.size += 1 self.items.append(data)   def dequeue(self): self.size -= 1 return self.items.pop(0)   def get_size(self): return self.size     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" 3120, 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-out,end="""")     np+=2     print(""\r"") " 3121,Python Program to Print an Inverted Star Pattern,"n=int(input(""Enter number of rows: "")) for i in range (n,0,-1): print((n-i) * ' ' + i * '*')" 3122,Write a program to print the alphabet 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),ord('A')-1,-1):         print(chr(out),end="" "")     print(""\r"") " 3123,Print lists 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 list_oc=9999 list_v=9999 for i in range(0, size):     if freq[arr[i]] < list_oc:         list_oc = freq[arr[i]]         list_v = arr[i] print(""The List occurring Number "",list_v,"" occurs "",list_oc,"" times."")" 3124,Python Program to Find the Sum of Digits in a Number without Recursion,"l=[] b=int(input(""Enter a number: "")) while(b>0): dig=b%10 l.append(dig) b=b//10 print(""Sum is:"") print(sum(l))" 3125,"Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers 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) sum1=0 sum2=0 sum3=0 for j in b: if(j>0): if(j%2==0): sum1=sum1+j else: sum2=sum2+j else: sum3=sum3+j print(""Sum of all positive even numbers:"",sum1) print(""Sum of all positive odd numbers:"",sum2) print(""Sum of all negative numbers:"",sum3)" 3126,Python Program to Implement D-ary-Heap,"class D_aryHeap: def __init__(self, d): self.items = [] self.d = d   def size(self): return len(self.items)   def parent(self, i): return (i - 1)//self.d   def child(self, index, position): return index*self.d + (position + 1)   def get(self, i): return self.items[i]   def get_max(self): if self.size() == 0: return None return self.items[0]   def extract_max(self): if self.size() == 0: return None largest = self.get_max() self.items[0] = self.items[-1] del self.items[-1] self.max_heapify(0) return largest   def max_heapify(self, i): largest = i for j in range(self.d): c = self.child(i, j) if (c < self.size() and self.get(c) > self.get(largest)): largest = c 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     d = int(input('Enter the value of D: ')); dheap = D_aryHeap(d)   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]) dheap.insert(data) elif operation == 'max': suboperation = do[1].strip().lower() if suboperation == 'get': print('Maximum value: {}'.format(dheap.get_max())) elif suboperation == 'extract': print('Maximum value removed: {}'.format(dheap.extract_max()))   elif operation == 'quit': break" 3127,Python Program to Read the Contents of a File in Reverse Order,"filename=input(""Enter file name: "") for line in reversed(list(open(filename))): print(line.rstrip())" 3128,"Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. :","Solution def printDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print d printDict() " 3129,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."")" 3130,Python Program to Find the Union of two Lists,"l1 = [] num1 = int(input('Enter size of list 1: ')) for n in range(num1): numbers1 = int(input('Enter any number:')) l1.append(numbers1)   l2 = [] num2 = int(input('Enter size of list 2:')) for n in range(num2): numbers2 = int(input('Enter any number:')) l2.append(numbers2)   union = list(set().union(l1,l2))   print('The Union of two lists is:',union)" 3131,Python Program to Implement Queue Data Structure using Linked List,"class Node: def __init__(self, data): self.data = data self.next = None   class Queue: def __init__(self): self.head = None self.last = None   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 = self.last.next   def dequeue(self): if self.head is None: return None else: to_return = self.head.data self.head = self.head.next return to_return   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': dequeued = a_queue.dequeue() if dequeued is None: print('Queue is empty.') else: print('Dequeued element: ', int(dequeued)) elif operation == 'quit': break" 3132," Print a unicode string ""hello world"". :"," unicodeString = u""hello world!"" print unicodeString " 3133," Please write a program to generate all sentences where subject is in [""I"", ""You""] and verb is in [""Play"", ""Love""] and the object is in [""Hockey"",""Football""]. :"," subjects=[""I"", ""You""] verbs=[""Play"", ""Love""] objects=[""Hockey"",""Football""] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = ""%s %s %s."" % (subjects[i], verbs[j], objects[k]) print sentence " 3134,Check whether a given number is a perfect square number or not. ," '''Write a Python program to check whether a given number is a perfect square number or not. or  Write a program to check whether a given number is a perfect square number or not using Python ''' import math num=int(input(""Enter a number:"")) sqr=math.sqrt(num) if sqr-math.floor(sqr)==0:    print(""It is a Perfect Square"") else:    print(""It is not a Perfect Square"") " 3135,Python Program to Calculate the Average of Numbers in a Given List,"  n=int(input(""Enter the number of elements to be inserted: "")) a=[] for i in range(0,n): elem=int(input(""Enter element: "")) a.append(elem) avg=sum(a)/n print(""Average of elements in the list"",round(avg,2))" 3136,Check whether number is Pronic Number or Not," import math num=int(input(""Enter a number:"")) flag=0 for i in range(0,num+1):     if i*(i+1)==num:         flag=1         break if flag==1:     print(""It is a Pronic Number."") else:    print(""It is Not a Pronic Number."")" 3137,Check if given String is palindrome using recursion,"c=0def Check_Palindrome(str,i,length):    global c    if (i < len(str)):        if (str[i] == str[length]):            c +=1            Check_Palindrome(str, i + 1, length-1)    return cstr=input(""Enter your String:"")if(Check_Palindrome(str,0,len(str)-1)==len(str)):    print(""It is a Palindrome String."")else: print(""It is not a Palindrome String."")" 3138,Find maximum product of 3 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)First_element=arr[0]Second_element=arr[1]third_element=arr[2]Max_Product=First_element*Second_element*third_elementfor i in range(0,size-2):    for j in range(i+1, size-1):        for k in range(j + 1, size):            product=arr[i]*arr[j]*arr[k]            if abs(product) >= abs(Max_Product):                Max_Product =product                First_element = arr[i]                Second_element = arr[j]                third_element=arr[k]print(""Maximum Product of 3 numbers pair is ("",First_element,"","",Second_element,"","",third_element,"")"")print(""Maximum Product of 3 numbers is "",Max_Product)" 3139,Print all the odd numbers from 1 to n," n=int(input(""Enter the n value:"")) print(""Printing Odd numbers between 1 to "",n) for i in range(1,n+1):     if i%2!=0:      print(i,end="" "")" 3140,"Program to print series 10,5,60,15,110...N"," print(""Enter the range of number(Limit):"") n=int(input()) a=10 b=5 i=1 while(i<=n):     if(i%2==0):         print(b,end="" "")         b += 10     else:         print(a, end="" "")         a += 50     i+=1" 3141,Program to find sum of series (1+(1+2)+(1+2+3)+...till 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):     for j in range(1,i+1):         sum+=j     i+=1 print(""The sum of the series = "",sum)" 3142,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)" 3143,Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat,"a=[] n= int(input(""Enter the number of elements in list:"")) for x in range(0,n): element=input(""Enter element"" + str(x+1) + "":"") a.append(element) print(a) c=[] count=0 b=input(""Enter word to remove: "") n=int(input(""Enter the occurrence to remove: "")) for i in a: if(i==b): count=count+1 if(count!=n): c.append(i) else: c.append(i) if(count==0): print(""Item not found "") else: print(""The number of repetitions is: "",count) print(""Updated list is: "",c) print(""The distinct elements are: "",set(a))" 3144,Program to convert Hexadecimal to Decimal ," 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 print(""Decimal Number is:"",decimal)" 3145,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)" 3146,Find factorial of a number using recursion,"def Factorial(num):    if num<=0:        return 1    else:        return num*Factorial(num-1)num=int(input(""Enter the Number:""))print(""Factorial of Given Number Using Recursion is:"",Factorial(num))" 3147,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))" 3148,Write a program to find the nth strong number," '''Write a Python program to find the nth strong number. or Write a program to find the nth strong number using Python ''' print(""Enter the Nth value:"") rangenumber=int(input()) num = 1 c = 0 letest = 0 while (c != rangenumber):     num2 = num     num1 = num     sum = 0     fact = 1     while (num1 != 0):         fact = 1         rem = num1 % 10         num1 = num1 // 10         for j in range(1,rem+1):             fact = fact * j         sum = sum + fact     if (sum == num2):         c+=1         letest = num     num = num + 1 print(rangenumber,""th strong number is "",letest)  " 3149,Python Program to Implement 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     g = Graph() print('Menu') print('add vertex ') print('add edge [weight]') 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): if len(do) == 5: weight = int(do[4]) g.add_edge(src, dest, weight) else: g.add_edge(src, dest) else: print('Edge already exists.')   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" 3150,program to find the prime factors of a number," import math num=int(input(""Enter a number:"")) print(""Prime Factors of "",num,end="" are \n"") while num%2==0:     print(2,)     num=num/2 for i in range(3,int(math.sqrt(num))+1,2):    while num%i==0:       print(i,)       num = num/i if num>2:   print(num) " 3151," 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 " 3152," Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. :"," import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) " 3153,Python Program to Take in Two Strings and Display the Larger String without Using Built-in Functions,"string1=raw_input(""Enter first string:"") string2=raw_input(""Enter second string:"") count1=0 count2=0 for i in string1: count1=count1+1 for j in string2: count2=count2+1 if(count1') print('add edge ') print('bellman-ford ') 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 == 'bellman-ford': key = int(do[1]) source = g.get_vertex(key) distance = bellman_ford(g, source) print('Distances from {}: '.format(key)) for v in distance: print('Distance to {}: {}'.format(v.get_key(), distance[v])) 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" 3158,Python Program to Count the Number of Blank Spaces in a Text File,"fname = input(""Enter file name: "") 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.isspace): k=k+1 print(""Occurrences of blank spaces:"") print(k)" 3159,Print the Solid Diamond Number Pattern,"row_size=int(input(""Enter the row size:""))x=1for 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(x,end="" "")    if out > 0:        x +=1    else:        x -=1    print(""\r"")" 3160,"With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. :","Solution tp=(1,2,3,4,5,6,7,8,9,10) tp1=tp[:5] tp2=tp[5:] print tp1 print tp2 " 3161,Find sum of Odd numbers using recursion in an array,"sum=0def SumOfOddElement(arr,n):    global sum    if(n>0):        i=n-1        if(arr[i]%2==1):            sum=sum+arr[i]        SumOfOddElement(arr,i)    return sumarr=[]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(""Sum of Odd Element is:"",SumOfOddElement(arr,n))" 3162,Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. ,"freq = {} # frequency of words in text line = raw_input() for word in line.split(): freq[word] = freq.get(word,0)+1 words = freq.keys() words.sort() for w in words: print ""%s:%d"" % (w,freq[w]) " 3163," Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. :"," li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li " 3164,Python Program to Exchange the Values of Two Numbers Without Using a Temporary Variable,"  a=int(input(""Enter value of first variable: "")) b=int(input(""Enter value of second variable: "")) a=a+b b=a-b a=a-b print(""a is:"",a,"" b is:"",b)" 3165,Python Program to Check if a Date is Valid and Print the Incremented Date if it is,"  date=input(""Enter the date: "") dd,mm,yy=date.split('/') dd=int(dd) mm=int(mm) yy=int(yy) if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12): max1=31 elif(mm==4 or mm==6 or mm==9 or mm==11): max1=30 elif(yy%4==0 and yy%100!=0 or yy%400==0): max1=29 else: max1=28 if(mm<1 or mm>12): print(""Date is invalid."") elif(dd<1 or dd>max1): print(""Date is invalid."") elif(dd==max1 and mm!=12): dd=1 mm=mm+1 print(""The incremented date is: "",dd,mm,yy) elif(dd==31 and mm==12): dd=1 mm=1 yy=yy+1 print(""The incremented date is: "",dd,mm,yy) else: dd=dd+1 print(""The incremented date is: "",dd,mm,yy)" 3166,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)" 3167,Python Program to Compute Simple Interest Given all the Required Values,"  principle=float(input(""Enter the principle amount:"")) time=int(input(""Enter the time(years):"")) rate=float(input(""Enter the rate:"")) simple_interest=(principle*time*rate)/100 print(""The simple interest is:"",simple_interest)" 3168,Program to Find nth Happy Number ," rangenumber=int(input(""Enter a Nth Number:"")) c = 0 letest = 0 num = 1 while c != rangenumber:     sum = 0     num1=num     while sum != 1 and sum != 4:         sum = 0         while num1 != 0:             rem = num1 % 10             sum += (rem * rem)             num1 //= 10         num1 = sum     if sum == 1:             c+=1             letest = num     num = num + 1 print(rangenumber,""th Happy number is "",letest)" 3169,Write a program to print the pattern," import java.util.Scanner; public class p10 { public static void main(String[] args) { Scanner cs=new Scanner(System.in); System.out.println(""Enter the row and column size:""); int row_size,out,in;   row_size=cs.nextInt();   for(out=row_size;out>=1;out--)   {    for(in=1;in<=row_size;in++)     System.out.print(out);         System.out.println();   } cs.close(); } }" 3170,Find out all Magic numbers present within a given range," print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Magic numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     num3 = i     num1 = i     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:         print(i,end="" "")" 3171,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)" 3172," Please write assert statements to verify that every number in the list [2,4,6,8] is even. :"," li = [2,4,6,8] for i in li: assert i%2==0 " 3173," Please write a program which count and print the numbers of each character in a string input by console. "," dic = {} s=raw_input() for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) " 3174, Find out all Armstrong numbers present within a given range," print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Armstrong numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     num2=i     num1=i     sum=0     while(num1!=0):         rem=num1%10         num1=int(num1/10)         sum=sum+rem*rem*rem     if sum==num2: print(i,end="" "")  " 3175,Python Program to Implement Gnome Sort,"def gnome_sort(alist): for pos in range(1, len(alist)): while (pos != 0 and alist[pos] < alist[pos - 1]): alist[pos], alist[pos - 1] = alist[pos - 1], alist[pos] pos = pos - 1     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] gnome_sort(alist) print('Sorted list: ', end='') print(alist)" 3176,Program to print Triangular Number series 1 3 6 10 15 ...N," print(""Enter the range of number(Limit):"") n=int(input()) i=1 while(i<=n):     print((int)((i*(i+1))/2),end="" "")     i+=1" 3177,Python Program to Find Shortest Path From a Vertex using BFS in an Unweighted 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 # dictionary containing destination vertices mapped to the weight of the # edge with which they are joined to this vertex 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_shortest_paths(src): """"""Returns tuple of two dictionaries: (parent, distance)   parent contains vertices mapped to their parent vertex in the shortest path from src to that vertex. distance contains vertices mapped to their shortest distance from src. """""" parent = {src: None} distance = {src: 0}   visited = set() q = Queue() q.enqueue(src) visited.add(src) 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 distance[dest] = distance[current] + 1 q.enqueue(dest) return (parent, distance)   g = Graph() print('Menu') print('add vertex ') print('add edge ') print('shortest ') 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 == 'shortest': key = int(do[1]) src = g.get_vertex(key) parent, distance = find_shortest_paths(src)   print('Path from destination vertices to source vertex {}:'.format(key)) for v in parent: print('Vertex {} (distance {}): '.format(v.get_key(), distance[v]), end='') while parent[v] is not None: print(v.get_key(), end = ' ') v = parent[v] print(src.get_key()) # print source vertex   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" 3178,Python Program to Find if Undirected Graph is Bipartite 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 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     def is_bipartite(vertex, visited): """"""Return True if component containing vertex is bipartite and put all vertices in its component in set visited."""""" colour = {vertex: 0} return is_bipartite_helper(vertex, visited, colour)     def is_bipartite_helper(v, visited, colour): """"""Return True if component containing vertex is bipartite and put all vertices in its component in set visited. Uses dictionary colour to keep track of colour of each vertex."""""" visited.add(v) next_colour = 1 - colour[v] # switch colour for dest in v.get_neighbours(): if dest not in visited: colour[dest] = next_colour if not is_bipartite_helper(dest, visited, colour): return False else: if colour[dest] != next_colour: return False return True     g = Graph() print('Undirected Graph') print('Menu') print('add vertex ') print('add edge ') print('bipartite') 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 == 'bipartite': bipartite = True visited = set() for v in g: if v not in visited: if not is_bipartite(v, visited): bipartite = False break   if bipartite: print('Graph is bipartite.') else: print('Graph is not bipartite.')   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" 3179,Subtract Two Numbers Operator without using Minus(-) operator," num1=int(input(""Enter first number:"")) num2=int(input(""Enter  second number:"")) sub=num1+(~num2+1)#number + 2's complement of number print(""Subtraction of two number is "",sub) " 3180,Python Program to Find Longest Common Subsequence using Dynamic Programming with Memoization,"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)] lcs_helper(u, v, c, 0, 0) return c     def lcs_helper(u, v, c, i, j): """"""Return length of LCS of u[i:] and v[j:] and fill in table c.   c[i][j] contains the length of LCS 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 else: if u[i] == v[j]: q = 1 + lcs_helper(u, v, c, i + 1, j + 1) else: q = max(lcs_helper(u, v, c, i + 1, j), lcs_helper(u, v, c, i, j + 1)) c[i][j] = q return q     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)" 3181,Python Program to Print the Alternate 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 alternate(self): self.alternate_helper(self.head)   def alternate_helper(self, current): if current is None: return print(current.data, end = ' ') if current.next: self.alternate_helper(current.next.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 alternate nodes of the linked list: ', end = '') a_llist.alternate()" 3182,Program to Find the factorial of a number," num=int(input(""Enter a number:"")) fact=1 for i in range(1,num+1):    fact=fact*i print(""The Factorial is"",fact) " 3183,Quick Sort Program in Python | Java | C | C++," def partition(arr,first,last):     i=first-1     x=arr[last]     for j in range(first,last):         if(arr[j]1 Please write a program to compute the value of f(n) with a given n input by console. "," def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) print f(n) " 3190," Please write a program which accepts a string from console and print it in reverse order. "," s=raw_input() s = s[::-1] print s " 3191,Sort array in ascending order using recursion,"def swap_Element(arr,i,j):    temp = arr[i]    arr[i] = arr[j]    arr[j] = tempdef 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)        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)sort_element(arr,n)print(""After ascending  order sort Array Elements are:"")printArr(arr, n)" 3192,Check whether a given number is a perfect number or not," num=int(input(""Enter a number:"")) sum=0 for i in range(1,num):    if(num%i==0):       sum=sum+i if sum==num:    print(""It is a Perfect Number"") else:     print(""It is not a Perfect Number"")  " 3193,Program to find sum of series 1!+2!+3!...+n!," print(""Enter the range of number:"") n=int(input()) sum=0 fact=1 for i in range(1,n+1):     fact*=i     sum+=fact print(""The sum of the series = "",sum)" 3194,Python Program to Check if a String is a Pangram or Not,"from string import ascii_lowercase as asc_lower def check(s): return set(asc_lower) - set(s.lower()) == set([]) strng=raw_input(""Enter string:"") if(check(strng)==True): print(""The string is a pangram"") else: print(""The string isn't a pangram"")" 3195,Program to Find area and perimeter of a square," side=int(input(""Enter side of a square :"")) area=side*side perimeter=4*side print(""Area of the Square="",area) print(""Perimeter of the square="",perimeter)" 3196,"Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence.","#!/usr/bin/env python import math c=50 h=30 value = [] items=[x for x in raw_input().split(',')] for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print ','.join(value) " 3197,Python Program to Find the Gravitational Force Acting Between Two Objects,"m1=float(input(""Enter the first mass: "")) m2=float(input(""Enter the second mass: "")) r=float(input(""Enter the distance between the centres of the masses: "")) G=6.673*(10**-11) f=(G*m1*m2)/(r**2) print(""Hence, the gravitational force is: "",round(f,2),""N"")" 3198,Print the ASCII value of character in a String," str=input(""Enter the String:"") print(""ASCII values of letters in string are:"") for i in range(len(str)):     print(str[i],"" ==> "",(ord)(str[i]))" 3199,Check prime number using Recursion,"def CheckPrime(i,num):    if num==i:        return 0    else:        if(num%i==0):            return 1        else:            return CheckPrime(i+1,num)num=int(input(""Enter your Number:""))if(CheckPrime(2,num)==0):    print(""It is a Prime Number."")else:    print(""It is not a Prime Number."")" 3200,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))" 3201, Find the largest 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) max=-sys.maxsize-1 for j in range(0,size):     if (arr[j] >= max):         max = arr[j] print(""The largest element of array: "",max)" 3202, Program to print the Solid Half Diamond Alphabet 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((chr)(inn+65),end="""")    print(""\r"")" 3203,Write a program to find the nth strong number," '''Write a Python program to find the nth strong number. or Write a program to find the nth strong number using Python ''' print(""Enter the Nth value:"") rangenumber=int(input()) num = 1 c = 0 letest = 0 while (c != rangenumber):     num2 = num     num1 = num     sum = 0     fact = 1     while (num1 != 0):         fact = 1         rem = num1 % 10         num1 = num1 // 10         for j in range(1,rem+1):             fact = fact * j         sum = sum + fact     if (sum == num2):         c+=1         letest = num     num = num + 1 print(rangenumber,""th strong number is "",letest)  " 3204,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 temp < alist[j]): alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = temp     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] insertion_sort(alist) print('Sorted list: ', end='') print(alist)" 3206,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)  " 3207,Program to calculate speed in km/hr," d=float(input(""Enter the Distance in Kms:"")) t=float(input(""Enter the Time in Hrs:"")) speed=d/t print(""Speed is "",speed,"" (Km/Hr)"")" 3208,Program to convert binary to decimal using while loop," print(""Enter Binary number:"") binary=int(input()) decimal= 0 temp = 0 while (binary!=0):         reminder = binary % 10         binary = binary // 10         decimal = decimal + reminder*pow(2,temp)         temp=temp+1 print(""Decimal number is: "",decimal)  " 3209,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)" 3210,Program to find sum of series 1!/1+2!/2+3!/3+4!/4+5!/5 ...+n!/n," print(""Enter the range of number:"") n=int(input()) sum=0.0 fact=1 for i in range(1,n+1):     fact*=i     sum+=fact/i print(""The sum of the series = "",sum)" 3211,Python Program to Find Minimum Spanning Tree using Prim’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 display(self): print('Vertices: ', end='') for v in self: print(v.get_key(), end=' ') print()   print('Edges: ') for v in self: for dest in v.get_neighbours(): w = v.get_weight(dest) print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))   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 mst_prim(g): """"""Return a minimum cost spanning tree of the connected graph g."""""" mst = Graph() # create new Graph object to hold the MST   # if graph is empty if not g: return mst   # nearest_neighbour[v] is the nearest neighbour of v that is in the MST # (v is a vertex outside the MST and has at least one neighbour in the MST) nearest_neighbour = {} # smallest_distance[v] is the distance of v to its nearest neighbour in the MST # (v is a vertex outside the MST and has at least one neighbour in the MST) smallest_distance = {} # v is in unvisited iff v has not been added to the MST unvisited = set(g)   u = next(iter(g)) # select any one vertex from g mst.add_vertex(u.get_key()) # add a copy of it to the MST unvisited.remove(u)   # for each neighbour of vertex u for n in u.get_neighbours(): if n is u: # avoid self-loops continue # update dictionaries nearest_neighbour[n] = mst.get_vertex(u.get_key()) smallest_distance[n] = u.get_weight(n)   # loop until smallest_distance becomes empty while (smallest_distance): # get nearest vertex outside the MST outside_mst = min(smallest_distance, key=smallest_distance.get) # get the nearest neighbour inside the MST inside_mst = nearest_neighbour[outside_mst]   # add a copy of the outside vertex to the MST mst.add_vertex(outside_mst.get_key()) # add the edge to the MST mst.add_edge(outside_mst.get_key(), inside_mst.get_key(), smallest_distance[outside_mst]) mst.add_edge(inside_mst.get_key(), outside_mst.get_key(), smallest_distance[outside_mst])   # now that outside_mst has been added to the MST, remove it from our # dictionaries and the set unvisited unvisited.remove(outside_mst) del smallest_distance[outside_mst] del nearest_neighbour[outside_mst]   # update dictionaries for n in outside_mst.get_neighbours(): if n in unvisited: if n not in smallest_distance: smallest_distance[n] = outside_mst.get_weight(n) nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key()) else: if smallest_distance[n] > outside_mst.get_weight(n): smallest_distance[n] = outside_mst.get_weight(n) nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())   return mst     g = Graph() print('Undirected Graph') print('Menu') print('add vertex ') print('add edge ') print('mst') 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) g.add_edge(dest, src, weight) else: print('Edge already exists.')   elif operation == 'mst': mst = mst_prim(g) print('Minimum Spanning Tree:') mst.display() print()   elif operation == 'display': g.display() print()   elif operation == 'quit': break" 3212,Print numbers from 1 to 100 using for loop,"for i in range(1,101):     print(i,end="" "")" 3213,Python Program to Find the Sum of all Nodes 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 sum_nodes(self): summation = self.key for child in self.children: summation = summation + child.sum_nodes() return summation     tree = None   print('Menu (this assumes no duplicate keys)') print('add at root') print('add below ') print('sum') 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 == 'sum': if tree is None: print('Tree is empty.') else: summation = tree.sum_nodes() print('Sum of all nodes: {}'.format(summation))   elif operation == 'quit': break" 3214,Print the Full Inverted Pyramid Number Pattern,"row_size=int(input(""Enter the row size:""))for out in range(row_size,0,-1):    for inn in range(row_size,out,-1):        print("" "",end="""")    for p in range(out,0,-1):        print(out,end="" "")    print(""\r"")" 3215,Program to find sum of series 1/2-2/3+3/4-4/5+5/6...+N/N+1," print(""Enter the range of number(Limit):"") n=int(input()) i=1 sum=0.0 while(i<=n):     if(i%2==0):         sum-=i/(i+1)     else:         sum+=i/(i+1)     i+=1 print(""The sum of the series = "",sum)" 3216,Check whether number is Happy Number or Not," num=int(input(""Enter a number:"")) sum=0 while sum != 1 and sum != 4:     sum=0     while num!=0:         rem = num % 10         sum += (rem*rem)         num //= 10     num=sum if sum==1:     print(""It is a Happy Number."") else:    print(""It is  an Unhappy Number."")" 3217,Find the length of the string using the inbuilt function," str=input(""Enter the String:"") print(""Your Enter String is:"", len(str))" 3218,Python Program to Take in a String and Replace Every Blank Space with Hyphen,"string=raw_input(""Enter string:"") string=string.replace(' ','-') print(""Modified string:"") print(string)" 3219,Python Program to Find the Cumulative Sum of a List where the ith Element is the Sum of the First i+1 Elements From The Original 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=[sum(a[0:x+1]) for x in range(0,len(a))] print(""The original list is: "",a) print(""The new list is: "",b)" 3220,Program to enter basic salary and calculate gross salary of an employee," basic=float(input(""Enter the basic salary of an employee:"")) da = (float)(15 * basic) / 100.0 hr = (float)(10 * basic) / 100.0 da_on_ta = (float)(3 * basic) / 100.0 gross = basic + da + hr + da_on_ta print(""Gross salary of an Employee= "",gross)" 3221,Python Program to Solve Rod Cutting Problem using Dynamic Programming with Bottom-Up Approach,"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) r[0] = 0   # s[i] is the length of the initial cut needed for rod length i # s[0] is not needed s = [-1]*(n + 1)   for i in range(1, n + 1): q = -1 for j in range(1, i + 1): temp = p[j] + r[i - j] if q < temp: q = temp s[i] = j r[i] = q   return r, s     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]" 3222,Python Program to Check Whether a String is a Palindrome or not Using Recursion,"def is_palindrome(s): if len(s) < 1: return True else: if s[0] == s[-1]: return is_palindrome(s[1:-1]) else: return False a=str(input(""Enter string:"")) if(is_palindrome(a)==True): print(""String is a palindrome!"") else: print(""String isn't a palindrome!"")" 3223,Program to Find the sum of series 1³+2³+3³+4³.....+N³,"n=int(input(""Enter the range of number:""))sum=0for i in range(1,n+1):    sum+=pow(i,3)print(""The sum of the series = "",sum)" 3224,Write C|Java|C++|Python Program to compute x^n/n!," n=int(input(""Enter the n Value:"")) x=int(input(""Enter the x value:"")) fact=1 for i in range(1,n+1):     fact*=i result=pow(x,n)/fact print(""Result(x^n/n!)= "",result) " 3225,Program to Convert Hexadecimal Number to Binary," print(""Enter a HexaDecimal number:"") hex=input() binary="""" i=0 j=1 for i in range(0,len(hex)):     if hex[i]=='F' :         binary=binary+""1111""     elif hex[i]==""E"":         binary=binary+""1110""     elif hex[i]==""D"":         binary=binary+""1101""     elif hex[i]==""C"":         binary=binary+""1100""     elif hex[i]==""B"":         binary=binary+""1011""     elif hex[i]==""A"":         binary=binary+""1010""     else:         st=hex[i:i+1]         decimal=0         temp=1         hexnum=int(st)         while hexnum!=0:             remainder=hexnum%2             hexnum=hexnum//2             decimal=decimal+remainder*temp             temp=temp*10         str1=str(decimal)         if len(str1)==3:             str1=""0""+str1         if len(str1)==2:             str1=""00""+str1         if len(str1)==1:             str1=""000""+str1         binary=binary+str1 print(""HexaDecimal to Binary is"",binary) " 3226," Write a method which can calculate square value of number :","def square(num): return num ** 2 print square(2) print square(3) " 3227,Find out all Happy numbers present within a given range," print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Happy numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     num=i     sum=0     while sum != 1 and sum != 4:         sum = 0         while num != 0:             rem = num % 10             sum += (rem * rem)             num //= 10         num = sum     if sum == 1:         print(i,end="" "")" 3228,Python Program to Print only Nodes in Left SubTree,"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 print_left(self): if self.left is not None: self.left.inorder()     btree = None   print('Menu (this assumes no duplicate keys)') print('insert at root') print('insert left of ') print('insert right of ') print('left') 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 == 'left': print('Nodes of left subtree: ', end='') if btree is not None: btree.print_left() print()   elif operation == 'quit': break" 3229,Print Average of Numbers in array at Odd position ," arr=[] cout=0 sum=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) for j in range(0, size):     if ((j+1) % 2 == 1):         sum += arr[j]         cout+=1 avg = (sum / cout) print(""Average of Numbers in array at odd position is "", avg)" 3230," With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. :"," set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print li " 3231,Sum of elements in array using recursion,"sum=0def SumOfArray(arr,n):    global sum    if(n>0):        i=n-1        sum=sum+arr[i]        SumOfArray(arr,i)    return sumarr=[]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(""Sum of Array Element is:"",SumOfArray(arr,n))" 3232,Find the sum of negative and positive numbers in 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_pos=0.0 sum_neg=0.0 for j in range(0,size):         if (arr[j] > 0):             sum_pos += arr[j]         else:             sum_neg += arr[j] print(""sum of positive number : "",sum_pos) print(""sum of Negative number : "",sum_neg)" 3233,Python Program to Check if a Number is a Perfect Number,"  n = int(input(""Enter any number: "")) sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): print(""The number is a Perfect number!"") else: print(""The number is not a Perfect number!"")" 3234,Python Program to Find Whether a Number is a Power of Two,"def is_power_of_two(n): """"""Return True if n is a power of two."""""" if n <= 0: return False else: return n & (n - 1) == 0     n = int(input('Enter a number: '))   if is_power_of_two(n): print('{} is a power of two.'.format(n)) else: print('{} is not a power of two.'.format(n))" 3235,Python Program to Select the ith Smallest Element from a List in Expected Linear Time,"def select(alist, start, end, i): """"""Find ith smallest element in alist[start... end-1]."""""" if end - start <= 1: return alist[start] pivot = partition(alist, start, end)   # number of elements in alist[start... pivot] k = pivot - start + 1   if i < k: return select(alist, start, pivot, i) elif i > k: return select(alist, pivot + 1, end, 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))" 3236,Program to print all alphabets from A to Z using loop,"print(""Printing A-Z using ASCII"") for i in range(65,90+1):     print(chr(i),end="" "")" 3237,Program to find the sum of series 1+3+5+7..+N," print(""Enter the range of number:"") n=int(input()) sum=0 i=1 while(i<=n):     sum+=i     i+=2 print(""The sum of the series = "",sum)" 3238,Find the Minimum occurring character in given string,"str=input(""Enter Your String:"")min=999arr=[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])] <= min:            min = arr[ord(str[i])]            ch=str[i]print(""The Minimum occurring character in a string is "",ch)" 3239,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)" 3240,"Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). :","Solution def printTuple(): li=list() for i in range(1,21): li.append(i**2) print tuple(li) printTuple() " 3241,Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers,"class sub: def f1(self, s1): return self.f2([], sorted(s1))   def f2(self, curr, s1): if s1: return self.f2(curr, s1[1:]) + self.f2(curr + [s1[0]], s1[1:]) return [curr] a=[] n=int(input(""Enter number of elements of list: "")) for i in range(0,n): b=int(input(""Enter element: "")) a.append(b) print(""Subsets: "") print(sub().f1(a))" 3242,Python Program to Print All Permutations of a String in Lexicographic Order using Recursion,"from math import factorial   def print_permutations_lexicographic_order(s): """"""Print all permutations of string s in lexicographic order."""""" seq = list(s) for _ in range(factorial(len(seq))): print(''.join(seq)) nxt = get_next_permutation(seq) # if seq is the highest permutation if nxt is None: # then reverse it seq.reverse() else: seq = nxt   def get_next_permutation(seq): """"""Return next greater lexicographic permutation. Return None if cannot.   This will return the next greater permutation of seq in lexicographic order. If seq is the highest permutation then this will return None.   seq is a list. """""" if len(seq) == 0: return None   nxt = get_next_permutation(seq[1:])   # if seq[1:] is the highest permutation if nxt is None: # reverse seq[1:], so that seq[1:] now is in ascending order seq[1:] = reversed(seq[1:])   # find q such that seq[q] is the smallest element in seq[1:] such that # seq[q] > seq[0] q = 1 while q < len(seq) and seq[0] > seq[q]: q += 1   # if cannot find q, then seq is the highest permutation if q == len(seq): return None   # swap seq[0] and seq[q] seq[0], seq[q] = seq[q], seq[0]   return seq else: return [seq[0]] + nxt     s = input('Enter the string: ') print_permutations_lexicographic_order(s)" 3243,Python Program to Remove the nth Index Character from a Non-Empty String,"def remove(string, n): first = string[:n] last = string[n+1:] return first + last string=raw_input(""Enter the sring:"") n=int(input(""Enter the index of the character to remove:"")) print(""Modified string:"") print(remove(string, n))" 3244,Write a Program to Find the nth Prime Number," '''Write a Python program to find the nth prime number. or Write a program to find the nth prime number using Python ''' print(""Enter Nth Number:"") rangenumber=int(input()) c = 0 num = 2 letest = 0 while (c != rangenumber):    count = 0    for i in range(2,num):       if (num % i == 0):          count+=1          break    if (count == 0):       c+=1       letest = num    num = num + 1 print (rangenumber,""th prime number is "",letest) " 3245,Find words ending with given characters(suffix),"str=input(""Enter Your String:"")ch=input(""Enter the Character:"")sub_str=str.split("" "")print(""All the words ending with "",ch,"" are:"")for inn in range(0,len(sub_str)):    if sub_str[inn].endswith(ch):        print(sub_str[inn],end="" "")" 3246,Python Program to Implement Linear Search,"def linear_search(alist, key): """"""Return index of key in alist. Return -1 if key not present."""""" for i in range(len(alist)): if alist[i] == key: return i return -1     alist = input('Enter the list of numbers: ') alist = alist.split() alist = [int(x) for x in alist] key = int(input('The number to search for: '))   index = linear_search(alist, key) if index < 0: print('{} was not found.'.format(key)) else: print('{} was found at index {}.'.format(key, index))" 3247,Python Program to Solve n-Queen Problem with 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 get_size(self): return self.size   def get_queens_count(self): return len(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 print_all_solutions_to_n_queen(size): """"""Display a chessboard for each possible configuration of placing n queens on an n x n chessboard where n = size and print the number of such configurations."""""" board = QueenChessBoard(size) number_of_solutions = print_all_solutions_helper(board) print('Number of solutions:', number_of_solutions)   def print_all_solutions_helper(board): """"""Display a chessboard for each possible configuration of filling the given board with queens and return the number of such configurations."""""" size = board.get_size()   # if board is full, display solution if size == board.get_queens_count(): board.display() print() return 1   number_of_solutions = 0 # place queen in next row for column in range(size): if board.is_this_column_safe_in_next_row(column): board.place_in_next_row(column) number_of_solutions += print_all_solutions_helper(board) board.remove_in_current_row()   return number_of_solutions     n = int(input('Enter n: ')) print_all_solutions_to_n_queen(n)" 3248,Python Program to Swap the First and Last Value of 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) temp=a[0] a[0]=a[n-1] a[n-1]=temp print(""New list is:"") print(a)" 3249,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"") " 3250,Program to convert a decimal number to Binary,"print(""Enter a Decimal Number: "") decimal=int(input()) binary = 0 temp = 1 while (decimal != 0):     reminder = decimal % 2     decimal = decimal // 2     binary =int (binary + (reminder * temp))     temp =int( temp * 10) print(""The Binary Number is: "",binary) " 3251,Find the sum of digits of a number using recursion,"def SumOfDigits(num):    if num==0:        return 0    else:        return ((num%10) +SumOfDigits(num//10))num=int(input(""Enter the Number:""))print(""Sum of digits of given Number Using Recursion is:"",SumOfDigits(num))" 3252,Check if a string contains at least one Number,"str=input(""Enter Your String:"")count=0for inn in range(0,len(str)):    if str[inn] >= '0' and  str[inn] <= '9':        count+=1if count>=1:    print(""String contains at least one digits."")else:    print(""String does not contains at least one digits."")" 3253,"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 values only. :","Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print v printDict() " 3254,Program to print series -1 4 -7 10 -13 16 -19...n," print(""Enter the range of number(Limit):"") n=int(input()) i=1 se=1 while(i<=n):     if(i%2==0):         print(se,end="" "")     else:         print(-1*se, end="" "")     se+=3     i+=1" 3255,Python Program to Print nth Fibonacci Number using Dynamic Programming with Bottom-Up Approach,"def fibonacci(n): """"""Return the nth Fibonacci number."""""" if n == 0: return 0   # r[i] will contain the ith Fibonacci number r = [-1]*(n + 1) r[0] = 0 r[1] = 1   for i in range(2, n + 1): r[i] = r[i - 1] + r[i - 2]   return r[n]     n = int(input('Enter n: '))   ans = fibonacci(n) print('The nth Fibonacci number:', ans)" 3256,Find the First small Letter in a given String," str=input(""Enter the String:"") ch=' ' for i in range(len(str)):     if str[i] >= 'a' and str[i] <= 'z':         ch = str[i]         break     else:         continue print(""First small letter in a given String is: "", ch)" 3257,Program to compute the area and perimeter of Octagon," import math print(""Enter the length of the side:"") a=int(input()) area=(2*(1+math.sqrt(2))*math.pow(a,2)) perimeter=(8*a) print(""Area of the Octagon = "",area) print(""Perimeter of the Octagon = "",perimeter) " 3258,Python Program to Check if a Number is a Palindrome,"  n=int(input(""Enter number:"")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print(""The number is a palindrome!"") else: print(""The number isn't a palindrome!"")" 3259,Print multiplication table using recursion,"def MultiplicationTable(num, i):    print(num,"" X "",i,"" = "",num * i)    if (i < 10):        MultiplicationTable(num, i + 1)num=int(input(""Enter a number:""))print(""Multiplication Table of "",num,"" is:"")MultiplicationTable(num, 1)" 3260,Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String,"string=raw_input(""Enter string:"") count=0 for i in string: count=count+1 new=string[0:2]+string[count-2:count] print(""Newly formed string is:"") print(new)" 3261,Program to find the sum of series 1+X+X^3...+X^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+=2print(""The sum of the series = "",sum)" 3262,Program to print Arithmetic series 1 4 7 10...N," print(""Enter the First Number:"") first_num=int(input()) print(""Enter the range of number(Limit):"") n=int(input()) print(""Enter the Difference Between two Number:"") diff=int(input()) while(first_num<=n):      print(first_num,end="" "")      first_num+=diff" 3263,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."")" 3264,Program to print ascii value of a character," ch=input(""Enter a character:"") ascii=ord(ch) #ord is used for returning the ASCII value a character, ord stands for ordinal print(""The ASCII value is"",ascii)" 3265,Find subtraction of two numbers using recursion,"def Subtraction(num1,num2):    if num2==0:        return num1    return Subtraction(num1-1, num2-1)print(""Enter the two Number:"")num1=int(input())num2=int(input())print(""Subtraction of Two Number Using Recursion is: "",Subtraction(num1,num2))" 3266,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)" 3267,Python Program to Find if Undirected Graph is Bipartite 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_bipartite(vertex, visited): """"""Return True if component containing vertex is bipartite and put all vertices in its component in set visited."""""" colour = {vertex: 0} visited.add(vertex) q = Queue() q.enqueue(vertex) while not q.is_empty(): current = q.dequeue()   next_colour = 1 - colour[current] # switch colour for dest in current.get_neighbours(): if dest not in visited: visited.add(dest) colour[dest] = next_colour q.enqueue(dest) else: if colour[dest] != next_colour: return False return True     g = Graph() print('Undirected Graph') print('Menu') print('add vertex ') print('add edge ') print('bipartite') 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 == 'bipartite': bipartite = True visited = set() for v in g: if v not in visited: if not is_bipartite(v, visited): bipartite = False break   if bipartite: print('Graph is bipartite.') else: print('Graph is not bipartite.')   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" 3268,Program to find sum of series 1+1/3+1/5+1/7+.....1/(N+2)," print(""Enter the range of number(Limit):"") n=int(input()) i=1 sum=0.0 while(i<=n):     sum+=1/i     i+=2 print(""The sum of the series = "",sum)" 3269,Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.,"values = raw_input() numbers = [x for x in values.split("","") if int(x)%2!=0] print "","".join(numbers) " 3270,Python Program to Find the Second 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(""Second largest element is:"",a[n-2])" 3271,Find a pair with maximum product in 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)First_element=arr[0]Second_element=arr[1]Max_Product=First_element*Second_elementfor i in range(0,size-1):    for j in range(i+1, size):        product = arr[i] * arr[j]        if abs(product) >= abs(Max_Product):            Max_Product =product            First_element = arr[i]            Second_element = arr[j]print(""Pair of Maximum Product is ("",First_element,"","",Second_element,"")"")print(""\nMaximum Product of 2 numbers is "",Max_Product)" 3272,Program to display 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()]) #Display Upper triangular matrix print(""Upper Triangular Matrix is:"") for i in range(len(matrix)): for j in range(len(matrix[0])): if i>j: print(""0 "",end="""") else: print(matrix[i][j],end="" "") print()" 3273,Python Program to Find Minimum Spanning Tree using Krusal’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_vertex_exist(self, key): return key in self.vertices   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 display(self): print('Vertices: ', end='') for v in self: print(v.get_key(), end=' ') print()   print('Edges: ') for v in self: for dest in v.get_neighbours(): w = v.get_weight(dest) print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w))   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 mst_krusal(g): """"""Return a minimum cost spanning tree of the connected graph g."""""" mst = Graph() # create new Graph object to hold the MST   if len(g) == 1: u = next(iter(g)) # get the single vertex mst.add_vertex(u.get_key()) # add a copy of it to mst return mst   # get all the edges in a list edges = [] for v in g: for n in v.get_neighbours(): # avoid adding two edges for each edge of the undirected graph if v.get_key() < n.get_key(): edges.append((v, n))   # sort edges edges.sort(key=lambda edge: edge[0].get_weight(edge[1]))   # initially, each vertex is in its own component component = {} for i, v in enumerate(g): component[v] = i   # next edge to try edge_index = 0   # loop until mst has the same number of vertices as g while len(mst) < len(g): u, v = edges[edge_index] edge_index += 1   # if adding edge (u, v) will not form a cycle if component[u] != component[v]:   # add to mst if not mst.does_vertex_exist(u.get_key()): mst.add_vertex(u.get_key()) if not mst.does_vertex_exist(v.get_key()): mst.add_vertex(v.get_key()) mst.add_edge(u.get_key(), v.get_key(), u.get_weight(v)) mst.add_edge(v.get_key(), u.get_key(), u.get_weight(v))   # merge components of u and v for w in g: if component[w] == component[v]: component[w] = component[u]   return mst     g = Graph() print('Undirected Graph') print('Menu') print('add vertex ') print('add edge ') print('mst') 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) g.add_edge(dest, src, weight) else: print('Edge already exists.')   elif operation == 'mst': mst = mst_krusal(g) print('Minimum Spanning Tree:') mst.display() print()   elif operation == 'display': g.display() print()   elif operation == 'quit': break" 3274,Check whether number is Magic Number or Not.," num=int(input(""Enter a number:"")) num1=num #Sum of digit sum=0 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==num:    print(""It is a Magic Number."") else:    print(""It is not a Magic Number."")" 3275,Program to Find the sum of series 3+7+13+21.....+N,"n=int(input(""Enter the range of number:""))sum=0for i in range(2,n+2):    sum+=1+(i*(i-1))print(""The sum of the series = "",sum)" 3276,Python Program to Solve the Celebrity Problem,"def eliminate_non_celebrities(matrix): """"""Take an n x n matrix that has m[i][j] = True iff i knows j and return person who is maybe a celebrity."""""" possible_celeb = 0 n = len(matrix) for p in range(1, n): if (matrix[possible_celeb][p] or not matrix[p][possible_celeb]): possible_celeb = p return possible_celeb     def check_if_celebrity(possible_celeb, matrix): """"""Take an n x n matrix that has m[i][j] = True iff i knows j and return True if possible_celeb is a celebrity."""""" for i in range(n): if matrix[possible_celeb][i] is True: return False   for i in range(n): if matrix[i][possible_celeb] is False: if i != possible_celeb: return False   return True     n = int(input('Number of people: '))   # create n x n matrix initialized to False that has m[i][j] = True iff i knows j m = [[False]*n for _ in range(n)]   for i in range(n): people = input('Enter list of people known to {}: '.format(i)).split() for p in people: p = int(p) m[i][p] = True   possible_celeb = eliminate_non_celebrities(m)   if check_if_celebrity(possible_celeb, m): print('{} is the celebrity.'.format(possible_celeb)) else: print('There is no celebrity.')" 3277,Python Program to Find the Sum of First N Natural Numbers,"n=int(input(""Enter a number: "")) sum1 = 0 while(n > 0): sum1=sum1+n n=n-1 print(""The sum of first n natural numbers is"",sum1)" 3278,Python Program to Implement Selection Sort,"def selection_sort(alist): for i in range(0, len(alist) - 1): smallest = i for j in range(i + 1, len(alist)): if alist[j] < alist[smallest]: smallest = j alist[i], alist[smallest] = alist[smallest], alist[i]     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] selection_sort(alist) print('Sorted list: ', end='') print(alist)" 3279,Find first non repeating character 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(""First Non-repeating character in a given string is: "",end="""")for i in range(len(str)):        if arr[ord(str[i])] ==1:            ch=str[i]            breakprint(ch,end="""")" 3280,Program to Find nth Perfect Square Number," import math rangenumber=int(input(""Enter a Nth Number:"")) c = 0 letest = 0 num = 1 while c != rangenumber:     num1 = num     sqr = math.sqrt(num1)     if sqr-math.floor(sqr)==0:         c+=1         letest = num     num = num + 1 print(rangenumber,""th Perfect Square number is "",latest)" 3281,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)" 3282,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)" 3283,Python Program to Find the Factorial of a Number Using Recursion,"def factorial(n): if(n <= 1): return 1 else: return(n*factorial(n-1)) n = int(input(""Enter number:"")) print(""Factorial:"") print(factorial(n))" 3284,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):     sum += pow(i, i) / i print(""The sum of the series = "",sum)" 3285,Python Program that Displays which Letters are Present in Both the Strings,"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)" 3286,Program to display 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()]) #Display Upper triangular matrix print(""Upper Triangular Matrix is:"") for i in range(len(matrix)): for j in range(len(matrix[0])): if i>j: print(""0 "",end="""") else: print(matrix[i][j],end="" "") print()" 3287,Python Program to Multiply All the Items in a Dictionary,"d={'A':10,'B':10,'C':239} tot=1 for i in d: tot=tot*d[i] print(tot)" 3288,Program to Sort an array in Descending 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] = tempprint(""\nAfter Decreasing order sort Array Elements are:"")for i in range(0, size):        print(arr[i],end="" "")" 3289,Python Program to Print Border of given Tree in Anticlockwise Direction,"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 print_left_boundary(self): current = self while True: if current.left is not None: print(current.key, end=' ') current = current.left elif current.right is not None: print(current.key, end=' ') current = current.right else: break   def print_right_boundary(self): if self.right is not None: self.right.print_right_boundary() print(self.key, end=' ') elif self.left is not None: self.left.print_right_boundary() print(self.key, end=' ')     def print_leaves(self): if self.left is not None: self.left.print_leaves() if self.right is not None: self.right.print_leaves() if (self.left is None and self.right is None): print(self.key, end=' ')   def print_border(self): print(self.key, end=' ') if self.left is not None: self.left.print_left_boundary() self.left.print_leaves() if self.right is not None: self.right.print_leaves() self.right.print_right_boundary()     btree = None   print('Menu (this assumes no duplicate keys)') print('insert at root') print('insert left of ') print('insert right of ') print('border') 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 == 'border': if btree is not None: print('Border of tree: ') btree.print_border() print()   elif operation == 'quit': break" 3290,Find out all Sunny numbers present within a given range," import math print(""Enter a range:"") range1=int(input()) range2=int(input()) print(""Sunny numbers between "",range1,"" and "",range2,"" are: "") for i in range(range1,range2+1):     root = math.sqrt(i+ 1)     if int(root)==root:         print(i,end="" "")" 3291,"Define a class named American which has a static method called printNationality. :","Solution class American(object): @staticmethod def printNationality(): print ""America"" anAmerican = American() anAmerican.printNationality() American.printNationality() " 3292,Program to Print the Double Pyramid Star Pattern,"row_size=int(input(""Enter the row size:""))for out in range(row_size,-(row_size+1),-1):    for inn in range(0,abs(out)+1):        print(""*"",end="""")    print(""\r"")" 3293,Python Program to Count the Occurrences of a Word in a Text File,"fname = input(""Enter file name: "") word=input(""Enter word to be searched:"") k = 0   with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==word): k=k+1 print(""Occurrences of the word:"") print(k)" 3294,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."")" 3295,Program to read and display a Matrix,"# Get size of matrixrow_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 matrixprint(""Enter the Matrix Element:"")for i in range(row_size):    matrix.append([int(j) for j in input().split()])# display the Matrixprint(""Given Matrix is:"")for m in matrix:    print(m)" 3296,Python Program to Find if a Number is Prime or Not Prime Using Recursion,"def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print(""Number not prime"") return False else: return check(n, div-1) else: print(""Number is prime"") return 'True' n=int(input(""Enter number: "")) check(n)" 3297,Find sum multiplication and an average of two numbers," num1=int(input(""Enter a number:"")) num2=int(input(""Enter a number:"")) addition=num1+num2 multiplication=num1*num2 average=(num1+num2)/2 print(""Addition ="",addition) print(""Multiplication ="",multiplication) print(""Average ="",average) " 3298,Find sum of two numbers using recursion,"def sum(num1,num2):    if num2==0:        return num1    return sum(num1, num2-1)+1print(""Enter the two Number:"")num1=int(input())num2=int(input())print(""Sum of Two Number Using Recursion is: "",sum(num1,num2))" 3299,Python Program to Count the Number of Words in a Text File,"fname = input(""Enter file name: "")   num_words = 0   with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print(""Number of words:"") print(num_words)" 3300,Python Program to Check if a Given Key Exists in a Dictionary or Not,"d={'A':1,'B':2,'C':3} key=raw_input(""Enter key to check:"") if key in d.keys(): print(""Key is present and value of the key is:"") print(d[key]) else: print(""Key isn't present!"")" 3301, Print the Full Pyramid Number Pattern,"row_size=int(input(""Enter the row size:""))for out in range(1,row_size+1):    for inn in range(row_size,out,-1):        print("" "",end="""")    for p in range(1,out+1):        print(out,end="" "")    print(""\r"")" 3302,Python Program to Check Whether a Number is Positive or Negative,"  n=int(input(""Enter number: "")) if(n>0): print(""Number is positive"") else: print(""Number is negative"")" 3303," The Fibonacci Sequence is computed based on the following formula: f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1 Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. "," def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) values = [str(f(x)) for x in range(0, n+1)] print "","".join(values) " 3304," Please raise a RuntimeError exception. :"," raise RuntimeError('something wrong') " 3305,Program to print inverted right triangle alphabet 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('A'),out+1):         print(chr(i),end="" "")     print(""\r"")" 3306,Program to find the sum of series 1+X+X^2/2...+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):     sum+=pow(x,i)/i     i+=1 print(""The sum of the series = "",sum)"