code
stringlengths
63
8.54k
code_length
int64
11
747
# 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)) 
104
# 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))
29
# 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)
29
# 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 )
57
# 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]))
34
# 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))
85
# 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))
103
# Write a Python program to check a dictionary is empty or not. my_dict = {} if not bool(my_dict): print("Dictionary is empty")
22
# 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])
48
# 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))
53
# 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)
33
# 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'))
41
# 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")
77
# 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)
59
# 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())
41
# 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)
41
# 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)) 
108
# 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))
98
# 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))
112
# 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)
60
# 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)
38
# 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)
39
# 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=' ')
102
# 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)
44
# 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) 
62
# 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)
31
# 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())
57
# 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))
116
# 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))
56
# 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'))
38
# 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)
28
# 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')
41
# 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)
46
# 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))
69
# 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]))
53
# 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)) 
81
# 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))
84
# 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))
21
# 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)
49
# 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))
64
# 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()
43
# 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))
44
# 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())
33
# 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))
62
# 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))
55
# 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])
52
# 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))
49
# 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()
152
# 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)
111
# 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)
25
# 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())
41
# 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)
36
# 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())
40
# 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()
52
# 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")
32
# 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)
92
# 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()
110
# 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])
60
# 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
54
# 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)
85
# 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))
61
# 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)
44
# 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()
71
# 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))
51
# 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) 
119
# 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))
86
# 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")
53
# 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)) 
107
# 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"])
28
# 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))))
41
# 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))
86
# 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)
37
# 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))
73
# 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)
36
# 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))
55
# 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)
31
# 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)
29
# 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))
53
# 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))
30
# 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)) 
109
# 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)
34
# 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))
124
# 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")
24
# 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)
37
# 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)
63
# 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)
24
# 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))
61
# 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__)
33
# 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)
45
# 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'));
49
# 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)
62
# 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
44
# 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))
62
# 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)
25
# 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))
55
# 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())
66
# 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))
179
# 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
49
# 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")
43
# 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)
59