code
stringlengths
63
8.54k
code_length
int64
11
747
# How to rename columns in Pandas DataFrame in Python # Import pandas package import pandas as pd     # Define a dictionary containing ICC rankings rankings = {'test': ['India', 'South Africa', 'England',                             'New Zealand', 'Australia'],               'odi': ['England', 'India', 'New Zealand',                             'South Africa', 'Pakistan'],                't20': ['Pakistan', 'India', 'Australia',                               'England', 'New Zealand']}     # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings)     # Before renaming the columns print(rankings_pd)     rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)     # After renaming the columns print("\nAfter modifying first column:\n", rankings_pd.columns)
81
# Write a Python program to Numpy matrix.tolist() # import the important module in python import numpy as np                # make matrix with numpy gfg = np.matrix('[4, 1, 12, 3]')                # applying matrix.tolist() method geek = gfg.tolist()      print(geek)
38
# Write a Python Lambda with underscore as an argument remainder = lambda num: num % 2    print(remainder(5))
18
# Write a NumPy program to generate a random number between 0 and 1. import numpy as np rand_num = np.random.normal(0,1,1) print("Random number between 0 and 1:") print(rand_num)
28
# Write a Python program to sort a given positive number in descending/ascending order. def test_dsc(n): return int(''.join(sorted(str(n), reverse = True))) def test_asc(n): return int(''.join(sorted(list(str(n))))[::1]) n = 134543 print("Original Number: ",n); print("Descending order of the said number: ", test_dsc(n)); print("Ascending order of the said number: ", test_asc(n)); n = 43750973 print("\nOriginal Number: ",n); print("Descending order of the said number: ", test_dsc(n)); print("Ascending order of the said number: ", test_asc(n));
69
# How to find the number of arguments in a Python function def no_of_argu(*args):           # using len() method in args to count     return(len(args)) a = 1 b = 3 # arguments passed n = no_of_argu(1, 2, 4, a) # result printed print(" The number of arguments are: ", n)
49
# Write a Python program to insert tags or strings immediately after specified tags or strings. from bs4 import BeautifulSoup soup = BeautifulSoup("<b>w3resource.com</b>", "lxml") print("Original Markup:") print(soup.b) tag = soup.new_tag("i") tag.string = "Python" print("\nNew Markup, after inserting the text:") soup.b.string.insert_after(tag) print(soup.b)
41
# Program to print the Half Pyramid Number Pattern row_size=int(input("Enter the row size:")) for out in range(1,row_size+1):     for i in range(row_size+1,out,-1):         print(out,end="")     print("\r")
23
# Write a Python program to Split Strings on Prefix Occurrence # Python3 code to demonstrate working of # Split Strings on Prefix Occurrence # Using loop + startswith() # initializing list test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"] # printing original list print("The original list is : " + str(test_list)) # initializing prefix pref = "geek" res = [] for val in test_list:           # checking for prefix     if val.startswith(pref):                   # if pref found, start new list         res.append([val])     else:                   # else append in current list         res[-1].append(val) # printing result print("Prefix Split List : " + str(res))
98
# Write a NumPy program to create an empty and a full array. import numpy as np # Create an empty array x = np.empty((3,4)) print(x) # Create a full array y = np.full((3,3),6) print(y)
35
# Write a Python program to Insertion at the beginning in OrderedDict # Python code to demonstrate # insertion of items in beginning of ordered dict from collections import OrderedDict    # initialising ordered_dict iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])    # inserting items in starting of dict  iniordered_dict.update({'manjeet':'3'}) iniordered_dict.move_to_end('manjeet', last = False)    # print result print ("Resultant Dictionary : "+str(iniordered_dict))
59
# Write a NumPy program to calculate cumulative sum of the elements along a given axis, sum over rows for each of the 3 columns and sum over columns for each of the 2 rows of a given 3x3 array. import numpy as np x = np.array([[1,2,3], [4,5,6]]) print("Original array: ") print(x) print("Cumulative sum of the elements along a given axis:") r = np.cumsum(x) print(r) print("\nSum over rows for each of the 3 columns:") r = np.cumsum(x,axis=0) print(r) print("\nSum over columns for each of the 2 rows:") r = np.cumsum(x,axis=1) print(r)
91
# Print every character of a string twice str=input("Enter Your String:")for inn in range(0,len(str)):    print(str[inn]+str[inn],end="")
15
# Write a NumPy program to get the number of nonzero elements in an array. import numpy as np x = np.array([[0, 10, 20], [20, 30, 40]]) print("Original array:") print(x) print("Number of non zero elements in the above array:") print(np.count_nonzero(x))
40
# Write a Python code to send a request to a web page, and print the response text and content. Also get the raw socket response from the server. import requests res = requests.get('https://www.google.com/') print("Response text of https://google.com/:") print(res.text) print("\n==============================================================================") print("\nContent of the said url:") print(res.content) print("\n==============================================================================") print("\nRaw data of the said url:") r = requests.get('https://api.github.com/events', stream = True) print(r.raw) print(r.raw.read(15))
61
# Write a NumPy program to access last two columns of a multidimensional columns. import numpy as np arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arra) result = arra[:,[1,2]] print(result)
34
# Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15. import numpy as np x = np.arange(21) print("Original vector:") print(x) print("After changing the sign of the numbers in the range from 9 to 15:") x[(x >= 9) & (x <= 15)] *= -1 print(x)
63
# Write a Python program to remove empty lists from a given list of lists. list1 = [[], [], [], 'Red', 'Green', [1,2], 'Blue', [], []] print("Original list:") print(list1) print("\nAfter deleting the empty lists from the said lists of lists") list2 = [x for x in list1 if x] print(list2)
50
# Write a Python program to find unique triplets whose three elements gives the sum of zero from an array of n integers. def three_sum(nums): result = [] nums.sort() for i in range(len(nums)-2): if i> 0 and nums[i] == nums[i-1]: continue l, r = i+1, len(nums)-1 while l < r: s = nums[i] + nums[l] + nums[r] if s > 0: r -= 1 elif s < 0: l += 1 else: # found three sum result.append((nums[i], nums[l], nums[r])) # remove duplicates while l < r and nums[l] == nums[l+1]: l+=1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1 r -= 1 return result x = [1, -6, 4, 2, -1, 2, 0, -2, 0 ] print(three_sum(x))
123
# Write a Python program to create a 3-tuple ISO year, ISO week number, ISO weekday and an ISO 8601 formatted representation of the date and time. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\n3-tuple - ISO year, ISO week number, ISO weekday:") print(arrow.utcnow().isocalendar()) print("\nISO 8601 formatted representation of the date and time:") print(arrow.utcnow().isoformat())
55
# How to create multiple CSV files from existing CSV file using Pandas in Python import pandas as pd # initialise data dictionary. data_dict = {'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],                             'Gender': ["Male", "Female", "Female", "Male",                         "Male", "Female", "Male", "Male",                         "Female", "Male"],                             'Age': [20, 21, 19, 18, 25, 26, 32, 41, 20, 19],                             'Annual Income(k$)': [10, 20, 30, 10, 25, 60, 70,                                    15, 21, 22],                             'Spending Score': [30, 50, 48, 84, 90, 65, 32, 46,                                 12, 56]} # Create DataFrame data = pd.DataFrame(data_dict) # Write to CSV file data.to_csv("Customers.csv") # Print the output. print(data)
99
# Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda. def sort_matrix(M): result = sorted(M, key=lambda matrix_row: sum(matrix_row)) return result matrix1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]] matrix2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]] print("Original Matrix:") print(matrix1) print("\nSort the said matrix in ascending order according to the sum of its rows") print(sort_matrix(matrix1)) print("\nOriginal Matrix:") print(matrix2) print("\nSort the said matrix in ascending order according to the sum of its rows") print(sort_matrix(matrix2))
90
# Write a Python program to Kth Column Product in Tuple List # Python3 code to demonstrate working of # Tuple List Kth Column Product # using list comprehension + loop    # getting Product def prod(val) :     res = 1      for ele in val:         res *= ele     return res     # initialize list test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]    # printing original list print("The original list is : " + str(test_list))    # initialize K K = 2    # Tuple List Kth Column Product # using list comprehension + loop res = prod([sub[K] for sub in test_list])    # printing result print("Product of Kth Column of Tuple List : " + str(res))
114
# Write a Python program to print even numbers in a list # Python program to print Even Numbers in a List    # list of numbers list1 = [10, 21, 4, 45, 66, 93]    # iterating each number in list for num in list1:            # checking condition     if num % 2 == 0:        print(num, end = " ")
58
# Write a Python program to create a symbolic link and read it to decide the original file pointed by the link. import os path = '/tmp/' + os.path.basename(__file__) print('Creating link {} -> {}'.format(path, __file__)) os.symlink(__file__, path) stat_info = os.lstat(path) print('\nFile Permissions:', oct(stat_info.st_mode)) print('\nPoints to:', os.readlink(path)) #removes the file path os.unlink(path)
51
# Write a Python program to convert list to list of dictionaries. color_name = ["Black", "Red", "Maroon", "Yellow"] color_code = ["#000000", "#FF0000", "#800000", "#FFFF00"] print([{'color_name': f, 'color_code': c} for f, c in zip(color_name, color_code)])
34
# Using Timedelta and Period to create DateTime based indexes in Pandas in Python # importing pandas as pd import pandas as pd    # Creating the timestamp ts = pd.Timestamp('02-06-2018')    # Print the timestamp print(ts)
35
# Write a Python program to remove all consecutive duplicates of a given string. from itertools import groupby def remove_all_consecutive(str1): result_str = [] for (key,group) in groupby(str1): result_str.append(key) return ''.join(result_str) str1 = 'xxxxxyyyyy' print("Original string:" + str1) print("After removing consecutive duplicates: " + str1) print(remove_all_consecutive(str1))
45
# Write a Python program to count the values associated with key in a dictionary. student = [{'id': 1, 'success': True, 'name': 'Lary'}, {'id': 2, 'success': False, 'name': 'Rabi'}, {'id': 3, 'success': True, 'name': 'Alex'}] print(sum(d['id'] for d in student)) print(sum(d['success'] for d in student))
45
# Python Program to Implement a Stack using Linked List class Node: def __init__(self, data): self.data = data self.next = None   class Stack: def __init__(self): self.head = None   def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node   def pop(self): if self.head is None: return None else: popped = self.head.data self.head = self.head.next return popped   a_stack = Stack() while True: print('push <value>') print('pop') print('quit') do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'quit': break
115
# Describe a NumPy Array in Python import numpy as np # sample array arr = np.array([4, 5, 8, 5, 6, 4,                 9, 2, 4, 3, 6]) print(arr)
28
# Write a Python program to extract year, month and date value from current datetime using arrow module. import arrow a = arrow.utcnow() print("Year:") print(a.year) print("\nMonth:") print(a.month) print("\nDate:") print(a.day)
29
# Write a Pandas program to split a given dataframe into groups and list all the keys from the GroupBy object. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) 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'], 'age': [12, 12, 13, 13, 14, 12], 'height': [173, 192, 186, 167, 151, 159], 'weight': [35, 32, 33, 30, 31, 32], 'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']}, index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6']) print("Original DataFrame:") print(df) print("\nSplit the data on school_code:"); gp = df.groupby('school_code') print("\nList of all the keys:") print(gp.groups.keys())
106
# Write a NumPy program to add a new row to an empty NumPy array. import numpy as np arr = np.empty((0,3), int) print("Empty array:") print(arr) arr = np.append(arr, np.array([[10,20,30]]), axis=0) arr = np.append(arr, np.array([[40,50,60]]), axis=0) print("After adding two new arrays:") print(arr)
42
# String slicing in Python to check if a string can become empty by recursive deletion def checkEmpty(input, pattern):               # If both are empty       if len(input)== 0 and len(pattern)== 0:           return 'true'          # If only pattern is empty      if len(pattern)== 0:           return 'true'          while (len(input) != 0):             # find sub-string in main string          index = input.find(pattern)             # check if sub-string founded or not          if (index ==(-1)):            return 'false'            # slice input string in two parts and concatenate          input = input[0:index] + input[index + len(pattern):]                      return 'true'      # Driver program  if __name__ == "__main__":      input ='GEEGEEKSKS'     pattern ='GEEKS'     print (checkEmpty(input, pattern))
100
# Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays. import numpy as np x = np.array([3, 5]) y = np.array([2, 5]) print("Original numbers:") print(x) print(y) print("Comparison - greater") print(np.greater(x, y)) print("Comparison - greater_equal") print(np.greater_equal(x, y)) print("Comparison - less") print(np.less(x, y)) print("Comparison - less_equal") print(np.less_equal(x, y))
55
# Write a program to print the pattern print("Enter the row and column size:"); row_size=int(input()) for out in range(1,row_size+1):     for i in range(0,row_size):         print(out,end="")     print("\r")
25
# Write a NumPy program to create 24 python datetime.datetime objects (single object for every hour), and then put it in a numpy array. import numpy as np import datetime start = datetime.datetime(2000, 1, 1) dt_array = np.array([start + datetime.timedelta(hours=i) for i in range(24)]) print(dt_array)
45
# Write a Pandas program to get all the sighting days of the unidentified flying object (ufo) which are less than or equal to 40 years (365*40 days). import pandas as pd import datetime df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') now = pd.to_datetime('today') duration = datetime.timedelta(days=365*40) print("Original Dataframe:") print(df.head()) print("\nCurrent date:") print(now) print("\nSighting days of the unidentified flying object (ufo) which are less than or equal to 40 years (365*40 days):") df = df[now - df['Date_time'] <= duration] print(df.head())
79
# Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda. def average_tuple(nums): result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums))) return result nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3)) print ("Original Tuple: ") print(nums) print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums)) nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3)) print ("\nOriginal Tuple: ") print(nums) print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums))
93
# Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Add the fare as a dimension of columns and partition fare column into 2 categories based on the values present in fare columns. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') fare = pd.qcut(df['fare'], 2) age = pd.cut(df['age'], [0, 10, 30, 60, 80]) result = df.pivot_table('survived', index=['sex', age], columns=[fare, 'pclass']) print(result)
78
# Write a NumPy program to calculate the arithmetic means of corresponding elements of two given arrays of same size. import numpy as np nums1 = np.array([[2, 5, 2], [1, 5, 5]]) nums2 = np.array([[5, 3, 4], [3, 2, 5]]) print("Array1:") print(nums1) print("Array2:") print(nums2) print("\nArithmetic means of corresponding elements of said two arrays:") print(np.divide(np.add(nums1, nums2), 2))
56
# Write a Python program to strip a set of characters from a string. def strip_chars(str, chars): return "".join(c for c in str if c not in chars) print("\nOriginal String: ") print("The quick brown fox jumps over the lazy dog.") print("After stripping a,e,i,o,u") print(strip_chars("The quick brown fox jumps over the lazy dog.", "aeiou")) print()
54
# Program to check whether a matrix is diagonal or not # 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()]) # check except Diagonal elements are 0 or not point=0 for i in range(len(matrix)): for j in range(len(matrix[0])): # check for diagonals element if i!=j and matrix[i][j]!=0: point=1 break if point==1: print("Given Matrix is not a diagonal Matrix.") else: print("Given Matrix is a diagonal Matrix.")
96
# Write a NumPy program to test whether any of the elements of a given array is non-zero. import numpy as np x = np.array([1, 0, 0, 0]) print("Original array:") print(x) print("Test whether any of the elements of a given array is non-zero:") print(np.any(x)) x = np.array([0, 0, 0, 0]) print("Original array:") print(x) print("Test whether any of the elements of a given array is non-zero:") print(np.any(x))
66
# Write a Python program to find common elements in three lists using sets # Python3 program to find common elements  # in three lists using sets    def IntersecOfSets(arr1, arr2, arr3):     # Converting the arrays into sets     s1 = set(arr1)     s2 = set(arr2)     s3 = set(arr3)            # Calculates intersection of      # sets on s1 and s2     set1 = s1.intersection(s2)         #[80, 20, 100]            # Calculates intersection of sets     # on set1 and s3     result_set = set1.intersection(s3)            # Converts resulting set to list     final_list = list(result_set)     print(final_list)    # Driver Code if __name__ == '__main__' :            # Elements in Array1     arr1 = [1, 5, 10, 20, 40, 80, 100]            # Elements in Array2     arr2 = [6, 7, 20, 80, 100]            # Elements in Array3     arr3 = [3, 4, 15, 20, 30, 70, 80, 120]            # Calling Function     IntersecOfSets(arr1, arr2, arr3)
137
# Write a Python program to check a list is empty or not. l = [] if not l: print("List is empty")
22
# Write a Python program to convert more than one list to nested dictionary. def nested_dictionary(l1, l2, l3): result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)] return result student_id = ["S001", "S002", "S003", "S004"] student_name = ["Adina Park", "Leyton Marsh", "Duncan Boyle", "Saim Richards"] student_grade = [85, 98, 89, 92] print("Original strings:") print(student_id) print(student_name) print(student_grade) print("\nNested dictionary:") ch='a' print(nested_dictionary(student_id, student_name, student_grade))
66
# Write a Pandas program to create a comparison of the top 10 years in which the UFO was sighted vs each Month. import pandas as pd #Source: https://bit.ly/1l9yjm9 df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') most_sightings_years = df['Date_time'].dt.year.value_counts().head(10) def is_top_years(year): if year in most_sightings_years.index: return year month_vs_year = df.pivot_table(columns=df['Date_time'].dt.month,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city') month_vs_year.index = month_vs_year.index.astype(int) month_vs_year.columns = month_vs_year.columns.astype(int) print("\nComparison of the top 10 years in which the UFO was sighted vs each month:") print(month_vs_year.head(10))
71
# numpy string operations | swapcase() function in Python # Python Program explaining # numpy.char.swapcase() function     import numpy as geek        in_arr = geek.array(['P4Q R', '4q Rp', 'Q Rp4', 'rp4q']) print ("input array : ", in_arr)    out_arr = geek.char.swapcase(in_arr) print ("output swapcasecased array :", out_arr)
44
# Write a Python program to Unique Tuple Frequency (Order Irrespective) # Python3 code to demonstrate working of  # Unique Tuple Frequency [ Order Irrespective ] # Using tuple() + list comprehension + sorted() + len()    # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]    # printing original list print("The original list is : " + str(test_list))    # Using tuple() + list comprehension + sorted() + len() # Size computed after conversion to set res = len(list(set(tuple(sorted(sub)) for sub in test_list)))    # printing result  print("Unique tuples Frequency : " + str(res)) 
95
# Create a Numpy array filled with all ones in Python # Python Program to create array with all ones import numpy as geek     a = geek.ones(3, dtype = int)  print("Matrix a : \n", a)     b = geek.ones([3, 3], dtype = int)  print("\nMatrix b : \n", b) 
47
# Write a NumPy program to get the largest integer smaller or equal to the division of the inputs. import numpy as np x = [1., 2., 3., 4.] print("Original array:") print(x) print("Largest integer smaller or equal to the division of the inputs:") print(np.floor_divide(x, 1.5))
45
# Write a Python program to convert a given list of strings and characters to a single list of characters. def l_strs_to_l_chars(lst): result = [i for element in lst for i in element] return result colors = ["red", "white", "a", "b", "black", "f"] print("Original list:") print(colors) print("\nConvert the said list of strings and characters to a single list of characters:") print(l_strs_to_l_chars(colors))
61
# Print the Inverted Full Pyramid Star Pattern row_size=int(input("Enter the row size:")) star_print=row_size*2-1 for out in range(row_size,0,-1):     for inn in range(row_size,out,-1):         print(" ",end="")     for p in range(0,star_print):         print("*",end="")     star_print-=2     print("\r")
30
# Write a Python program to Remove keys with substring values # Python3 code to demonstrate working of  # Remove keys with substring values # Using any() + generator expression    # initializing dictionary test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}    # printing original dictionary print("The original dictionary : " + str(test_dict))    # initializing substrings sub_list = ['love', 'good']    # Remove keys with substring values # Using any() + generator expression res = dict() for key, val in test_dict.items():    if not any(ele in val for ele in sub_list):        res[key] = val           # printing result  print("Filtered Dictionary : " + str(res)) 
111
# Write a Python program to Extract Symmetric Tuples # Python3 code to demonstrate working of  # Extract Symmetric Tuples # Using dictionary comprehension + set()    # initializing list test_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]    # printing original list print("The original list is : " + str(test_list))    # Extract Symmetric Tuples # Using dictionary comprehension + set() temp = set(test_list) & {(b, a) for a, b in test_list} res = {(a, b) for a, b in temp if a < b}    # printing result  print("The Symmetric tuples : " + str(res)) 
99
# String slicing in Python to rotate a string # Function to rotate string left and right by d length     def rotate(input,d):         # slice string in two parts for left and right      Lfirst = input[0 : d]      Lsecond = input[d :]      Rfirst = input[0 : len(input)-d]      Rsecond = input[len(input)-d : ]         # now concatenate two parts together      print ("Left Rotation : ", (Lsecond + Lfirst) )     print ("Right Rotation : ", (Rsecond + Rfirst))     # Driver program  if __name__ == "__main__":      input = 'GeeksforGeeks'     d=2     rotate(input,d) 
86
# Generate Random Numbers From The Uniform Distribution using NumPy in Python # importing module import numpy as np       # numpy.random.uniform() method r = np.random.uniform(size=4)    # printing numbers print(r)
29
# Write a Python program to reverse each list in a given list of lists. def reverse_list_lists(nums): for l in nums: l.sort(reverse = True) return nums nums = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print("Original list of lists:") print(nums) print("\nReverse each list in the said list of lists:") print(reverse_list_lists(nums))
59
# Write a Python program to extract a specified column from a given nested list. def remove_column(nums, n): result = [i.pop(n) for i in nums] return result list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]] n = 0 print("Original Nested list:") print(list1) print("Extract 1st column:") print(remove_column(list1, n)) list2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]] n = 2 print("\nOriginal Nested list:") print(list2) print("Extract 3rd column:") print(remove_column(list2, n))
73
# K’th Non-repeating Character in Python using List Comprehension and OrderedDict # Function to find k'th non repeating character  # in string  from collections import OrderedDict     def kthRepeating(input,k):         # OrderedDict returns a dictionary data          # structure having characters of input      # string as keys in the same order they          # were inserted and 0 as their default value      dict=OrderedDict.fromkeys(input,0)         # now traverse input string to calculate          # frequency of each character      for ch in input:          dict[ch]+=1        # now extract list of all keys whose value          # is 1 from dict Ordered Dictionary      nonRepeatDict = [key for (key,value) in dict.items() if value==1]             # now return (k-1)th character from above list      if len(nonRepeatDict) < k:          return 'Less than k non-repeating characters in input.'      else:          return nonRepeatDict[k-1]     # Driver function  if __name__ == "__main__":      input = "geeksforgeeks"     k = 3     print (kthRepeating(input, k)) 
140
# Write a Python program to generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. from operator import itemgetter DEBUG = False # like the built-in __debug__ def spermutations(n): """permutations by swapping. Yields: perm, sign""" sign = 1 p = [[i, 0 if i == 0 else -1] # [num, direction] for i in range(n)] if DEBUG: print(' #', p) yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): # moving i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: # Swap down i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] # If this causes the chosen element to reach the First or last # position within the permutation, or if the next element in the # same direction is larger than the chosen element: if i2 == 0 or p[i2 - 1][0] > n1: # The direction of the chosen element is set to zero p[i2][1] = 0 elif d1 == 1: # Swap up i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] # If this causes the chosen element to reach the first or Last # position within the permutation, or if the next element in the # same direction is larger than the chosen element: if i2 == n - 1 or p[i2 + 1][0] > n1: # The direction of the chosen element is set to zero p[i2][1] = 0 if DEBUG: print(' #', p) yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print(' # Set Moving') if __name__ == '__main__': from itertools import permutations for n in (3, 4): print('\nPermutations and sign of %i items' % n) sp = set() for i in spermutations(n): sp.add(i[0]) print('Permutation: %r Sign: %2i' % i) #if DEBUG: raw_input('?') # Test p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
350
# Write a Python Code for time Complexity plot of Heap Sort # Python Code for Implementation and running time Algorithm # Complexity plot of Heap Sort # by Ashok Kajal # This python code intends to implement Heap Sort Algorithm # Plots its time Complexity on list of different sizes # ---------------------Important Note ------------------- # numpy, time and matplotlib.pyplot are required to run this code import time from numpy.random import seed from numpy.random import randint import matplotlib.pyplot as plt # find left child of node i def left(i):     return 2 * i + 1 # find right child of node i def right(i):     return 2 * i + 2 # calculate and return array size def heapSize(A):     return len(A)-1 # This function takes an array and Heapyfies # the at node i def MaxHeapify(A, i):     # print("in heapy", i)     l = left(i)     r = right(i)           # heapSize = len(A)     # print("left", l, "Rightt", r, "Size", heapSize)     if l<= heapSize(A) and A[l] > A[i] :         largest = l     else:         largest = i     if r<= heapSize(A) and A[r] > A[largest]:         largest = r     if largest != i:        # print("Largest", largest)         A[i], A[largest]= A[largest], A[i]        # print("List", A)         MaxHeapify(A, largest)       # this function makes a heapified array def BuildMaxHeap(A):     for i in range(int(heapSize(A)/2)-1, -1, -1):         MaxHeapify(A, i)           # Sorting is done using heap of array def HeapSort(A):     BuildMaxHeap(A)     B = list()     heapSize1 = heapSize(A)     for i in range(heapSize(A), 0, -1):         A[0], A[i]= A[i], A[0]         B.append(A[heapSize1])         A = A[:-1]         heapSize1 = heapSize1-1         MaxHeapify(A, 0)           # randomly generates list of different # sizes and call HeapSort function elements = list() times = list() for i in range(1, 10):     # generate some integers     a = randint(0, 1000 * i, 1000 * i)     # print(i)     start = time.clock()     HeapSort(a)     end = time.clock()     # print("Sorted list is ", a)     print(len(a), "Elements Sorted by HeapSort in ", end-start)     elements.append(len(a))     times.append(end-start) plt.xlabel('List Length') plt.ylabel('Time Complexity') plt.plot(elements, times, label ='Heap Sort') plt.grid() plt.legend() plt.show() # This code is contributed by Ashok Kajal
332
# Binary Search (bisect) in Python # Python code to demonstrate working # of binary search in library from bisect import bisect_left    def BinarySearch(a, x):     i = bisect_left(a, x)     if i != len(a) and a[i] == x:         return i     else:         return -1    a  = [1, 2, 4, 4, 8] x = int(4) res = BinarySearch(a, x) if res == -1:     print(x, "is absent") else:     print("First occurrence of", x, "is present at", res)
72
# How to change border color in Tkinter widget in Python # import tkinter  from tkinter import *    # Create Tk object  window = Tk()     # Set the window title  window.title('GFG')     # Create a Frame for border border_color = Frame(window, background="red")    # Label Widget inside the Frame label = Label(border_color, text="This is a Label widget", bd=0)    # Place the widgets with border Frame label.pack(padx=1, pady=1) border_color.pack(padx=40, pady=40)    window.mainloop()
68
# Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). : Solution tp=(1,2,3,4,5,6,7,8,9,10) li=list() for i in tp: if tp[i]%2==0: li.append(tp[i]) tp2=tuple(li) print tp2
34
# Find the number of rows and columns of a given matrix using NumPy in Python import numpy as np       matrix= np.arange(1,9).reshape((3, 3))    # Original matrix print(matrix)    # Number of rows and columns of the said matrix print(matrix.shape)
38
# Write a Python program to print content of elements that contain a specified string of a given web page. import requests import re from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("\nContent of elements that contain 'Python' string:") str1 = soup.find_all(string=re.compile('Python')) for txt in str1: print(" ".join(txt.split()))
54
# How to extract youtube data in Python from youtube_statistics import YTstats    # paste the API key generated by you here API_KEY = "AIzaSyA-0KfpLK04NpQN1XghxhSlzG-WkC3DHLs"     # paste the channel id here channel_id = "UC0RhatS1pyxInC00YKjjBqQ"     yt = YTstats(API_KEY, channel_id) yt.get_channel_statistics() yt.dump()
39
# Write a NumPy program to convert a NumPy array into Python list structure. import numpy as np x= np.arange(6).reshape(3, 2) print("Original array elements:") print(x) print("Array to list:") print(x.tolist())
29
# Python Program to Remove the Characters of Odd Index Values in a String def modify(string): final = "" for i in range(len(string)): if i % 2 == 0: final = final + string[i] return final string=raw_input("Enter string:") print("Modified string is:") print(modify(string))
42
# Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. def add_string(str1): length = len(str1) if length > 2: if str1[-3:] == 'ing': str1 += 'ly' else: str1 += 'ing' return str1 print(add_string('ab')) print(add_string('abc')) print(add_string('string'))
73
# Write a Pandas program to calculate the total number of missing values in a DataFrame. import pandas as pd import numpy as np pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[np.nan,np.nan,70002,np.nan,np.nan,70005,np.nan,70010,70003,70012,np.nan,np.nan], 'purch_amt':[np.nan,270.65,65.26,np.nan,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,np.nan], 'ord_date': [np.nan,'2012-09-10',np.nan,np.nan,'2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17',np.nan], 'customer_id':[np.nan,3001,3001,np.nan,3002,3001,3001,3004,3003,3002,3001,np.nan]}) print("Original Orders DataFrame:") print(df) print("\nTotal number of missing values of the said DataFrame:") result = df.isna().sum().sum() print(result)
54
# Write a Python program to count the occurrences of the items in a given list using lambda. def count_occurrences(nums): result = dict(map(lambda el : (el, list(nums).count(el)), nums)) return result nums = [3,4,5,8,0,3,8,5,0,3,1,5,2,3,4,2] print("Original list:") print(nums) print("\nCount the occurrences of the items in the said list:") print(count_occurrences(nums))
47
# Write a NumPy program to compute the condition number of a given matrix. import numpy as np from numpy import linalg as LA a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) print("Original matrix:") print(a) print("The condition number of the said matrix:") print(LA.cond(a))
46
# Compute the condition number of a given matrix using NumPy in Python # Importing library import numpy as np    # Creating a 2X2 matrix matrix = np.array([[4, 2], [3, 1]])    print("Original matrix:") print(matrix)    # Output result =  np.linalg.cond(matrix)    print("Condition number of the matrix:") print(result)
45
# Write a Python program to find the indices of elements of a given list, greater than a specified value. def test(lst, value): result = [i for i,val in enumerate(lst) if val > value] return result nums = [1234, 1522, 1984, 19372, 1000, 2342, 7626] print("\nOriginal list:") print(nums) val = 3000 print("Indices of elements of the said list, greater than",val) print(test(nums,val)) nums = [1234, 1522, 1984, 19372, 1000, 2342, 7626] print("\nOriginal list:") print(nums) val = 20000 print("Indices of elements of the said list, greater than",val) print(test(nums,val))
86
# Write a Python program to split a given list into specified sized chunks using itertools module. from itertools import islice def split_list(lst, n): lst = iter(lst) result = iter(lambda: tuple(islice(lst, n)), ()) return list(result) nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83] print("Original list:") print(nums) n = 3 print("\nSplit the said list into equal size",n) print(split_list(nums,n)) n = 4 print("\nSplit the said list into equal size",n) print(split_list(nums,n)) n = 5 print("\nSplit the said list into equal size",n) print(split_list(nums,n))
74
# Write a NumPy program to save a NumPy array to a text file. import numpy as np a = np.arange(1.0, 2.0, 36.2) np.savetxt('file.out', a, delimiter=',')
26
# Write a NumPy program to stack arrays in sequence horizontally (column wise). import numpy as np print("\nOriginal arrays:") x = np.arange(9).reshape(3,3) y = x*3 print("Array-1") print(x) print("Array-2") print(y) new_array = np.hstack((x,y)) print("\nStack arrays in sequence horizontally:") print(new_array)
38
# Write a NumPy program to merge three given NumPy arrays of same shape. import numpy as np arr1 = np.random.random(size=(25, 25, 1)) arr2 = np.random.random(size=(25, 25, 1)) arr3 = np.random.random(size=(25, 25, 1)) print("Original arrays:") print(arr1) print(arr2) print(arr3) result = np.concatenate((arr1, arr2, arr3), axis=-1) print("\nAfter concatenate:") print(result)
47
# Write a Python program to Count Uppercase, Lowercase, special character and numeric values using Regex import re       string = "ThisIsGeeksforGeeks !, 123"    # Creating separate lists using  # the re.findall() method. uppercase_characters = re.findall(r"[A-Z]", string) lowercase_characters = re.findall(r"[a-z]", string) numerical_characters = re.findall(r"[0-9]", string) special_characters = re.findall(r"[, .!?]", string)    print("The no. of uppercase characters is", len(uppercase_characters)) print("The no. of lowercase characters is", len(lowercase_characters)) print("The no. of numerical characters is", len(numerical_characters)) print("The no. of special characters is", len(special_characters))
77
# Write a Python program to Extract Unique values dictionary values # Python3 code to demonstrate working of  # Extract Unique values dictionary values # Using set comprehension + values() + sorted()    # initializing dictionary test_dict = {'gfg' : [5, 6, 7, 8],              'is' : [10, 11, 7, 5],              'best' : [6, 12, 10, 8],              'for' : [1, 2, 5]}    # printing original dictionary print("The original dictionary is : " + str(test_dict))    # Extract Unique values dictionary values # Using set comprehension + values() + sorted() res = list(sorted({ele for val in test_dict.values() for ele in val}))    # printing result  print("The unique values list is : " + str(res)) 
109
# Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) print("Original set elements:") print(color_list_1) print(color_list_2) print("\nDifferenct of color_list_1 and color_list_2:") print(color_list_1.difference(color_list_2)) print("\nDifferenct of color_list_2 and color_list_1:") print(color_list_2.difference(color_list_1))
48
# Write a NumPy program to test whether all elements in an array evaluate to True. import numpy as np print(np.all([[True,False],[True,True]])) print(np.all([[True,True],[True,True]])) print(np.all([10, 20, 0, -50])) print(np.all([10, 20, -50]))
29
# Count the number of white spaces in a Sentence str=input("Enter the String:") count = 0 for i in range(len(str)):     if str[i] == ' ':         count+=1 print("Number of white space in a string are ",count)
35
# Python Program to Read a Number n And Print the Series "1+2+…..+n= " n=int(input("Enter a number: ")) a=[] for i in range(1,n+1): print(i,sep=" ",end=" ") if(i<n): print("+",sep=" ",end=" ") a.append(i) print("=",sum(a))   print()
33
# Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. : values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values)
64
# Write a NumPy program to divide each row by a vector element. import numpy as np x = np.array([[20,20,20],[30,30,30],[40,40,40]]) print("Original array:") print(x) v = np.array([20,30,40]) print("Vector:") print(v) print(x / v[:,None])
31
# Write a Python program to find the indexes of all None items in a given list. def relative_order(lst): result = [i for i in range(len(lst)) if lst[i] == None] return result nums = [1, None, 5, 4,None, 0, None, None] print("Original list:") print(nums) print("\nIndexes of all None items of the list:") print(relative_order(nums))
53
# Scrape LinkedIn Using Selenium And Beautiful Soup in Python from selenium import webdriver from bs4 import BeautifulSoup import time    # Creating a webdriver instance driver = webdriver.Chrome("Enter-Location-Of-Your-Web-Driver") # This instance will be used to log into LinkedIn    # Opening linkedIn's login page driver.get("https://linkedin.com/uas/login")    # waiting for the page to load time.sleep(5)    # entering username username = driver.find_element_by_id("username")    # In case of an error, try changing the element # tag used here.    # Enter Your Email Address username.send_keys("User_email")      # entering password pword = driver.find_element_by_id("password") # In case of an error, try changing the element  # tag used here.    # Enter Your Password pword.send_keys("User_pass")            # Clicking on the log in button # Format (syntax) of writing XPath -->  # //tagname[@attribute='value'] driver.find_element_by_xpath("//button[@type='submit']").click() # In case of an error, try changing the # XPath used here.
133
# Write a Python program to find all index positions of the maximum and minimum values in a given list of numbers. def position_max_min(nums): max_val = max(nums) min_val = min(nums) max_result = [i for i, j in enumerate(nums) if j == max_val] min_result = [i for i, j in enumerate(nums) if j == min_val] return max_result,min_result nums = [12,33,23,10,67,89,45,667,23,12,11,10,54] print("Original list:") print(nums) result = position_max_min(nums) print("\nIndex positions of the maximum value of the said list:") print(result[0]) print("\nIndex positions of the minimum value of the said list:") print(result[1])
87
# By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. : li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li
37
# Write a Python program to print a nested lists (each list on a new line) using the print() function. colors = [['Red'], ['Green'], ['Black']] print('\n'.join([str(lst) for lst in colors]))
30
# Write a Python program to convert a given list of lists to a dictionary. def test(lst): result = {item[0]: item[1:] for item in lst} return result students = [[1, 'Jean Castro', 'V'], [2, 'Lula Powell', 'V'], [3, 'Brian Howell', 'VI'], [4, 'Lynne Foster', 'VI'], [5, 'Zachary Simon', 'VII']] print("\nOriginal list of lists:") print(students) print("\nConvert the said list of lists to a dictionary:") print(test(students))
64
# Program to Find nth Pronic Number import math rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     flag = 0     for j in range(0, num + 1):         if j * (j + 1) == num:             flag = 1             break     if flag == 1:             c+=1             letest = num     num = num + 1 print(rangenumber,"th Pronic number is ",letest)
66
# Write a Pandas program to split a dataset, group by one column and get mean, min, and max values by group. Using the following dataset find the mean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id). import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) orders_data = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013], 'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6], 'ord_date': ['2012-10-05','2012-09-10','2012-10-05','2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002], 'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]}) print("Original Orders DataFrame:") print(orders_data) result = orders_data.groupby('customer_id').agg({'purch_amt': ['mean', 'min', 'max']}) print("\nMean, min, and max values of purchase amount (purch_amt) group by customer id (customer_id).") print(result)
86
# Write a Python program to count repeated characters in a string. import collections str1 = 'thequickbrownfoxjumpsoverthelazydog' d = collections.defaultdict(int) for c in str1: d[c] += 1 for c in sorted(d, key=d.get, reverse=True): if d[c] > 1: print('%s %d' % (c, d[c]))
42
# Write a NumPy program to count the number of dimensions, number of elements and number of bytes for each element in a given array. import numpy as np print("\nOriginal arrays:") x = np.array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]) print(x) print("\nNumber of dimensions:") print(x.ndim) print("Number of elements:") print(x.size) print("Number of bytes for each element in the said array:") print(x.itemsize)
78