code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to Extract elements with Frequency greater than K # Python3 code to demonstrate working of  # Extract elements with Frequency greater than K # Using count() + loop    # initializing list test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]    # printing string print("The original list : " + str(test_list))    # initializing K  K = 2    res = []  for i in test_list:             # using count() to get count of elements     freq = test_list.count(i)             # checking if not already entered in results     if freq > K and i not in res:          res.append(i)    # printing results  print("The required elements : " + str(res))
110
# Python Program to Create a Linked List & Display the Elements in the List 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 display(self): current = self.head while current is not None: print(current.data, end = ' ') current = current.next   a_llist = LinkedList() n = int(input('How many elements would you like to add? ')) for i in range(n): data = int(input('Enter data item: ')) a_llist.append(data) print('The linked list: ', end = '') a_llist.display()
107
# Write a NumPy program to select indices satisfying multiple conditions in a NumPy array. import numpy as np a = np.array([97, 101, 105, 111, 117]) b = np.array(['a','e','i','o','u']) print("Original arrays") print(a) print(b) print("Elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110:") print(b[(100 < a) & (a < 110)])
61
# Write a Python program to Generate k random dates between two other dates # Python3 code to demonstrate working of # Random K dates in Range # Using choices() + timedelta() + loop from datetime import date, timedelta from random import choices    # initializing dates ranges  test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1)    # printing dates  print("The original range : " + str(test_date1) + " " + str(test_date2))    # initializing K K = 7    res_dates = [test_date1]    # loop to get each date till end date while test_date1 != test_date2:     test_date1 += timedelta(days=1)     res_dates.append(test_date1)    # random K dates from pack res = choices(res_dates, k=K)    # printing  print("K random dates in range : " + str(res))
118
# Python Program to Detect if Two Strings are Anagrams s1=raw_input("Enter first string:") s2=raw_input("Enter second string:") if(sorted(s1)==sorted(s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.")
26
# Write a Pandas program to extract date (format: mm-dd-yyyy) from a given column of a given DataFrame. import pandas as pd import re as re df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'], 'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'], 'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0] }) print("Original DataFrame:") print(df) def find_valid_dates(dt): #format: mm-dd-yyyy result = re.findall(r'\b(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/([0-9]{4})\b',dt) return result df['valid_dates']=df['date_of_sale'].apply(lambda dt : find_valid_dates(dt)) print("\nValid dates (format: mm-dd-yyyy):") print(df)
64
# Write a Python program to find second largest number in a list # Python program to find second largest # number in a list # list of numbers - length of # list should be at least 2 list1 = [10, 20, 4, 45, 99] mx=max(list1[0],list1[1]) secondmax=min(list1[0],list1[1]) n =len(list1) for i in range(2,n):     if list1[i]>mx:         secondmax=mx         mx=list1[i]     elif list1[i]>secondmax and \         mx != list1[i]:         secondmax=list1[i] print("Second highest number is : ",\       str(secondmax))
73
# How to convert a Python datetime.datetime to excel serial date number # Python3 code to illustrate the conversion of # datetime.datetime to excel serial date number # Importing datetime module import datetime # Calling the now() function to return # current date and time current_datetime = datetime.datetime.now() # Calling the strftime() function to convert # the above current datetime into excel serial date number print(current_datetime.strftime('%x %X'))
67
# Write a Pandas program to manipulate and convert date times with timezone information. import pandas as pd dtt = pd.date_range('2018-01-01', periods=3, freq='H') dtt = dtt.tz_localize('UTC') print(dtt) print("\nFrom UTC to America/Los_Angeles:") dtt = dtt.tz_convert('America/Los_Angeles') print(dtt)
35
# Write a Python program to Get file id of windows file # importing popen from the os library from os import popen # Path to the file whose id we would # be obtaining (relative / absolute) file = r"C:\Users\Grandmaster\Desktop\testing.py" # Running the command for obtaining the fileid, # and saving the output of the command output = popen(fr"fsutil file queryfileid {file}").read() # printing the output of the previous command print(output)
72
# Write a Python program to Convert Nested dictionary to Mapped Tuple # Python3 code to demonstrate working of  # Convert Nested dictionary to Mapped Tuple # Using list comprehension + generator expression    # initializing dictionary test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},                                       'best' : {'x' : 8, 'y' : 3}}    # printing original dictionary print("The original dictionary is : " + str(test_dict))    # Convert Nested dictionary to Mapped Tuple # Using list comprehension + generator expression res = [(key, tuple(sub[key] for sub in test_dict.values()))                                 for key in test_dict['gfg']]    # printing result  print("The grouped dictionary : " + str(res)) 
110
# Write a Python program to Convert Tuple to Tuple Pair # Python3 code to demonstrate working of  # Convert Tuple to Tuple Pair # Using product() + next() from itertools import product    # initializing tuple test_tuple = ('G', 'F', 'G')    # printing original tuple print("The original tuple : " + str(test_tuple))    # Convert Tuple to Tuple Pair # Using product() + next() test_tuple = iter(test_tuple) res = list(product(next(test_tuple), test_tuple))    # printing result  print("The paired records : " + str(res))
80
# Write a NumPy program to create a 90x30 array filled with random point numbers, increase the number of items (10 edge elements) shown by the print statement. import numpy as np nums = np.random.randint(10, size=(90, 30)) print("Original array:") print(nums) print("\nIncrease the number of items (10 edge elements) shown by the print statement:") np.set_printoptions(edgeitems=10) print(nums)
55
# Mapping external values to dataframe values in Pandas in Python # Creating new dataframe import pandas as pd    initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'],          'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'],          'Age': [42, 52, 36, 21, 23],          'City': ['Mumbai', 'Noida', 'Pune', 'Delhi', 'Bihar']}    df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name',                                                       'Age', 'City'])    # Create new column using dictionary new_data = { "Ram":"B.Com",              "Mohan":"IAS",              "Tina":"LLB",              "Jeetu":"B.Tech",              "Meera":"MBBS" }    # combine this new data with existing DataFrame df["Qualification"] = df["First_name"].map(new_data)    print(df)
81
# Check whether a year is leap year or not year=int(input("Enter a Year:")) if ((year % 100 == 0 and year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)):      print("It is a Leap Year") else: print("It is not a Leap Year")
49
# Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. values=raw_input() l=values.split(",") t=tuple(l) print l print t
31
# Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1)
49
# Find the maximum element in the matrix import sys # 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()]) #compute the maximum element of the given 2d array max=-sys.maxsize-1 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]>=max: max=matrix[i][j] # Display the largest element of the given matrix print("The Maximum element of the Given 2d array is: ",max)
89
# Write a Pandas program to count year-country wise frequency of reporting dates of unidentified flying object(UFO). import pandas as pd df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) df['Year'] = df['Date_time'].apply(lambda x: "%d" % (x.year)) result = df.groupby(['Year', 'country']).size() print("\nCountry-year wise frequency of reporting dates of UFO:") print(result)
50
# Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed. import numpy as np result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) print("\nCopy of a matrix with the elements below the k-th diagonal zeroed:") print(result)
41
# Write a Python program to Test if tuple is distinct # Python3 code to demonstrate working of # Test if tuple is distinct # Using loop    # initialize tuple  test_tup = (1, 4, 5, 6, 1, 4)    # printing original tuple  print("The original tuple is : " + str(test_tup))    # Test if tuple is distinct # Using loop res = True  temp = set() for ele in test_tup:     if ele in temp:         res = False          break     temp.add(ele)    # printing result print("Is tuple distinct ? : " + str(res))
89
# Access the elements of a Series in Pandas 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")     ser = pd.Series(df['Name']) ser.head(10) # or simply df['Name'].head(10)
34
# Program to remove all numbers from a String str=input("Enter the String:") str2 = [] i = 0 while i < len(str):     ch = str[i]     if not(ch >= '0' and ch <= '9'):         str2.append(ch)     i += 1 Final_String = ''.join(str2) print("After removing numbers string is:",Final_String)
45
# Write a Python program generate permutations of specified elements, drawn from specified values. from itertools import product def permutations_colors(inp, n): for x in product(inp, repeat=n): c = ''.join(x) print(c,end=', ') str1 = "Red" print("Original String: ",str1) print("Permutations of specified elements, drawn from specified values:") n=1 print("\nn = 1") permutations_colors(str1,n) n=2 print("\nn = 2") permutations_colors(str1,n) n=3 print("\nn = 3") permutations_colors(str1,n) lst1 = ["Red","Green","Black"] print("\n\nOriginal list: ",lst1) print("Permutations of specified elements, drawn from specified values:") n=1 print("\nn = 1") permutations_colors(lst1,n) n=2 print("\nn = 2") permutations_colors(lst1,n) n=3 print("\nn = 3") permutations_colors(lst1,n)
89
# Write a Python program to count the number of sublists contain a particular element. def count_element_in_list(input_list, x): ctr = 0 for i in range(len(input_list)): if x in input_list[i]: ctr+= 1 return ctr list1 = [[1, 3], [5, 7], [1, 11], [1, 15, 7]] print("Original list:") print(list1) print("\nCount 1 in the said list:") print(count_element_in_list(list1, 1)) print("\nCount 7 in the said list:") print(count_element_in_list(list1, 7)) list1 = [['A', 'B'], ['A', 'C'], ['A', 'D', 'E'], ['B', 'C', 'D']] print("\nOriginal list:") print(list1) print("\nCount 'A' in the said list:") print(count_element_in_list(list1, 'A')) print("\nCount 'E' in the said list:") print(count_element_in_list(list1, 'E'))
94
# Bisect Algorithm Functions in Python # Python code to demonstrate the working of # bisect(), bisect_left() and bisect_right()    # importing "bisect" for bisection operations import bisect    # initializing list li = [1, 3, 4, 4, 4, 6, 7]    # using bisect() to find index to insert new element # returns 5 ( right most possible index ) print ("The rightmost index to insert, so list remains sorted is  : ", end="") print (bisect.bisect(li, 4))    # using bisect_left() to find index to insert new element # returns 2 ( left most possible index ) print ("The leftmost index to insert, so list remains sorted is  : ", end="") print (bisect.bisect_left(li, 4))    # using bisect_right() to find index to insert new element # returns 4 ( right most possible index ) print ("The rightmost index to insert, so list remains sorted is  : ", end="") print (bisect.bisect_right(li, 4, 0, 4))
149
# With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. : def removeDuplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li)
49
# Write a Python program to move the specified number of elements to the start of the given list. def move_start(nums, offset): return nums[-offset:] + nums[:-offset] print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 3)) print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -3)) print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 8)) print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -8)) print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 7)) print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -7))
80
# Write a Python program to append a list to the second list. list1 = [1, 2, 3, 0] list2 = ['Red', 'Green', 'Black'] final_list = list1 + list2 print(final_list)
30
# How to count number of instances of a class in Python # code class geeks:          # this is used to print the number     # of instances of a class     counter = 0        # constructor of geeks class     def __init__(self):                  # increment         geeks.counter += 1       # object or instance of geeks class g1 = geeks() g2 = geeks() g3 = geeks() print(geeks.counter)
62
# Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise. import pandas as pd import numpy as np df = pd.read_excel('E:\SaleData.xlsx') print(pd.pivot_table(df,index = ["Region","Manager"], values = ["Sale_amt"],aggfunc=np.sum))
37
# How to Convert an image to NumPy array and saveit to CSV file using Python # import required libraries from PIL import Image import numpy as gfg # read an image img = Image.open('geeksforgeeks.jpg') # convert image object into array imageToMatrice = gfg.asarray(img) # printing shape of image print(imageToMatrice.shape)
50
# Write a Python program to sort each sublist of strings in a given list of lists using lambda. def sort_sublists(input_list): result = [sorted(x, key = lambda x:x[0]) for x in input_list] return result color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]] print("\nOriginal list:") print(color1) print("\nAfter sorting each sublist of the said list of lists:") print(sort_sublists(color1))
57
# Write a Pandas program to split the following dataset using group by on first column and aggregate over multiple lists on second column. 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({ 'student_id': ['S001','S001','S002','S002','S003','S003'], 'marks': [[88,89,90],[78,81,60],[84,83,91],[84,88,91],[90,89,92],[88,59,90]]}) print("Original DataFrame:") print(df) print("\nGroupby and aggregate over multiple lists:") result = df.set_index('student_id')['marks'].groupby('student_id').apply(list).apply(lambda x: np.mean(x,0)) print(result)
58
# Write a Python program to sort a list of elements using shell sort algorithm. def shellSort(alist): sublistcount = len(alist)//2 while sublistcount > 0: for start_position in range(sublistcount): gap_InsertionSort(alist, start_position, sublistcount) print("After increments of size",sublistcount, "The list is",nlist) sublistcount = sublistcount // 2 def gap_InsertionSort(nlist,start,gap): for i in range(start+gap,len(nlist),gap): current_value = nlist[i] position = i while position>=gap and nlist[position-gap]>current_value: nlist[position]=nlist[position-gap] position = position-gap nlist[position]=current_value nlist = [14,46,43,27,57,41,45,21,70] shellSort(nlist) print(nlist)
69
# Write a Pandas program to count of occurrence of a specified substring in a DataFrame column. import pandas as pd df = pd.DataFrame({ 'name_code': ['c001','c002','c022', 'c2002', 'c2222'], 'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'], 'age': [18.5, 21.2, 22.5, 22, 23] }) print("Original DataFrame:") print(df) print("\nCount occurrence of 2 in date_of_birth column:") df['count'] = list(map(lambda x: x.count("2"), df['name_code'])) print(df)
55
# Write a NumPy program to find point by point distances of a random vector with shape (10,2) representing coordinates. import numpy as np a= np.random.random((10,2)) x,y = np.atleast_2d(a[:,0], a[:,1]) d = np.sqrt( (x-x.T)**2 + (y-y.T)**2) print(d)
37
# Write a Python program to insert an element in a given list after every nth position. def insert_elemnt_nth(lst, ele, n): result = [] for st_idx in range(0, len(lst), n): result.extend(lst[st_idx:st_idx+n]) result.append(ele) result.pop() return result nums = [1,2,3,4,5,6,7,8,9,0] print("Original list:") print(nums) i_ele = 'a' i_ele_pos = 2 print("\nInsert",i_ele,"in the said list after",i_ele_pos,"nd element:") print(insert_elemnt_nth(nums, i_ele, i_ele_pos)) i_ele = 'b' i_ele_pos = 4 print("\nInsert",i_ele,"in the said list after",i_ele_pos,"th element:") print(insert_elemnt_nth(nums, i_ele, i_ele_pos))
71
# Write a NumPy program to calculate the absolute value element-wise. import numpy as np x = np.array([-10.2, 122.2, .20]) print("Original array:") print(x) print("Element-wise absolute value:") print(np.absolute(x))
27
# Write a Python program to sort unsorted strings using natural sort. #Ref.https://bit.ly/3a657IZ from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: def alphanum_key(key): return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] return sorted(input_list, key=alphanum_key) strs = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] print("\nOriginal list:") print(strs) natural_sort(strs) print("Sorted order is:", strs) strs = ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] print("\nOriginal list:") print(strs) natural_sort(strs) print("Sorted order is:", strs) strs = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] print("\nOriginal list:") print(strs) natural_sort(strs) print("Sorted order is:", strs) strs = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] print("\nOriginal list:") print(strs) natural_sort(strs) print("Sorted order is:", strs)
136
# Subtract Two Numbers Operator without using Minus(-) operator num1=int(input("Enter first number:")) num2=int(input("Enter  second number:")) sub=num1+(~num2+1)#number + 2's complement of number print("Subtraction of two number is ",sub)
27
# Write a Python program to Remove words containing list characters # Python3 code to demonstrate  # Remove words containing list characters # using list comprehension + all() from itertools import groupby    # initializing list  test_list = ['gfg', 'is', 'best', 'for', 'geeks']    # initializing char list  char_list = ['g', 'o']    # printing original list print ("The original list is : " + str(test_list))    # printing character list print ("The character list is : " + str(char_list))    # Remove words containing list characters # using list comprehension + all() res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]    # printing result  print ("The filtered strings are : " + str(res))
116
# Write a Python program to sort unsorted numbers using Merge-insertion sort. #Ref.https://bit.ly/3r32ezJ from __future__ import annotations def merge_insertion_sort(collection: list[int]) -> list[int]: """Pure implementation of merge-insertion sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_insertion_sort([99]) [99] >>> merge_insertion_sort([-2, -5, -45]) [-45, -5, -2] """ def binary_search_insertion(sorted_list, item): left = 0 right = len(sorted_list) - 1 while left <= right: middle = (left + right) // 2 if left == right: if sorted_list[middle] < item: left = middle + 1 break elif sorted_list[middle] < item: left = middle + 1 else: right = middle - 1 sorted_list.insert(left, item) return sorted_list def sortlist_2d(list_2d): def merge(left, right): result = [] while left and right: if left[0][0] < right[0][0]: result.append(left.pop(0)) else: result.append(right.pop(0)) return result + left + right length = len(list_2d) if length <= 1: return list_2d middle = length // 2 return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:])) if len(collection) <= 1: return collection """ Group the items into two pairs, and leave one element if there is a last odd item. Example: [999, 100, 75, 40, 10000] -> [999, 100], [75, 40]. Leave 10000. """ two_paired_list = [] has_last_odd_item = False for i in range(0, len(collection), 2): if i == len(collection) - 1: has_last_odd_item = True else: """ Sort two-pairs in each groups. Example: [999, 100], [75, 40] -> [100, 999], [40, 75] """ if collection[i] < collection[i + 1]: two_paired_list.append([collection[i], collection[i + 1]]) else: two_paired_list.append([collection[i + 1], collection[i]]) """ Sort two_paired_list. Example: [100, 999], [40, 75] -> [40, 75], [100, 999] """ sorted_list_2d = sortlist_2d(two_paired_list) """ 40 < 100 is sure because it has already been sorted. Generate the sorted_list of them so that you can avoid unnecessary comparison. Example: group0 group1 40 100 75 999 -> group0 group1 [40, 100] 75 999 """ result = [i[0] for i in sorted_list_2d] """ 100 < 999 is sure because it has already been sorted. Put 999 in last of the sorted_list so that you can avoid unnecessary comparison. Example: group0 group1 [40, 100] 75 999 -> group0 group1 [40, 100, 999] 75 """ result.append(sorted_list_2d[-1][1]) """ Insert the last odd item left if there is. Example: group0 group1 [40, 100, 999] 75 -> group0 group1 [40, 100, 999, 10000] 75 """ if has_last_odd_item: pivot = collection[-1] result = binary_search_insertion(result, pivot) """ Insert the remaining items. In this case, 40 < 75 is sure because it has already been sorted. Therefore, you only need to insert 75 into [100, 999, 10000], so that you can avoid unnecessary comparison. Example: group0 group1 [40, 100, 999, 10000] ^ You don't need to compare with this as 40 < 75 is already sure. 75 -> [40, 75, 100, 999, 10000] """ is_last_odd_item_inserted_before_this_index = False for i in range(len(sorted_list_2d) - 1): if result[i] == collection[-i]: is_last_odd_item_inserted_before_this_index = True pivot = sorted_list_2d[i][1] # If last_odd_item is inserted before the item's index, # you should forward index one more. if is_last_odd_item_inserted_before_this_index: result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot) else: result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot) return result nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) print("After applying Merge-insertion Sort the said list becomes:") print(merge_insertion_sort(nums)) print(nums) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) print("After applying Merge-insertion Sort the said list becomes:") print(merge_insertion_sort(nums)) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Merge-insertion Sort the said list becomes:") print(merge_insertion_sort(nums)) chars = ['z','a','y','b','x','c'] print("\nOriginal list:") print(chars) print("After applying Merge-insertion Sort the said list becomes:") print(merge_insertion_sort(chars))
613
# Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5. import numpy as np x = np.diag([1, 2, 3, 4, 5]) print(x)
36
# Python Program to Implement Binomial Heap class BinomialTree: def __init__(self, key): self.key = key self.children = [] self.order = 0   def add_at_end(self, t): self.children.append(t) self.order = self.order + 1     class BinomialHeap: def __init__(self): self.trees = []   def extract_min(self): if self.trees == []: return None smallest_node = self.trees[0] for tree in self.trees: if tree.key < smallest_node.key: smallest_node = tree self.trees.remove(smallest_node) h = BinomialHeap() h.trees = smallest_node.children self.merge(h)   return smallest_node.key   def get_min(self): if self.trees == []: return None least = self.trees[0].key for tree in self.trees: if tree.key < least: least = tree.key return least   def combine_roots(self, h): self.trees.extend(h.trees) self.trees.sort(key=lambda tree: tree.order)   def merge(self, h): self.combine_roots(h) if self.trees == []: return i = 0 while i < len(self.trees) - 1: current = self.trees[i] after = self.trees[i + 1] if current.order == after.order: if (i + 1 < len(self.trees) - 1 and self.trees[i + 2].order == after.order): after_after = self.trees[i + 2] if after.key < after_after.key: after.add_at_end(after_after) del self.trees[i + 2] else: after_after.add_at_end(after) del self.trees[i + 1] else: if current.key < after.key: current.add_at_end(after) del self.trees[i + 1] else: after.add_at_end(current) del self.trees[i] i = i + 1   def insert(self, key): g = BinomialHeap() g.trees.append(BinomialTree(key)) self.merge(g)     bheap = BinomialHeap()   print('Menu') print('insert <data>') print('min get') print('min extract') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'insert': data = int(do[1]) bheap.insert(data) elif operation == 'min': suboperation = do[1].strip().lower() if suboperation == 'get': print('Minimum value: {}'.format(bheap.get_min())) elif suboperation == 'extract': print('Minimum value removed: {}'.format(bheap.extract_min()))   elif operation == 'quit': break
251
# Find the number of occurrences of a sequence in a NumPy array in Python # importing package import numpy    # create numpy array arr = numpy.array([[2, 8, 9, 4],                     [9, 4, 9, 4],                    [4, 5, 9, 7],                    [2, 9, 4, 3]])    # Counting sequence output = repr(arr).count("9, 4")    # view output print(output)
53
# Write a Python program to split a given multiline string into a list of lines. def split_lines(s): return s.split('\n') print("Original string:") print("This\nis a\nmultiline\nstring.\n") print("Split the said multiline string into a list of lines:") print(split_lines('This\nis a\nmultiline\nstring.\n'))
36
# Write a Pandas program to compare the elements of the two Pandas Series. import pandas as pd ds1 = pd.Series([2, 4, 6, 8, 10]) ds2 = pd.Series([1, 3, 5, 7, 10]) print("Series1:") print(ds1) print("Series2:") print(ds2) print("Compare the elements of the said Series:") print("Equals:") print(ds1 == ds2) print("Greater than:") print(ds1 > ds2) print("Less than:") print(ds1 < ds2)
57
# Write a Python program to convert string values of a given dictionary, into integer/float datatypes. def convert_to_int(lst): result = [dict([a, int(x)] for a, x in b.items()) for b in lst] return result def convert_to_float(lst): result = [dict([a, float(x)] for a, x in b.items()) for b in lst] return result nums =[{ 'x':'10' , 'y':'20' , 'z':'30' }, { 'p':'40', 'q':'50', 'r':'60'}] print("Original list:") print(nums) print("\nString values of a given dictionary, into integer types:") print(convert_to_int(nums)) nums =[{ 'x':'10.12', 'y':'20.23', 'z':'30'}, { 'p':'40.00', 'q':'50.19', 'r':'60.99'}] print("\nOriginal list:") print(nums) print("\nString values of a given dictionary, into float types:") print(convert_to_float(nums))
97
# Write a Python program to check if a nested list is a subset of another nested list. def checkSubset(input_list1, input_list2): return all(map(input_list1.__contains__, input_list2)) list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]] list2 = [[1, 3],[13,15,17]] print("Original list:") print(list1) print(list2) print("\nIf the one of the said list is a subset of another.:") print(checkSubset(list1, list2)) list1 = [ [ [1,2],[2,3] ], [ [3,4],[5,6] ] ] list2 = [ [ [3,4], [5, 6] ] ] print("Original list:") print(list1) print(list2) print("\nIf the one of the said list is a subset of another.:") print(checkSubset(list1, list2)) list1 = [ [ [1,2],[2,3] ], [ [3,4],[5,7] ] ] list2 = [ [ [3,4], [5, 6] ] ] print("Original list:") print(list1) print(list2) print("\nIf the one of the said list is a subset of another.:") print(checkSubset(list1, list2))
131
# Write a Pandas program to extract only non alphanumeric characters 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#','[email protected]^2','$c0003', 'c0003', '&c0004'], 'year': ['year 1800','year 1700','year 2300', 'year 1900', 'year 2200'] }) print("Original DataFrame:") print(df) def find_nonalpha(text): result = re.findall("[^A-Za-z0-9 ]",text) return result df['nonalpha']=df['company_code'].apply(lambda x: find_nonalpha(x)) print("\Extracting only non alphanumeric characters from company_code:") print(df)
69
# Write a Python program to remove a specified dictionary from a given list. def remove_dictionary(colors, r_id): colors[:] = [d for d in colors if d.get('id') != r_id] return colors colors = [{"id" : "#FF0000", "color" : "Red"}, {"id" : "#800000", "color" : "Maroon"}, {"id" : "#FFFF00", "color" : "Yellow"}, {"id" : "#808000", "color" : "Olive"}] print('Original list of dictionary:') print(colors) r_id = "#FF0000" print("\nRemove id",r_id,"from the said list of dictionary:") print(remove_dictionary(colors, r_id))
73
# How to iterate over files in directory using Python # import required module import os # assign directory directory = 'files' # iterate over files in # that directory for filename in os.listdir(directory):     f = os.path.join(directory, filename)     # checking if it is a file     if os.path.isfile(f):         print(f)
48
# Write a Python program to remove duplicates from Dictionary. student_data = {'id1': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id2': {'name': ['David'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id3': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id4': {'name': ['Surya'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, } result = {} for key,value in student_data.items(): if value not in result.values(): result[key] = value print(result)
69
# Write a Python program to Check if two strings are Rotationally Equivalent # Python3 code to demonstrate working of  # Check if two strings are Rotationally Equivalent # Using loop + string slicing    # initializing strings test_str1 = 'geeks' test_str2 = 'eksge'    # printing original strings print("The original string 1 is : " + str(test_str1)) print("The original string 2 is : " + str(test_str2))    # Check if two strings are Rotationally Equivalent # Using loop + string slicing res = False for idx in range(len(test_str1)):         if test_str1[idx: ] + test_str1[ :idx] == test_str2:             res = True             break    # printing result  print("Are two strings Rotationally equal ? : " + str(res)) 
111
# Write a NumPy program to add an extra column to a NumPy array. import numpy as np x = np.array([[10,20,30], [40,50,60]]) y = np.array([[100], [200]]) print(np.append(x, y, axis=1))
29
# Write a function to compute 5/0 and use try/except to catch the exceptions. : def throws(): return 5/0 try: throws() except ZeroDivisionError: print "division by zero!" except Exception, err: print 'Caught an exception' finally: print 'In finally block for cleanup'
41
# Write a Python Program for Cocktail Sort # Python program for implementation of Cocktail Sort    def cocktailSort(a):     n = len(a)     swapped = True     start = 0     end = n-1     while (swapped==True):            # reset the swapped flag on entering the loop,         # because it might be true from a previous         # iteration.         swapped = False            # loop from left to right same as the bubble         # sort         for i in range (start, end):             if (a[i] > a[i+1]) :                 a[i], a[i+1]= a[i+1], a[i]                 swapped=True            # if nothing moved, then array is sorted.         if (swapped==False):             break            # otherwise, reset the swapped flag so that it         # can be used in the next stage         swapped = False            # move the end point back by one, because         # item at the end is in its rightful spot         end = end-1            # from right to left, doing the same         # comparison as in the previous stage         for i in range(end-1, start-1,-1):             if (a[i] > a[i+1]):                 a[i], a[i+1] = a[i+1], a[i]                 swapped = True            # increase the starting point, because         # the last stage would have moved the next         # smallest number to its rightful spot.         start = start+1    # Driver code to test above a = [5, 1, 4, 2, 8, 0, 2] cocktailSort(a) print("Sorted array is:") for i in range(len(a)):     print ("%d" %a[i]),
219
# Write a Python program to get information about the file pertaining to the file mode. Print the information - ID of device containing file, inode number, protection, number of hard links, user ID of owner, group ID of owner, total size (in bytes), time of last access, time of last modification and time of last status change. import os path = 'e:\\testpath\\p.txt' fd = os.open(path, os.O_RDWR) info = os.fstat(fd) print (f"ID of device containing file: {info.st_dev}") print (f"Inode number: {info.st_ino}") print (f"Protection: {info.st_mode}") print (f"Number of hard links: {info.st_nlink}") print (f"User ID of owner: {info.st_uid}") print (f"Group ID of owner: {info.st_gid}") print (f"Total size, in bytes: {info.st_size}") print (f"Time of last access: {info.st_atime}") print (f"Time of last modification: {info.st_mtime }") print (f"Time of last status change: {info.st_ctime }") os.close( fd)
131
# Write a Python program to Consecutive Kth column Difference in Tuple List # Python3 code to demonstrate working of  # Consecutive Kth column Difference in Tuple List # Using loop    # initializing list test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]    # printing original list print("The original list is : " + str(test_list))    # initializing K  K = 1     res = [] for idx in range(0, len(test_list) - 1):        # getting difference using abs()     res.append(abs(test_list[idx][K] - test_list[idx + 1][K]))        # printing result  print("Resultant tuple list : " + str(res))
96
# Find the size of a Set in Python import sys    # sample Sets Set1 = {"A", 1, "B", 2, "C", 3} Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"} Set3 = {(1, "Lion"), ( 2, "Tiger"), (3, "Fox")}    # print the sizes of sample Sets print("Size of Set1: " + str(sys.getsizeof(Set1)) + "bytes") print("Size of Set2: " + str(sys.getsizeof(Set2)) + "bytes") print("Size of Set3: " + str(sys.getsizeof(Set3)) + "bytes")
70
# Evaluate Einstein’s summation convention of two multidimensional NumPy arrays in Python # Importing library import numpy as np    # Creating two 2X2 matrix matrix1 = np.array([[1, 2], [0, 2]]) matrix2 = np.array([[0, 1], [3, 4]])    print("Original matrix:") print(matrix1) print(matrix2)    # Output result = np.einsum("mk,kn", matrix1, matrix2)    print("Einstein’s summation convention of the two matrix:") print(result)
55
# Python Program to Count the Number of Digits in a Number n=int(input("Enter number:")) count=0 while(n>0): count=count+1 n=n//10 print("The number of digits in the number are:",count)
26
# 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
# Python Program to Add a Key-Value Pair to the Dictionary key=int(input("Enter the key (int) to be added:")) value=int(input("Enter the value for the key to be added:")) d={} d.update({key:value}) print("Updated dictionary is:") print(d)
33
# Write a Python program to print even length words in a string # Python3 program to print  #  even length words in a string     def printWords(s):            # split the string      s = s.split(' ')             # iterate in words of string      for word in s:                     # if length is even          if len(word)%2==0:             print(word)        # Driver Code  s = "i am muskan"  printWords(s) 
62
# Program to Find the sum of series 3+33+333.....+N n=int(input("Enter the range of number:"))sum=0p=3for i in range(1,n+1):    sum += p    p=(p*10)+3print("The sum of the series = ",sum)
27
# Write a Python program to replace hour, minute, day, month, year and timezone with specified value of current datetime using arrow. import arrow a = arrow.utcnow() print("Current date and time:") print(a) print("\nReplace hour and minute with 5 and 35:") print(a.replace(hour=5, minute=35)) print("\nReplace day with 2:") print(a.replace(day=2)) print("\nReplace year with 2021:") print(a.replace(year=2021)) print("\nReplace month with 11:") print(a.replace(month=11)) print("\nReplace timezone with 'US/Pacific:") print(a.replace(tzinfo='US/Pacific'))
62
# Write a Python program to get the number of datasets currently listed on data.gov. from lxml import html import requests response = requests.get('http://www.data.gov/') doc_gov = html.fromstring(response.text) link_gov = doc_gov.cssselect('small a')[0] print("Number of datasets currently listed on data.gov:") print(link_gov.text)
39
# Write a Python program to compare two given lists and find the indices of the values present in both lists. def matched_index(l1, l2): l2 = set(l2) return [i for i, el in enumerate(l1) if el in l2] nums1 = [1, 2, 3, 4, 5 ,6] nums2 = [7, 8, 5, 2, 10, 12] print("Original lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2)) nums1 = [1, 2, 3, 4, 5 ,6] nums2 = [7, 8, 5, 7, 10, 12] print("\nOriginal lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2)) nums1 = [1, 2, 3, 4, 15 ,6] nums2 = [7, 8, 5, 7, 10, 12] print("\nOriginal lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2))
149
# Get all rows in a Pandas DataFrame containing given substring in Python # importing pandas  import pandas as pd    # Creating the dataframe with dict of lists df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'],                    'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'],                    'Position': ['PG', 'PG', 'UG', 'PG', 'UG'],                    'Number': [3, 4, 7, 11, 5],                    'Age': [33, 25, 34, 35, 28],                    'Height': ['6-2', '6-4', '5-9', '6-1', '5-8'],                    'Weight': [89, 79, 113, 78, 84],                    'College': ['MIT', 'MIT', 'MIT', 'Stanford', 'Stanford'],                    'Salary': [99999, 99994, 89999, 78889, 87779]},                    index =['ind1', 'ind2', 'ind3', 'ind4', 'ind5']) print(df, "\n")    print("Check PG values in Position column:\n") df1 = df['Position'].str.contains("PG") print(df1)
102
# Write a Python program to Count tuples occurrence in list of tuples # Python code to count unique  # tuples in list of list    import collections  Output = collections.defaultdict(int)    # List initialization Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],          [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]    # Using iteration for elem in Input:       Output[elem[0]] += 1        # Printing output print(Output)
59
# Separate even and odd numbers in an array arr=[] size = int(input("Enter the size of the array: ")) print("Enter the Element of the array:") for i in range(0,size):     num = int(input())     arr.append(num) print("\nOdd numbers are:") for i in range(0,size):     if (arr[i] % 2 != 0):         print(arr[i],end=" ") print("\nEven numbers are:") for i in range(0,size):     if (arr[i] % 2 == 0):         print(arr[i],end=" ")
63
# Program to check the given number is a palindrome or not '''Write a Python program to check the given number is a palindrome or not. or     Write a program to check the given number is a palindrome or not using Python ''' num=int(input("Enter a number:")) num1=num num2=0 while(num!=0):    rem=num%10    num=int(num/10)    num2=num2*10+rem if(num1==num2):         print("It is Palindrome") else:         print("It is not Palindrome") 
61
# Write a NumPy program to sort the specified number of elements from beginning of a given array. import numpy as np nums = np.random.rand(10) print("Original array:") print(nums) print("\nSorted first 5 elements:") print(nums[np.argpartition(nums,range(5))])
33
# Write a Python program to replace dictionary values with their average. def sum_math_v_vi_average(list_of_dicts): for d in list_of_dicts: n1 = d.pop('V') n2 = d.pop('VI') d['V+VI'] = (n1 + n2)/2 return list_of_dicts student_details= [ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 2, 'subject' : 'math', 'V' : 73, 'VI' : 74}, {'id' : 3, 'subject' : 'math', 'V' : 75, 'VI' : 86} ] print(sum_math_v_vi_average(student_details))
71
# Write a Python program to get variable unique identification number or string. x = 100 print(format(id(x), 'x')) s = 'w3resource' print(format(id(s), 'x'))
23
# Write a Python program to set a new value of an item in a singly linked list using index value. class Node: # Singly linked node def __init__(self, data=None): self.data = data self.next = None class singly_linked_list: def __init__(self): # Createe an empty list self.tail = None self.head = None self.count = 0 def append_item(self, data): #Append items on the list node = Node(data) if self.head: self.head.next = node self.head = node else: self.tail = node self.head = node self.count += 1 def __getitem__(self, index): if index > self.count - 1: return "Index out of range" current_val = self.tail for n in range(index): current_val = current_val.next return current_val.data def __setitem__(self, index, value): if index > self.count - 1: raise Exception("Index out of range.") current = self.tail for n in range(index): current = current.next current.data = value items = singly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') print("Modify items by index:") items[1] = "SQL" print("New value: ",items[1]) items[4] = "Perl" print("New value: ",items[4])
161
# Create Address Book in Write a Python program to Using Tkinter # Import Module from tkinter import *    # Create Object root = Tk()    # Set geometry root.geometry('400x500')    # Add Buttons, Label, ListBox Name = StringVar() Number = StringVar()    frame = Frame() frame.pack(pady=10)    frame1 = Frame() frame1.pack()    frame2 = Frame() frame2.pack(pady=10)    Label(frame, text = 'Name', font='arial 12 bold').pack(side=LEFT) Entry(frame, textvariable = Name,width=50).pack()    Label(frame1, text = 'Phone No.', font='arial 12 bold').pack(side=LEFT) Entry(frame1, textvariable = Number,width=50).pack()    Label(frame2, text = 'Address', font='arial 12 bold').pack(side=LEFT) address = Text(frame2,width=37,height=10) address.pack()    Button(root,text="Add",font="arial 12 bold").place(x= 100, y=270) Button(root,text="View",font="arial 12 bold").place(x= 100, y=310) Button(root,text="Delete",font="arial 12 bold").place(x= 100, y=350) Button(root,text="Reset",font="arial 12 bold").place(x= 100, y=390)    scroll_bar = Scrollbar(root, orient=VERTICAL) select = Listbox(root, yscrollcommand=scroll_bar.set, height=12) scroll_bar.config (command=select.yview) scroll_bar.pack(side=RIGHT, fill=Y) select.place(x=200,y=260)    # Execute Tkinter root.mainloop()
124
# Write a Pandas program to import given excel data (employee.xlsx ) into a Pandas dataframe and sort based on multiple given columns. import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') result = df.sort_values(by=['first_name','last_name'],ascending=[0,1]) result
38
# Write a Python program to remove words from a given list of strings containing a character or string. def remove_words(in_list, char_list): new_list = [] for line in in_list: new_words = ' '.join([word for word in line.split() if not any([phrase in word for phrase in char_list])]) new_list.append(new_words) return new_list str_list = ['Red color', 'Orange#', 'Green', 'Orange @', "White"] print("Original list:") print("list1:",str_list) char_list = ['#', 'color', '@'] print("\nCharacter list:") print(char_list) print("\nNew list:") print(remove_words(str_list, char_list))
73
# Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0. import numpy as np x = np.eye(3) print(x)
28
# Write a Python program to Replace words from Dictionary # Python3 code to demonstrate working of  # Replace words from Dictionary # Using split() + join() + get()    # initializing string test_str = 'geekforgeeks best for geeks'    # printing original string print("The original string is : " + str(test_str))    # lookup Dictionary lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}    # performing split() temp = test_str.split() res = [] for wrd in temp:            # searching from lookp_dict     res.append(lookp_dict.get(wrd, wrd))        res = ' '.join(res)    # printing result  print("Replaced Strings : " + str(res)) 
97
# Program to check whether a matrix is sparse 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()]) count_zero=0 #Count number of zeros present in the given Matrix for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]==0: count_zero+=1 #check if zeros present in the given Matrix>(row*column)/2 if count_zero>(row_size*col_size)//2: print("Given Matrix is a sparse Matrix.") else: print("Given Matrix is not a sparse Matrix.")
96
# Write a NumPy program to remove all rows in a NumPy array that contain non-numeric values. import numpy as np x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]]) print("Original array:") print(x) print("Remove all non-numeric elements of the said array") print(x[~np.isnan(x).any(axis=1)])
41
# Program to find the sum of an upper triangular matrix # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) #Calculate sum of Upper triangular matrix element sum=0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i>j: sum += matrix[i][j] # display the sum of the Upper triangular matrix element print("Sum of Upper Triangular Matrix Elements is: ",sum)
89
# Write a Python program to create the smallest possible number using the elements of a given list of positive integers. def create_largest_number(lst): if all(val == 0 for val in lst): return '0' result = ''.join(sorted((str(val) for val in lst), reverse=False, key=lambda i: i*( len(str(min(lst))) * 2 // len(i)))) return result nums = [3, 40, 41, 43, 74, 9] print("Original list:") print(nums) print("Smallest possible number using the elements of the said list of positive integers:") print(create_largest_number(nums)) nums = [10, 40, 20, 30, 50, 60] print("\nOriginal list:") print(nums) print("Smallest possible number using the elements of the said list of positive integers:") print(create_largest_number(nums)) nums = [8, 4, 2, 9, 5, 6, 1, 0] print("\nOriginal list:") print(nums) print("Smallest possible number using the elements of the said list of positive integers:") print(create_largest_number(nums))
128
# Write a Python program to sort a list of dictionaries using Lambda. models = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'Mi Max', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}] print("Original list of dictionaries :") print(models) sorted_models = sorted(models, key = lambda x: x['color']) print("\nSorting the List of dictionaries :") print(sorted_models)
47
# Write a Pandas program to find out the 'WHO region, 'Country', 'Beverage Types' in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' from the world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nThe world alcohol consumption details ('WHO region','Country','Beverage Types') \nin the year ‘1986’ or ‘1989’ where WHO region is ‘Americas’ or 'Europe':") print(w_a_con[((w_a_con['Year']==1985) | (w_a_con['Year']==1989)) & ((w_a_con['WHO region']=='Americas') | (w_a_con['WHO region']=='Europe'))][['WHO region','Country','Beverage Types']].head(10))
83
# Write a Python program to lowercase first n characters in a string. str1 = 'W3RESOURCE.COM' print(str1[:4].lower() + str1[4:])
19
# Write a Python program to set a random seed and get a random number between 0 and 1. Use random.random. import random print("Set a random seed and get a random number between 0 and 1:") random.seed(0) new_random_value = random.random() print(new_random_value) random.seed(1) new_random_value = random.random() print(new_random_value) random.seed(2) new_random_value = random.random() print(new_random_value)
51
# Write a Pandas program to convert given datetime to timestamp. import pandas as pd import datetime as dt import numpy as np df = pd.DataFrame(index=pd.DatetimeIndex(start=dt.datetime(2019,1,1,0,0,1), end=dt.datetime(2019,1,1,10,0,1), freq='H'))\ .reset_index().rename(columns={'index':'datetime'}) print("Sample datetime data:") print(df.head(10)) df['ts'] = df.datetime.values.astype(np.int64) // 10 ** 9 print("\nConvert datetime to timestamp:") print (df)
46
# Python Program to Remove the Given Key from a Dictionary d = {'a':1,'b':2,'c':3,'d':4} print("Initial dictionary") print(d) key=raw_input("Enter the key to delete(a-d):") if key in d: del d[key] else: print("Key not found!") exit(0) print("Updated dictionary") print(d)
36
# Write a NumPy program to get the qr factorization of a given array. import numpy as np a = np.array([[4, 12, -14], [12, 37, -53], [-14, -53, 98]], dtype=np.int32) print("Original array:") print(a) q, r = np.linalg.qr(a) print("qr factorization of the said array:") print( "q=\n", q, "\nr=\n", r)
48
# Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3). import numpy as np p = np.array([[0], [10], [20]]) q= np.array([10, 11, 12]) print("Original arrays:") print("Array-1") print(p) print("Array-2") print(q) print("\nNew Array:") new_array1 = p + q print(new_array1)
43
# How to insert a space between characters of all the elements of a given NumPy array in Python # importing numpy as np import numpy as np       # creating array of string x = np.array(["geeks", "for", "geeks"],              dtype=np.str) print("Printing the Original Array:") print(x)    # inserting space using np.char.join() r = np.char.join(" ", x) print("Printing the array after inserting space\ between the elements") print(r)
64
# Write a NumPy program to convert a given array into bytes, and load it as array. import numpy as np import os a = np.array([1, 2, 3, 4, 5, 6]) print("Original array:") print(a) a_bytes = a.tostring() a2 = np.fromstring(a_bytes, dtype=a.dtype) print("After loading, content of the text file:") print(a2) print(np.array_equal(a, a2))
51
# Print mirrored right triangle Alphabet pattern print("Enter the row and column size:"); row_size=input() for out in range(ord('A'),ord(row_size)+1):     for i in range(ord('A'),out+1):         print(chr(i),end=" ")     print("\r")
25
# Write a NumPy program to create an array of equal shape and data type of a given array. import numpy as np nums = np.array([[5.54, 3.38, 7.99], [3.54, 8.32, 6.99], [1.54, 2.39, 9.29]]) print("Original array:") print(nums) print("\nNew array of equal shape and data type of the said array filled by 0:") print(np.zeros_like(nums))
53
# Write a Pandas program to join two dataframes using keys from right dataframe only. 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 (keys from data2):") merged_data = pd.merge(data1, data2, how='right', on=['key1', 'key2']) print(merged_data) print("\nMerged Data (keys from data1):") merged_data = pd.merge(data2, data1, how='right', on=['key1', 'key2']) print(merged_data)
94