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 li...
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 Ami...
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) resul...
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 word...
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...
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("Origi...
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...
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) p...
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...
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(p...
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' : [...
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], ...
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("\nFi...
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...
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'], ...
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 ...
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 pr...
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("\nSor...
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', '...
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",...
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     n...
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 ...
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...
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...
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   ...
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]])     # usin...
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]=...
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 p...
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 outp...
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 ...
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} ne...
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("O...
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)...
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'...
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_pl...
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 ...
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("\nConve...
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...
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':[100...
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: ...
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]:             re...
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...
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("\...
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 ...
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...
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....
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 produ...
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(...
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,...
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,...
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 to...
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:             ...
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 targ...
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_ma...
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...
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("Sec...
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...
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(tes...
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"): ...
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):                 ...
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, ...
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='...
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", ...
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 ("Or...
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...
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     ...
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...
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 ...
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 origin...
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 = ...
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','s...
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) ...
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.recor...
50