code
stringlengths
63
8.54k
code_length
int64
11
747
# Enter marks of five subjects and calculate total, average, and percentage print("Enter marks of 5 subjects out of 100:") sub1=float(input("Enter sub1 marks:")) sub2=float(input("Enter sub2 marks:")) sub3=float(input("Enter sub3 marks:")) sub4=float(input("Enter sub4 marks:")) sub5=float(input("Enter sub5 marks:")) ...
42
# Please write a program to randomly print a integer number between 7 and 15 inclusive. : import random print random.randrange(7,16)
21
# Write a Pandas program to Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. import pandas as pd df1 = pd.DataFrame({'A': [None, 0, None], 'B': [3, 4, 5]}) df2 = pd.DataFrame({'A': [1, 1, 3], 'B': [3, None, 3]}) df1.combine_first(df2) print("Original Da...
63
# Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5. def test_number5(x, y): if x == y or abs(x-y) == 5 or (x+y) == 5: return True else: return False print(test_number5(7, 2)) print(test_number5(3, 2)) print(test_number5(2, 2)) ...
54
# Write a Python program to Order Tuples by List # Python3 code to demonstrate working of  # Order Tuples by List # Using dict() + list comprehension    # initializing list test_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]    # printing original list print("The original list is : " + str(test_list))    ...
96
# Write a Python program to display the examination schedule. (extract the date from exam_st_date). exam_st_date = (11,12,2014) print( "The examination will start from : %i / %i / %i"%exam_st_date)
30
# Write a Python program to check whether any word in a given sting contains duplicate characrters or not. Return True or False. def duplicate_letters(text): word_list = text.split() for word in word_list: if len(word) > len(set(word)): return False return True text = "Filter out the factorials of the said l...
111
# Write a Python program to Remove items from Set # Python program to remove elements from set # Using the pop() method def Remove(initial_set):     while initial_set:         initial_set.pop()         print(initial_set)    # Driver Code initial_set = set([12, 10, 13, 15, 8, 9]) Remove(initial_set)
41
# How to check whether specified values are present in NumPy array in Python # importing Numpy package import numpy as np    # creating a Numpy array n_array = np.array([[2, 3, 0],                     [4, 1, 6]])    print("Given array:") print(n_array)    # Checking whether specific values # are present in "n_array" ...
65
# Write a Pandas program to split a dataset to group by two columns and then sort the aggregated results within the groups. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012...
67
# Print Fibonacci Series using recursion def FibonacciSeries(n):    if n==0:        return 0    elif(n==1):        return 1    else:        return FibonacciSeries(n-1)+FibonacciSeries(n-2)n=int(input("Enter the Limit:"))print("All Fibonacci Numbers in the given Range are:")for i in range(0,n):    print(FibonacciSerie...
32
# Create a list from rows in Pandas DataFrame | Set 2 in Python # importing pandas as pd 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, ...
46
# Write a Python program to get the volume of a sphere with radius 6. pi = 3.1415926535897931 r= 6.0 V= 4.0/3.0*pi* r**3 print('The volume of the sphere is: ',V)
30
# Write a Python program to Convert set into a list # Python3 program to convert a  # set into a list my_set = {'Geeks', 'for', 'geeks'}    s = list(my_set) print(s)
31
# Write a NumPy program to calculate the sum of all columns of a 2D NumPy array. import numpy as np num = np.arange(36) arr1 = np.reshape(num, [4, 9]) print("Original array:") print(arr1) result = arr1.sum(axis=0) print("\nSum of all columns:") print(result)
40
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to set dataframe background Color black and font color yellow. import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), ...
74
# Lambda and filter in Python Examples # Python Program to find numbers divisible  # by thirteen from a list using anonymous  # function    # Take a list of numbers.  my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]    # use anonymous function to filter and comparing  # if divisible or not result = list(filter(lam...
70
# Write a Python program to get the maximum value of a list, after mapping each element to a value using a given function. def max_by(lst, fn): return max(map(fn, lst)) print(max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
50
# Write a Python program to Word location in String # Python3 code to demonstrate working of  # Word location in String # Using findall() + index() import re    # initializing string test_str = 'geeksforgeeks is best for geeks'    # printing original string print("The original string is : " + test_str)    # initializ...
99
# Write a NumPy program to find indices of elements equal to zero in a NumPy array. import numpy as np nums = np.array([1,0,2,0,3,0,4,5,6,7,8]) print("Original array:") print(nums) print("Indices of elements equal to zero of the said array:") result = np.where(nums == 0)[0] print(result)
43
# Program to print inverted right triangle star pattern print("Enter the row size:") row_size=int(input()) for out in range(row_size+1):     for j in range(row_size,out,-1):         print("*",end="")     print("\r")
24
# Write a Python program to create a localized, humanized representation of a relative difference in time using arrow module. import arrow print("Current datetime:") print(arrow.utcnow()) earlier = arrow.utcnow().shift(hours=-4) print(earlier.humanize()) later = earlier.shift(hours=3) print(later.humanize(earlier))
33
# Write a NumPy program to check two random arrays are equal or not. import numpy as np x = np.random.randint(0,2,6) print("First array:") print(x) y = np.random.randint(0,2,6) print("Second array:") print(y) print("Test above two arrays are equal or not!") array_equal = np.allclose(x, y) print(array_equal)
43
# Find out all Trimorphic numbers present within a given range print("Enter a range:") range1=int(input()) range2=int(input()) print("Trimorphic numbers between ",range1," and ",range2," are: ") for i in range(range1,range2+1):     flag = 0     num=i     cube_power = num * num * num     while num != 0:         if nu...
67
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display bar charts in dataframe on specified columns. import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), column...
73
# Write a NumPy program to replace all elements of NumPy array that are greater than specified array. import numpy as np x = np.array([[ 0.42436315, 0.48558583, 0.32924763], [ 0.7439979,0.58220701,0.38213418], [ 0.5097581,0.34528799,0.1563123 ]]) print("Original array:") print(x) print("Replace all elements of the s...
56
# Write a Pandas program to drop those rows from a given DataFrame in which specific columns have missing values. import pandas as pd import numpy as np pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[np.nan,np.nan,70002,np.nan,np.nan,70005,np.nan,700...
60
# Write a Python program to Ways to add row/columns in numpy array # Python code to demonstrate # adding columns in numpy array import numpy as np ini_array = np.array([[1, 2, 3], [45, 4, 7], [9, 6, 10]]) # printing initial array print("initial_array : ", str(ini_array)); # Array to be added as column column_...
76
# Program to print series 2,15,41,80...n print("Enter the range of number(Limit):") n=int(input()) i=1 value=2 while(i<=n):     print(value,end=" ")     value+=i*13     i+=1
19
# Write a Python program to select a random element from a list, set, dictionary (value) and a file from a directory. Use random.choice() import random import os print("Select a random element from a list:") elements = [1, 2, 3, 4, 5] print(random.choice(elements)) print(random.choice(elements)) print(random.choice(e...
110
# Write a Python program to create an iterator that returns consecutive keys and groups from an iterable. import itertools as it print("Iterate over characters of a string and display\nconsecutive keys and groups from the iterable:") str1 = 'AAAAJJJJHHHHNWWWEERRRSSSOOIIU' data_groupby = it.groupby(str1) for key, gro...
83
# Write a Python program to convert tuple into list by adding the given string after every element # Python3 code to demonstrate working of # Convert tuple to List with succeeding element # Using list comprehension # initializing tuple test_tup = (5, 6, 7, 4, 9) # printing original tuple print("The original tuple...
94
# Program to find the normal and trace of a matrix import math # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.appe...
107
# Test the given page is found or not on the server Using Python # import module from urllib.request import urlopen from urllib.error import * # try block to read URL try:     html = urlopen("https://www.geeksforgeeks.org/")       # except block to catch # exception # and identify error except HTTPError as e:     p...
68
# Write a Python program to get the daylight savings time adjustment using arrow module. import arrow print("Daylight savings time adjustment:") a = arrow.utcnow().dst() print(a)
25
# Write a Pandas program to split a given dataset using group by on multiple columns and drop last n rows of from each group. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,700...
84
# Write a Python program to extract single key-value pair of a dictionary in variables. d = {'Red': 'Green'} (c1, c2), = d.items() print(c1) print(c2)
25
# Write a Python program to print the calendar of a given month and year. import calendar y = int(input("Input the year : ")) m = int(input("Input the month : ")) print(calendar.month(y, m))
33
# Write a Python program to Possible Substring count from String # Python3 code to demonstrate working of # Possible Substring count from String # Using min() + list comprehension + count() # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str...
89
# Write a Pandas program to split the following dataframe into groups by school code and get mean, min, and max value of age with customized column name for each school. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) student_data = pd.DataFrame({ 'school_c...
124
# Write a Python program to Print an Inverted Star Pattern # python 3 code to print inverted star # pattern     # n is the number of rows in which # star is going to be printed. n=11    # i is going to be enabled to # range between n-i t 0 with a # decrement of 1 with each iteration. # and in print function, for each...
107
# Write a Pandas program to extract numbers less than 100 from the specified column of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'], 'address': ['72 Surrey Ave.11','92 N. Bishop ...
93
# Write a Python program to Factors Frequency Dictionary # Python3 code to demonstrate working of  # Factors Frequency Dictionary # Using loop    # initializing list test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]    # printing original list print("The original list : " + str(test_list))    res = dict()    # iterating...
92
# Write a Python program to concatenate the consecutive numbers in a given string. import re txt = "Enter at 1 20 Kearny Street. The security desk can direct you to floor 1 6. Please have your identification ready." print("Original string:") print(txt) new_txt = re.sub(r"(?<=\d)\s(?=\d)", '', txt) print('\nAfter con...
57
# Plot line graph from NumPy array in Python # importing the modules import numpy as np import matplotlib.pyplot as plt # data to be plotted x = np.arrange(1, 11) y = x * x # plotting plt.title("Line graph") plt.xlabel("X axis") plt.ylabel("Y axis") plt.plot(x, y, color ="red") plt.show()
48
# Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no common letters print "No common characters". from collections import Counter def common_chars(str1,str2): d1 = Counter(str1) d2 = Counter(str2) common_dict = d1 & d2 if len...
94
# numpy string operations | count() function in Python # Python program explaining # numpy.char.count() method     # importing numpy as geek import numpy as geek    # input arrays   in_arr = geek.array(['Sayantan', '  Sayan  ', 'Sayansubhra']) print ("Input array : ", in_arr)     # output arrays  out_arr = geek.char....
54
# Write a Python program to count number of unique sublists within a given list. def unique_sublists(input_list): result ={} for l in input_list: result.setdefault(tuple(l), list()).append(1) for a, b in result.items(): result[a] = sum(b) return result list1 = [[1, 3], [5, 7], [1,...
82
# Write a Python program to remove additional spaces in a given list. def test(lst): result =[] for i in lst: j = i.replace(' ','') result.append(j) return result text = ['abc ', ' ', ' ', 'sdfds ', ' ', ' ', 'sdfds ', 'huy'] print("\nOriginal list:") print(text) print("Remove addit...
56
# Please write a program to print the running time of execution of "1+1" for 100 times. : from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit()
30
# Write a Pandas program to check if a specified value exists in single and multiple column index dataframe. 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 Parke...
157
# Write a NumPy program to get all 2D diagonals of a 3D NumPy array. import numpy as np np_array = np.arange(3*4*5).reshape(3,4,5) print("Original Numpy array:") print(np_array) print("Type: ",type(np_array)) result = np.diagonal(np_array, axis1=1, axis2=2) print("\n2D diagonals: ") print(result) print("Type: ",type...
39
# Write a NumPy program to create a function cube which cubes all the elements of an array. import numpy as np def cube(e): it = np.nditer([e, None]) for a, b in it: b[...] = a*a*a return it.operands[1] print(cube([1,2,3]))
39
# Find a matrix or vector norm using NumPy in Python # import library import numpy as np # initialize vector vec = np.arange(10) # compute norm of vector vec_norm = np.linalg.norm(vec) print("Vector norm:") print(vec_norm)
35
# Write a Python program to find the maximum and minimum values in a given list within specified index range. def reverse_list_of_lists(nums,lr,hr): temp = [] for idx, el in enumerate(nums): if idx >= lr and idx < hr: temp.append(el) result_max = max(temp) result_min = min(temp) ...
76
# Write a Python program to generate an infinite cycle of elements from an iterable. import itertools as it def cycle_data(iter): return it.cycle(iter) # Following loops will run for ever #List result = cycle_data(['A','B','C','D']) print("The said function print never-ending items:") for i in result: p...
61
# Write a Python program to print a variable without spaces between values. x = 30 print('Value of x is "{}"'.format(x))
21
# Write a Python program to convert a list of characters into a string. s = ['a', 'b', 'c', 'd'] str1 = ''.join(s) print(str1)
24
# Write a Python program to cast the provided value as a list if it's not one. def cast_list(val): return list(val) if isinstance(val, (tuple, list, set, dict)) else [val] d1 = [1] print(type(d1)) print(cast_list(d1)) d2 = ('Red', 'Green') print(type(d2)) print(cast_list(d2)) d3 = {'Red', 'Green'} print(type(d3)...
56
# Write a Python Program to Convert String Matrix Representation to Matrix import re    # initializing string test_str = "[gfg,is],[best,for],[all,geeks]"    # printing original string print("The original string is : " + str(test_str))    flat_1 = re.findall(r"\[(.+?)\]", test_str) res = [sub.split(",") for sub in fl...
60
# Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAdd...
49
# Write a NumPy program to extract all the elements of the first row from a given (4x4) array. import numpy as np arra_data = np.arange(0,16).reshape((4, 4)) print("Original array:") print(arra_data) print("\nExtracted data: First row") print(arra_data[0])
35
# Compute the outer product of two given vectors using NumPy in Python # Importing library import numpy as np    # Creating two 1-D arrays array1 = np.array([6,2]) array2 = np.array([2,5]) print("Original 1-D arrays:") print(array1) print(array2)    # Output print("Outer Product of the two array is:") result = np.out...
50
# Write a Python program to get the powerset of a given iterable. from itertools import chain, combinations def powerset(iterable): s = list(iterable) return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1))) nums = [1, 2] print("Original list elements:") print(nums) print("Powerset of the sa...
60
# Write a Pandas program to create a monthly time period and display the list of names in the current local scope. import pandas as pd mtp = pd.Period('2021-11','M') print("Monthly time perid: ",mtp) print("\nList of names in the current local scope:") print(dir(mtp))
42
# Write a Python program to multiply all the items in a dictionary. my_dict = {'data1':100,'data2':-54,'data3':247} result=1 for key in my_dict: result=result * my_dict[key] print(result)
25
# Python Program to Find the GCD of Two Numbers import fractions a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) print("The GCD of the two numbers is",fractions.gcd(a,b))
27
# Write a Python program to create a dictionary from two lists without losing duplicate values. from collections import defaultdict class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII'] id_list = [1, 2, 2, 3] temp = defaultdict(set) for c, i in zip(class_list, id_list): temp[c].add(i) print(temp)
43
# Write a Python program to calculate the maximum aggregate from the list of tuples (pairs). from collections import defaultdict def max_aggregate(st_data): temp = defaultdict(int) for name, marks in st_data: temp[name] += marks return max(temp.items(), key=lambda x: x[1]) students = [('Juan Wh...
60
# rite a Python program to remove spaces from a given string. def remove_spaces(str1): str1 = str1.replace(' ','') return str1 print(remove_spaces("w 3 res ou r ce")) print(remove_spaces("a b c"))
29
# Bidirectional Bubble Sort Program in Python | Java | C | C++ size=int(input("Enter the size of the array:")); arr=[] print("Enter the element of the array:"); for i in range(0,size):     num = int(input())     arr.append(num) print("Before Sorting Array Element are: ",arr) low = 0 high= size-1 while low < high:   ...
80
# Program to print the Full Pyramid Number Pattern row_size=int(input("Enter the row size:")) np=1 for out in range(0,row_size):     for in1 in range(row_size-1,out,-1):         print(" ",end="")     for in2 in range(np,0,-1):         print(in2,end="")     np+=2     print("\r")
31
# Write a Python program to Remove punctuation from string # Python3 code to demonstrate working of # Removing punctuations in string # Using loop + punctuation string # initializing string test_str = "Gfg, is best : for ! Geeks ;" # printing original string print("The original string is : " + test_str) # initi...
95
# Write a Python program to Test if Substring occurs in specific position # Python3 code to demonstrate working of  # Test if Substring occurs in specific position # Using loop    # initializing string  test_str = "Gfg is best"    # printing original string  print("The original string is : " + test_str)    # initiali...
122
# Write a Pandas program to draw a horizontal and cumulative histograms plot of opening stock prices of Alphabet Inc. between two specific dates. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-4-3...
73
# Write a Python program to change the tag's contents and replace with the given string. from bs4 import BeautifulSoup html_doc = '<a href="http://example.com/">HTML<i>example.com</i></a>' soup = BeautifulSoup(html_doc, "lxml") tag = soup.a print("\nOriginal Markup:") print(tag) print("\nOriginal Markup with new tex...
43
# numpy.random.laplace() in Python # import numpy  import numpy as np import matplotlib.pyplot as plt    # Using numpy.random.laplace() method gfg = np.random.laplace(1.45, 15, 1000)    count, bins, ignored = plt.hist(gfg, 30, density = True) plt.show()
34
# Write a Pandas program to count the missing values 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,70012,np.nan,70013], 'purch_amt'...
52
# Write a NumPy program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2. import numpy as np array1 = np.array([0, 10, 20, 40, 60, 80]) print("Array1: ",array1) array2 = [10, 30, 40, 50, 70] print("Array2: ",array2) print("Unique valu...
63
# Write a Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list. from functools import reduce from operator import getitem def get(d, selectors): return reduce(getitem, selectors, d) users = { 'freddy': { 'name': { 'first': 'Fateh', ...
65
# Write a Python datetime to integer timestamp from datetime import datetime curr_dt = datetime.now() print("Current datetime: ", curr_dt) timestamp = int(round(curr_dt.timestamp())) print("Integer timestamp of current datetime: ",       timestamp)
29
# Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data. import numpy as np student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]) student_height...
81
# Write a NumPy program to split of an array of shape 4x4 it into two arrays along the second axis. import numpy as np x = np.arange(16).reshape((4, 4)) print("Original array:",x) print("After splitting horizontally:") print(np.hsplit(x, [2, 6]))
37
# Write a Python program to remove duplicate dictionary from a given list. def remove_duplicate_dictionary(list_color): result = [dict(e) for e in {tuple(d.items()) for d in list_color}] return result list_color = [{'Green': '#008000'}, {'Black': '#000000'}, {'Blue': '#0000FF'}, {'Green': '#008000'}] print ...
54
# Write a Python program to calculate the difference between the squared sum of first n natural numbers and the sum of squared first n natural numbers.(default value of number=2). def sum_difference(n=2): sum_of_squares = 0 square_of_sum = 0 for num in range(1, n+1): sum_of_squares += num * num ...
61
# Write a Python program to Filter out integers from float numpy array # Python code to demonstrate # filtering integers from numpy array # containing integers and float import numpy as np # initialising array ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0]) # printing initial array print ("initial array : ...
69
# Write a Python program to Retain records with N occurrences of K # Python3 code to demonstrate working of # Retain records with N occurrences of K # Using count() + list comprehension # initializing list test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)] # printing original list print("The original ...
111
# How to keep old content when Writing to Files in Python # Python program to keep the old content of the file # when using write.    # Opening the file with append mode file = open("gfg input file.txt", "a")    # Content to be added content = "\n\n# This Content is added through the program #"    # Writing the file ...
67
# Write a Pandas program to split the following dataset using group by on 'salesman_id' and find the first order date for each group. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,7...
60
# Write a Python program to remove the K'th element from a given list, print the new list. def remove_kth_element(n_list, L): return n_list[:L-1] + n_list[L:] n_list = [1,1,2,3,4,4,5,1] print("Original list:") print(n_list) kth_position = 3 result = remove_kth_element(n_list, kth_position) print("\nAfter remo...
51
# Write a Pandas program to import three datasheets from a given excel data (coalpublic2013.xlsx ) and combine in to a single dataframe. import pandas as pd import numpy as np df1 = pd.read_excel('E:\employee.xlsx',sheet_name=0) df2 = pd.read_excel('E:\employee.xlsx',sheet_name=1) df3 = pd.read_excel('E:\employee.xl...
46
# Write a Python program to rotate a given list by specified number of items to the right or left direction. nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("original List:") print(nums1) print("\nRotate the said list in left direction by 4:") result = nums1[3:] + nums1[:4] print(result) print("\nRotate the said list ...
96
# Sorting rows in pandas DataFrame in Python # import modules import pandas as pd    # create dataframe data = {'name': ['Simon', 'Marsh', 'Gaurav', 'Alex', 'Selena'],          'Maths': [8, 5, 6, 9, 7],          'Science': [7, 9, 5, 4, 7],         'English': [7, 4, 7, 6, 8]}    df = pd.DataFrame(data)    # Sort the d...
71
# Write a Python program find the common values that appear in two given strings. def intersection_of_two_string(str1, str2): result = "" for ch in str1: if ch in str2 and not ch in result: result += ch return result str1 = 'Python3' str2 = 'Python2.7' print("Original strings:") prin...
56
# Write a NumPy program to copy data from a given array to another array. import numpy as np x = np.array([24, 27, 30, 29, 18, 14]) print("Original array:") print(x) y = np.empty_like (x) y[:] = x print("\nCopy of the said array:") print(y)
43
# Write a Python program to create a new Arrow object, representing the "floor" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute. import arrow print(arrow.utcnow()) print("Hour ceiling:") print(arrow.utcnow().floor('hour'))...
51
# Write a Python program to add two strings as they are numbers (Positive integer values). Return a message if the numbers are string. def test(n1, n2): n1, n2 = '0' + n1, '0' + n2 if (n1.isnumeric() and n2.isnumeric()): return str(int(n1) + int(n2)) else: return 'Error in input!' print(t...
55
# Write a Pandas program to get the current date, oldest date and number of days between Current date and oldest date of Ufo dataset. import pandas as pd df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) print("\nCurrent date of Ufo ...
65
# Write a Python program to split a given list into specified sized chunks. def split_list(lst, n): result = list((lst[i:i+n] for i in range(0, len(lst), n))) return result nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83] print("Original list:") print(nums) n = 3 print("\nSplit the said list into equal...
67
# Write a Python program to Convert Character Matrix to single String # Python3 code to demonstrate working of  # Convert Character Matrix to single String # Using join() + list comprehension    # initializing list test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]    # printing original list print("The ...
93