code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to format a specified string limiting the length of a string. str_num = "1234567890" print("Original string:",str_num) print('%.6s' % str_num) print('%.9s' % str_num) print('%.10s' % str_num)
30
# Getting all CSV files from a directory using Python # importing the required modules import glob import pandas as pd    # specifying the path to csv files path = "csvfoldergfg"    # csv files in the path files = glob.glob(path + "/*.csv")    # defining an empty list to store  # content data_frame = pd.DataFrame() c...
95
# Write a Python Program for ShellSort # Python program for implementation of Shell Sort    def shellSort(arr):        # Start with a big gap, then reduce the gap     n = len(arr)     gap = n/2        # Do a gapped insertion sort for this gap size.     # The first gap elements a[0..gap-1] are already in gapped      #...
193
# Write a Python program to generate all sublists of a list. from itertools import combinations def sub_lists(my_list): subs = [] for i in range(0, len(my_list)+1): temp = [list(x) for x in combinations(my_list, i)] if len(temp)>0: subs.extend(temp) return subs l1 = [10, 20, 30, 40] l2 = ['X', 'Y', '...
70
# Write a Python program to extract year, month and date value from current datetime using arrow module. import arrow a = arrow.utcnow() print("Year:") print(a.year) print("\nMonth:") print(a.month) print("\nDate:") print(a.day)
29
# Write a Python program to convert all the characters in uppercase and lowercase and eliminate duplicate letters from a given sequence. Use map() function. def change_cases(s): return str(s).upper(), str(s).lower() chrars = {'a', 'b', 'E', 'f', 'a', 'i', 'o', 'U', 'a'} print("Original Characters:\n",chrars) r...
60
# Write a NumPy program to replace a specific character with another in a given array of string values. import numpy as np str1 = np.array([['Python-NumPy-Exercises'], ['-Python-']]) print("Original array of string values:") print(str1) print("\nReplace '-' with '=' character in the said array of st...
65
# Write a NumPy program to create an array which looks like below array. import numpy as np x = np.triu(np.arange(2, 14).reshape(4, 3), -1) print(x)
25
# Write a Python program to read a square matrix from console and print the sum of matrix primary diagonal. Accept the size of the square matrix and elements for each column separated with a space (for every row) as input from the user. size = int(input("Input the size of the matrix: ")) matrix = [[0] * size for row...
101
# Write a Python program to interleave two given list into another list randomly using map() function. import random def randomly_interleave(nums1, nums2): result = list(map(next, random.sample([iter(nums1)]*len(nums1) + [iter(nums2)]*len(nums2), len(nums1)+len(nums2)))) return result nums1 = [1,2,7,8,3,7] ...
51
# Write a Python program to Remove Tuples from the List having every element as None # Python3 code to demonstrate working of  # Remove None Tuples from List # Using all() + list comprehension    # initializing list test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]    # printing original list print("Th...
96
# Write a Python program to multiply all the numbers in a given list using lambda. from functools import reduce def mutiple_list(nums): result = reduce(lambda x, y: x*y, nums) return result nums = [4, 3, 2, 2, -1, 18] print ("Original list: ") print(nums) print("Mmultiply all the numbers of the said list:"...
74
# Write a NumPy program to print all the values of an array. import numpy as np np.set_printoptions(threshold=np.nan) x = np.zeros((4, 4)) print(x)
23
# Write a Python program to alter the owner and the group id of a specified file. import os fd = os.open( "/tmp", os.O_RDONLY ) os.fchown( fd, 100, -1) os.fchown( fd, -1, 50) print("Changed ownership successfully..") os.close( fd )
39
# Minimum difference between two elements in an array import sysarr=[]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)Min_diff=sys.maxsizefor i in range(0,size-1):    for j in range(i+1, size):        if abs(arr[...
52
# Write a Python program to Replace NaN values with average of columns # Python code to demonstrate # to replace nan values # with an average of columns    import numpy as np    # Initialising numpy array ini_array = np.array([[1.3, 2.5, 3.6, np.nan],                        [2.6, 3.3, np.nan, 5.5],                   ...
106
# Maximum of two numbers in Python # Python program to find the # maximum of two numbers def maximum(a, b):           if a >= b:         return a     else:         return b       # Driver code a = 2 b = 4 print(maximum(a, b))
41
# Write a Pandas program to convert index of a given dataframe into a column. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcnei...
74
# Isoformat to datetime – Python # importing datetime module from datetime import datetime    # Getting today's date todays_Date = datetime.now()    # Get date into the isoformat isoformat_date = todays_Date.isoformat()    # print the type of date print(type(isoformat_date))    # convert string date into datetime for...
48
# Write a NumPy program to create an array of ones and an array of zeros. import numpy as np print("Create an array of zeros") x = np.zeros((1,2)) print("Default type is float") print(x) print("Type changes to int") x = np.zeros((1,2), dtype = np.int) print(x) print("Create an array of ones") y= np.ones((1,2)) prin...
67
# Write a Pandas program to create a yearly time period from a specified year and display the properties of this period. import pandas as pd ytp = pd.Period('2020','A-DEC') print("Yearly time perid:",ytp) print("\nAll the properties of the said period:") print(dir(ytp))
40
# Write a Pandas program to remove the duplicates from 'WHO region' column of 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("\nAfter removing the duplicate...
46
# Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i n=int(raw_input()) values = [] for i in NumGenerator(...
56
# Write a Python program to Convert JSON to string import json # create a sample json a = {"name" : "GeeksforGeeks", "Topic" : "Json to String", "Method": 1} # Convert JSON to String y = json.dumps(a) print(y) print(type(y))
39
# Write a Python program to use double quotes to display strings. import json print(json.dumps({'Alex': 1, 'Suresh': 2, 'Agnessa': 3}))
20
# Write a NumPy program to sort a given array by row and column in ascending order. import numpy as np nums = np.array([[5.54, 3.38, 7.99], [3.54, 4.38, 6.99], [1.54, 2.39, 9.29]]) print("Original array:") print(nums) print("\nSort the said array by row in ascending order:") print(np.so...
56
# Write a Python function to reverses a string if it's length is a multiple of 4. def reverse_string(str1): if len(str1) % 4 == 0: return ''.join(reversed(str1)) return str1 print(reverse_string('abcd')) print(reverse_string('python'))
31
# Write a Python program to Convert Tuple Matrix to Tuple List # Python3 code to demonstrate working of  # Convert Tuple Matrix to Tuple List # Using list comprehension + zip()    # initializing list test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]    # printing original list print("The origina...
94
# Write a Python program to add leading zeroes to a string. str1='122.22' print("Original String: ",str1) print("\nAdded trailing zeros:") str1 = str1.ljust(8, '0') print(str1) str1 = str1.ljust(10, '0') print(str1) print("\nAdded leading zeros:") str1='122.22' str1 = str1.rjust(8, '0') print(str1) str1 = str1.rjust...
43
# Write a NumPy program to make all the elements of a given string to a numeric string of 5 digits with zeros on its left. import numpy as np x = np.array(['2', '11', '234', '1234', '12345'], dtype=np.str) print("\nOriginal Array:") print(x) r = np.char.zfill(x, 5) print("\nNumeric string of 5 digits with zeros:") p...
53
# Write a Python program which iterates the integers from 1 to a given number and print "Fizz" for multiples of three, print "Buzz" for multiples of five, print "FizzBuzz" for multiples of both three and five using itertools module. #Source:https://bit.ly/30PS62m import itertools as it def fizz_buzz(n): fizzes...
93
# Write a Pandas program to convert year and day of year into a single datetime column of a dataframe. import pandas as pd data = {\ "year": [2002, 2003, 2015, 2018], "day_of_the_year": [250, 365, 1, 140] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) df["combined"] = df["year"]*1000 + df["day_of_th...
58
# How to Change a Dictionary Into a Class in Python # Turns a dictionary into a class class Dict2Class(object):            def __init__(self, my_dict):                    for key in my_dict:             setattr(self, key, my_dict[key])    # Driver Code if __name__ == "__main__":            # Creating the dictionary  ...
67
# Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib. import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.2) y = np.sin(x) print("Plot the points using matpl...
63
# Write a Python Program to Reverse a linked list # Python program to reverse a linked list # Time Complexity : O(n) # Space Complexity : O(n) as 'next' #variable is getting created in each loop. # Node class class Node:     # Constructor to initialize the node object     def __init__(self, data):         sel...
179
# Write a NumPy program to change the data type of an array. import numpy as np x = np.array([[2, 4, 6], [6, 8, 10]], np.int32) print(x) print("Data type of the array x is:",x.dtype) # Change the data type of x y = x.astype(float) print("New Type: ",y.dtype) print(y)
48
# Count distinct substrings of a string using Rabin Karp algorithm in Python # importing libraries import sys import math as mt t = 1 # store prime to reduce overflow mod = 9007199254740881 for ___ in range(t):     # string to check number of distinct substring     s = 'abcd'     # to store substrings     l = [...
137
# 7.2 Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. : class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width aR...
49
# Write a Python program to swap two sublists in a given list. nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print("Original list:") print(nums) nums[6:10], nums[1:3] = nums[1:3], nums[6:10] print("\nSwap two sublists of the said list:") print(nums) nums[1:3], nums[4:6] = nums[4:6], nums[1:3] print("...
60
# Longest palindromic substring in a string def reverse(s):  str = ""  for i in s:    str = i + str  return strstr=input("Enter Your String:")sub_str=str.split(" ")sub_str1=[]p=0flag=0maxInd=0max=0str_rev=""print("Palindrome Substring are:")for inn in range(len(sub_str)):    str_rev= sub_str[inn]    if reverse(str_re...
69
# Write a Python program to find all the h2 tags and list the first four from the webpage python.org. import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("First four h2 tags from the webpage python.org.:") print(soup.fin...
45
# Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array. import numpy as np arra=np.ones((1,8,8)) print("Original array:") print(arra) result = np.triu(arra, k=1) print("\nResult:") print(result)
37
# How to add time onto a DateTime object in Python # Python3 code to illustrate the addition # of time onto the datetime object    # Importing datetime import datetime    # Initializing a date and time date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)    print("Original time:") print(date_and_time)    # Callin...
69
# Write a Python program to print the first n Lucky Numbers. n=int(input("Input a Number: ")) List=range(-1,n*n+9,2) i=2 while List[i:]:List=sorted(set(List)-set(List[List[i]::List[i]]));i+=1 print(List[1:n+1])
21
# Write a Python program to sort a list of elements using the insertion sort algorithm. def insertionSort(nlist): for index in range(1,len(nlist)): currentvalue = nlist[index] position = index while position>0 and nlist[position-1]>currentvalue: nlist[position]=nlist[position-1] ...
42
# rite a Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output (all characters in lower case). lines = [] while True: l = input() if l: lines.append(l.upper()) else: break; for l in lines: print(l)
46
# How to get element-wise true division of an array using Numpy in Python # import library import numpy as np    # create 1d-array x = np.arange(5)    print("Original array:",        x)    # apply true division  # on each array element rslt = np.true_divide(x, 4)    print("After the element-wise division:",        rs...
48
# Select any row from a Dataframe using iloc[] and iat[] in Pandas in Python import pandas as pd     # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'Cost':[10000, 5000, 15000...
77
# How to create filename containing date or time in Python # import module from datetime import datetime    # get current date and time current_datetime = datetime.now() print("Current date & time : ", current_datetime)    # convert datetime obj to string str_current_datetime = str(current_datetime)    # create a fil...
64
# Saving a Networkx graph in GEXF format and visualize using Gephi in Python # importing the required module import networkx as nx # making a simple graph with 1 node. G = nx.path_graph(10) # saving graph created above in gexf format nx.write_gexf(G, "geeksforgeeks.gexf")
44
# Write a Python program to generate a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit. def arithmetic_progression(n, x): return list(range(n, x + 1, n)) print(arithmetic_progression(1, 15)) print(arithmetic_progression(3, 37)) print(arithmetic_...
42
# Write a Python program to get the current value of the recursion limit. import sys print() print("Current value of the recursion limit:") print(sys.getrecursionlimit()) print()
25
# Python Program to Find the Total Sum of a Nested List Using Recursion def sum1(lst): total = 0 for element in lst: if (type(element) == type([])): total = total + sum1(element) else: total = total + element return total print( "Sum is:",sum1([[1,2],[3,4]]))
43
# Write a Python program to extract every first or specified element from a given two-dimensional list. def specified_element(nums, N): result = [i[N] for i in nums] return result nums = [ [1,2,3,2], [4,5,6,2], [7,1,9,5], ] print("Original list of lists:") print(nums)...
73
# Write a Python program to create multiple lists. obj = {} for i in range(1, 21): obj[str(i)] = [] print(obj)
21
# Write a Python program to combines two or more dictionaries, creating a list of values for each key. from collections import defaultdict def test(*dicts): result = defaultdict(list) for el in dicts: for key in el: result[key].append(el[key]) return dict(result) d1 = {'w': 50, 'x': 100, 'y': 'Gree...
73
# Program to check whether number is Spy Number or Not num=int(input("Enter a number:")) sum=0 mult=1 while num!=0:     rem = num % 10     sum += rem     mult *= rem     num //= 10 if sum==mult:     print("It is a spy Number.") else:    print("It is not a spy Number.")
46
# How to compute the eigenvalues and right eigenvectors of a given square array using NumPY in Python # importing numpy library import numpy as np    # create numpy 2d-array m = np.array([[1, 2],               [2, 3]])    print("Printing the Original square array:\n",       m)    # finding eigenvalues and eigenvector...
78
# Write a Python program to find the minimum, maximum value for each tuple position in a given list of tuples. def max_min_list_tuples(nums): zip(*nums) result1 = map(max, zip(*nums)) result2 = map(min, zip(*nums)) return list(result1), list(result2) nums = [(2,3),(2,4),(0,6),(7,1)] print("Original ...
70
# Python Program to Reverse a Stack using Recursion class Stack: def __init__(self): self.items = []   def is_empty(self): return self.items == []   def push(self, data): self.items.append(data)   def pop(self): return self.items.pop()   def display(self): f...
85
# Write a Pandas program to drop the columns where at least one element is missing in a given 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,70...
60
# Pandas | Basic of Time Series Manipulation in Python import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019',                                                    freq ='Min') print(range_date)
31
# Write a Pandas program to get the items of a given series not present in another given series. import pandas as pd sr1 = pd.Series([1, 2, 3, 4, 5]) sr2 = pd.Series([2, 4, 6, 8, 10]) print("Original Series:") print("sr1:") print(sr1) print("sr2:") print(sr2) print("\nItems of sr1 not present in sr2:") result = sr1[...
54
# Check if element exists in list in Python # Python code to demonstrate # checking of element existence # using loops and in # Initializing list test_list = [ 1, 6, 3, 5, 3, 4 ] print("Checking if 4 exists in list ( using loop ) : ") # Checking if 4 exists in list # using loop for i in test_list:     if(i == 4...
99
# Write a Python program to calculate arc length of an angle. def arclength(): pi=22/7 diameter = float(input('Diameter of circle: ')) angle = float(input('angle measure: ')) if angle >= 360: print("Angle is not possible") return arc_length = (pi*diameter) * (angle/360) print(...
46
# Write a Python program to construct a Decimal from a float and a Decimal from a string. Also represent the Decimal value as a tuple. Use decimal.Decimal import decimal print("Construct a Decimal from a float:") pi_val = decimal.Decimal(3.14159) print(pi_val) print(pi_val.as_tuple()) print("\nConstruct a Decimal fro...
52
# Write a NumPy program to test a given array element-wise for finiteness (not infinity or not a Number). import numpy as np a = np.array([1, 0, np.nan, np.inf]) print("Original array") print(a) print("Test a given array element-wise for finiteness :") print(np.isfinite(a))
41
# Write a NumPy program to create a white image of size 512x256. from PIL import Image import numpy as np a = np.full((512, 256, 3), 255, dtype=np.uint8) image = Image.fromarray(a, "RGB") image.save("white.png", "PNG")
34
# Python Program to Compute Prime Factors of an Integer   n=int(input("Enter an integer:")) print("Factors are:") i=1 while(i<=n): k=0 if(n%i==0): j=1 while(j<=i): if(i%j==0): k=k+1 j=j+1 if(k==2): print(i) i=i+1
27
# Write a Python program to Convert numeric words to numbers # Python3 code to demonstrate working of  # Convert numeric words to numbers # Using join() + split()    help_dict = {     'one': '1',     'two': '2',     'three': '3',     'four': '4',     'five': '5',     'six': '6',     'seven': '7',     'eight': '8',   ...
105
# Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string. def first_three(str): return str[:3] if len(str) > 3 else str print(first_three('ipy')) print(first_three('python')) print(first_three('py'...
47
# Write a Pandas program to set value in a specific cell in a given dataframe using index. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton'...
88
# Program to compute the perimeter of Trapezoid print("Enter the value of base:") a=int(input()) b=int(input()) print("Enter the value of side:") c=int(input()) d=int(input()) perimeter=a+b+c+d print("Perimeter of the Trapezoid = ",perimeter)
29
# Maximum difference between two elements in an array import sysarr=[]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)Max_diff=-sys.maxsize-1for i in range(0,size-1):    for j in range(i+1, size):        if abs(a...
52
# Create two arrays of six elements. Write a NumPy program to count the number of instances of a value occurring in one array on the condition of another array. import numpy as np x = np.array([10,-10,10,-10,-10,10]) y = np.array([.85,.45,.9,.8,.12,.6]) print("Original arrays:") print(x) print(y) result = np.sum((x ...
70
# Program to Print the Hollow Half Pyramid Star Pattern row_size=int(input("Enter the row size:"))print_control_x=row_size//2+1for out in range(1,row_size+1):    for inn in range(1,row_size+1):        if inn==1 or out==inn or out==row_size:            print("*",end="")        else:            print(" ", end="")    pr...
33
# Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns. import pandas as pd df = pd.DataFrame({'year': [2018, 2019, 2020], 'month': [2, 3, 4], 'day': [4, 5, 6], ...
73
# Difference between List comprehension and Lambda in Python lst  =  [x ** 2  for x in range (1, 11)   if  x % 2 == 1] print(lst)
27
# Pretty print Linked List in Python class Node:     def __init__(self, val=None):         self.val = val         self.next = None       class LinkedList:     def __init__(self, head=None):         self.head = head        def __str__(self):                  # defining a blank res variable         res = ""            ...
143
# numpy string operations | not_equal() function in Python # Python program explaining # numpy.char.not_equal() method     # importing numpy  import numpy as geek    # input arrays   in_arr1 = geek.array('numpy') print ("1st Input array : ", in_arr1)    in_arr2 = geek.array('nump') print ("2nd Input array : ", in_arr...
62
# Write a Pandas program to create a time series object that has time indexed data. Also select the dates of same year and select the dates between certain dates. import pandas as pd index = pd.DatetimeIndex(['2011-09-02', '2012-08-04', '2015-09-03', '2010-08-04', ...
73
# Write a NumPy program to create two arrays with shape (300,400, 5), fill values using unsigned integer (0 to 255). Insert a new axis that will appear at the beginning in the expanded array shape. Now combine the said two arrays into one. import numpy as np nums1 = np.random.randint(low=0, high=256, size=(200, 300...
84
# Write a Python program to convert any base to decimal by using int() method # Python program to convert any base # number to its corresponding decimal # number    # Function to convert any base number # to its corresponding decimal number def any_base_to_decimal(number, base):            # calling the builtin funct...
104
# Write a Python program to change a given string to a new string where the first and last chars have been exchanged. def change_sring(str1): return str1[-1:] + str1[1:-1] + str1[:1] print(change_sring('abcd')) print(change_sring('12345'))
33
# Write a NumPy program to create to concatenate two given arrays of shape (2, 2) and (2,1). import numpy as np nums1 = np.array([[4.5, 3.5], [5.1, 2.3]]) nums2 = np.array([[1], [2]]) print("Original arrays:") print(nums1) print(nums2) print("\nConcatenating the said two arrays:")...
44
# Write a Python program to create a doubly linked list, append some items and iterate through the list (print forward). class Node(object): # Doubly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linke...
131
# Write a Pandas program to create a Pivot table and calculate number of women and men were in a particular cabin class. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table(index=['sex'], columns=['pclass'], aggfunc='count') print(result)
40
# Write a Python program to list the tables of given SQLite database file. 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() # Create two tables ...
81
# Find out all Perfect numbers present within a given range '''Write a Python program to find out all Perfect numbers present within a given range. or Write a program to find out all Perfect numbers present within a given range using Python ''' print("Enter a range:") range1=int(input()) range2=int(input()) prin...
73
# Write a Python program to find the first repeated character in a given string. def first_repeated_char(str1): for index,c in enumerate(str1): if str1[:index+1].count(c) > 1: return c return "None" print(first_repeated_char("abcdabcd")) print(first_repeated_char("abcd"))
31
# Write a Python program to concatenate all elements in a list into a string and return it. def concatenate_list_data(list): result= '' for element in list: result += str(element) return result print(concatenate_list_data([1, 5, 12, 2]))
35
# Program to check whether a matrix is symmetric 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(...
136
# Write a NumPy program to create a vector of size 10 with values ranging from 0 to 1, both excluded. import numpy as np x = np.linspace(0,1,12,endpoint=True)[1:-1] print(x)
29
# Write a Python program to print a given doubly linked list in reverse order. class Node(object): # Singly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linked_list(object): def __init__(self): ...
156
# Write a Python program to split values into two groups, based on the result of the given filtering function. def bifurcate_by(lst, fn): return [ [x for x in lst if fn(x)], [x for x in lst if not fn(x)] ] print(bifurcate_by(['red', 'green', 'black', 'white'], lambda x: x[0] == 'w'))
50
# Write a Pandas program to get the index of an element of a given Series. import pandas as pd ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8]) print("Original Series:") print(ds) print("\nIndex of 11 in the said series:") x = ds[ds == 11].index[0] print(x)
40
# Write a Python program to Maximum record value key in dictionary # Python3 code to demonstrate working of  # Maximum record value key in dictionary # Using loop    # initializing dictionary test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},              'is' : {'Manjeet' : 8, 'Himani' : 9},              'best' : ...
118
# Write a Python program to print a long text, convert the string to a list and print all the words and their frequencies. string_words = '''United States Declaration of Independence From Wikipedia, the free encyclopedia The United States Declaration of Independence is the statement adopted by the Second Continental...
673
# Write a Python program to replace a given tag with whatever's inside a given tag. from bs4 import BeautifulSoup markup = '<a href="https://w3resource.com/">Python exercises.<i>w3resource.com</i></a>' soup = BeautifulSoup(markup, "lxml") a_tag = soup.a print("Original markup:") print(a_tag) a_tag.i.unwrap() print("...
39
# Creating a dataframe from Pandas series in Python import pandas as pd import matplotlib.pyplot as plt    author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']    auth_series = pd.Series(author) print(auth_series)
27