code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to display vertically each element of a given list, list of lists. text = ["a", "b", "c", "d","e", "f"] print("Original list:") print(text) print("\nDisplay each element vertically of the said list:") for i in text: print(i) nums = [[1, 2, 5], [4, 5, 8], [7, 3, 6]] print("Original list:") print(nums) print("\nDisplay each element vertically of the said list of lists:") for a,b,c in zip(*nums): print(a, b, c)
71
# Python Program to Check If Two Numbers are Amicable Numbers x=int(input('Enter number 1: ')) y=int(input('Enter number 2: ')) sum1=0 sum2=0 for i in range(1,x): if x%i==0: sum1+=i for j in range(1,y): if y%j==0: sum2+=j if(sum1==y and sum2==x): print('Amicable!') else: print('Not Amicable!')
42
# Write a Python program to make an iterator that drops elements from the iterable as long as the elements are negative; afterwards, returns every element. import itertools as it def drop_while(nums): return it.takewhile(lambda x : x < 0, nums) nums = [-1,-2,-3,4,-10,2,0,5,12] print("Original list: ",nums) result = drop_while(nums) print("Drop elements from the said list as long as the elements are negative\n",list(result)) #Alternate solution def negative_num(x): return x < 0 def drop_while(nums): return it.dropwhile(negative_num, nums) nums = [-1,-2,-3,4,-10,2,0,5,12] print("Original list: ",nums) result = drop_while(nums) print("Drop elements from the said list as long as the elements are negative\n",list(result))
97
# Write a Python program to capitalize the first and last character of each word in a string # Python program to capitalize # first and last character of  # each word of a String       # Function to do the same def word_both_cap(str):            #lamda function for capitalizing the     # first and last letter of words in      # the string     return ' '.join(map(lambda s: s[:-1]+s[-1].upper(),                          s.title().split()))               # Driver's code s = "welcome to geeksforgeeks" print("String before:", s) print("String after:", word_both_cap(str))
79
# Print the Alphabet Inverted Half Pyramid Pattern print("Enter the row and column size:") row_size=input() for out in range(ord(row_size),ord('A')-1,-1):     for i in range(ord(row_size)-1,out-1,-1):         print(" ",end="")     for p in range(ord('A'), out+1):         print(chr(out),end="")     print("\r")
32
# Write a Python program to convert a list into a nested dictionary of keys. num_list = [1, 2, 3, 4] new_dict = current = {} for name in num_list: current[name] = {} current = current[name] print(new_dict)
37
# Write a Python program to Convert tuple to float value # Python3 code to demonstrate working of # Convert tuple to float # using join() + float() + str() + generator expression    # initialize tuple test_tup = (4, 56)    # printing original tuple  print("The original tuple : " + str(test_tup))    # Convert tuple to float # using join() + float() + str() + generator expression res = float('.'.join(str(ele) for ele in test_tup))    # printing result print("The float after conversion from tuple is : " + str(res))
87
# Write a Python program to get the index of the first element, which is greater than a specified element using itertools module. from itertools import takewhile def first_index(l1, n): return len(list(takewhile(lambda x: x[1] <= n, enumerate(l1)))) nums = [12,45,23,67,78,90,100,76,38,62,73,29,83] print("Original list:") print(nums) n = 73 print("\nIndex of the first element which is greater than",n,"in the said list:") print(first_index(nums,n)) n = 21 print("\nIndex of the first element which is greater than",n,"in the said list:") print(first_index(nums,n)) n = 80 print("\nIndex of the first element which is greater than",n,"in the said list:") print(first_index(nums,n)) n = 55 print("\nIndex of the first element which is greater than",n,"in the said list:") print(first_index(nums,n))
107
# Python Program to Find the Length of the Linked List without using Recursion class Node: def __init__(self, data): self.data = data self.next = None   class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next   def length(self): current = self.head length = 0 while current: length = length + 1 current = current.next return length   a_llist = LinkedList() data_list = input('Please enter the elements in the linked list: ').split() for data in data_list: a_llist.append(int(data))   print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')
109
# Write a Python program to rotate a Deque Object specified number (negative) of times. import collections # declare an empty deque object dq_object = collections.deque() # Add elements to the deque - left to right dq_object.append(2) dq_object.append(4) dq_object.append(6) dq_object.append(8) dq_object.append(10) print("Deque before rotation:") print(dq_object) # Rotate once in negative direction dq_object.rotate(-1) print("\nDeque after 1 negative rotation:") print(dq_object) # Rotate twice in negative direction dq_object.rotate(-2) print("\nDeque after 2 negative rotations:") print(dq_object)
71
# Write a Python program to create a datetime object, converted to the specified timezone using arrow module. import arrow utc = arrow.utcnow() pacific=arrow.now('US/Pacific') nyc=arrow.now('America/Chicago').tzinfo print(pacific.astimezone(nyc))
26
# Please write a program to shuffle and print the list [3,6,7,8]. : from random import shuffle li = [3,6,7,8] shuffle(li) print li
23
# Write a Python program to Ways to remove multiple empty spaces from string List # Python3 code to demonstrate working of  # Remove multiple empty spaces from string List # Using loop + strip()    # initializing list test_list = ['gfg', '   ', ' ', 'is', '            ', 'best']    # printing original list print("The original list is : " + str(test_list))    # Remove multiple empty spaces from string List # Using loop + strip() res = [] for ele in test_list:     if ele.strip():         res.append(ele)        # printing result  print("List after filtering non-empty strings : " + str(res)) 
96
# Write a Python program to Sorting string using order defined by another string # Python program to sort a string and return # its reverse string according to pattern string    # This function will return the reverse of sorted string # according to the pattern    def sortbyPattern(pat, str):        priority = list(pat)        # Create a dictionary to store priority of each character     myDict = { priority[i] : i for i in range(len(priority))}        str = list(str)        # Pass lambda function as key in sort function     str.sort( key = lambda ele : myDict[ele])        # Reverse the string using reverse()     str.reverse()        new_str = ''.join(str)     return new_str       if __name__=='__main__':     pat = "asbcklfdmegnot"     str =  "eksge"     new_str = sortbyPattern(pat, str)     print(new_str)
116
# Write a Python program to Swapping Hierarchy in Nested Dictionaries # Python3 code to demonstrate working of # Swapping Hierarchy in Nested Dictionaries # Using loop + items() # initializing dictionary test_dict = {'Gfg': { 'a' : [1, 3], 'b' : [3, 6], 'c' : [6, 7, 8]},              'Best': { 'a' : [7, 9], 'b' : [5, 3, 2], 'd' : [0, 1, 0]}} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Swapping Hierarchy in Nested Dictionaries # Using loop + items() res = dict() for key, val in test_dict.items():     for key_in, val_in in val.items():         if key_in not in res:             temp = dict()         else:             temp = res[key_in]         temp[key] = val_in         res[key_in] = temp # printing result print("The rearranged dictionary : " + str(res))
128
# Write a python program to find the next previous palindrome of a specified number. def Previous_Palindrome(num): for x in range(num-1,0,-1): if str(x) == str(x)[::-1]: return x print(Previous_Palindrome(99)); print(Previous_Palindrome(1221));
29
# Write a NumPy program to create an array of 10's with the same shape and type of a given array. import numpy as np x = np.arange(4, dtype=np.int64) y = np.full_like(x, 10) print(y)
34
# Write a NumPy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix. import numpy as np arra = np.array([[ 1, 1, 0], [ 0, 0, 0], [ 0, 2, 3], [ 0, 0, 0], [ 0, -1, 1], [ 0, 0, 0]]) print("Original array:") print(arra) temp = {(0, 0, 0)} result = [] for idx, row in enumerate(map(tuple, arra)): if row not in temp: result.append(idx) print("\nNon-zero unique rows:") print(arra[result])
83
# Write a Pandas program convert the first and last character of each word to upper case in each word of a given series. import pandas as pd series1 = pd.Series(['php', 'python', 'java', 'c#']) print("Original Series:") print(series1) result = series1.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper()) print("\nFirst and last character of each word to upper case:") print(result)
57
# Write a Python program to calculate the difference between two iterables, without filtering duplicate values. def difference(x, y): _y = set(y) return [item for item in x if item not in _y] print(difference([1, 2, 3], [1, 2, 4]))
39
# Write a Pandas program to filter all columns where all entries present, check which rows and columns has a NaN and finally drop rows with any NaNs from world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nFind all columns which all entries present:") print(w_a_con.loc[:, w_a_con.notnull().all()]) print("\nRows and columns has a NaN:") print(w_a_con.loc[:,w_a_con.isnull().any()]) print("\nDrop rows with any NaNs:") print(w_a_con.dropna(how='any'))
73
# Write a Pandas program to extract the unique sentences from a given column of a given DataFrame. import pandas as pd import re as re df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'], 'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'], 'address': ['9910 Surrey Avenue\n9910 Surrey Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.\n102 Dunbar St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def find_unique_sentence(str1): result = re.findall(r'(?sm)(^[^\r\n]+$)(?!.*^\1$)', str1) return result df['unique_sentence']=df['address'].apply(lambda st : find_unique_sentence(st)) print("\nExtract unique sentences :") print(df)
78
# Write a Python program for removing i-th character from a string # Python3 program for removing i-th  # indexed character from a string    # Removes character at index i def remove(string, i):         # Characters before the i-th indexed     # is stored in a variable a     a = string[ : i]             # Characters after the nth indexed     # is stored in a variable b     b = string[i + 1: ]            # Returning string after removing     # nth indexed character.     return a + b        # Driver Code if __name__ == '__main__':            string = "geeksFORgeeks"            # Remove nth index element     i = 5          # Print the new string     print(remove(string, i))
108
# Priority Queue using Queue and Heapdict module in Python from queue import PriorityQueue    q = PriorityQueue()    # insert into queue q.put((2, 'g')) q.put((3, 'e')) q.put((4, 'k')) q.put((5, 's')) q.put((1, 'e'))    # remove and return  # lowest priority item print(q.get()) print(q.get())    # check queue size print('Items in queue :', q.qsize())    # check if queue is empty print('Is queue empty :', q.empty())    # check if queue is full print('Is queue full :', q.full())
72
# Defining a Python function at runtime # importing the module from types import FunctionType    # functttion during run-time f_code = compile('def gfg(): return "GEEKSFORGEEKS"', "<string>", "exec") f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")    # calling the function print(f_func())
37
# Write a Python program to sort a given matrix in ascending order according to the sum of its rows. def sort_matrix(M): result = sorted(M, key=sum) 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))
86
# Write a NumPy program to compute numerical negative value for all elements in a given array. import numpy as np x = np.array([0, 1, -1]) print("Original array: ") print(x) r1 = np.negative(x) r2 = -x assert np.array_equal(r1, r2) print("Numerical negative value for all elements of the said array:") print(r1)
50
# Write a Pandas program to extract a single row, rows and a specific value from a MultiIndex levels DataFrame. import pandas as pd import numpy as np sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'], ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']] sales_tuples = list(zip(*sales_arrays)) sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city']) print(sales_tuples) print("\nConstruct a Dataframe using the said MultiIndex levels: ") df = pd.DataFrame(np.random.randn(8, 5), index=sales_index) print(df) print("\nExtract a single row from the said dataframe:") print(df.loc[('sale2', 'city2')]) print("\nExtract a single row from the said dataframe:") print(df.loc[('sale2', 'city2')]) print("\nExtract number of rows from the said dataframe:") print(df.loc['sale1']) print("\nExtract number of rows from the said dataframe:") print(df.loc['sale3']) print("\nExtract a single value from the said dataframe:") print(df.loc[('sale1', 'city2'), 1]) print("\nExtract a single value from the said dataframe:") print(df.loc[('sale4', 'city1'), 4])
130
# Write a Python program to Convert a list of Tuples into Dictionary # Python code to convert into dictionary    def Convert(tup, di):     for a, b in tup:         di.setdefault(a, []).append(b)     return di        # Driver Code     tups = [("akash", 10), ("gaurav", 12), ("anand", 14),       ("suraj", 20), ("akhil", 25), ("ashish", 30)] dictionary = {} print (Convert(tups, dictionary))
55
# Program to find the nth Magic Number rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     num3 = num     num1 = num     sum = 0     # Sum of digit     while num1 != 0:         rem = num1 % 10         sum += rem         num1 //= 10     # Reverse of sum     rev = 0     num2 = sum     while num2 != 0:         rem2 = num2 % 10         rev = rev * 10 + rem2         num2 //= 10     if sum * rev == num3:         c+=1         letest = num     num = num + 1 print(rangenumber,"th Magic number is ",letest)
102
# Write a Python program to Assigning Subsequent Rows to Matrix first row elements # Python3 code to demonstrate working of  # Assigning Subsequent Rows to Matrix first row elements # Using dictionary comprehension    # initializing list test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]    # printing original list print("The original list : " + str(test_list))    # pairing each 1st col with next rows in Matrix res = {test_list[0][ele] :  test_list[ele + 1] for ele in range(len(test_list) - 1)}    # printing result  print("The Assigned Matrix : " + str(res))
95
# Write a NumPy program to build an array of all combinations of three NumPy arrays. import numpy as np x = [1, 2, 3] y = [4, 5] z = [6, 7] print("Original arrays:") print("Array-1") print(x) print("Array-2") print(y) print("Array-3") print(z) new_array = np.array(np.meshgrid(x, y, z)).T.reshape(-1,3) print("Combine array:") print(new_array)
49
# Write a Python program to store a given dictionary in a json file. d = {"students":[{"firstName": "Nikki", "lastName": "Roysden"}, {"firstName": "Mervin", "lastName": "Friedland"}, {"firstName": "Aron ", "lastName": "Wilkins"}], "teachers":[{"firstName": "Amberly", "lastName": "Calico"}, {"firstName": "Regine", "lastName": "Agtarap"}]} print("Original dictionary:") print(d) print(type(d)) import json with open("dictionary", "w") as f: json.dump(d, f, indent = 4, sort_keys = True) print("\nJson file to dictionary:") with open('dictionary') as f: data = json.load(f) print(data)
68
# Program to Find nth Trimorphic Number rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     flag = 0     num1=num     cube_power = num * num * num     while num1 != 0:         if num1 % 10 != cube_power % 10:             flag = 1             break         num1 //= 10         cube_power //= 10     if flag == 0:             c+=1             letest = num     num = num + 1 print(rangenumber,"th Trimorphic number is ",latest)
75
# Write a Python program to extract all the text from a given web page. import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("Text from the said page:") print(soup.get_text())
37
# Write a Python program to Numpy np.polygrid3d() method # Python program explaining # numpy.polygrid3d() method     # importing numpy as np    import numpy as np  from numpy.polynomial.polynomial import polygrid3d    # Input polynomial series coefficients c = np.array([[1, 3, 5], [2, 4, 6], [10, 11, 12]])     # using np.polygrid3d() method  ans = polygrid3d([7, 9], [8, 10], [5, 6], c) print(ans)
59
# Sort names in alphabetical order size=int(input("Enter number of names:")) print("Enter ",size," names:") str=[] for i in range(size):     ele=input()     str.append(ele) for i in range(size):     for j in range(i+1,size):                if (str[i]>str[j])>0:                   temp=str[i]                   str[i]=str[j]                   str[j]=temp print("After sorting names are:") for i in range(size):     print(str[i])
42
# How to subtract one polynomial to another using NumPy in Python # importing package import numpy    # define the polynomials # p(x) = 5(x**2) + (-2)x +5 px = (5,-2,5)    # q(x) = 2(x**2) + (-5)x +2 qx = (2,-5,2)    # subtract the polynomials rx = numpy.polynomial.polynomial.polysub(px,qx)    # print the resultant polynomial print(rx)
54
# How to count unique values inside a list in Python # taking an input list input_list = [1, 2, 2, 5, 8, 4, 4, 8]    # taking an input list l1 = []    # taking an counter count = 0    # travesing the array for item in input_list:     if item not in l1:         count += 1         l1.append(item)    # printing the output print("No of unique items are:", count)
68
# Write a Python program to get the most frequent element in a given list of numbers. def most_frequent(nums): return max(set(nums), key = nums.count) print(most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2])) nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,2,4,6,9,1,2] print ("Original list:") print(nums) print("Item with maximum frequency of the said list:") print(most_frequent(nums)) nums = [1, 2, 3, 1, 2, 3, 2, 1, 4, 3, 3] print ("\nOriginal list:") print(nums) print("Item with maximum frequency of the said list:") print(most_frequent(nums))
75
# Write a NumPy program to round array elements to the given number of decimals. import numpy as np x = np.round([1.45, 1.50, 1.55]) print(x) x = np.round([0.28, .50, .64], decimals=1) print(x) x = np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value print(x)
46
# Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. : import random print random.sample([i for i in range(100,201) if i%2==0], 5)
31
# Write a Python program to create an instance of an OrderedDict using a given dictionary. Sort the dictionary during the creation and print the members of the dictionary in reverse order. from collections import OrderedDict dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376, 'Angola': 244} new_dict = OrderedDict(dict.items()) for key in new_dict: print (key, new_dict[key]) print("\nIn reverse order:") for key in reversed(new_dict): print (key, new_dict[key])
68
# Write a Python program to extract specified number of elements from a given list, which follows each other continuously. from itertools import groupby def extract_elements(nums, n): result = [i for i, j in groupby(nums) if len(list(j)) == n] return result nums1 = [1, 1, 3, 4, 4, 5, 6, 7] n = 2 print("Original list:") print(nums1) print("Extract 2 number of elements from the said list which follows each other continuously:") print(extract_elements(nums1, n)) nums2 = [0, 1, 2, 3, 4, 4, 4, 4, 5, 7] n = 4 print("Original lists:") print(nums2) print("Extract 4 number of elements from the said list which follows each other continuously:") print(extract_elements(nums2, n))
107
# Write a Pandas program to subtract two timestamps of same time zone or different time zone. import pandas as pd print("Subtract two timestamps of same time zone:") date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern') date2 = pd.Timestamp('2019-04-01 07:00', tz='US/Eastern') print("Difference: ", (date2-date1)) print("\nSubtract two timestamps of different time zone:") date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern') date2 = pd.Timestamp('2019-03-01 07:00', tz='US/Pacific') # Remove the time zone and do the subtraction print("Difference: ", (date1.tz_localize(None) - date2.tz_localize(None)))
72
# numpy.random.geometric() in Python # import numpy and geometric import numpy as np import matplotlib.pyplot as plt    # Using geometric() method gfg = np.random.geometric(0.65, 1000)    count, bins, ignored = plt.hist(gfg, 40, density = True) plt.show()
35
# Write a Python program to Convert List of Lists to Tuple of Tuples # Python3 code to demonstrate working of  # Convert List of Lists to Tuple of Tuples # Using tuple + list comprehension    # initializing list test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],                             ['Gfg', 'is', 'for', 'Geeks']]    # printing original list print("The original list is : " + str(test_list))    # Convert List of Lists to Tuple of Tuples # Using tuple + list comprehension res = tuple(tuple(sub) for sub in test_list)    # printing result  print("The converted data : " + str(res)) 
95
# Write a NumPy program to create a record array from a (flat) list of arrays. import numpy as np a1=np.array([1,2,3,4]) a2=np.array(['Red','Green','White','Orange']) a3=np.array([12.20,15,20,40]) result= np.core.records.fromarrays([a1, a2, a3],names='a,b,c') print(result[0]) print(result[1]) print(result[2])
30
# Write a Python program to add two positive integers without using the '+' operator. def add_without_plus_operator(a, b): while b != 0: data = a & b a = a ^ b b = data << 1 return a print(add_without_plus_operator(2, 10)) print(add_without_plus_operator(-20, 10)) print(add_without_plus_operator(-10, -20))
45
# How to Build a Simple Auto-Login Bot with Python # Used to import the webdriver from selenium from selenium import webdriver  import os # Get the path of chromedriver which you have install def startBot(username, password, url):     path = "C:\\Users\\hp\\Downloads\\chromedriver"           # giving the path of chromedriver to selenium websriver     driver = webdriver.Chrome(path)           # opening the website  in chrome.     driver.get(url)           # find the id or name or class of     # username by inspecting on username input     driver.find_element_by_name(         "id/class/name of username").send_keys(username)           # find the password by inspecting on password input     driver.find_element_by_name(         "id/class/name of password").send_keys(password)           # click on submit     driver.find_element_by_css_selector(         "id/class/name/css selector of login button").click() # Driver Code # Enter below your login credentials username = "Enter your username" password = "Enter your password" # URL of the login page of site # which you want to automate login. url = "Enter the URL of login page of website" # Call the function startBot(username, password, url)
154
# Write a Python program to convert a given list of tuples to a list of strings. def tuples_to_list_str(lst): result = [("%s "*len(el)%el).strip() for el in lst] return result colors = [('red', 'green'), ('black', 'white'), ('orange', 'pink')] print("Original list of tuples:") print(colors) print("\nConvert the said list of tuples to a list of strings:") print(tuples_to_list_str(colors)) names = [('Laiba','Delacruz'), ('Mali','Stacey','Drummond'), ('Raja','Welch'), ('Saarah','Stone')] print("\nOriginal list of tuples:") print(names) print("\nConvert the said list of tuples to a list of strings:") print(tuples_to_list_str(names))
77
# Write a Python Program for BogoSort or Permutation Sort # Python program for implementation of Bogo Sort import random # Sorts array a[0..n-1] using Bogo sort def bogoSort(a):     n = len(a)     while (is_sorted(a)== False):         shuffle(a) # To check if array is sorted or not def is_sorted(a):     n = len(a)     for i in range(0, n-1):         if (a[i] > a[i+1] ):             return False     return True # To generate permutation of the array def shuffle(a):     n = len(a)     for i in range (0,n):         r = random.randint(0,n-1)         a[i], a[r] = a[r], a[i] # Driver code to test above a = [3, 2, 4, 1, 0, 5] bogoSort(a) print("Sorted array :") for i in range(len(a)):     print ("%d" %a[i]),
114
# Insert row at given position in Pandas Dataframe in Python # importing pandas as pd import pandas as pd # Let's create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '12/2/2011', '13/2/2011', '14/2/2011'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'Cost':[10000, 5000, 15000, 2000]}) # Let's visualize the dataframe print(df)
45
# Python Program to test Collatz Conjecture for a Given Number def collatz(n): while n > 1: print(n, end=' ') if (n % 2): # n is odd n = 3*n + 1 else: # n is even n = n//2 print(1, end='')     n = int(input('Enter n: ')) print('Sequence: ', end='') collatz(n)
52
# Write a NumPy program to calculate hyperbolic sine, hyperbolic cosine, and hyperbolic tangent for all elements in a given array. import numpy as np x = np.array([-1., 0, 1.]) print(np.sinh(x)) print(np.cosh(x)) print(np.tanh(x))
33
# Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50. import numpy as np v = np.linspace(10, 49, 5) print("Length 10 with values evenly distributed between 5 and 50:") print(v)
40
# Write a Python Program for Iterative Merge Sort # Recursive Python Program for merge sort    def merge(left, right):     if not len(left) or not len(right):         return left or right        result = []     i, j = 0, 0     while (len(result) < len(left) + len(right)):         if left[i] < right[j]:             result.append(left[i])             i+= 1         else:             result.append(right[j])             j+= 1         if i == len(left) or j == len(right):             result.extend(left[i:] or right[j:])             break         return result    def mergesort(list):     if len(list) < 2:         return list        middle = len(list)/2     left = mergesort(list[:middle])     right = mergesort(list[middle:])        return merge(left, right)        seq = [12, 11, 13, 5, 6, 7] print("Given array is") print(seq);  print("\n") print("Sorted array is") print(mergesort(seq))    # Code Contributed by Mohit Gupta_OMG 
111
# Write a NumPy program to get the index of a maximum element in a NumPy array along one axis. import numpy as np a = np.array([[1,2,3],[4,3,1]]) print("Original array:") print(a) i,j = np.unravel_index(a.argmax(), a.shape) print("Index of a maximum element in a numpy array along one axis:") print(a[i,j])
47
# How to Sort CSV by multiple columns in Python # importing pandas package import pandas as pd    # making data frame from csv file data = pd.read_csv("diamonds.csv")    # sorting data frame by a column data.sort_values("carat", axis=0, ascending=True,                  inplace=True, na_position='first')    # display data.head(10)
43
# Write a Python program to filter a dictionary based on values. marks = {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190} print("Original Dictionary:") print(marks) print("Marks greater than 170:") result = {key:value for (key, value) in marks.items() if value >= 170} print(result)
46
# Write a NumPy program to create a contiguous flattened array. import numpy as np x = np.array([[10, 20, 30], [20, 40, 50]]) print("Original array:") print(x) y = np.ravel(x) print("New flattened array:") print(y)
33
# Write a Python program to determine whether variable is defined or not. try: x = 1 except NameError: print("Variable is not defined....!") else: print("Variable is defined.") try: y except NameError: print("Variable is not defined....!") else: print("Variable is defined.")
39
# Program to print the Alphabet Inverted Half Pyramid Pattern print("Enter the row and column size:") row_size=input() for out in range(ord(row_size),ord('A')-1,-1):     for i in range(ord(row_size)-1,out-1,-1):         print(" ",end="")     for p in range(ord('A'), out+1):         print(chr(p),end="")     print("\r")
34
# NumPy.histogram() Method in Python # Import libraries import numpy as np        # Creating dataset a = np.random.randint(100, size =(50))    # Creating histogram np.histogram(a, bins = [0, 10, 20, 30, 40,                         50, 60, 70, 80, 90,                         100])    hist, bins = np.histogram(a, bins = [0, 10,                                       20, 30,                                      40, 50,                                      60, 70,                                      80, 90,                                      100])     # printing histogram print() print (hist)  print (bins)  print()
63
# Write a NumPy program to create an inner product of two arrays. import numpy as np x = np.arange(24).reshape((2,3,4)) print("Array x:") print(x) print("Array y:") y = np.arange(4) print(y) print("Inner of x and y arrays:") print(np.inner(x, y))
37
# Write a Pandas program to rename all and only some of the column names from world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') new_w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nRename all the column names:") w_a_con.columns = ['year','who_region','country','beverage_types','display_values'] print(w_a_con.head()) print("\nRenaming only some of the column names:") new_w_a_con.rename(columns = {"WHO region":"WHO_region","Display Value":"Display_Value" },inplace = True) print(new_w_a_con.head())
66
# Python Program to Count the Number of Vowels in a String string=raw_input("Enter string:") vowels=0 for i in string: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels=vowels+1 print("Number of vowels are:") print(vowels)
44
# Write a Python program to create a file and write some text and rename the file name. import glob import os with open('a.txt', 'w') as f: f.write('Python program to create a symbolic link and read it to decide the original file pointed by the link.') print('\nInitial file/dir name:', os.listdir()) with open('a.txt', 'r') as f: print('\nContents of a.txt:', repr(f.read())) os.rename('a.txt', 'b.txt') print('\nAfter renaming initial file/dir name:', os.listdir()) with open('b.txt', 'r') as f: print('\nContents of b.txt:', repr(f.read()))
76
# Get n-largest values from a particular column in Pandas DataFrame in Python # importing pandas module  import pandas as pd       # making data frame  df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     df.head(10)
29
# Write a NumPy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2). import numpy as np nums1 = np.ones((2,2,3)) nums2 = 3*np.ones((2,2)) print("Original array:") print(nums1) new_array = nums1 * nums2[:,:,None] print("\nNew array:") print(new_array)
39
# Write a NumPy program to compute the cross product of two given vectors. import numpy as np p = [[1, 0], [0, 1]] q = [[1, 2], [3, 4]] print("original matrix:") print(p) print(q) result1 = np.cross(p, q) result2 = np.cross(q, p) print("cross product of the said two vectors(p, q):") print(result1) print("cross product of the said two vectors(q, p):") print(result2)
60
# Write a python program to find the next smallest palindrome of a specified number. import sys def Next_smallest_Palindrome(num): numstr = str(num) for i in range(num+1,sys.maxsize): if str(i) == str(i)[::-1]: return i print(Next_smallest_Palindrome(99)); print(Next_smallest_Palindrome(1221));
34
# Write a Pandas program to replace NaNs with a single constant value in specified columns 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,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',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001], 'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]}) print("Original Orders DataFrame:") print(df) print("\nReplace NaNs with a single constant value:") result = df['ord_no'].fillna(0, inplace=False) print(result)
57
# How to move Files and Directories in Python # Python program to move # files and directories       import shutil    # Source path source = "D:\Pycharm projects\gfg\Test\B"    # Destination path destination = "D:\Pycharm projects\gfg\Test\A"    # Move the content of # source to destination dest = shutil.move(source, destination)    # print(dest) prints the  # Destination of moved directory
56
# Write a Python program to sort a list of elements using Topological sort. # License https://bit.ly/2InTS3W # a # / \ # b c # / \ # d e edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} vertices = ['a', 'b', 'c', 'd', 'e'] def topological_sort(start, visited, sort): """Perform topolical sort on a directed acyclic graph.""" current = start # add current to visited visited.append(current) neighbors = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: sort = topological_sort(neighbor, visited, sort) # if all neighbors visited add current to sort sort.append(current) # if all vertices haven't been visited select a new one to visit if len(visited) != len(vertices): for vertice in vertices: if vertice not in visited: sort = topological_sort(vertice, visited, sort) # return sort return sort sort = topological_sort('a', [], []) print(sort)
149
# Program to Print the Hollow Diamond Star Pattern row_size=int(input("Enter the row size:")) print_control_x=row_size//2+1 for out in range(1,row_size+1):     for inn in range(1,row_size+1):         if inn==print_control_x or inn==row_size-print_control_x+1:             print("*",end="")         else:             print(" ", end="")     if out <= row_size // 2:         print_control_x-=1     else:         print_control_x+=1     print("\r")
41
# Write a Python program to Split by repeating substring # Python3 code to demonstrate working of  # Split by repeating substring # Using * operator + len()    # initializing string test_str = "gfggfggfggfggfggfggfggfg"    # printing original string print("The original string is : " + test_str)    # initializing target K = 'gfg'    # Split by repeating substring # Using * operator + len() temp = len(test_str) // len(str(K)) res = [K] * temp    # printing result  print("The split string is : " + str(res)) 
84
# Write a Python program to alter a given SQLite table. import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) def sql_table(conn): cursorObj = conn.cursor() cursorObj.execute("CREATE TABLE agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);") print("\nagent_master file has created.") # adding a new column in the agent_master table cursorObj.execute(""" ALTER TABLE agent_master ADD COLUMN FLAG BOOLEAN; """) print("\nagent_master file altered.") conn.commit() sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
80
# Write a Pandas program to create a time series object with a time zone. import pandas as pd print("Timezone: Europe/Berlin:") print("Using pytz:") date_pytz = pd.Timestamp('2019-01-01', tz = 'Europe/Berlin') print(date_pytz.tz) print("Using dateutil:") date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/Europe/Berlin') print(date_util.tz) print("\nUS/Pacific:") print("Using pytz:") date_pytz = pd.Timestamp('2019-01-01', tz = 'US/Pacific') print(date_pytz.tz) print("Using dateutil:") date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/US/Pacific') print(date_util.tz)
58
# Write a Python program to calculate the area of the sector. def sectorarea(): pi=22/7 radius = float(input('Radius of Circle: ')) angle = float(input('angle measure: ')) if angle >= 360: print("Angle is not possible") return sur_area = (pi*radius**2) * (angle/360) print("Sector Area: ", sur_area) sectorarea()
45
# Check whether a given Character is Upper case, Lower case, Number or Special Character ch=input("Enter a character:") if(ch>='a' and ch<='z'):         print("The character is lower case") elif(ch>='A' and ch<='Z'):         print("The character is upper case") elif(ch>='0' and ch<='9'):         print("The character is number") else: print("It is a special character") 
47
# Write a Python program to Pair elements with Rear element in Matrix Row # Python3 code to demonstrate  # Pair elements with Rear element in Matrix Row # using list comprehension    # Initializing list test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]    # printing original list print("The original list is : " + str(test_list))    # Pair elements with Rear element in Matrix Row # using list comprehension res = [] for sub in test_list:     res.append([[ele, sub[-1]] for ele in sub[:-1]])        # printing result  print ("The list after pairing is : " + str(res))
97
# Write a Python program to get the third side of right angled triangle from two given sides. def pythagoras(opposite_side,adjacent_side,hypotenuse): if opposite_side == str("x"): return ("Opposite = " + str(((hypotenuse**2) - (adjacent_side**2))**0.5)) elif adjacent_side == str("x"): return ("Adjacent = " + str(((hypotenuse**2) - (opposite_side**2))**0.5)) elif hypotenuse == str("x"): return ("Hypotenuse = " + str(((opposite_side**2) + (adjacent_side**2))**0.5)) else: return "You know the answer!" print(pythagoras(3,4,'x')) print(pythagoras(3,'x',5)) print(pythagoras('x',4,5)) print(pythagoras(3,4,5))
66
# Write a Python program to sort a list of tuples by second Item # Python program to sort a list of tuples by the second Item    # Function to sort the list of tuples by its second item def Sort_Tuple(tup):             # getting length of list of tuples     lst = len(tup)      for i in range(0, lst):                     for j in range(0, lst-i-1):              if (tup[j][1] > tup[j + 1][1]):                  temp = tup[j]                  tup[j]= tup[j + 1]                  tup[j + 1]= temp      return tup     # Driver Code  tup =[('for', 24), ('is', 10), ('Geeks', 28),        ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)]           print(Sort_Tuple(tup)) 
97
# Write a Python program to Sort Tuples by Total digits # Python3 code to demonstrate working of  # Sort Tuples by Total digits # Using sort() + len() + sum()    def count_digs(tup):            # gets total digits in tuples     return sum([len(str(ele)) for ele in tup ])    # initializing list test_list = [(3, 4, 6, 723), (1, 2), (12345,), (134, 234, 34)]    # printing original list print("The original list is : " + str(test_list))    # performing sort  test_list.sort(key = count_digs)    # printing result  print("Sorted tuples : " + str(test_list))
88
# How to round elements of the NumPy array to the nearest integer in Python import numpy as n    # create array y = n.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7]) print("Original array:", end=" ") print(y)    # rount to nearest integer y = n.rint(y) print("After rounding off:", end=" ") print(y)
49
# Write a Pandas program to create a subset of a given series based on value and condition. import pandas as pd s = pd.Series([0, 1,2,3,4,5,6,7,8,9,10]) print("Original Data Series:") print(s) print("\nSubset of the above Data Series:") n = 6 new_s = s[s < n] print(new_s)
45
# Write a Pandas program to create a Pivot table and count survival by gender, categories wise age of various classes. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') age = pd.cut(df['age'], [0, 10, 30, 60, 80]) result = df.pivot_table('survived', index=['sex',age], columns='pclass', aggfunc='count') print(result)
47
# How to extract paragraph from a website and save it as a text file in Python import urllib.request from bs4 import BeautifulSoup    # here we have to pass url and path # (where you want to save ur text file) urllib.request.urlretrieve("https://www.geeksforgeeks.org/grep-command-in-unixlinux/?ref=leftbar-rightbar",                            "/home/gpt/PycharmProjects/pythonProject1/test/text_file.txt")    file = open("text_file.txt", "r") contents = file.read() soup = BeautifulSoup(contents, 'html.parser')    f = open("test1.txt", "w")    # traverse paragraphs from soup for data in soup.find_all("p"):     sum = data.get_text()     f.writelines(sum)    f.close()
72
# Write a Python program to count most and least common characters in a given string. from collections import Counter def max_least_char(str1): temp = Counter(str1) max_char = max(temp, key = temp.get) min_char = min(temp, key = temp.get) return (max_char, min_char) str1 = "hello world" print ("Original string: ") print(str1) result = max_least_char(str1) print("\nMost common character of the said string:",result[0]) print("Least common character of the said string:",result[1])
66
# How to read all CSV files in a folder in Pandas in Python # import necessary libraries import pandas as pd import os import glob       # use glob to get all the csv files  # in the folder path = os.getcwd() csv_files = glob.glob(os.path.join(path, "*.csv"))       # loop over the list of csv files for f in csv_files:            # read the csv file     df = pd.read_csv(f)            # print the location and filename     print('Location:', f)     print('File Name:', f.split("\\")[-1])            # print the content     print('Content:')     display(df)     print()
84
# Program to Find nth Evil Number rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     one_c = 0     num1 = num     while num1 != 0:         if num1 % 2 == 1:             one_c += 1         num1 //= 2     if one_c % 2 == 0:             c+=1             letest = num     num = num + 1 print(rangenumber,"th Evil number is ",latest)
66
# Write a Python program to sort a given list of strings(numbers) numerically using lambda. def sort_numeric_strings(nums_str): result = sorted(nums_str, key=lambda el: int(el)) return result nums_str = ['4','12','45','7','0','100','200','-12','-500'] print("Original list:") print(nums_str) print("\nSort the said list of strings(numbers) numerically:") print(sort_numeric_strings(nums_str))
39
# Write a Python program to find the maximum and minimum values in a given list of tuples using lambda function. def max_min_list_tuples(class_students): return_max = max(class_students,key=lambda item:item[1])[1] return_min = min(class_students,key=lambda item:item[1])[1] return return_max, return_min class_students = [('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)] print("Original list with tuples:") print(class_students) print("\nMaximum and minimum values of the said list of tuples:") print(max_min_list_tuples(class_students))
64
# Write a Python program to Remove Consecutive K element records # Python3 code to demonstrate working of  # Remove Consecutive K element records # Using zip() + list comprehension    # initializing list test_list = [(4, 5, 6, 3), (5, 6, 6, 9), (1, 3, 5, 6), (6, 6, 7, 8)]    # printing original list print("The original list is : " + str(test_list))    # initializing K  K = 6    # Remove Consecutive K element records # Using zip() + list comprehension res = [idx for idx in test_list if (K, K) not in zip(idx, idx[1:])]    # printing result  print("The records after removal : " + str(res)) 
106
# Write a Python program to convert a given array elements to a height balanced Binary Search Tree (BST). class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def array_to_bst(array_nums): if not array_nums: return None mid_num = len(array_nums)//2 node = TreeNode(array_nums[mid_num]) node.left = array_to_bst(array_nums[:mid_num]) node.right = array_to_bst(array_nums[mid_num+1:]) return node def preOrder(node): if not node: return print(node.val) preOrder(node.left) preOrder(node.right) array_nums = [1,2,3,4,5,6,7] print("Original array:") print(array_nums) result = array_to_bst(array_nums) print("\nArray to a height balanced BST:") print(preOrder(result))
79
# Write a Python program to check whether an integer fits in 64 bits. int_val = 30 if int_val.bit_length() <= 63: print((-2 ** 63).bit_length()) print((2 ** 63).bit_length())
27
# Write a Pandas program to split the following given dataframe into groups based on school code and cast grouping as a list. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) student_data = 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(student_data) print('\nCast grouping as a list:') result = student_data.groupby(['school_code']) print(list(result))
103
# How to get size of folder using Python # import module import os # assign size size = 0 # assign folder path Folderpath = 'C:/Users/Geetansh Sahni/Documents/R' # get size for path, dirs, files in os.walk(Folderpath):     for f in files:         fp = os.path.join(path, f)         size += os.path.getsize(fp) # display size print("Folder size: " + str(size))
56
# Write a NumPy program to create a record array from a given regular array. import numpy as np arra1 = np.array([("Yasemin Rayner", 88.5, 90), ("Ayaana Mcnamara", 87, 99), ("Jody Preece", 85.5, 91)]) print("Original arrays:") print(arra1) print("\nRecord array;") result = np.core.records.fromarrays(arra1.T, names='col1, col2, col3', formats = 'S80, f8, i8') print(result)
50