code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to Convert Key-Value list Dictionary to List of Lists # Python3 code to demonstrate working of  # Convert Key-Value list Dictionary to Lists of List # Using loop + items()    # initializing Dictionary test_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]}    # printing original dictionary print("The original dictionary is : " + str(test_dict))    # Convert Key-Value list Dictionary to Lists of List # Using loop + items() res = [] for key, val in test_dict.items():     res.append([key] + val)    # printing result  print("The converted list is : " + str(res)) 
101
# Reverse words in a given String in Python # Function to reverse words of string     def rev_sentence(sentence):         # first split the string into words      words = sentence.split(' ')         # then reverse the split string list and join using space      reverse_sentence = ' '.join(reversed(words))         # finally return the joined string      return reverse_sentence     if __name__ == "__main__":      input = 'geeks quiz practice code'     print (rev_sentence(input))
64
# Write a NumPy program to sort an given array by the n import numpy as np print("Original array:\n") nums = np.random.randint(0,10,(3,3)) print(nums) print("\nSort the said array by the nth column: ") print(nums[nums[:,1].argsort()])
33
# Write a Python program to create a ctime formatted representation of the date and time using arrow module. import arrow print("Ctime formatted representation of the date and time:") a = arrow.utcnow().ctime() print(a)
33
# Write a Pandas program to extract word mention someone in tweets using @ from the specified column of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'tweets': ['@Obama says goodbye','Retweets for @cash','A political endorsement in @Indonesia', '1 dog = many #retweets', 'Just a simple #egg'] }) print("Original DataFrame:") print(df) def find_at_word(text): word=re.findall(r'(?<[email protected])\w+',text) return " ".join(word) df['at_word']=df['tweets'].apply(lambda x: find_at_word(x)) print("\Extracting @word from dataframe columns:") print(df)
74
# Write a Python program to Avoid Spaces in string length # Python3 code to demonstrate working of  # Avoid Spaces in Characters Frequency # Using isspace() + sum()    # initializing string test_str = 'geeksforgeeks 33 is   best'    # printing original string print("The original string is : " + str(test_str))    # isspace() checks for space  # sum checks count  res = sum(not chr.isspace() for chr in test_str)        # printing result  print("The Characters Frequency avoiding spaces : " + str(res)) 
79
# Write a Pandas program to select a specific row of given series/dataframe by integer index. import pandas as pd ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8]) print("Original Series:") print(ds) print("\nPrint specified row from the said series using location based indexing:") print("\nThird row:") print(ds.iloc[[2]]) print("\nFifth row:") print(ds.iloc[[4]]) df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 32, 33, 30, 31, 32]}) print("Original DataFrame with single index:") print(df) print("\nPrint specified row from the said DataFrame using location based indexing:") print("\nThird row:") print(df.iloc[[2]]) print("\nFifth row:") print(df.iloc[[4]])
99
# Program to print Fibonacci series in Python | C | C++ | Java print("Enter the range of number(Limit):") n=int(input()) i=1 a=0 b=1 c=a+b while(i<=n):     print(c,end=" ")     c = a + b     a = b     b = c     i+=1
39
# Python Program to Solve Matrix-Chain Multiplication using Dynamic Programming with Memoization def matrix_product(p): """Return m and s.   m[i][j] is the minimum number of scalar multiplications needed to compute the product of matrices A(i), A(i + 1), ..., A(j).   s[i][j] is the index of the matrix after which the product is split in an optimal parenthesization of the matrix product.   p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i]. """ length = len(p) # len(p) = number of matrices + 1   # m[i][j] is the minimum number of multiplications needed to compute the # product of matrices A(i), A(i+1), ..., A(j) # s[i][j] is the matrix after which the product is split in the minimum # number of multiplications needed m = [[-1]*length for _ in range(length)] s = [[-1]*length for _ in range(length)]   matrix_product_helper(p, 1, length - 1, m, s)   return m, s     def matrix_product_helper(p, start, end, m, s): """Return minimum number of scalar multiplications needed to compute the product of matrices A(start), A(start + 1), ..., A(end).   The minimum number of scalar multiplications needed to compute the product of matrices A(i), A(i + 1), ..., A(j) is stored in m[i][j].   The index of the matrix after which the above product is split in an optimal parenthesization is stored in s[i][j].   p[0... n] is a list such that matrix A(i) has dimensions p[i - 1] x p[i]. """ if m[start][end] >= 0: return m[start][end]   if start == end: q = 0 else: q = float('inf') for k in range(start, end): temp = matrix_product_helper(p, start, k, m, s) \ + matrix_product_helper(p, k + 1, end, m, s) \ + p[start - 1]*p[k]*p[end] if q > temp: q = temp s[start][end] = k   m[start][end] = q return q     def print_parenthesization(s, start, end): """Print the optimal parenthesization of the matrix product A(start) x A(start + 1) x ... x A(end).   s[i][j] is the index of the matrix after which the product is split in an optimal parenthesization of the matrix product. """ if start == end: print('A[{}]'.format(start), end='') return   k = s[start][end]   print('(', end='') print_parenthesization(s, start, k) print_parenthesization(s, k + 1, end) print(')', end='')     n = int(input('Enter number of matrices: ')) p = [] for i in range(n): temp = int(input('Enter number of rows in matrix {}: '.format(i + 1))) p.append(temp) temp = int(input('Enter number of columns in matrix {}: '.format(n))) p.append(temp)   m, s = matrix_product(p) print('The number of scalar multiplications needed:', m[1][n]) print('Optimal parenthesization: ', end='') print_parenthesization(s, 1, n)
415
# Write a Python program to Maximum frequency character in String # Python 3 code to demonstrate  # Maximum frequency character in String # naive method     # initializing string  test_str = "GeeksforGeeks"    # printing original string print ("The original string is : " + test_str)    # using naive method to get # Maximum frequency character in String all_freq = {} for i in test_str:     if i in all_freq:         all_freq[i] += 1     else:         all_freq[i] = 1 res = max(all_freq, key = all_freq.get)     # printing result  print ("The maximum of all characters in GeeksforGeeks is : " + str(res))
97
# Write a NumPy program to swap columns in a given array. import numpy as np my_array = np.arange(12).reshape(3, 4) print("Original array:") print(my_array) my_array[:,[0, 1]] = my_array[:,[1, 0]] print("\nAfter swapping arrays:") print(my_array)
32
# Write a Python program to find the Strongest Neighbour # define a function for finding # the maximum for adjacent # pairs in the array def maximumAdjacent(arr1, n):            # array to store the max      # value between adjacent pairs     arr2 = []              # iterate from 1 to n - 1     for i in range(1, n):                  # find max value between          # adjacent  pairs gets          # stored in r         r = max(arr1[i], arr1[i-1])                    # add element          arr2.append(r)                # printing the elements     for ele in arr2 :         print(ele,end=" ")    if __name__ == "__main__" :        # size of the input array   n = 6          # input array   arr1 = [1,2,2,3,4,5]        # function calling   maximumAdjacent(arr1, n)
113
# Write a Python program to Find common elements in three sorted arrays by dictionary intersection # Function to find common elements in three # sorted arrays from collections import Counter    def commonElement(ar1,ar2,ar3):      # first convert lists into dictionary      ar1 = Counter(ar1)      ar2 = Counter(ar2)      ar3 = Counter(ar3)            # perform intersection operation      resultDict = dict(ar1.items() & ar2.items() & ar3.items())      common = []             # iterate through resultant dictionary      # and collect common elements      for (key,val) in resultDict.items():           for i in range(0,val):                common.append(key)         print(common)    # Driver program if __name__ == "__main__":     ar1 = [1, 5, 10, 20, 40, 80]     ar2 = [6, 7, 20, 80, 100]     ar3 = [3, 4, 15, 20, 30, 70, 80, 120]     commonElement(ar1,ar2,ar3)
115
# Write a NumPy program to convert numpy datetime64 to Timestamp. import numpy as np from datetime import datetime dt = datetime.utcnow() print("Current date:") print(dt) dt64 = np.datetime64(dt) ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') print("Timestamp:") print(ts) print("UTC from Timestamp:") print(datetime.utcfromtimestamp(ts))
42
# Program to print series 1,3,7,15,31...N n=int(input("Enter the range of number(Limit):"))i=1pr=0while i<=n:    pr = (pr * 2) + 1    print(pr,end=" ")    i+=1
22
# Write a NumPy program to find unique rows in a NumPy array. import numpy as np x = np.array([[20, 20, 20, 0], [0, 20, 20, 20], [0, 20, 20, 20], [20, 20, 20, 0], [10, 20, 20,20]]) print("Original array:") print(x) y = np.ascontiguousarray(x).view(np.dtype((np.void, x.dtype.itemsize * x.shape[1]))) _, idx = np.unique(y, return_index=True) unique_result = x[idx] print("Unique rows of the above array:") print(unique_result)
62
# Write a Python program to get unique values from a list. my_list = [10, 20, 30, 40, 20, 50, 60, 40] print("Original List : ",my_list) my_set = set(my_list) my_new_list = list(my_set) print("List of unique numbers : ",my_new_list)
38
# Write a Python program to read last n lines of a file. import sys import os def file_read_from_tail(fname,lines): bufsize = 8192 fsize = os.stat(fname).st_size iter = 0 with open(fname) as f: if bufsize > fsize: bufsize = fsize-1 data = [] while True: iter +=1 f.seek(fsize-bufsize*iter) data.extend(f.readlines()) if len(data) >= lines or f.tell() == 0: print(''.join(data[-lines:])) break file_read_from_tail('test.txt',2)
59
# Write a NumPy program to compute the Kronecker product of two given mulitdimension arrays. import numpy as np a = np.array([1,2,3]) b = np.array([0,1,0]) print("Original 1-d arrays:") print(a) print(b) result = np.kron(a, b) print("Kronecker product of the said arrays:") print(result) x = np.arange(9).reshape(3, 3) y = np.arange(3, 12).reshape(3, 3) print("Original Higher dimension:") print(x) print(y) result = np.kron(x, y) print("Kronecker product of the said arrays:") print(result)
66
# Write a Python program to find the type of IP Address using Regex # Python program to find the type of Ip address # re module provides support # for regular expressions import re # Make a regular expression # for validating an Ipv4 ipv4 = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(             25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(             25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(             25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$''' # Make a regular expression # for validating an Ipv6 ipv6 = '''(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|         ([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:)         {1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1         ,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}         :){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{         1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA         -F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a         -fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0         -9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,         4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}         :){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9         ])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0         -9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]         |1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]         |1{0,1}[0-9]){0,1}[0-9]))''' # Define a function for finding # the type of Ip address def find(Ip):          # pass the regular expression     # and the string in search() method     if re.search(ipv4, Ip):         print("IPv4")     elif re.search(ipv6, Ip):         print("IPv6")     else:         print("Neither") # Driver Code  if __name__ == '__main__' :              # Enter the Ip address     Ip = "192.0.2.126"             # calling run function      find(Ip)         Ip = "3001:0da8:75a3:0000:0000:8a2e:0370:7334"     find(Ip)         Ip = "36.12.08.20.52"     find(Ip)
143
# Write a Python program to Odd Frequency Characters # Python3 code to demonstrate working of  # Odd Frequency Characters # Using list comprehension + defaultdict() from collections import defaultdict    # helper_function def hlper_fnc(test_str):     cntr = defaultdict(int)     for ele in test_str:         cntr[ele] += 1     return [val for val, chr in cntr.items() if chr % 2 != 0]    # initializing string test_str = 'geekforgeeks is best for geeks'    # printing original string print("The original string is : " + str(test_str))    # Odd Frequency Characters # Using list comprehension + defaultdict() res = hlper_fnc(test_str)    # printing result  print("The Odd Frequency Characters are : " + str(res))
104
# Write a Python program to convert an array to an ordinary list with the same items. from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) print("Original array: "+str(array_num)) num_list = array_num.tolist() print("Convert the said array to an ordinary list with the same items:") print(num_list)
51
# Write a Python program to create a shallow copy of a given list. Use copy.copy import copy nums_x = [1, [2, 3, 4]] print("Original list: ", nums_x) nums_y = copy.copy(nums_x) print("\nCopy of the said list:") print(nums_y) print("\nChange the value of an element of the original list:") nums_x[1][1] = 10 print(nums_x) print("\nSecond list:") print(nums_y) nums = [[1], [2]] nums_copy = copy.copy(nums) print("\nOriginal list:") print(nums) print("\nCopy of the said list:") print(nums_copy) print("\nChange the value of an element of the original list:") nums[0][0] = 0 print("\nFirst list:") print(nums) print("\nSecond list:") print(nums_copy)
89
# Write a Pandas program to remove the html tags within the specified column of a given DataFrame. import pandas as pd import re as re df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'], 'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'], 'address': ['9910 Surrey <b>Avenue</b>','92 N. Bishop Avenue','9910 <br>Golden Star Avenue', '102 Dunbar <i></i>St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def remove_tags(string): result = re.sub('<.*?>','',string) return result df['with_out_tags']=df['address'].apply(lambda cw : remove_tags(cw)) print("\nSentences without tags':") print(df)
72
# Write a Python program to sum of three given integers. However, if two values are equal sum will be zero. def sum(x, y, z): if x == y or y == z or x==z: sum = 0 else: sum = x + y + z return sum print(sum(2, 1, 2)) print(sum(3, 2, 2)) print(sum(2, 2, 2)) print(sum(1, 2, 3))
60
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight dataframe's specific columns with different colors. import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[0, 2] = np.nan df.iloc[3, 3] = np.nan df.iloc[4, 1] = np.nan df.iloc[9, 4] = np.nan print("Original array:") print(df) print("\nDifferent background color:") coldict = {'B':'red', 'D':'yellow'} def highlight_cols(x): #copy df to new - original data are not changed df = x.copy() #select all values to default value - red color df.loc[:,:] = 'background-color: red' #overwrite values grey color df[['B','C', 'E']] = 'background-color: grey' #return color df return df df.style.apply(highlight_cols, axis=None)
116
# Write a Python program to get the size of a file. import os file_size = os.path.getsize("abc.txt") print("\nThe size of abc.txt is :",file_size,"Bytes") print()
24
# Python Program to Find the LCM of Two Numbers a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) if(a>b): min1=a else: min1=b while(1): if(min1%a==0 and min1%b==0): print("LCM is:",min1) break min1=min1+1
30
# Write a Python program to find middle of a linked list using one traversal # Python 3 program to find the middle of a   # given linked list     # Node class  class Node:         # Function to initialise the node object      def __init__(self, data):          self.data = data          self.next = None     class LinkedList:        def __init__(self):         self.head = None        def push(self, new_data):         new_node = Node(new_data)         new_node.next = self.head         self.head = new_node        # Function to get the middle of      # the linked list     def printMiddle(self):         slow_ptr = self.head         fast_ptr = self.head            if self.head is not None:             while (fast_ptr is not None and fast_ptr.next is not None):                 fast_ptr = fast_ptr.next.next                 slow_ptr = slow_ptr.next             print("The middle element is: ", slow_ptr.data)    # Driver code list1 = LinkedList() list1.push(5) list1.push(4) list1.push(2) list1.push(3) list1.push(1) list1.printMiddle()
127
# Write a Pandas program to extract only phone number from the specified column of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'], 'company_phone_no': ['Company1-Phone no. 4695168357','Company2-Phone no. 8088729013','Company3-Phone no. 6204658086', 'Company4-Phone no. 5159530096', 'Company5-Phone no. 9037952371'] }) print("Original DataFrame:") print(df) def find_phone_number(text): ph_no = re.findall(r"\b\d{10}\b",text) return "".join(ph_no) df['number']=df['company_phone_no'].apply(lambda x: find_phone_number(x)) print("\Extracting numbers from dataframe columns:") print(df)
69
# Write a Python program to find the length of the text of the first <h2> 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("Length of the text of the first <h2> tag:") print(len(soup.find('h2').text))
176
# Write a Python program to find common items from two lists. color1 = "Red", "Green", "Orange", "White" color2 = "Black", "Green", "White", "Pink" print(set(color1) & set(color2))
27
# Write a NumPy program to normalize a 3x3 random matrix. import numpy as np x= np.random.random((3,3)) print("Original Array:") print(x) xmax, xmin = x.max(), x.min() x = (x - xmin)/(xmax - xmin) print("After normalization:") print(x)
35
# Python Program to Put Even and Odd elements in a List into Two Different Lists a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=int(input("Enter element:")) a.append(b) even=[] odd=[] for j in a: if(j%2==0): even.append(j) else: odd.append(j) print("The even list",even) print("The odd list",odd)
44
# Write a NumPy program to get the unique elements of an array. import numpy as np x = np.array([10, 10, 20, 20, 30, 30]) print("Original array:") print(x) print("Unique elements of the above array:") print(np.unique(x)) x = np.array([[1, 1], [2, 3]]) print("Original array:") print(x) print("Unique elements of the above array:") print(np.unique(x))
51
# Program to compute the area and perimeter of Rhombus print("Enter the two Diagonals Value:") p=int(input()) q=int(input()) a=int(input("Enter the length of the side value:")) area=(p*q)/2.0 perimeter=(4*a) print("Area of the Rhombus = ",area) print("Perimeter of the Rhombus = ",perimeter)
38
# How to iterate over rows in Pandas Dataframe in Python # importing pandas import pandas as pd    # list of dicts input_df = [{'name':'Sujeet', 'age':10},             {'name':'Sameer', 'age':11},             {'name':'Sumit', 'age':12}]    df = pd.DataFrame(input_df) print('Original DataFrame: \n', df)       print('\nRows iterated using iterrows() : ') for index, row in df.iterrows():     print(row['name'], row['age'])
50
# Find the average of an unknown number of inputs in Python        # function that takes arbitary # number of inputs def avgfun(*n):     sums = 0        for t in n:         sums = sums + t        avg = sums / len(n)     return avg           # Driver Code  result1 = avgfun(1, 2, 3) result2 = avgfun(2, 6, 4, 8)    # Printing average of the list  print(round(result1, 2)) print(round(result2, 2))
66
# numpy.percentile() in python # Python Program illustrating # numpy.percentile() method     import numpy as np     # 1D array arr = [20, 2, 7, 1, 34] print("arr : ", arr) print("50th percentile of arr : ",        np.percentile(arr, 50)) print("25th percentile of arr : ",        np.percentile(arr, 25)) print("75th percentile of arr : ",        np.percentile(arr, 75))
53
# Write a NumPy program to remove the first dimension from a given array of shape (1,3,4). import numpy as np nums = np.array([[[1, 2, 3, 4], [0, 1, 3, 4], [5, 0, 3, 2]]]) print('Shape of the said array:') print(nums.shape) print("\nAfter removing the first dimension of the shape of the said array:")
53
# Write a Python program to Find the Number Occurring Odd Number of Times using Lambda expression and reduce function # Python program to Find the Number  # Occurring Odd Number of Times # using Lambda expression and reduce function    from functools import reduce    def oddTimes(input):      # write lambda expression and apply      # reduce function over input list      # until single value is left      # expression reduces value of a ^ b into single value      # a starts from 0 and b from 1      # ((((((1 ^ 2)^3)^2)^3)^1)^3)      print (reduce(lambda a, b: a ^ b, input))    # Driver program if __name__ == "__main__":     input = [1, 2, 3, 2, 3, 1, 3]     oddTimes(input)
113
# Reindexing in Pandas DataFrame in Python # import numpy and pandas module import pandas as pd import numpy as np column=['a','b','c','d','e'] index=['A','B','C','D','E'] # create a dataframe of random values of array df1 = pd.DataFrame(np.random.rand(5,5),             columns=column, index=index) print(df1) print('\n\nDataframe after reindexing rows: \n', df1.reindex(['B', 'D', 'A', 'C', 'E']))
48
# Write a Python program to sort unsorted numbers using Strand sort. #Ref:https://bit.ly/3qW9FIX import operator def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution lst = [4, 3, 5, 1, 2] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst)) lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst)) lst = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst))
158
# Write a Python program to interleave two given list into another list randomly. import random def randomly_interleave(nums1, nums2): result = [x.pop(0) for x in random.sample([nums1]*len(nums1) + [nums2]*len(nums2), len(nums1)+len(nums2))] return result nums1 = [1,2,7,8,3,7] nums2 = [4,3,8,9,4,3,8,9] print("Original lists:") print(nums1) print(nums2) print("\nInterleave two given list into another list randomly:") print(randomly_interleave(nums1, nums2))
51
# Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm def find_max_subarray(alist, start, end): """Returns (l, r, m) such that alist[l:r] is the maximum subarray in A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x < end.""" max_ending_at_i = max_seen_so_far = alist[start] max_left_at_i = max_left_so_far = start # max_right_at_i is always i + 1 max_right_so_far = start + 1 for i in range(start + 1, end): if max_ending_at_i > 0: max_ending_at_i += alist[i] else: max_ending_at_i = alist[i] max_left_at_i = i if max_ending_at_i > max_seen_so_far: max_seen_so_far = max_ending_at_i max_left_so_far = max_left_at_i max_right_so_far = i + 1 return max_left_so_far, max_right_so_far, max_seen_so_far     alist = input('Enter the list of numbers: ') alist = alist.split() alist = [int(x) for x in alist] start, end, maximum = find_max_subarray(alist, 0, len(alist)) print('The maximum subarray starts at index {}, ends at index {}' ' and has sum {}.'.format(start, end - 1, maximum))
149
# Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. : Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[5:] printList()
51
# Write a Pandas program to merge two given datasets using multiple join keys. import pandas as pd data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K1'], 'P': ['P0', 'P1', 'P2', 'P3'], 'Q': ['Q0', 'Q1', 'Q2', 'Q3']}) data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 'key2': ['K0', 'K0', 'K0', 'K0'], 'R': ['R0', 'R1', 'R2', 'R3'], 'S': ['S0', 'S1', 'S2', 'S3']}) print("Original DataFrames:") print(data1) print("--------------------") print(data2) print("\nMerged Data:") merged_data = pd.merge(data1, data2, on=['key1', 'key2']) print(merged_data)
76
# Write a Python program to find palindromes in a given list of strings using Lambda. texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"] print("Orginal list of strings:") print(texts) result = list(filter(lambda x: (x == "".join(reversed(x))), texts)) print("\nList of palindromes:") print(result)
41
# LRU Cache in Python using OrderedDict from collections import OrderedDict class LRUCache:     # initialising capacity     def __init__(self, capacity: int):         self.cache = OrderedDict()         self.capacity = capacity     # we return the value of the key     # that is queried in O(1) and return -1 if we     # don't find the key in out dict / cache.     # And also move the key to the end     # to show that it was recently used.     def get(self, key: int) -> int:         if key not in self.cache:             return -1         else:             self.cache.move_to_end(key)             return self.cache[key]     # first, we add / update the key by conventional methods.     # And also move the key to the end to show that it was recently used.     # But here we will also check whether the length of our     # ordered dictionary has exceeded our capacity,     # If so we remove the first key (least recently used)     def put(self, key: int, value: int) -> None:         self.cache[key] = value         self.cache.move_to_end(key)         if len(self.cache) > self.capacity:             self.cache.popitem(last = False) # RUNNER # initializing our cache with the capacity of 2 cache = LRUCache(2) cache.put(1, 1) print(cache.cache) cache.put(2, 2) print(cache.cache) cache.get(1) print(cache.cache) cache.put(3, 3) print(cache.cache) cache.get(2) print(cache.cache) cache.put(4, 4) print(cache.cache) cache.get(1) print(cache.cache) cache.get(3) print(cache.cache) cache.get(4) print(cache.cache) #This code was contributed by Sachin Negi
208
# Write a Python program to sum two or more lists, the lengths of the lists may be different. def sum_lists_diff_length(test_list): result = [sum(x) for x in zip(*map(lambda x:x+[0]*max(map(len, test_list)) if len(x)<max(map(len, test_list)) else x, test_list))] return result nums = [[1,2,4],[2,4,4],[1,2]] print("\nOriginal list:") print(nums) print("Sum said lists with different lengths:") print(sum_lists_diff_length(nums)) nums = [[1],[2,4,4],[1,2],[4]] print("\nOriginal list:") print(nums) print("Sum said lists with different lengths:") print(sum_lists_diff_length(nums))
64
# Python Program to Implement Radix Sort def radix_sort(alist, base=10): if alist == []: return   def key_factory(digit, base): def key(alist, index): return ((alist[index]//(base**digit)) % base) return key largest = max(alist) exp = 0 while base**exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist   def counting_sort(alist, largest, key): c = [0]*(largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1   # Find the last index for each element c[0] = c[0] - 1 # to decrement each element for zero-based indexing for i in range(1, largest + 1): c[i] = c[i] + c[i - 1]   result = [None]*len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1   return result   alist = input('Enter the list of (nonnegative) numbers: ').split() alist = [int(x) for x in alist] sorted_list = radix_sort(alist) print('Sorted list: ', end='') print(sorted_list)
155
# Program to print the Full Pyramid Number Pattern row_size=int(input("Enter the row size:")) np=1 for out in range(0,row_size):     for in1 in range(row_size-1,out,-1):         print(" ",end="")     for in2 in range(1, np+1):         print(in2,end="")     np+=2     print("\r")
32
# Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes n=int(input("Enter upper limit of range: ")) sieve=set(range(2,n+1)) while sieve: prime=min(sieve) print(prime,end="\t") sieve-=set(range(prime,n+1,prime))   print()
28
# Python Program to Print nth Fibonacci Number using Dynamic Programming with Memoization def fibonacci(n): """Return the nth Fibonacci number.""" # r[i] will contain the ith Fibonacci number r = [-1]*(n + 1) return fibonacci_helper(n, r)     def fibonacci_helper(n, r): """Return the nth Fibonacci number and store the ith Fibonacci number in r[i] for 0 <= i <= n.""" if r[n] >= 0: return r[n]   if (n == 0 or n == 1): q = n else: q = fibonacci_helper(n - 1, r) + fibonacci_helper(n - 2, r) r[n] = q   return q     n = int(input('Enter n: '))   ans = fibonacci(n) print('The nth Fibonacci number:', ans)
105
# Write a NumPy program to sort an along the first, last axis of an array. import numpy as np a = np.array([[4, 6],[2, 1]]) print("Original array: ") print(a) print("Sort along the first axis: ") x = np.sort(a, axis=0) print(x) print("Sort along the last axis: ") y = np.sort(x, axis=1) print(y)
51
# Check whether a Numpy array contains a specified row in Python # importing package import numpy    # create numpy array arr = numpy.array([[1, 2, 3, 4, 5],                    [6, 7, 8, 9, 10],                    [11, 12, 13, 14, 15],                    [16, 17, 18, 19, 20]                    ])    # view array print(arr)    # check for some lists print([1, 2, 3, 4, 5] in arr.tolist()) print([16, 17, 20, 19, 18] in arr.tolist()) print([3, 2, 5, -4, 5] in arr.tolist()) print([11, 12, 13, 14, 15] in arr.tolist())
81
# Write a NumPy program to move the specified axis backwards, until it lies in a given position. import numpy as np x = np.ones((2,3,4,5)) print(np.rollaxis(x, 3, 1).shape)
28
# Write a Python program to generate all possible permutations of n different objects. import itertools def permutations_all(l): for values in itertools.permutations(l): print(values) permutations_all([1]) print("\n") permutations_all([1,2]) print("\n") permutations_all([1,2,3])
28
# Count distinct elements in an array import sys arr=[] freq=[] max=-sys.maxsize-1 size = int(input("Enter the size of the array: ")) print("Enter the Element of the array:") for i in range(0,size):     num = int(input())     arr.append(num) for i in range(0, size):     if(arr[i]>=max):         max=arr[i] for i in range(0,max+1):     freq.append(0) for i in range(0, size):     freq[arr[i]]+=1 count=0 for i in range(0, max+1):     if freq[i] == 1:         count+=1 print("Numbers of distinct elements are ",count)
70
# Write a Python program to get the items from a given list with specific condition. def first_index(l1): return sum(1 for i in l1 if (i> 45 and i % 2 == 0)) nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83] print("Original list:") print(nums) n = 45 print("\nNumber of Items of the said list which are even and greater than",n) print(first_index(nums))
56
# Write a Python program to List product excluding duplicates # Python 3 code to demonstrate # Duplication Removal List Product # using naive methods # getting Product def prod(val) :     res = 1     for ele in val:         res *= ele     return res  # initializing list test_list = [1, 3, 5, 6, 3, 5, 6, 1] print ("The original list is : " + str(test_list)) # using naive method # Duplication Removal List Product res = [] for i in test_list:     if i not in res:         res.append(i) res = prod(res) # printing list after removal print ("Duplication removal list product : " + str(res))
104
# Write a Python program to search a date from a given string using arrow module. import arrow print("\nSearch a date from a string:") d1 = arrow.get('David was born in 11 June 2003', 'DD MMMM YYYY') print(d1)
37
# Write a Python program to create datetime from integers, floats and strings timestamps using arrow module. import arrow i = arrow.get(1857900545) print("Date from integers: ") print(i) f = arrow.get(1857900545.234323) print("\nDate from floats: ") print(f) s = arrow.get('1857900545') print("\nDate from Strings: ") print(s)
43
# Write a Python program to shift last element to first position and first element to last position in a given list. def shift_first_last(lst): x = lst.pop(0) y = lst.pop() lst.insert(0, y) lst.insert(len(lst), x) return lst nums = [1,2,3,4,5,6,7] print("Original list:") print(nums) print("Shift last element to first position and first element to last position of the said list:") print(shift_first_last(nums)) chars = ['s','d','f','d','s','s','d','f'] print("\nOriginal list:") print(chars) print("Shift last element to first position and first element to last position of the said list:") print(shift_first_last(chars))
82
# Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2. def substring_copy(str, n): flen = 2 if flen > len(str): flen = len(str) substr = str[:flen] result = "" for i in range(n): result = result + substr return result print(substring_copy('abcdef', 2)) print(substring_copy('p', 3));
70
# Write a Python program to Flatten a 2d numpy array into 1d array # Python code to demonstrate # flattening a 2d numpy array # into 1d array    import numpy as np    ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])    # printing initial arrays print("initial array", str(ini_array1))    # Multiplying arrays result = ini_array1.flatten()    # printing result print("New resulting array: ", result)
65
# Write a Python program to create a time object with the same hour, minute, second, microsecond and a timestamp representation of the Arrow object, in UTC time. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nTime object with the same hour, minute, second, microsecond:") print(arrow.utcnow().time()) print("\nTimestamp representation of the Arrow object, in UTC time:") print(arrow.utcnow().timestamp)
56
# Write a NumPy program to change the dimension of an array. import numpy as np x = np.array([1, 2, 3, 4, 5, 6]) print("6 rows and 0 columns") print(x.shape) y = np.array([[1, 2, 3],[4, 5, 6],[7,8,9]]) print("(3, 3) -> 3 rows and 3 columns ") print(y) x = np.array([1,2,3,4,5,6,7,8,9]) print("Change array shape to (3, 3) -> 3 rows and 3 columns ") x.shape = (3, 3) print(x)
68
# How to get all 2D diagonals of a 3D NumPy array in Python # Import the numpy package import numpy as np    # Create 3D-numpy array # of 4 rows and 4 columns arr = np.arange(3 * 4 * 4).reshape(3, 4, 4)    print("Original 3d array:\n",        arr)    # Create 2D diagonal array diag_arr = np.diagonal(arr,                         axis1 = 1,                        axis2 = 2)    print("2d diagonal array:\n",        diag_arr)
65
# Program to Find the multiplication of two matrices # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) matrix1=[] # Taking input of the 2nd matrix print("Enter the Matrix Element:") for i in range(row_size): matrix1.append([int(j) for j in input().split()]) sum=0 # Compute Multiplication of two matrices mul_matrix=[[0 for i in range(col_size)] for i in range(row_size)] for i in range(len(matrix)): for j in range(len(matrix[0])): for k in range(row_size): sum+=matrix[i][j]*matrix1[i][j] mul_matrix[i][j]=sum # display the Multiplication of two matrices print("Multiplication of the two Matrices is:") for m in mul_matrix: print(m)
118
# Write a NumPy program to create display every element of a NumPy array. import numpy as np x = np.arange(12).reshape(3, 4) for x in np.nditer(x): print(x,end=' ') print()
29
# Write a Pandas program to add 100 days with reporting date of unidentified flying object (UFO). import pandas as pd from datetime import timedelta df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) print("\nAdd 100 days with reporting date:") df['New_doc_dt'] = df['Date_time'] + timedelta(days=180) print(df)
46
# Python Program to Find the Length of the Linked List using Recursion class Node: def __init__(self, data): self.data = data self.next = None   class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next   def length(self): return self.length_helper(self.head)   def length_helper(self, current): if current is None: return 0 return 1 + self.length_helper(current.next)   a_llist = LinkedList() data_list = input('Please enter the elements in the linked list: ').split() for data in data_list: a_llist.append(int(data))   print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')
105
# Write a Python program to build flashcard using class in Python class flashcard:     def __init__(self, word, meaning):         self.word = word         self.meaning = meaning     def __str__(self):                  #we will return a string          return self.word+' ( '+self.meaning+' )'          flash = [] print("welcome to flashcard application")    #the following loop will be repeated until #user stops to add the flashcards while(True):     word = input("enter the name you want to add to flashcard : ")     meaning = input("enter the meaning of the word : ")            flash.append(flashcard(word, meaning))     option = int(input("enter 0 , if you want to add another flashcard : "))            if(option):         break            # printing all the flashcards  print("\nYour flashcards") for i in flash:     print(">", i)
111
# Write a NumPy program to create an array of all the even integers from 30 to 70. import numpy as np array=np.arange(30,71,2) print("Array of all the even integers from 30 to 70") print(array)
34
# Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series. import pandas as pd import numpy as np num_series = pd.Series(np.random.randint(1, 10, 9)) print("Original Series:") print(num_series) result = np.argwhere(num_series % 5==0) print("Positions of numbers that are multiples of 5:") print(result)
50
# Write a NumPy program to compute pearson product-moment correlation coefficients of two given arrays. import numpy as np x = np.array([0, 1, 3]) y = np.array([2, 4, 5]) print("\nOriginal array1:") print(x) print("\nOriginal array1:") print(y) print("\nPearson product-moment correlation coefficients of the said arrays:\n",np.corrcoef(x, y))
44
# Write a NumPy program to test whether each element of a 1-D array is also present in a second array. import numpy as np array1 = np.array([0, 10, 20, 40, 60]) print("Array1: ",array1) array2 = [0, 40] print("Array2: ",array2) print("Compare each element of array1 and array2") print(np.in1d(array1, array2))
49
# Write a Python program to Creating a Pandas dataframe column based on a given condition # importing pandas as pd import pandas as pd    # Creating the dataframe df = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011',                                         '11/11/2011', '11/12/2011'],                 'Event' : ['Music', 'Poetry', 'Music', 'Music', 'Poetry']})    # Print the dataframe print(df)
50
# Write a Python program to Extract tuples having K digit elements # Python3 code to demonstrate working of # Extract K digit Elements Tuples # Using all() + list comprehension    # initializing list test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]    # printing original list print("The original list is : " + str(test_list))    # initializing K K = 2    # using len() and str() to check length and  # perform string conversion res = [sub for sub in test_list if all(len(str(ele)) == K for ele in sub)]    # printing result print("The Extracted tuples : " + str(res))
102
# Write a Python program to Convert a set into dictionary # Python code to demonstrate # converting set into dictionary # using fromkeys() # initializing set ini_set = {1, 2, 3, 4, 5} # printing initialized set print ("initial string", ini_set) print (type(ini_set)) # Converting set to dictionary res = dict.fromkeys(ini_set, 0) # printing final result and its type print ("final list", res) print (type(res))
66
# Write a Python program to calculate surface volume and area of a sphere. pi=22/7 radian = float(input('Radius of sphere: ')) sur_area = 4 * pi * radian **2 volume = (4/3) * (pi * radian ** 3) print("Surface Area is: ", sur_area) print("Volume is: ", volume)
47
# Write a Python program to print number with commas as thousands separators(from right side). print("{:,}".format(1000000)) print("{:,}".format(10000))
17
# Write a Python program to count integer in a given mixed list. def count_integer(list1): ctr = 0 for i in list1: if isinstance(i, int): ctr = ctr + 1 return ctr list1 = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22] print("Original list:") print(list1) print("\nNumber of integers in the said mixed list:") print(count_integer(list1))
57
# Write a Python program to decapitalize the first letter of a given string. def decapitalize_first_letter(s, upper_rest = False): return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])]) print(decapitalize_first_letter('Java Script')) print(decapitalize_first_letter('Python'))
29
# Python Program to Print all the Paths from the Root to the Leaf in a Tree class Tree: def __init__(self, data=None): self.key = data self.children = []   def set_root(self, data): self.key = data   def add(self, node): self.children.append(node)   def search(self, key): if self.key == key: return self for child in self.children: temp = child.search(key) if temp is not None: return temp return None   def print_all_paths_to_leaf(self): self.print_all_paths_to_leaf_helper([])   def print_all_paths_to_leaf_helper(self, path_till_now): path_till_now.append(self.key) if self.children == []: for key in path_till_now: print(key, end=' ') print() else: for child in self.children: child.print_all_paths_to_leaf_helper(path_till_now[:])     tree = None   print('Menu (this assumes no duplicate keys)') print('add <data> at root') print('add <data> below <data>') print('paths') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'add': data = int(do[1]) new_node = Tree(data) suboperation = do[2].strip().lower() if suboperation == 'at': tree = new_node elif suboperation == 'below': position = do[3].strip().lower() key = int(position) ref_node = None if tree is not None: ref_node = tree.search(key) if ref_node is None: print('No such key.') continue ref_node.add(new_node)   elif operation == 'paths': if tree is None: print('Tree is empty.') else: tree.print_all_paths_to_leaf()   elif operation == 'quit': break
189
# Program to display a lower triangular matrix # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) #Display Lower triangular matrix print("Lower Triangular Matrix is:\n") for i in range(len(matrix)): for j in range(len(matrix[0])): if i<j: print("0 ",end="") else: print(matrix[i][j],end=" ") print()
71
# Write a Python program to chunk a given list into n smaller lists. from math import ceil def chunk_list_into_n(nums, n): size = ceil(len(nums) / n) return list( map(lambda x: nums[x * size:x * size + size], list(range(n))) ) print(chunk_list_into_n([1, 2, 3, 4, 5, 6, 7], 4))
47
# Write a Python program to get all unique combinations of two Lists # python program to demonstrate # unique combination of two lists # using zip() and permutation of itertools # import itertools package import itertools from itertools import permutations # initialize lists list_1 = ["a", "b", "c","d"] list_2 = [1,4,9] # create empty list to store the # combinations unique_combinations = [] # Getting all permutations of list_1 # with length of list_2 permut = itertools.permutations(list_1, len(list_2)) # zip() is called to pair each permutation # and shorter list element into combination for comb in permut:     zipped = zip(comb, list_2)     unique_combinations.append(list(zipped)) # printing unique_combination list print(unique_combinations)
108
# How To Automate Google Chrome Using Foxtrot and Python # Import the required modules from selenium import webdriver import time    # Main Function if __name__ == '__main__':        # Provide the email and password     email = ''     password = ''        options = webdriver.ChromeOptions()     options.add_argument("--start-maximized")        # Provide the path of chromedriver     # present on your system.     driver = webdriver.Chrome(         executable_path="C:/chromedriver/chromedriver.exe",        chrome_options=options)     driver.set_window_size(1920, 1080)        # Send a get request to the url     driver.get('https://auth.geeksforgeeks.org/')     time.sleep(5)        # Finds the input box by name     # in DOM tree to send both     # the provided email and password in it.     driver.find_element_by_name('user').send_keys(email)     driver.find_element_by_name('pass').send_keys(password)        # Find the signin button and click on it.     driver.find_element_by_css_selector(         'button.btn.btn-green.signin-button').click()     time.sleep(5)        # Returns the list of elements     # having the following css selector.     container = driver.find_elements_by_css_selector(         'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold')        # Extracts the text from name,     # institution, email_id css selector.     name = container[0].text     try:         institution = container[1].find_element_by_css_selector('a').text     except:         institution = container[1].text     email_id = container[2].text        # Output     print({"Name": name, "Institution": institution,            "Email ID": email})        # Quits the driver     driver.quit()
163
# Write a Pandas program to split a given dataset using group by on specified column into two labels and ranges. import pandas as pd import numpy as np pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'salesman_id': [5001,5002,5003,5004,5005,5006,5007,5008,5009,5010,5011,5012], 'sale_jan':[150.5, 270.65, 65.26, 110.5, 948.5, 2400.6, 1760, 2983.43, 480.4, 1250.45, 75.29,1045.6]}) print("Original Orders DataFrame:") print(df) result = df.groupby(pd.cut(df['salesman_id'], bins=[0,5006,np.inf], labels=['S1', 'S2']))['sale_jan'].sum().reset_index() print("\nGroupBy with condition of two labels and ranges:") print(result)
68
# Select row with maximum and minimum value in Pandas dataframe in Python # importing pandas and numpy import pandas as pd import numpy as np    # data of 2018 drivers world championship dict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen',                   'Verstappen', 'Bottas', 'Ricciardo',                   'Hulkenberg', 'Perez', 'Magnussen',                    'Sainz', 'Alonso', 'Ocon', 'Leclerc',                   'Grosjean', 'Gasly', 'Vandoorne',                   'Ericsson', 'Stroll', 'Hartley', 'Sirotkin'],                              'Points':[408, 320, 251, 249, 247, 170, 69, 62, 56,                    53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1],                               'Age':[33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37,                       22, 21, 32, 22, 26, 28, 20, 29, 23]}                          # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) print(df.head(10))
104
# Get the index of minimum value in DataFrame column in Python # importing pandas module  import pandas as pd       # making data frame  df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     df.head(10)
28
# Write a Python program to sort a list of elements using Gnome sort. def gnome_sort(nums): if len(nums) <= 1: return nums i = 1 while i < len(nums): if nums[i-1] <= nums[i]: i += 1 else: nums[i-1], nums[i] = nums[i], nums[i-1] i -= 1 if (i == 0): i = 1 user_input = input("Input numbers separated by a comma:\n").strip() nums = [int(item) for item in user_input.split(',')] gnome_sort(nums) print(nums)
69
# Limited rows selection with given column in Pandas | Python # Import pandas package  import pandas as pd       # Define a dictionary containing employee data  data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],          'Age':[27, 24, 22, 32],          'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],          'Qualification':['Msc', 'MA', 'MCA', 'Phd']}       # Convert the dictionary into DataFrame   df = pd.DataFrame(data)       # select three rows and two columns  print(df.loc[1:3, ['Name', 'Qualification']])
63
# Program to print the Inverted V Star Pattern row_size=int(input("Enter the row size:")) print_control_x=row_size print_control_y=row_size for out in range(1,row_size+1):     for in1 in range(1,row_size*2+1):         if in1==print_control_x or in1==print_control_y:             print("*",end="")         else:             print(" ", end="")     print_control_x-=1     print_control_y+=1     print("\r")
35
# Write a Python program to split an iterable and generate iterables specified number of times. import itertools as it def tee_data(iter, n): return it.tee(iter, n) #List result = tee_data(['A','B','C','D'], 5) print("Generate iterables specified number of times:") for i in result: print(list(i)) #String result = tee_data("Python itertools", 4) print("\nGenerate iterables specified number of times:") for i in result: print(list(i))
59
# Program to convert decimal to octal using while loop sem=1 octal=0 print("Enter the Decimal Number:") number=int(input()) while(number !=0):       octal=octal+(number%8)*sem       number=number//8       sem=int(sem*10) print("Octal Number is ",octal)
26
# Write a Python program to add to a tag's contents in a given html document. from bs4 import BeautifulSoup html_doc = '<a href="http://example.com/">HTML<i>w3resource.com</i></a>' soup = BeautifulSoup(html_doc, "lxml") print("\nOriginal Markup:") print(soup.a) soup.a.append("CSS") print("\nAfter append a text in the new link:") print(soup.a)
41
# Write a Python program to find the numbers of a given string and store them in a list, display the numbers which are bigger than the length of the list in sorted form. Use lambda function to solve the problem. str1 = "sdf 23 safs8 5 sdfsd8 sdfs 56 21sfs 20 5" print("Original string: ",str1) str_num=[i for i in str1.split(' ')] lenght=len(str_num) numbers=sorted([int(x) for x in str_num if x.isdigit()]) print('Numbers in sorted form:') for i in ((filter(lambda x:x>lenght,numbers))): print(i,end=' ')
81