code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to find the highest 3 values of corresponding keys in a dictionary. from heapq import nlargest my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} three_largest = nlargest(3, my_dict, key=my_dict.get) print(three_largest)
36
# Write a NumPy program to extract all the elements of the third column 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: Third column") print(arra_data[:,2])
35
# Write a Python Script to change name of a file to its timestamp import time import os       # Getting the path of the file f_path = "/location/to/gfg.png"    # Obtaining the creation time (in seconds) # of the file/folder (datatype=int) t = os.path.getctime(f_path)    # Converting the time to an epoch string # (the...
149
# Write a Pandas program to extract only punctuations 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.','c000,2','c0003', 'c0003#', 'c0004,'], 'year': ['year 1800','year 1700','year 2300',...
62
# Scraping Reddit with Python and BeautifulSoup # import module import requests from bs4 import BeautifulSoup
16
# Write a Python Program for Recursive Insertion Sort # Recursive Python program for insertion sort # Recursive function to sort an array using insertion sort def insertionSortRecursive(arr, n):     # base case     if n <= 1:         return     # Sort first n-1 elements     insertionSortRecursive(arr, n - 1)   ...
148
# How to add 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)    # add the polynomials rx = numpy.polynomial.polynomial.polyadd(px,qx)    # print the resultant polynomial ...
54
# Write a Python program to Program to accept the strings which contains all vowels # Python program to accept the strings # which contains all the vowels # Function for check if string # is accepted or not def check(string) :     string = string.lower()     # set() function convert "aeiou"     # string into se...
178
# Write a Pandas program to find integer index of rows with missing data in a given dataframe. import pandas as pd import numpy as np df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan ...
94
# Write a Pandas program to create the mean and standard deviation of the data of a given Series. import pandas as pd s = pd.Series(data = [1,2,3,4,5,6,7,8,9,5,3]) print("Original Data Series:") print(s) print("Mean of the said Data Series:") print(s.mean()) print("Standard deviation of the said Data Series:") print...
47
# Write a NumPy program to compute the inverse of a given matrix. import numpy as np m = np.array([[1,2],[3,4]]) print("Original matrix:") print(m) result = np.linalg.inv(m) print("Inverse of the said matrix:") print(result)
32
# Write a Pandas program to split a string of a column of a given DataFrame into multiple columns. import pandas as pd df = pd.DataFrame({ 'name': ['Alberto Franco','Gino Ann Mcneill','Ryan Parkes', 'Eesha Artur Hinton', 'Syed Wharton'], 'date_of_birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/200...
62
# Write a Python program to print all permutations with given repetition number of characters of a given string. from itertools import product def all_repeat(str1, rno): chars = list(str1) results = [] for c in product(chars, repeat = rno): results.append(c) return results print(all_repeat('xyz', 3)) pri...
48
# Write a Python program to Remove substring list from String # Python3 code to demonstrate working of  # Remove substring list from String # Using loop + replace()    # initializing string test_str = "gfg is best for all geeks"    # printing original string print("The original string is : " + test_str)    # initiali...
98
# Write a Python program to Convert Matrix to Custom Tuple Matrix # Python3 code to demonstrate working of  # Convert Matrix to Custom Tuple Matrix # Using zip() + loop    # initializing lists test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]    # printing original list print("The original list is : " + str(test_list))  ...
103
# Write a Python program to get the index of the first element which is greater than a specified element. def first_index(l1, n): return next(a[0] for a in enumerate(l1) if a[1] > n) 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 ...
103
# Write a Python dictionary, set and counter to check if frequencies can become same # Function to Check if frequency of all characters # can become same by one removal from collections import Counter    def allSame(input):            # calculate frequency of each character     # and convert string into dictionary   ...
100
# Write a Python program to configure the rounding to round to the nearest, with ties going to the nearest even integer. Use decimal.ROUND_HALF_EVEN import decimal print("Configure the rounding to round to the nearest, with ties going to the nearest even integer:") decimal.getcontext().prec = 1 decimal.getcontext().r...
51
# Write a Pandas program to capitalize all the string values of specified columns of a given DataFrame. import pandas as pd df = pd.DataFrame({ 'name': ['alberto','gino','ryan', 'Eesha', 'syed'], 'date_of_birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'age': [18.5, 21.2, 22....
53
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in table style and border around the table and not around the rows. 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.Data...
91
# Program to check if a string contains any special character in Python // C++ program to check if a string  // contains any special character    // import required packages #include <iostream>  #include <regex>  using namespace std;     // Function checks if the string  // contains any special character void run(str...
113
# Write a Python program to interchange first and last elements in a list # Python3 program to swap first # and last element of a list # Swap function def swapList(newList):     size = len(newList)           # Swapping     temp = newList[0]     newList[0] = newList[size - 1]     newList[size - 1] = temp           r...
63
# Write a Python program that accepts a word from the user and reverse it. word = input("Input a word to reverse: ") for char in range(len(word) - 1, -1, -1): print(word[char], end="") print("\n")
34
# Write a NumPy program to calculate mean across dimension, in a 2D numpy array. import numpy as np x = np.array([[10, 30], [20, 60]]) print("Original array:") print(x) print("Mean of each column:") print(x.mean(axis=0)) print("Mean of each row:") print(x.mean(axis=1))
38
# Write a Python program to Merging two Dictionaries # Python code to merge dict using update() method def Merge(dict1, dict2):     return(dict2.update(dict1))       # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # This return None print(Merge(dict1, dict2)) # changes made in dict2 print(dict2)
49
# Shortest 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=0minInd=0min=0str_rev=""print("Palindrome Substrings are:")for inn in range(len(sub_str)):    str_rev= sub_str[inn]    if reverse(str_...
69
# Repeat all the elements of a NumPy array of strings in Python # importing the module import numpy as np    # created array of strings arr = np.array(['Akash', 'Rohit', 'Ayush',                  'Dhruv', 'Radhika'], dtype = np.str) print("Original Array :") print(arr)    # with the help of np.char.multiply() # repea...
60
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in Heatmap style. import pandas as pd import numpy as np import seaborn as sns np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4...
61
# Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even in Python // C++ program for // the above approach #include <bits/stdc++.h> using namespace std; void sub_mat_even(int N) {   // Counter to initialize   // the values in 2-D array   int K = 1;       // To crea...
220
# Write a Python program to Permutation of a given string using inbuilt function # Function to find permutations of a given string from itertools import permutations    def allPermutations(str):              # Get all permutations of string 'ABC'      permList = permutations(str)         # print all permutations     ...
60
# Division Two Numbers Operator without using Division(/) operator num1=int(input("Enter first number:")) num2=int(input("Enter  second number:")) div=0 while num1>=num2:         num1=num1-num2         div+=1 print("Division of two number is ",div)
26
# Write a NumPy program to split an array of 14 elements into 3 arrays, each of which has 2, 4, and 8 elements in the original order. import numpy as np x = np.arange(1, 15) print("Original array:",x) print("After splitting:") print(np.split(x, [2, 6]))
43
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the maximum value in last two 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), columns=lis...
104
# Sorting objects of user defined class in Python print(sorted([1,26,3,9]))    print(sorted("Geeks foR gEEks".split(), key=str.lower))
14
# Write a Python program to rotate a Deque Object specified number (positive) 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 function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2). def insert_end(str): sub_str = str[-2:] return sub_str * 4 print(insert_end('Python')) print(insert_end('Exercises'))
39
# Write a Python program to numpy.nanmean() function # Python code to demonstrate the # use of numpy.nanmean import numpy as np     # create 2d array with nan value. arr = np.array([[20, 15, 37], [47, 13, np.nan]])     print("Shape of array is", arr.shape)     print("Mean of array without using nanmean function:",   ...
54
# Write a Python program to Convert Matrix to dictionary # Python3 code to demonstrate working of  # Convert Matrix to dictionary  # Using dictionary comprehension + range()    # initializing list test_list = [[5, 6, 7], [8, 3, 2], [8, 2, 1]]     # printing original list print("The original list is : " + str(test_lis...
81
# Write a Python program to Assign Frequency to Tuples # Python3 code to demonstrate working of  # Assign Frequency to Tuples # Using Counter() + items() + * operator + list comprehension from collections import Counter    # initializing list test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]    # p...
101
# Write a NumPy program to multiply a matrix by another matrix of complex numbers and create a new matrix of complex numbers. import numpy as np x = np.array([1+2j,3+4j]) print("First array:") print(x) y = np.array([5+6j,7+8j]) print("Second array:") print(y) z = np.vdot(x, y) print("Product of above two arrays:") p...
49
# 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 delete a specific item from a given doubly linked list. class Node(object): # Singly linked node def __init__(self, value=None, next=None, prev=None): self.value = value self.next = next self.prev = prev class doubly_linked_list(object): def __init__(s...
216
# Program to compute the area and perimeter of Hexagon import math print("Enter the length of the side:") a=int(input()) area=(3*math.sqrt(3)*math.pow(a,2))/2.0 perimeter=(6*a) print("Area of the Hexagon = ",area) print("Perimeter of the Hexagon = ",perimeter)
33
# Write a NumPy program to create a 5x5 matrix with row values ranging from 0 to 4. import numpy as np x = np.zeros((5,5)) print("Original array:") print(x) print("Row values ranging from 0 to 4.") x += np.arange(5) print(x)
39
# Write a Python program to Sum of tuple elements # Python3 code to demonstrate working of  # Tuple summation # Using list() + sum()    # initializing tup  test_tup = (7, 8, 9, 1, 10, 7)     # printing original tuple print("The original tuple is : " + str(test_tup))     # Tuple elements inversions # Using list() + su...
73
# Write a Python code to send a request to a web page and stop waiting for a response after a given number of seconds. In the event of times out of request, raise Timeout exception. import requests print("timeout = 0.001") try: r = requests.get('https://github.com/', timeout = 0.001) print(r.text) except req...
70
# Write a Pandas program to keep the valid entries of 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':[np.nan,np.nan,70002,np.nan,np.nan,70005,np.nan,70010,70003,70012,np.nan,np.nan], 'purch_amt...
50
# Write a Python program to sort an odd-even sort or odd-even transposition sort. def odd_even_transposition(arr: list) -> list: arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], a...
90
# Write a Python program to Convert Integer Matrix to String Matrix # Python3 code to demonstrate working of  # Convert Integer Matrix to String Matrix # Using str() + list comprehension    # initializing list test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]    # printing original list print("The original l...
92
# Write a Pandas program to check the equality of two given series. import pandas as pd nums1 = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]) nums2 = pd.Series([1, 8, 7, 5, 6, 5, 3, 4, 7, 1]) print("Original Series:") print(nums1) print(nums2) print("Check 2 series are equal or not?") print(nums1 == nums2)
55
# Write a Python program to round a Decimal value to the nearest multiple of 0.10, unless already an exact multiple of 0.05. Use decimal.Decimal from decimal import Decimal #Source: https://bit.ly/3hEyyY4 def round_to_10_cents(x): remainder = x.remainder_near(Decimal('0.10')) if abs(remainder) == Decimal('0....
65
# Remove all duplicates from a given string in Python from collections import OrderedDict     # Function to remove all duplicates from string  # and order does not matter  def removeDupWithoutOrder(str):         # set() --> A Set is an unordered collection      #         data type that is iterable, mutable,      #   ...
122
# Write a Python program to get the frequency of the elements in a list. import collections my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30] print("Original List : ",my_list) ctr = collections.Counter(my_list) print("Frequency of the elements in the List : ",ctr)
36
# Write a NumPy program to get the magnitude of a vector in NumPy. import numpy as np x = np.array([1,2,3,4,5]) print("Original array:") print(x) print("Magnitude of the vector:") print(np.linalg.norm(x))
29
# Find the sum of Even numbers using recursion def SumEven(num1,num2):    if num1>num2:        return 0    return num1+SumEven(num1+2,num2)num1=2print("Enter your Limit:")num2=int(input())print("Sum of all Even numbers in the given range is:",SumEven(num1,num2))
28
# Write a Python program to find the character position of Kth word from a list of strings # Python3 code to demonstrate working of # Word Index for K position in Strings List # Using enumerate() + list comprehension    # initializing list test_list = ["geekforgeeks", "is", "best", "for", "geeks"]    # printing origi...
112
# Write a Python program to find three integers which gives the sum of zero in a given array of integers using Binary Search (bisect). from bisect import bisect, bisect_left from collections import Counter class Solution: def three_Sum(self, nums): """ :type nums: List[int] :rtype: List[L...
196
# Write a Python program to accept a filename from the user and print the extension of that. filename = input("Input the Filename: ") f_extns = filename.split(".") print ("The extension of the file is : " + repr(f_extns[-1]))
38
# Write a Python program to sort an unsorted array numbers using Wiggle sort. def wiggle_sort(arra_nums): for i, _ in enumerate(arra_nums): if (i % 2 == 1) == (arra_nums[i - 1] > arra_nums[i]): arra_nums[i - 1], arra_nums[i] = arra_nums[i], arra_nums[i - 1] return arra_nums print("Input...
65
# Write a Python program to find the years where 25th of December be a Sunday between 2000 and 2150. '''Days of the week''' # Source:https://bit.ly/30NoXF8 from datetime import date from itertools import islice # xmasIsSunday :: Int -> Bool def xmasIsSunday(y): '''True if Dec 25 in the given year is a Sund...
300
# Write a Python program to concatenate elements of a list. color = ['red', 'green', 'orange'] print('-'.join(color)) print(''.join(color))
18
# Python Program to Calculate the Number of Digits and Letters in a String string=raw_input("Enter string:") count1=0 count2=0 for i in string: if(i.isdigit()): count1=count1+1 count2=count2+1 print("The number of digits is:") print(count1) print("The number of characters is:") print(count2)
37
# Write a Python program to form Bigrams of words in a given list of strings. def bigram_sequence(text_lst): result = [a for ls in text_lst for a in zip(ls.split(" ")[:-1], ls.split(" ")[1:])] return result text = ["Sum all the items in a list", "Find the second smallest number in a list"] print("Original li...
61
# Different ways to clear a list in Python # Python program to clear a list # using clear() method     # Creating list GEEK = [6, 0, 4, 1] print('GEEK before clear:', GEEK)     # Clearing list  GEEK.clear()  print('GEEK after clear:', GEEK) 
41
# Write a Python program to map two lists into a dictionary. keys = ['red', 'green', 'blue'] values = ['#FF0000','#008000', '#0000FF'] color_dictionary = dict(zip(keys, values)) print(color_dictionary)
26
# Write a Python program to find the list of words that are longer than n from a given list of words. def long_words(n, str): word_len = [] txt = str.split(" ") for x in txt: if len(x) > n: word_len.append(x) return word_len print(long_words(3, "The quick brown fox jumps over the...
53
# Python Program to Find All Connected Components using DFS in an Undirected Graph class Graph: def __init__(self): # dictionary containing keys that map to the corresponding vertex object self.vertices = {}   def add_vertex(self, key): """Add a vertex with the given key to the graph."...
476
# Print even numbers in given range using recursion def even(num1,num2):    if num1>num2:        return    print(num1,end=" ")    return even(num1+2,num2)num1=2print("Enter your Limit:")num2=int(input())print("All Even number given range are:")even(num1,num2)
25
# Write a NumPy program to calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to a given array. import numpy as np x = np.array([1, 3, 5, 7, 0]) print("Original array: ") print(x) r1 = np.ediff1d(x, to_begin=[0, 0], to_end=[200]) r2 = np.insert(np.append(np.diff(x...
70
# Write a Pandas program to check inequality over the index axis of a given dataframe and a given series. import pandas as pd df_data = pd.DataFrame({'W':[68,75,86,80,None],'X':[78,75,None,80,86], 'Y':[84,94,89,86,86],'Z':[86,97,96,72,83]}); sr_data = pd.Series([68, 75, 86, 80, None]) print("Original DataFrame:") p...
54
# Write a Python program to parse a given CSV string and get the list of lists of string values. Use csv.reader import csv csv_string = """1,2,3 4,5,6 7,8,9 """ print("Original string:") print(csv_string) lines = csv_string.splitlines() print("List of CSV formatted strings:") print(lines) reader = csv.reader(lines) p...
55
# Python Program to Construct a Tree & Perform Insertion, Deletion, Display class Tree: def __init__(self, data=None, parent=None): self.key = data self.children = [] self.parent = parent   def set_root(self, data): self.key = data   def add(self, node): self.childr...
257
# Write a Pandas program to find out the records where consumption of beverages per person average >=4 and Beverage Types is Beer, Wine, Spirits 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 sam...
83
# Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees of a specified year. import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') df2 = df.set_index(['hire_date']) result = df2["2005"] result
43
# Convert Text file to JSON in Python # Python program to convert text # file to JSON       import json       # the file to be converted to  # json format filename = 'data.txt'    # dictionary where the lines from # text will be stored dict1 = {}    # creating dictionary with open(filename) as fh:        for line in ...
108
# Write a Python program to generate a random color hex, a random alphabetical string, random value between two integers (inclusive) and a random multiple of 7 between 0 and 70. Use random.randint() import random import string print("Generate a random color hex:") print("#{:06x}".format(random.randint(0, 0xFFFFFF))) ...
92
# Write a Pandas program to create a Pivot table and find the region wise Television and Home Theater sold. import pandas as pd df = pd.read_excel('E:\SaleData.xlsx') table = pd.pivot_table(df,index=["Region", "Item"], values="Units") print(table.query('Item == ["Television","Home Theater"]'))
36
# How to set the tab size in Text widget in Tkinter in Python # Import Module from tkinter import *    # Create Object root = Tk()    # Set Geometry root.geometry("400x400")    # Execute Tkinter root.mainloop()
35
# Write a Python program to perform Counter arithmetic and set operations for aggregating results. import collections c1 = collections.Counter([1, 2, 3, 4, 5]) c2 = collections.Counter([4, 5, 6, 7, 8]) print('C1:', c1) print('C2:', c2) print('\nCombined counts:') print(c1 + c2) print('\nSubtraction:') print(c1 - c2)...
57
# Program to print the Solid Inverted Half Diamond Alphabet Pattern row_size=int(input("Enter the row size:"))for out in range(row_size,-(row_size+1),-1):    for in1 in range(1,abs(out)+1):        print(" ",end="")    for p in range(abs(out),row_size+1):        print((chr)(p+65),end="")    print("\r")
30
# Write a Pandas program to split a dataset to group by two columns and count by each row. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) orders_data = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013], 'purch_am...
55
# Write a NumPy program to add one polynomial to another, subtract one polynomial from another, multiply one polynomial by another and divide one polynomial by another. from numpy.polynomial import polynomial as P x = (10,20,30) y = (30,40,50) print("Add one polynomial to another:") print(P.polyadd(x,y)) print("Subt...
63
# Write a Python program to sort unsorted numbers using Patience sorting. #Ref.https://bit.ly/2YiegZB from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, ot...
127
# Write a Python program to Right and Left Shift characters in String # Python3 code to demonstrate working of  # Right and Left Shift characters in String # Using String multiplication + string slicing    # initializing string test_str = 'geeksforgeeks'    # printing original string print("The original string is : "...
111
# Write a Python program to Key with maximum unique values # Python3 code to demonstrate working of  # Key with maximum unique values # Using loop    # initializing dictionary test_dict = {"Gfg" : [5, 7, 5, 4, 5],              "is" : [6, 7, 4, 3, 3],               "Best" : [9, 9, 6, 5, 5]}    # printing original dict...
110
# Write a Python program to remove first specified number of elements from a given list satisfying a condition. def condition_match(x): return ((x % 2) == 0) def remove_items_con(data, N): ctr = 1 result = [] for x in data: if ctr > N or not condition_match(x): result.append(x) ...
76
# Write a Python program to print all positive numbers in a range # Python program to print positive Numbers in given range    start, end = -4, 19    # iterating each number in list for num in range(start, end + 1):            # checking condition     if num >= 0:         print(num, end = " ")
53
# Write a NumPy program to sort a given complex array using the real part first, then the imaginary part. import numpy as np complex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j] print("Original array:") print(complex_num) print("\nSorted a given complex array using the real part first, then the imaginary part.") p...
59
# Write a Pandas program to create a Pivot table and find number of adult male, adult female and children. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table('sex', 'who', aggfunc = 'count') print(result)
39
# Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array. import numpy as np x = np.array([[0, 10, 20], [20, 30, 40]]) print("Original array: ") print(x) print("Values bigger than 10 =", x[x>10]) print("Their indices are ", np.nonzero(x > 10))
52
# Find the sum of N numbers in an array arr=[] size = int(input("Enter the size of the array: ")) print("Enter the Element of the array:") for i in range(0,size):     num = float(input())     arr.append(num) sum=0.0 for j in range(0,size):             sum+= arr[j] print("sum of ",size," number : ",sum)
47
# Write a Pandas program to drop the rows 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,70012...
60
# Write a Python program to convert string element to integer inside a given tuple using lambda. def tuple_int_str(tuple_str): result = tuple(map(lambda x: (int(x[0]), int(x[2])), tuple_str)) return result tuple_str = (('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34')) print("Origin...
47
# Write a NumPy program to compute xy, element-wise where x, y are two given arrays. import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[1, 2], [1, 2]]) print("Array1: ") print(x) print("Array1: ") print(y) print("Result- x^y:") r1 = np.power(x, y) print(r1)
45
# Write a Python program to configure the rounding to round up and round down a given decimal value. Use decimal.Decimal import decimal print("Configure the rounding to round up:") decimal.getcontext().prec = 1 decimal.getcontext().rounding = decimal.ROUND_UP print(decimal.Decimal(30) / decimal.Decimal(4)) print("\nC...
69
# Write a Python program to Skew Nested Tuple Summation # Python3 code to demonstrate working of  # Skew Nested Tuple Summation # Using infinite loop    # initializing tuple test_tup = (5, (6, (1, (9, (10, None)))))    # printing original tuple print("The original tuple is : " + str(test_tup))    res = 0 while test_t...
77
# Write a NumPy program to count the number of "P" in a given array, element-wise. import numpy as np x1 = np.array(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str) print("\nOriginal Array:") print(x1) print("Number of ‘P’:") r = np.char.count(x1, "P") print(r)
39
# Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters. def count_k_dist(str1, k): str_len = len(str1) result = 0 ctr = [0] * 27 for i in range(0, str_len): dist_ctr = 0 ctr = [0] * 27 for j in range(i, str_len):...
107
# Write a Python program to get a list with n elements removed from the left, right. def drop_left_right(a, n = 1): return a[n:], a[:-n] nums = [1, 2, 3] print("Original list elements:") print(nums) result = drop_left_right(nums) print("Remove 1 element from left of the said list:") print(result[0]) print("Remove...
125
# Write a Pandas program to replace NaNs with median or mean of the specified columns 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...
66