code
stringlengths
63
8.54k
code_length
int64
11
747
# Python Program to Count all Paths in a Grid with Holes using Dynamic Programming with Memoization def count_paths(m, n, holes): """Return number of paths from (0, 0) to (m, n) in an m x n grid.   holes is a list of tuples (x, y) where each tuple is a coordinate which is blocked for a path. """ paths = [[-1]*(m + 1) for _ in range(n + 1)] return count_paths_helper(m, n, holes, paths, n, m)     def count_paths_helper(m, n, holes, paths, x, y): """Return number of paths from (0, 0) to (x, y) in an m x n grid.   holes is a list of tuples (x, y) where each tuple is a coordinate which is blocked for a path.   The function uses the table paths (implemented as a list of lists) where paths[a][b] will store the number of paths from (0, 0) to (a, b). """ if paths[x][y] >= 0: return paths[x][y]   if (x, y) in holes: q = 0 elif x == 0 and y == 0: q = 1 elif x == 0: q = count_paths_helper(m, n, holes, paths, x, y - 1) elif y == 0: q = count_paths_helper(m, n, holes, paths, x - 1, y) else: q = count_paths_helper(m, n, holes, paths, x - 1, y) \ + count_paths_helper(m, n, holes, paths, x, y - 1)   paths[x][y] = q return q     m, n = input('Enter m, n for the size of the m x n grid (m rows and n columns): ').split(',') m = int(m) n = int(n) print('Enter the coordinates of holes on each line (empty line to stop): ') holes = [] while True: hole = input('') if not hole.strip(): break hole = hole.split(',') hole = (int(hole[0]), int(hole[1])) holes.append(hole)   count = count_paths(m, n, holes) print('Number of paths from (0, 0) to ({}, {}): {}.'.format(n, m, count))
302
# Write a Python function that takes two lists and returns True if they have at least one common member. def common_data(list1, list2): result = False for x in list1: for y in list2: if x == y: result = True return result print(common_data([1,2,3,4,5], [5,6,7,8,9])) print(common_data([1,2,3,4,5], [6,7,8,9]))
47
# Write a Python program to count the same pair in three given lists. def count_same_pair(nums1, nums2, nums3): result = sum(m == n == o for m, n, o in zip(nums1, nums2, nums3)) return result nums1 = [1,2,3,4,5,6,7,8] nums2 = [2,2,3,1,2,6,7,9] nums3 = [2,1,3,1,2,6,7,9] print("Original lists:") print(nums1) print(nums2) print(nums3) print("\nNumber of same pair of the said three given lists:") print(count_same_pair(nums1, nums2, nums3))
62
# Write a NumPy program to extract first and third elements of the first and third rows from a given (4x4) array. import numpy as np arra_data = np.arange(0,16).reshape((4, 4)) print("Original array:") print(arra_data) print("\nExtracted data: First and third elements of the first and third rows ") print(arra_data[::2, ::2])
48
# Functions that accept variable length key value pair as arguments in Python # using kwargs # in functions def printKwargs(**kwargs):     print(kwargs) # driver code if __name__ == "__main__":     printKwargs(Argument_1='gfg', Argument_2='GFG')
31
# Write a NumPy program to create one-dimensional array of single, two and three digit numbers. import numpy as np nums = np.arange(1, 21) print("One-dimensional array of single digit numbers:") print(nums) nums = np.arange(10, 21) print("\nOne-dimensional array of two digit numbers:") print(nums) nums = np.arange(100, 201) print("\nOne-dimensional array of three digit numbers:") print(nums)
53
# Write a Python program to input two integers in a single line. print("Input the value of x & y") x, y = map(int, input().split()) print("The value of x & y are: ",x,y)
33
# Split a String into columns using regex in pandas DataFrame in Python # import the regex library import pandas as pd import re    # Create a list with all the strings movie_data = ["Name: The_Godfather Year: 1972 Rating: 9.2",             "Name: Bird_Box Year: 2018 Rating: 6.8",             "Name: Fight_Club Year: 1999 Rating: 8.8"]    # Create a dictionary with the required columns  # Used later to convert to DataFrame movies = {"Name":[], "Year":[], "Rating":[]}    for item in movie_data:            # For Name field     name_field = re.search("Name: .*",item)            if name_field is not None:         name = re.search('\w*\s\w*',name_field.group())     else:         name = None     movies["Name"].append(name.group())            # For Year field     year_field = re.search("Year: .*",item)     if year_field is not None:         year = re.search('\s\d\d\d\d',year_field.group())     else:         year = None     movies["Year"].append(year.group().strip())            # For rating field     rating_field = re.search("Rating: .*",item)     if rating_field is not None:          rating = re.search('\s\d.\d',rating_field.group())     else:          rating - None     movies["Rating"].append(rating.group().strip())    # Creating DataFrame df = pd.DataFrame(movies) print(df)
146
# Program to find the sum of an upper triangular matrix # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) #Calculate sum of Upper triangular matrix element sum=0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i>j: sum += matrix[i][j] # display the sum of the Upper triangular matrix element print("Sum of Upper Triangular Matrix Elements is: ",sum)
89
# Write a Pandas program to get all the sighting days of the unidentified flying object (ufo) between 1950-10-10 and 1960-10-10. import pandas as pd df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) print("\nSighting days of the unidentified flying object (ufo) between 1949-10-10 and 1960-10-10:") selected_period = df[(df['Date_time'] >= '1950-01-01 00:00:00') & (df['Date_time'] <= '1960-12-31 23:59:59')] print(selected_period)
58
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and find a list of specified customers by name. import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df.query('Mine_Name == ["Shoal Creek Mine", "Piney Woods Preparation Plant"]').head()
44
# Write a Python program to remove existing indentation from all of the lines in a given text. import textwrap sample_text = ''' Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. ''' text_without_Indentation = textwrap.dedent(sample_text) print() print(text_without_Indentation ) print()
70
# Write a Pandas program to find the positions of the values neighboured by smaller values on both sides in a given series. import pandas as pd import numpy as np nums = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]) print("Original series:") print(nums) print("\nPositions of the values surrounded by smaller values on both sides:") temp = np.diff(np.sign(np.diff(nums))) result = np.where(temp == -2)[0] + 1 print(result)
68
# Write a NumPy program to compute the condition number of a given matrix. import numpy as np m = np.array([[1,2],[3,4]]) print("Original matrix:") print(m) result = np.linalg.cond(m) print("Condition number of the said matrix:") print(result)
34
# Write a NumPy program to remove nan values from a given array. import numpy as np x = np.array([200, 300, np.nan, np.nan, np.nan ,700]) y = np.array([[1, 2, 3], [np.nan, 0, np.nan] ,[6,7,np.nan]] ) print("Original array:") print(x) print("After removing nan values:") result = x[np.logical_not(np.isnan(x))] print(result) print("\nOriginal array:") print(y) print("After removing nan values:") result = y[np.logical_not(np.isnan(y))] print(result)
57
# Write a Python program to remove leading zeros from an IP address. def remove_zeros_from_ip(ip_add): new_ip_add = ".".join([str(int(i)) for i in ip_add.split(".")]) return new_ip_add ; print(remove_zeros_from_ip("255.024.01.01")) print(remove_zeros_from_ip("127.0.0.01 "))
28
# Scraping And Finding Ordered Words In A Dictionary using Python # Python program to find ordered words import requests    # Scrapes the words from the URL below and stores  # them in a list def getWords():        # contains about 2500 words     url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"     fetchData = requests.get(url)        # extracts the content of the webpage     wordList = fetchData.content        # decodes the UTF-8 encoded text and splits the      # string to turn it into a list of words     wordList = wordList.decode("utf-8").split()        return wordList       # function to determine whether a word is ordered or not def isOrdered():        # fetching the wordList     collection = getWords()        # since the first few of the elements of the      # dictionary are numbers, getting rid of those     # numbers by slicing off the first 17 elements     collection = collection[16:]     word = ''        for word in collection:         result = 'Word is ordered'         i = 0         l = len(word) - 1            if (len(word) < 3): # skips the 1 and 2 lettered strings             continue            # traverses through all characters of the word in pairs         while i < l:                      if (ord(word[i]) > ord(word[i+1])):                 result = 'Word is not ordered'                 break             else:                 i += 1            # only printing the ordered words         if (result == 'Word is ordered'):             print(word,': ',result)       # execute isOrdered() function if __name__ == '__main__':     isOrdered()
217
# Write a Python program to Numpy matrix.mean() # import the important module in python import numpy as np            # make matrix with numpy gfg = np.matrix('[64, 1; 12, 3]')            # applying matrix.mean() method geeks = gfg.mean()      print(geeks)
38
# Write a Python program to Intersection in Tuple Records Data # Python3 code to demonstrate working of # Intersection in Tuple Records Data # Using list comprehension    # Initializing lists test_list1 = [('gfg', 1), ('is', 2), ('best', 3)] test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]    # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2))    # Intersection in Tuple Records Data # Using list comprehension res = [ele1 for ele1 in test_list1         for ele2 in test_list2 if ele1 == ele2]    # printing result print("The Intersection of data records is : " + str(res))
107
# Ways to sort list of dictionaries by values in Write a Python program to Using itemgetter # Python code demonstrate the working of sorted() # and itemgetter    # importing "operator" for implementing itemgetter from operator import itemgetter    # Initializing list of dictionaries lis = [{ "name" : "Nandini", "age" : 20},  { "name" : "Manjeet", "age" : 20 }, { "name" : "Nikhil" , "age" : 19 }]    # using sorted and itemgetter to print list sorted by age  print "The list printed sorting by age: " print sorted(lis, key=itemgetter('age'))    print ("\r")    # using sorted and itemgetter to print list sorted by both age and name # notice that "Manjeet" now comes before "Nandini" print "The list printed sorting by age and name: " print sorted(lis, key=itemgetter('age', 'name'))    print ("\r")    # using sorted and itemgetter to print list sorted by age in descending order print "The list printed sorting by age in descending order: " print sorted(lis, key=itemgetter('age'),reverse = True)
161
# Write a Python program to get string representing the date, controlled by an explicit format string. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nString representing the date, controlled by an explicit format string:") print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
41
# Write a Python program which iterates the integers from 1 to 50. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". for fizzbuzz in range(51): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print("fizzbuzz") continue elif fizzbuzz % 3 == 0: print("fizz") continue elif fizzbuzz % 5 == 0: print("buzz") continue print(fizzbuzz)
78
# Write a Pandas program to extract only words from a given column of a given DataFrame. import pandas as pd import re as re df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'], 'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'], 'address': ['9910 Surrey Ave.','92 N. Bishop Ave.','9910 Golden Star Ave.', '102 Dunbar St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def search_words(text): result = re.findall(r'\b[^\d\W]+\b', text) return " ".join(result) df['only_words']=df['address'].apply(lambda x : search_words(x)) print("\nOnly words:") print(df)
72
# How to Remove rows in Numpy array that contains non-numeric values in Python # Importing Numpy module import numpy as np    # Creating 2X3 2-D Numpy array n_arr = np.array([[10.5, 22.5, 3.8],                   [41, np.nan, np.nan]])    print("Given array:") print(n_arr)    print("\nRemove all rows containing non-numeric elements") print(n_arr[~np.isnan(n_arr).any(axis=1)])
46
# Sort an array of 0s, 1s and 2s arr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size):    num = int(input())    arr.append(num)for i in range(0,size):    for j in range(i+1, size):        if arr[i]>=arr[j]:            temp = arr[i]            arr[i] = arr[j]            arr[j] = tempprint("After segregate 0s, 1s and 2s in an Array, Array is:",arr)
59
# Write a NumPy program to create an array of (3, 4) shape and convert the array elements in smaller chunks. import numpy as np x= np.arange(12).reshape(3, 4) print("Original array elements:") print(x) print("Above array in small chuncks:") for a in np.nditer(x, flags=['external_loop'], order='F'): print(a)
44
# Iterate over a set in Python # Creating a set using string test_set = set("geEks") # Iterating using for loop for val in test_set:     print(val)
26
# Write a NumPy program to convert specified inputs to arrays with at least one dimension. import numpy as np x= 12.0 print(np.atleast_1d(x)) x = np.arange(6.0).reshape(2, 3) print(np.atleast_1d(x)) print(np.atleast_1d(1, [3, 4]))
31
# Write a Python program to Zip two given lists of lists. list1 = [[1, 3], [5, 7], [9, 11]] list2 = [[2, 4], [6, 8], [10, 12, 14]] print("Original lists:") print(list1) print(list2) result = list(map(list.__add__, list1, list2)) print("\nZipped list:\n" + str(result))
42
# Write a NumPy program to create a vector with values ranging from 15 to 55 and print all values except the first and last. import numpy as np v = np.arange(15,55) print("Original vector:") print(v) print("All values except the first and last of the said vector:") print(v[1:-1])
47
# Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. def chars_mix_up(a, b): new_a = b[:2] + a[2:] new_b = a[:2] + b[2:] return new_a + ' ' + new_b print(chars_mix_up('abc', 'xyz'))
49
# Write a Pandas program to sort a given Series. import pandas as pd s = pd.Series(['100', '200', 'python', '300.12', '400']) print("Original Data Series:") print(s) new_s = pd.Series(s).sort_values() print(new_s)
29
# Write a Python program to Group Sublists by another List # Python3 code to demonstrate  # Group Sublists by another List # using loop + generator(yield)    # helper function def grp_ele(test_list1, test_list2):     temp = []     for i in test_list1:          if i in test_list2:             if temp:                   yield temp                  temp = []             yield i           else:              temp.append(i)     if temp:          yield temp    # Initializing lists test_list1 = [8, 5, 9, 11, 3, 7] test_list2 = [9, 11]    # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2))    # Group Sublists by another List # using loop + generator(yield) res = list(grp_ele(test_list1, test_list2))    # printing result  print ("The Grouped list is : " + str(res))
123
# Write a Pandas program to filter all records starting from the 2nd row, access every 5th row from world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nStarting from the 2nd row, access every 5th row:") print(w_a_con.iloc[1::5].head(10))
51
# Write a Pandas program to generate sequences of fixed-frequency dates and time spans intervals. import pandas as pd print("Sequences of fixed-frequency dates and time spans (1 H):\n") r1 = pd.date_range('2030-01-01', periods=10, freq='H') print(r1) print("\nSequences of fixed-frequency dates and time spans (3 H):\n") r2 = pd.date_range('2030-01-01', periods=10, freq='3H') print(r2)
49
# Calculate the average, variance and standard deviation in Python using NumPy # Python program to get average of a list    # Importing the NumPy module import numpy as np    # Taking a list of elements list = [2, 4, 4, 4, 5, 5, 7, 9]    # Calculating average using average() print(np.average(list))
52
# Write a NumPy program to create an array of 4,5 shape and swap column1 with column4. import numpy as np array_nums = np.arange(20).reshape(4,5) print("Original array:") print(array_nums) print("\nAfter swapping column1 with column4:") array_nums[:,[0,3]] = array_nums[:,[3,0]] print(array_nums)
36
# Write a NumPy program to extract all the rows to compute the student weight from a given array (student information) where a specific column starts with a given character. import numpy as np np.set_printoptions(linewidth=100) student = np.array([['01', 'V', 'Debby Pramod', 30.21], ['02', 'V', 'Artemiy Ellie', 29.32], ['03', 'V', 'Baptist Kamal', 31.00], ['04', 'V', 'Lavanya Davide', 30.22], ['05', 'V', 'Fulton Antwan', 30.21], ['06', 'V', 'Euanthe Sandeep', 31.00], ['07', 'V', 'Endzela Sanda', 32.00], ['08', 'V', 'Victoire Waman', 29.21], ['09', 'V', 'Briar Nur', 30.00], ['10', 'V', 'Rose Lykos', 32.00]]) print("Original array:") print(student) char='E' result = student[np.char.startswith(student[:,2], char)] print("\nTotal weight, where student name starting with",char) print(np.round(result[:, 3].astype(float).sum(), 2)) char='D' result = student[np.char.startswith(student[:,2], char)] print("\nTotal weight, where student name starting with",char) print(np.round(result[:, 3].astype(float).sum(), 2))
120
# Write a Pandas program to import three datasheets from a given excel data (employee.xlsx ) into a single dataframe and export the result into new Excel file. import pandas as pd import numpy as np df1 = pd.read_excel('E:\employee.xlsx',sheet_name=0) df2 = pd.read_excel('E:\employee.xlsx',sheet_name=1) df3 = pd.read_excel('E:\employee.xlsx',sheet_name=2) df = pd.concat([df1, df2, df3]) df.to_excel('e:\output.xlsx', index=False)
52
# Write a Python program to join two given list of lists of same length, element wise. def elementswise_join(l1, l2): result = [x + y for x, y in zip(l1, l2)] return result nums1 = [[10,20], [30,40], [50,60], [30,20,80]] nums2 = [[61], [12,14,15], [12,13,19,20], [12]] print("Original lists:") print(nums1) print(nums2) print("\nJoin the said two lists element wise:") print(elementswise_join(nums1, nums2)) list1 = [['a','b'], ['b','c','d'], ['e', 'f']] list2 = [['p','q'], ['p','s','t'], ['u','v','w']] print("\nOriginal lists:") print(list1) print(list2) print("\nJoin the said two lists element wise:") print(elementswise_join(list1, list2))
82
# Python Program to Count the Occurrences of Each Word in a Given String Sentence string=raw_input("Enter string:") word=raw_input("Enter word:") a=[] count=0 a=string.split(" ") for i in range(0,len(a)): if(word==a[i]): count=count+1 print("Count of the word is:") print(count)
35
# Write a NumPy program to calculate the difference between neighboring elements, element-wise of a given array. import numpy as np x = np.array([1, 3, 5, 7, 0]) print("Original array: ") print(x) print("Difference between neighboring elements, element-wise of the said array.") print(np.diff(x))
42
# Write a Python program to check whether a JSON string contains complex object or not. import json def is_complex_num(objct): if '__complex__' in objct: return complex(objct['real'], objct['img']) return objct complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex_num) simple_object =json.loads('{"real": 4, "img": 3}', object_hook = is_complex_num) print("Complex_object: ",complex_object) print("Without complex object: ",simple_object)
53
# How to get the n-largest values of an array using NumPy in Python # import library import numpy as np    # create numpy 1d-array arr = np.array([2, 0,  1, 5,                 4, 1, 9])    print("Given array:", arr)    # sort an array in # ascending order    # np.argsort() return # array of indices for # sorted array sorted_index_array = np.argsort(arr)    # sorted array sorted_array = arr[sorted_index_array]    print("Sorted array:", sorted_array)    # we want 1 largest value n = 1    # we are using negative # indexing concept    # take n largest value rslt = sorted_array[-n : ]    # show the output print("{} largest value:".format(n),       rslt[0])
103
# Write a Python program to a Sort Matrix by index-value equality count # Python3 code to demonstrate working of # Sort Matrix by index-value equality count # Using sort() + len() + enumerate()       def get_idx_ele_count(row):        # getting required count     # element and index compared, if equal added     # in list, length computed using len()     return len([ele for idx, ele in enumerate(row) if ele == idx])       # initializing list test_list = [[3, 1, 2, 5, 4], [0, 1, 2, 3, 4],               [6, 5, 4, 3, 2], [0, 5, 4, 2]]    # printing original list print("The original list is : " + str(test_list))    # inplace sorting using sort() test_list.sort(key=get_idx_ele_count)    # printing result print("Sorted List : " + str(test_list))
117
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the minimum value in each column. import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[0, 2] = np.nan df.iloc[3, 3] = np.nan df.iloc[4, 1] = np.nan df.iloc[9, 4] = np.nan print("Original array:") print(df) def highlight_min(s): ''' highlight the minimum in a Series red. ''' is_max = s == s.min() return ['background-color: red' if v else '' for v in is_max] print("\nHighlight the minimum value in each column:") df.style.apply(highlight_min,subset=pd.IndexSlice[:, ['B', 'C', 'D', 'E']])
104
# Convert Python datetime to epoch # import datetime module import datetime    # convert datetime to epoch using strftime from # time stamp 2021/7/7/1/2/1 # for linux: epoch = datetime.datetime(2021, 7, 7, 1, 2, 1).strftime('%s') # for windows: # epoch = datetime.datetime(2021, 7,7 , 1,2,1).strftime('%S') print(epoch)    # convert datetime to epoch using strftime from # time stamp 2021/3/3/4/3/4 epoch = datetime.datetime(2021, 3, 3, 4, 3, 4).strftime('%s') print(epoch)    # convert datetime to epoch using strftime from # time stamp 2021/7/7/12/12/34 epoch = datetime.datetime(2021, 7, 7, 12, 12, 34).strftime('%s') print(epoch)    # convert datetime to epoch using strftime from  # time stamp 2021/7/7/12/56/00 epoch = datetime.datetime(2021, 7, 7, 12, 56, 0).strftime('%s') print(epoch)
109
# Write a Python program to solve the Fibonacci sequence using recursion. def fibonacci(n): if n == 1 or n == 2: return 1 else: return (fibonacci(n - 1) + (fibonacci(n - 2))) print(fibonacci(7))
34
# Write a Python program to multiply two integers without using the * operator in python. def multiply(x, y): if y < 0: return -multiply(x, -y) elif y == 0: return 0 elif y == 1: return x else: return x + multiply(x, y - 1) print(multiply(3, 5));
48
# Write a Python program to create a list by concatenating a given list which range goes from 1 to n. my_list = ['p', 'q'] n = 4 new_list = ['{}{}'.format(x, y) for y in range(1, n+1) for x in my_list] print(new_list)
42
# Python Program to Check if a Number is a Strong Number   sum1=0 num=int(input("Enter a number:")) temp=num while(num): i=1 f=1 r=num%10 while(i<=r): f=f*i i=i+1 sum1=sum1+f num=num//10 if(sum1==temp): print("The number is a strong number") else: print("The number is not a strong number")
41
# Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array. import numpy as np X = np.array([1, 7, 13, 105]) print("Original array:") print(X) print("Size of the memory occupied by the said array:") print("%d bytes" % (X.size * X.itemsize))
55
# Write a Python program to find the href of the first <a> tag of a given html document. from bs4 import BeautifulSoup html_doc = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>An example of HTML page</title> </head> <body> <h2>This is an example HTML page</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit, aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo. Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim elementum nunc, non elementum felis condimentum eu. In in turpis quis erat imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu, euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl euismod porta.</p> <p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from w3resource.com</a></p> <p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from w3resource.com</a></p> </body> </html> """ soup = BeautifulSoup(html_doc, 'html.parser') print("href of the first <a> tag:") print(soup.find('a').attrs['href'])
170
# Write a Python program to sort a list of lists by a given index of the inner list. from operator import itemgetter def index_on_inner_list(list_data, index_no): result = sorted(list_data, key=itemgetter(index_no)) return result students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] print ("Original list:") print(students) index_no = 0 print("\nSort the said list of lists by a given index","( Index = ",index_no,") of the inner list") print(index_on_inner_list(students, index_no)) index_no = 2 print("\nSort the said list of lists by a given index","( Index = ",index_no,") of the inner list") print(index_on_inner_list(students, index_no))
98
# Write a Python class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case. class IOString(): def __init__(self): self.str1 = "" def get_String(self): self.str1 = input() def print_String(self): print(self.str1.upper()) str1 = IOString() str1.get_String() str1.print_String()
47
# Write a Python program to count number of non-empty substrings of a given string. def number_of_substrings(str): str_len = len(str); return int(str_len * (str_len + 1) / 2); str1 = input("Input a string: ") print("Number of substrings:") print(number_of_substrings(str1))
38
# Write a Pandas program to sort a MultiIndex of a DataFrame. Also sort on various levels of index. import pandas as pd import numpy as np sales_arrays = [['sale1', 'sale1', 'sale3', 'sale3', 'sale2', 'sale2', 'sale4', 'sale4'], ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']] sales_tuples = list(zip(*sales_arrays)) sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city']) print(sales_tuples) print("\nConstruct a Dataframe using the said MultiIndex levels: ") df = pd.DataFrame(np.random.randn(8, 5), index=sales_index) print(df) print("\nSort on MultiIndex DataFrame:") df1 = df.sort_index() print("\nSort on Index level=0 of the DataFrame:") df2 = df.sort_index(level=0) print(df2) print("\nSort on Index level=1 of the DataFrame:") df2 = df.sort_index(level=1) print(df2) print("\nPass a level name to sort the DataFrame:") df3 = df.sort_index(level="city") print(df3)
110
# Write a Pandas program to split a given dataframe into groups and create a new column with count from GroupBy. import pandas as pd pd.set_option('display.max_rows', None) df = pd.DataFrame({ 'book_name':['Book1','Book2','Book3','Book4','Book1','Book2','Book3','Book5'], 'book_type':['Math','Physics','Computer','Science','Math','Physics','Computer','English'], 'book_id':[1,2,3,4,1,2,3,5]}) print("Original Orders DataFrame:") print(df) print("\nNew column with count from groupby:") result = df.groupby(["book_name", "book_type"])["book_type"].count().reset_index(name="count") print(result)
48
# Write a NumPy program to calculate inverse sine, inverse cosine, and inverse tangent for all elements in a given array. import numpy as np x = np.array([-1., 0, 1.]) print("Inverse sine:", np.arcsin(x)) print("Inverse cosine:", np.arccos(x)) print("Inverse tangent:", np.arctan(x))
39
# Write a Python Lambda Functions # Python program to demonstrate # lambda functions string ='GeeksforGeeks' # lambda returns a function object print(lambda string : string)
26
# Write a Python program to extract and display all the image links from en.wikipedia.org/wiki/Peter_Jeffrey_(RAAF_officer). import requests r = requests.get("https://analytics.usa.gov/data/live/browsers.json") print("90 days of visits broken down by browser for all sites:") print(r.json()['totals']['browser'])
32
# Write a NumPy program to find the 4th element of a specified array. import numpy as np x = np.array([[2, 4, 6], [6, 8, 10]], np.int32) print(x) e1 = x.flat[3] print("Forth e1ement of the array:") print(e1)
37
# Remove element from an array by index arr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size):    num = int(input())    arr.append(num)pos=int(input("Enter the position of the Element:"))print("Before deleting array elements are:")for i in range(0,size):    print(arr[i],end=" ")arr.pop(pos)print("\nAfter Deleting Array Element are:")print(arr)
47
# Write a Python program to remove duplicate words from a given string use collections module. from collections import OrderedDict text_str = "Python Exercises Practice Solution Exercises" print("Original String:") print(text_str) print("\nAfter removing duplicate words from the said string:") result = ' '.join(OrderedDict((w,w) for w in text_str.split()).keys()) print(result)
47
# Write a Pandas program to change the order of index of a given series. import pandas as pd s = pd.Series(data = [1,2,3,4,5], index = ['A', 'B', 'C','D','E']) print("Original Data Series:") print(s) s = s.reindex(index = ['B','A','C','D','E']) print("Data Series after changing the order of index:") print(s)
47
# Write a Python program to check whether a given datetime is between two dates and times using arrow module. import arrow print("Test whether a given datetime is between two dates and times:") start = arrow.get(datetime(2017, 6, 5, 12, 30, 10)) end = arrow.get(datetime(2017, 6, 5, 12, 30, 36)) print(arrow.get(datetime(2017, 6, 5, 12, 30, 27)).is_between(start, end)) start = arrow.get(datetime(2017, 5, 5)) end = arrow.get(datetime(2017, 5, 8)) print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[]')) start = arrow.get(datetime(2017, 5, 5)) end = arrow.get(datetime(2017, 5, 8)) print(arrow.get(datetime(2017, 5, 8)).is_between(start, end, '[)'))
86
# Python Program to Find the Largest Number in a List a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=int(input("Enter element:")) a.append(b) a.sort() print("Largest element is:",a[n-1])
27
# Write a Python program to calculate the sum of all items of a container (tuple, list, set, dictionary). s = sum([10,20,30]) print("\nSum of the container: ", s) print()
29
# Python Program to Implement Counting Sort def counting_sort(alist, largest): c = [0]*(largest + 1) for i in range(len(alist)): c[alist[i]] = c[alist[i]] + 1   # Find the last index for each element c[0] = c[0] - 1 # to decrement each element for zero-based indexing for i in range(1, largest + 1): c[i] = c[i] + c[i - 1]   result = [None]*len(alist)   # Though it is not required here, # it becomes necessary to reverse the list # when this function needs to be a stable sort for x in reversed(alist): result[c[x]] = x c[x] = c[x] - 1   return result     alist = input('Enter the list of (nonnegative) numbers: ').split() alist = [int(x) for x in alist] k = max(alist) sorted_list = counting_sort(alist, k) print('Sorted list: ', end='') print(sorted_list)
129
# Write a Python program to check common elements between two given list are in same order or not. def same_order(l1, l2): common_elements = set(l1) & set(l2) l1 = [e for e in l1 if e in common_elements] l2 = [e for e in l2 if e in common_elements] return l1 == l2 color1 = ["red","green","black","orange"] color2 = ["red","pink","green","white","black"] color3 = ["white","orange","pink","black"] print("Original lists:") print(color1) print(color2) print(color3) print("\nTest common elements between color1 and color2 are in same order?") print(same_order(color1, color2)) print("\nTest common elements between color1 and color3 are in same order?") print(same_order(color1, color3)) print("\nTest common elements between color2 and color3 are in same order?") print(same_order(color2, color3))
106
# Write a Python program to find the specified number of maximum values in a given dictionary. def test(dictt, N): result = sorted(dictt, key=dictt.get, reverse=True)[:N] return result dictt = {'a':5, 'b':14, 'c': 32, 'd':35, 'e':24, 'f': 100, 'g':57, 'h':8, 'i': 100} print("\nOriginal Dictionary:") print(dictt) N = 1 print("\n",N,"maximum value(s) in the said dictionary:") print(test(dictt, N)) N = 2 print("\n",N,"maximum value(s) in the said dictionary:") print(test(dictt, N)) N = 5 print("\n",N,"maximum value(s) in the said dictionary:") print(test(dictt, N))
77
# How to Remove repetitive characters from words of the given Pandas DataFrame using Regex in Python # importing required libraries import pandas as pd import re # creating Dataframe with column # as name and common_comments df = pd.DataFrame(   {     'name' : ['Akash', 'Ayush', 'Diksha',               'Priyanka', 'Radhika'],           'common_comments' : ['hey buddy meet me today ',                          'sorry bro i cant meet',                          'hey akash i love geeksforgeeks',                          'twiiter is the best way to comment',                          'geeksforgeeks is good for learners']     },         columns = ['name', 'common_comments'] ) # printing Dataframe df
88
# Write a Python program to Maximum Consecutive Substring Occurrence # Python3 code to demonstrate working of  # Maximum Consecutive Substring  Occurrence # Using max() + re.findall() import re    # initializing string test_str = 'geeksgeeks are geeks for all geeksgeeksgeeks'    # printing original string print("The original string is : " + str(test_str))    # initializing subs  sub_str = 'geeks'    # Maximum Consecutive Substring  Occurrence # Using max() + re.findall() res = max(re.findall('((?:' + re.escape(sub_str) + ')*)', test_str), key = len)    # printing result  print("The maximum run of Substring : " + res) 
91
# Write a Python Program for Cycle Sort # Python program to impleament cycle sort    def cycleSort(array):   writes = 0        # Loop through the array to find cycles to rotate.   for cycleStart in range(0, len(array) - 1):     item = array[cycleStart]            # Find where to put the item.     pos = cycleStart     for i in range(cycleStart + 1, len(array)):       if array[i] < item:         pos += 1            # If the item is already there, this is not a cycle.     if pos == cycleStart:       continue            # Otherwise, put the item there or right after any duplicates.     while item == array[pos]:       pos += 1     array[pos], item = item, array[pos]     writes += 1            # Rotate the rest of the cycle.     while pos != cycleStart:                # Find where to put the item.       pos = cycleStart       for i in range(cycleStart + 1, len(array)):         if array[i] < item:           pos += 1                # Put the item there or right after any duplicates.       while item == array[pos]:         pos += 1       array[pos], item = item, array[pos]       writes += 1        return writes      #  driver code  arr = [1, 8, 3, 9, 10, 10, 2, 4 ] n = len(arr)  cycleSort(arr)    print("After sort : ") for i in range(0, n) :      print(arr[i], end = \' \')    # Code Contributed by Mohit Gupta_OMG <(0_o)>
209
# Write a Python program to combine two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values. The values of the first list need to be unique and hashable. def test(keys, values): return dict(zip(keys, values)) l1 = ['a', 'b', 'c', 'd', 'e', 'f'] l2 = [1, 2, 3, 4, 5] print("Original lists:") print(l1) print(l2) print("\nCombine the values of the said two lists into a dictionary:") print(test(l1, l2))
84
# Write a NumPy program to move axes of an array to new positions. Other axes remain in their original order. import numpy as np x = np.zeros((2, 3, 4)) print(np.moveaxis(x, 0, -1).shape) print(np.moveaxis(x, -1, 0).shape)
36
# Write a Python program to select all the Sundays of a specified year. from datetime import date, timedelta def all_sundays(year): # January 1st of the given year dt = date(year, 1, 1) # First Sunday of the given year dt += timedelta(days = 6 - dt.weekday()) while dt.year == year: yield dt dt += timedelta(days = 7) for s in all_sundays(2020): print(s)
63
# Write a Python program to extract a tag or string from a given tree of html document. from bs4 import BeautifulSoup html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>' soup = BeautifulSoup(html_content, "lxml") print("Original Markup:") print(soup.a) i_tag = soup.i.extract() print("\nExtract i tag from said html Markup:") print(i_tag)
45
# Write a Pandas program to split the following datasets into groups on customer id and calculate the number of customers starting with 'C', the list of all products and the difference of maximum purchase amount and minimum purchase amount. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013], 'purch_amt':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 5760, 1983.43, 2480.4, 250.45, 75.29, 3045.6], 'ord_date': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'], 'customer_id':['C3001','C3001','D3005','D3001','C3005','D3001','C3005','D3001','D3005','C3001','D3005','D3005'], 'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]}) print("Original Orders DataFrame:") print(df) def customer_id_C(x): return (x.str[0] == 'C').sum() result = df.groupby(['salesman_id'])\ .agg(customer_id_start_C = ('customer_id', customer_id_C), customer_id_list = ('customer_id', lambda x: ', '.join(x)), purchase_amt_gap = ('purch_amt', lambda x: x.max()-x.min()) ) print("\nNumber of customers starting with ‘C’, the list of all products and the difference of maximum purchase amount and minimum purchase amount:") print(result)
123
# Write a Python program to find the common tuples between two given lists. def test(list1, list2): result = set(list1).intersection(list2) return list(result) list1 = [('red', 'green'), ('black', 'white'), ('orange', 'pink')] list2 = [('red', 'green'), ('orange', 'pink')] print("\nOriginal lists:") print(list1) print(list2) print("\nCommon tuples between two said lists") print(test(list1,list2)) list1 = [('red', 'green'), ('orange', 'pink')] list2 = [('red', 'green'), ('black', 'white'), ('orange', 'pink')] print("\nOriginal lists:") print(list1) print(list2) print("\nCommon tuples between two said lists") print(test(list1,list2))
72
# Write a Python program to create a naïve (without time zone) datetime representation of the Arrow object. import arrow a = arrow.utcnow() print("Current datetime:") print(a) r = arrow.now('US/Mountain') print("\nNaive datetime representation:") print(r.naive)
33
# How to create an empty class in Python # Incorrect empty class in  # Python    class Geeks:
18
# Write a NumPy program to calculate the Euclidean distance. from scipy.spatial import distance p1 = (1, 2, 3) p2 = (4, 5, 6) d = distance.euclidean(p1, p2) print("Euclidean distance: ",d)
31
# Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: if c.isupper(): d["UPPER CASE"]+=1 elif c.islower(): d["LOWER CASE"]+=1 else: pass print "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"]
51
# Write a Python program to Extract words starting with K in String List # Python3 code to demonstrate working of  # Extract words starting with K in String List # Using loop + split()    # initializing list test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]     # printing original list print("The original list is : " + str(test_list))    # initializing K  K = "g"    res = [] for sub in test_list:     # splitting phrases     temp = sub.split()     for ele in temp:                    # checking for matching elements         if ele[0].lower() == K.lower():             res.append(ele)    # printing result  print("The filtered elements : " + str(res))
105
# Write a Python program to retrieve all descendants of the body tag from a given web page. import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("\nDescendants of the body tag (https://www.python.org):\n") root = soup.html root_childs = [e.name for e in root.descendants if e.name is not None] print(root_childs)
56
# Write a Python program to clone or copy a list. original_list = [10, 22, 44, 23, 4] new_list = list(original_list) print(original_list) print(new_list)
23
# Write a Python program to make an iterator that drops elements from the iterable as soon as an element is a positive number. import itertools as it def drop_while(nums): return it.dropwhile(lambda x : x < 0, nums) nums = [-1,-2,-3,4,-10,2,0,5,12] print("Original list: ",nums) result = drop_while(nums) print("Drops elements from the iterable when a positive number arises \n",list(result)) #Alternate solution def negative_num(x): return x < 0 def drop_while(nums): return it.dropwhile(negative_num, nums) nums = [-1,-2,-3,4,-10,2,0,5,12] print("Original list: ",nums) result = drop_while(nums) print("Drops elements from the iterable when a positive number arises \n",list(result))
91
# Write a Python program to count number of lists in a given list of lists. def count_list(input_list): return len(input_list) list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]] list2 = [[2, 4], [[6,8], [4,5,8]], [10, 12, 14]] print("Original list:") print(list1) print("\nNumber of lists in said list of lists:") print(count_list(list1)) print("\nOriginal list:") print(list2) print("\nNumber of lists in said list of lists:") print(count_list(list2))
64
# Write a Python program to Count Strings with substring String List # Python code to demonstrate  # Count Strings with substring String List # using list comprehension + len()    # initializing list  test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']    # printing original list  print ("The original list is : " + str(test_list))    # initializing substring subs = 'Geek'    # using list comprehension + len() # Count Strings with substring String List res = len([i for i in test_list if subs in i])    # printing result  print ("All strings count with given substring are : " + str(res))
97
# Write a Pandas program to plot the volatility over a period of time of Alphabet Inc. stock price between two specific dates. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-9-30') df['Date'] = pd.to_datetime(df['Date']) new_df = (df['Date']>= start_date) & (df['Date']<= end_date) df1 = df.loc[new_df] df2 = df1[['Date', 'Close']] df3 = df2.set_index('Date') data_filled = df3.asfreq('D', method='ffill') data_returns = data_filled.pct_change() data_std = data_returns.rolling(window=30, min_periods=30).std() plt.figure(figsize=(20,20)) data_std.plot(); plt.suptitle('Volatility over a period of time of Alphabet Inc. stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black') plt.grid(True) plt.show()
90
# Write a Pandas program to find the index of the first occurrence of the smallest and largest value of a given series. import pandas as pd nums = pd.Series([1, 3, 7, 12, 88, 23, 3, 1, 9, 0]) print("Original Series:") print(nums) print("Index of the first occurrence of the smallest and largest value of the said series:") print(nums.idxmin()) print(nums.idxmax())
59
# Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements. Write a NumPy program to find the number of occurrences of a sequence in the said array. import numpy as np np_array = np.array([[1, 2, 3], [2, 1, 2]], np.int32) print("Original Numpy array:") print(np_array) print("Type: ",type(np_array)) print("Sequence: 1,2",) result = repr(np_array).count("1, 2") print("Number of occurrences of the said sequence:",result)
64
# Find all non repeated characters in a string str=input("Enter Your String:")arr=[0]*256for i in range(len(str)):    if str[i]!=' ':        num=ord(str[i])        arr[num]+=1ch=' 'print("All Non-repeating character in a given string is: ",end="")for i in range(len(str)):        if arr[ord(str[i])] ==1:            ch=str[i]            print(ch,end=" ")
38
# Nested Lambda Function in Python # Python program to demonstrate # nested lambda functions       f = lambda a = 2, b = 3:lambda c: a+b+c    o = f() print(o(4))
30
# Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. d=dict() for x in range(1,16): d[x]=x**2 print(d)
34
# Write a NumPy program to calculate exp(x) - 1 for all elements in a given array. import numpy as np x = np.array([1., 2., 3., 4.], np.float32) print("Original array: ") print(x) print("\nexp(x)-1 for all elements of the said array:") r1 = np.expm1(x) r2 = np.exp(x) - 1. assert np.allclose(r1, r2) print(r1)
52
# Python Program to Find the Area of a Rectangle Using Classes class rectangle(): def __init__(self,breadth,length): self.breadth=breadth self.length=length def area(self): return self.breadth*self.length a=int(input("Enter length of rectangle: ")) b=int(input("Enter breadth of rectangle: ")) obj=rectangle(a,b) print("Area of rectangle:",obj.area())   print()
37
# Check strong number using recursion def Factorial(num):    if num<=0:        return 1    else:        return num*Factorial(num-1)sum=0def check_StrongNumber(num):    global sum    if (num>0):        fact = 1        rem = num % 10        check_StrongNumber(num // 10)        fact = Factorial(rem)        sum+=fact    return sumnum=int(input("Enter a number:"))if (check_StrongNumber(num) == num):    print("It is a strong Number.")else:    print("It is not a strong Number.")
53
# Write a Python program to generate a random alphabetical character, alphabetical string and alphabetical string of a fixed length. Use random.choice() import random import string print("Generate a random alphabetical character:") print(random.choice(string.ascii_letters)) print("\nGenerate a random alphabetical string:") max_length = 255 str1 = "" for i in range(random.randint(1, max_length)): str1 += random.choice(string.ascii_letters) print(str1) print("\nGenerate a random alphabetical string of a fixed length:") str1 = "" for i in range(10): str1 += random.choice(string.ascii_letters) print(str1)
72