code
stringlengths
63
8.54k
code_length
int64
11
747
# 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))
65
# 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()
158
# 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))
44
# 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)
33
# 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))) 
95
# 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)
63
# 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")
97
# 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))
33
# 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)
63
# 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)
76
# 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)
24
# Write a Python Selenium – Find element by text <!DOCTYPE html> <html>  <body>  <button type= “button” >Geeks For Geeks</button>  </body>  <html>
22
# 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))
32
# 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)
62
# 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))
83
# 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)
37
# 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']])
79
# 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))
47
# 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<print_control_y:             print(" ",end="")         else:             print("*", end="")     print_control_x-=1     print_control_y+=1     print("\r")
35
# 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))
104
# 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))
109
# 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)) 
53
# 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)
56
# 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")
25
# 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)
38
# 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))
85
# 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)
37
# 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))
108
# 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)
38
# 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
69
# 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))
91
# 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))
118
# 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))
62
# 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)) 
80
# 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))
48
# 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
46
# 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))
46
# 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)
52
# 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)
52
# 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))
71
# 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))
40
# 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('-'))
32
# 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)
63
# 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)
33
# 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)
131
# 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))
46
# 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)
40
# 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)
85
# 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)
82
# 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)) 
110
# 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)))
56
# 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'))
50
# 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))
30
# 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)
81
# 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)
47
# 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)
106
# 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)
66
# 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))
42
# 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))
103
# 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))
45
# 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)
36
# 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)
63
# 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))
59
# 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)
50
# 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=" ")
27
# 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()
36
# 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)
27
# 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))
83
# 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))
72
# 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
# 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))
39
# 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]))
64
# 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<last):         mid =first + (last - first)// 2         mergesort(arr, first, mid)         mergesort(arr, mid + 1, last)         merge(arr, first, mid, last) 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) mergesort(arr,0,size-1) print("\nAfter Sorting Array Element are: ",arr)
154
# 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()
45
# 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))
53
# 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))
90
# 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)
39
# 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))
102
# 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))
19
# 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'))
39
# 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)
41
# 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)
82
# 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']
98
# 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))
75
# 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'))
38
# 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))
93
# 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)
41
# 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")
176
# 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)
65
# 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)
35
# 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'))
43
# 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)
178
# 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))
50
# 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)
29
# 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))
55
# 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)
77
# 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.'))
51
# 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
# Convert temperature from Fahrenheit to Celsius fahrenheit=int(input("Enter degree in fahrenheit: ")) celsius= (fahrenheit-32)*5/9; print("Degree in celsius is",celsius)
18
# Insertion 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(1,size-1):     temp = arr[out]     inn=out     while inn > 0 and arr[inn -1] >= temp:         arr[inn] = arr[inn -1]         inn-=1     arr[inn] = temp print("\nAfter Sorting Array Element are: ",arr)
70