code
stringlengths
63
8.54k
code_length
int64
11
747
# 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,"%")
42
# Please write a program to randomly print a integer number between 7 and 15 inclusive. : import random print random.randrange(7,16)
21
# 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)
63
# 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))
54
# 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)) 
96
# 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)
30
# 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))
111
# 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)
41
# 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)
65
# 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())
67
# 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=" ")
32
# 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)
46
# 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)
30
# 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)
31
# 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)
40
# 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'})
74
# 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) 
70
# 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']))
50
# 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)) 
99
# 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)
43
# 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")
24
# 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))
33
# 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)
43
# 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=" ")
67
# 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')
73
# 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)
56
# 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)
60
# 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))
76
# 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
19
# 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("/")))
110
# 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))
83
# 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)
94
# 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)
107
# 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 ')
68
# 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 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)
84
# 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)
25
# 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))
33
# 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))
89
# 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)
124
# 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 * '*')
107
# 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)
93
# 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))
92
# 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)
57
# 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()
48
# 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))
94
# 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) 
54
# 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))
82
# 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))
56
# 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()
30
# 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])
157
# 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))
39
# 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]))
39
# 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)
35
# 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))
76
# 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)
61
# Write a Python program to print a variable without spaces between values. x = 30 print('Value of x is "{}"'.format(x))
21
# Write a Python program to convert a list of characters into a string. s = ['a', 'b', 'c', 'd'] str1 = ''.join(s) print(str1)
24
# 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))
56
# 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))
60
# Assuming that we have some email addresses in the "[email protected]" 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)
49
# 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])
35
# 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)
50
# 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))
60
# 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))
42
# 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)
25
# 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))
27
# 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)
43
# 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))
60
# 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"))
29
# 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)
80
# 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")
31
# 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)
95
# 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)) 
122
# 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()
73
# Write a Python program to change the tag's contents and replace with the given string. from bs4 import BeautifulSoup html_doc = '<a href="http://example.com/">HTML<i>example.com</i></a>' soup = BeautifulSoup(html_doc, "lxml") tag = soup.a print("\nOriginal Markup:") print(tag) print("\nOriginal Markup with new text:") tag.string = "CSS" print(tag)
43
# 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()
34
# 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)
52
# 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))
63
# 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]))
65
# 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)
29
# 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])
81
# 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]))
37
# 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))
54
# 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))
61
# 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)
69
# 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))
111
# 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()
67
# 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)
60
# 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)
51
# 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)
46
# 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)
96
# 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)
71
# 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))
56
# 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)
43
# 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'))
51
# 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"))
55
# 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)
65
# 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))
67
# 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) 
93