code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array.
import numpy as np
m = np.mat("3 -2;1 0")
print("Original matrix:")
print("a\n", m)
w, v = np.linalg.eig(m)
print( "Eigenvalues of the said matrix",w)
print( "Eigenvectors of the said matrix",v)
| 46 |
# Write a NumPy program to create a NumPy array of 10 integers from a generator.
import numpy as np
iterable = (x for x in range(10))
print(np.fromiter(iterable, np.int))
| 29 |
# Write a Pandas program to extract year between 1800 to 2200 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'],
'year': ['year 1800','year 1700','year 23... | 68 |
# Program to print window pattern in Python
// C++ program to print the pattern
// hollow square with plus inside it
// window pattern
#include <bits/stdc++.h>
using namespace std;
// Function to print pattern n means
// number of rows which we want
void window_pattern (int n)
{
int c, d;
// If n ... | 235 |
# Print the frequency of all numbers in an array
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
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)
for i in range(0, size):
if(arr[i]>=max):
max=arr[i]... | 66 |
# Write a Python program to count the even, odd numbers in a given array of integers using Lambda.
array_nums = [1, 2, 3, 5, 7, 8, 9, 10]
print("Original arrays:")
print(array_nums)
odd_ctr = len(list(filter(lambda x: (x%2 != 0) , array_nums)))
even_ctr = len(list(filter(lambda x: (x%2 == 0) , array_nums)))
print("\... | 70 |
# Write a Python program to pack consecutive duplicates of a given list elements into sublists.
from itertools import groupby
def pack_consecutive_duplicates(l_nums):
return [list(group) for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print("Original list:")
print(n... | 63 |
# Python Program to Print all Numbers in a Range Divisible by a Given Number
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i) | 36 |
# Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix.
import numpy as np
nums = np.random.randint(0,4,(6,3))
print("Original vector:")
print(nums)
new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1)
result = nums[~new_nums]
print("\nRows with unequal values:")
p... | 40 |
# Write a Pandas program to find which years have all non-zero values and which years have any non-zero values from world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(w_a_con.head()... | 59 |
# Write a NumPy program to collapse a 3-D array into one dimension array.
import numpy as np
x = np.eye(3)
print("3-D array:")
print(x)
f = np.ravel(x, order='F')
print("One dimension array:")
print(f)
| 32 |
# Write a Python program to Remove Dictionary Key Words
# Python3 code to demonstrate working of
# Remove Dictionary Key Words
# Using split() + loop + replace()
# initializing string
test_str = 'gfg is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializ... | 97 |
# Write a Python program to create a new deque with three items and iterate over the deque's elements.
from collections import deque
dq = deque('aeiou')
for element in dq:
print(element)
| 31 |
# numpy.squeeze() in Python
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])
print ("Input array : ", in_arr)
print("Shape of input array : ", in_arr.shape)
out_arr = geek.squeeze(in_arr)
print ("output squeezed array : ", out_... | 53 |
# Write a Python program to Find missing and additional values in two lists
# Python program to find the missing
# and additional elements
# examples of lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
# prints the missing and additional elements in list2
print("Missing values in second list:", (set(... | 86 |
# Write a Numpy program to test whether numpy array is faster than Python list or not.
import time
import numpy as np
SIZE = 200000
list1 = range(SIZE)
list2 = range(SIZE)
arra1 = np.arange(SIZE)
arra2 = np.arange(SIZE)
start_list = time.time()
result=[(x,y) for x,y in zip(list1,list2)]
print("Time to aggregates e... | 68 |
# Change data type of given numpy array in Python
# importing the numpy library as np
import numpy as np
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
# Print the array
print(arr) | 38 |
# Program to Find the reverse of a given number
num=int(input("Enter a number:"))
num2=0
while(num!=0):
rem=num%10
num=int(num/10)
num2=num2*10+rem
print("The reverse of the number is",num2)
| 24 |
# Write a Pandas program to extract email from a specified column of string type of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'name_email': ['Alberto Franco [email protected]','Gino Mcneill [email protected]','Ryan Parkes [email protected]... | 70 |
# 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 |
# Define a class named American and its subclass NewYorker.
:
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
print anAmerican
print aNewYorker
| 27 |
# Write a Pandas program to calculate the number of characters in each word in a given series.
import pandas as pd
series1 = pd.Series(['Php', 'Python', 'Java', 'C#'])
print("Original Series:")
print(series1)
result = series1.map(lambda x: len(x))
print("\nNumber of characters in each word in the said series:")
prin... | 47 |
# Create a list from rows in Pandas dataframe 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, 5000, 15... | 43 |
# Write a Python program to Row-wise element Addition in Tuple Matrix
# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing ori... | 109 |
# Write a NumPy program to round elements of the array to the nearest integer.
import numpy as np
x = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0])
print("Original array:")
print(x)
x = np.rint(x)
print("Round elements of the array to the nearest integer:")
print(x)
| 44 |
# Python Program to Find the Number of Nodes in a Binary Tree
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder(self):
if self.left is not None:
self.... | 236 |
# Write a Python program to get string representing the date, controlled by an explicit format string.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nString representing the date, controlled by an explicit format string:")
print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S'))
print(arrow.... | 41 |
# Write a Pandas program to create a bar plot of the trading volume of Alphabet Inc. stock 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-30') ... | 74 |
# Given variables x=30 and y=20, write a Python program to print "30+20=50".
x = 30
y = 20
print("\n%d+%d=%d" % (x, y, x+y))
print()
| 25 |
# Python Program to Count Number of Non Leaf Nodes of a given Tree
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
... | 191 |
# Write a Python program to remove spaces from dictionary keys.
student_list = {'S 001': ['Math', 'Science'], 'S 002': ['Math', 'English']}
print("Original dictionary: ",student_list)
student_dict = {x.translate({32: None}): y for x, y in student_list.items()}
print("New dictionary: ",student_dict)
| 37 |
# Write a Python Program for Comb Sort
# Python program for implementation of CombSort
# To find next gap from current
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10)/13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
... | 190 |
# Write a Python program to insert an item in front of a given doubly linked list.
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)... | 157 |
# Program to Print series 1,2,8,16,32...n
n=int(input("Enter the range of number(Limit):"))i=1while i<=n: print(i,end=" ") i*=2 | 15 |
# Check whether number is Evil Number or Not
num=int(input("Enter a number:"))
one_c=0
while num!=0:
if num%2==1:
one_c+=1
num//=2
if one_c%2==0:
print("It is an Evil Number.")
else:
print("It is Not an Evil Number.") | 33 |
# Write a Pandas program to create a dataframe and set a title or name of the index 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... | 88 |
# Write a Python program to find the index position of the largest value smaller than a given number in a sorted list using Binary Search (bisect).
from bisect import bisect_left
def Binary_Search(l, x):
i = bisect_left(l, x)
if i:
return (i-1)
else:
return -1
nums = [1, 2, 3, 4,... | 82 |
# Linear Search Program in C | C++ | Java | Python
arr=[]
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)
search_elm=int(input("Enter the search element: "))
found=0
for i in range(size):
if arr[i]==... | 61 |
# Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length.
def check_string(s):
messg = []
if not any(x.isupper() for x in s):
messg.append('String must have 1 upper case character.')
if not any(x.islower() for x in s):
... | 94 |
# Write a Python program to count the frequency of the elements of a given unordered list.
from itertools import groupby
uno_list = [2,1,3,8,5,1,4,2,3,4,0,8,2,0,8,4,2,3,4,2]
print("Original list:")
print(uno_list)
uno_list.sort()
print(uno_list)
print("\nSort the said unordered list:")
print(uno_list)
print("\nFreq... | 53 |
# Write a Python program to remove an element from a given list.
student = ['Ricky Rivera', 98, 'Math', 90, 'Science']
print("Original list:")
print(student)
print("\nAfter deleting an element:, using index of the element:")
del(student[0])
print(student)
| 35 |
# Implementation of XOR Linked List in Python
# import required module
import ctypes
# create node class
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
... | 744 |
# Write a Python program to count positive and negative numbers in a list
# Python program to count positive and negative numbers in a List
# list of numbers
list1 = [10, -21, 4, -45, 66, -93, 1]
pos_count, neg_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
... | 82 |
# Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters.
def to_uppercase(str1):
num_upper = 0
for letter in str1[:4]:
if letter.upper() == letter:
num_upper += 1
if num_upper >= 2:
return s... | 52 |
# Write a Python program to find the list with maximum and minimum length.
def max_length_list(input_list):
max_length = max(len(x) for x in input_list )
max_list = max(input_list, key = len)
return(max_length, max_list)
def min_length_list(input_list):
min_length = min(len(x) for x in input_list )
... | 139 |
# Write a Python program to read a given string character by character and compress repeated character by storing the length of those character(s).
from itertools import groupby
def encode_str(input_str):
return [(len(list(n)), m) for m,n in groupby(input_str)]
str1 = "AAASSSSKKIOOOORRRREEETTTTAAAABBBBBBDDDDD"... | 53 |
# Program to convert binary to octal using while loop
print("Enter a binary number: ")
binary=int(input());
octal = 0
decimal = 0
i = 0
while (binary != 0):
decimal = decimal + (binary % 10) * pow (2, i)
i+=1
binary = binary // 10
i = 1
while (decimal != 0):
octal = octal + (decimal % 8) * i
... | 75 |
# Write a Python program to perform an action if a condition is true.
n=1
if n == 1:
print("\nFirst day of a Month!")
print()
| 25 |
# Write a Pandas program to join the two dataframes with matching records from both sides where available.
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
... | 89 |
# Write a Python program to Combinations of sum with tuples in tuple list
# Python3 code to demonstrate working of
# Summation combination in tuple lists
# Using list comprehension + combinations
from itertools import combinations
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]
# printing origi... | 100 |
# Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x2 matrix representing cartesian coordinates.
import numpy as np
z= np.random.random((10,2))
x,y = z[:,0], z[:,1]
r = np.sqrt(x**2+y**2)
t = np.arctan2(y,x)
print(r)
print(t)
| 38 |
# Write a Python program to Find Mean of a List of Numpy Array
# Python code to find mean of every numpy array in list
# Importing module
import numpy as np
# List Initialization
Input = [np.array([1, 2, 3]),
np.array([4, 5, 6]),
np.array([7, 8, 9])]
# Output list initialization
Output = []... | 66 |
# Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n):
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
| 35 |
# Convert alternate characters to capital letters
str=input("Enter the String:")
j=0
newStr=""
for i in range(len(str)):
if j%2==1:
if str[i]>='A' and str[i]<='Z' :
ch=chr(ord(str[i])+32)
newStr=newStr+ch
else:
newStr=newStr+str[i]
else:
if str[i] >... | 52 |
# Write a Python program to split a list based on first character of word.
from itertools import groupby
from operator import itemgetter
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
... | 39 |
# Write a NumPy program to count the lowest index 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("count the lowest index of ‘P’:")
r = np.char.find(x1, "P")
print(r)
| 43 |
# Write a Python program to list home directory without absolute path.
import os.path
print(os.path.expanduser('~'))
| 15 |
# Write a NumPy program to convert a Python dictionary to a NumPy ndarray.
import numpy as np
from ast import literal_eval
udict = """{"column0":{"a":1,"b":0.0,"c":0.0,"d":2.0},
"column1":{"a":3.0,"b":1,"c":0.0,"d":-1.0},
"column2":{"a":4,"b":1,"c":5.0,"d":-1.0},
"column3":{"a":3.0,"b":-1.0,"c":-1.0,"d":-1.... | 56 |
# Write a NumPy program to create a 3x3 identity matrix.
import numpy as np
array_2D=np.identity(3)
print('3x3 matrix:')
print(array_2D)
| 19 |
# Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it.
import numpy as np
import os
x = np.arange(10)
y = np.arange(11, 20)
print("Original arrays:")
print(x)
print(y)
np.savez('temp_arra.npz', x=x, y=y)
print("Load arrays from the 'temp_arra.npz' file:")
... | 60 |
# Write a Python program to format a number with a percentage.
x = 0.25
y = -0.25
print("\nOriginal Number: ", x)
print("Formatted Number with percentage: "+"{:.2%}".format(x));
print("Original Number: ", y)
print("Formatted Number with percentage: "+"{:.2%}".format(y));
print()
| 37 |
# Write a Python program to compute the sum of non-zero groups (separated by zeros) of a given list of numbers.
def test(lst):
result = []
ele_val = 0
for digit in lst:
if digit == 0:
if ele_val != 0:
result.append(ele_val)
ele_val = 0
else:
... | 76 |
# Write a Python program to Multiply 2d numpy array corresponding to 1d array
# Python code to demonstrate
# multiplication of 2d array
# with 1d array
import numpy as np
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
ini_array2 = np.array([0, 2, 3])
# printing initial arrays
print("initial array",... | 72 |
# Execute a String of Code in Python
# Python program to illustrate use of exec to
# execute a given code as string.
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
... | 54 |
# Python Program to Form a Dictionary from an Object of a Class
class A(object):
def __init__(self):
self.A=1
self.B=2
obj=A()
print(obj.__dict__) | 21 |
# Write a Pandas program to create a Pivot table and find the probability of survival by class, gender, solo boarding and port of embarkation.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', ['sex' , 'alone' ], [ 'embark_town', 'class' ])
print(result)
| 48 |
# Python Program to Generate all the Divisors of an Integer
n=int(input("Enter an integer:"))
print("The divisors of the number are:")
for i in range(1,n+1):
if(n%i==0):
print(i) | 26 |
# Program to convert Decimal to Hexadecimal
i=0
dec=int(input("Enter Decimal number: "))
Hex=['0']*50
while dec!=0:
rem=dec%16;
#Convert Integer to char
if rem<10:
Hex[i]=chr(rem+48)#48 Ascii=0
i+=1
else:
Hex[i]=chr(rem+55) #55 Ascii=7
i+=1
dec//=16
print("Hexadeci... | 39 |
# How to access different rows of a multidimensional NumPy array in Python
# Importing Numpy module
import numpy as np
# Creating a 3X3 2-D Numpy array
arr = np.array([[10, 20, 30],
[40, 5, 66],
[70, 88, 94]])
print("Given Array :")
print(arr)
# Access the First and Last row... | 59 |
# Write a Python program to count number of items in a dictionary value that is a list.
dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']}
ctr = sum(map(len, dict.values()))
print(ctr)
| 32 |
# Write a Python program to extract the nth element from a given list of tuples.
def extract_nth_element(test_list, n):
result = [x[n] for x in test_list]
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print ("Original list:... | 84 |
# Write a Pandas program to add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit.
import pandas as pd
nums = {'amount': ['10', '250', '3000', '40000', '500000']}
print("Original dataframe:")
df = pd.DataFrame(nums)
print(df)
print("\nAdd leading zeros:")
df['amoun... | 55 |
# Write a Python program to Add Space between Potential Words
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using loop + join()
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
r... | 109 |
# Program to display a lower triangular matrix
# 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.append([int(j) for j... | 71 |
# Write a Pandas program to check whether only space is present in a given column of a DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF ', ' ', 'abcd', ' '],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 2333... | 57 |
# Write a Python program to chose specified number of colours from three different colours and generate all the combinations with repetitions.
from itertools import combinations_with_replacement
def combinations_colors(l, n):
return combinations_with_replacement(l,n)
l = ["Red","Green","Blue"]
print("Original ... | 55 |
# Write a Python program to Sort dictionaries list by Key’s Value list index
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda
# initializing lists
test_list = [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10},
{"Gfg" : [2, 0, 3], "is" : ... | 130 |
# Write a Python program to convert a string to a list.
import ast
color ="['Red', 'Green', 'White']"
print(ast.literal_eval(color))
| 19 |
# Write a Python program to remove a specified column from a given nested list.
def remove_column(nums, n):
for i in nums:
del i[n]
return nums
list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
n = 0
print("Original Nested list:")
print(list1)
print("After removing 1st column:")
print(remove_column(list1, n))
... | 74 |
# Write a NumPy program to count a given word in each row of a given array of string values.
import numpy as np
str1 = np.array([['Python','NumPy','Exercises'],
['Python','Pandas','Exercises'],
['Python','Machine learning','Python']])
print("Original array of string values:")
pri... | 49 |
# Write a Python program that reads a given expression and evaluates it.
#https://bit.ly/2lxQysi
import re
print("Input number of data sets:")
class c(int):
def __add__(self,n):
return c(int(self)+int(n))
def __sub__(self,n):
return c(int(self)-int(n))
def __mul__(self,n):
return ... | 47 |
# Write a Python function that takes a list of words and return the longest word and the length of the longest one.
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result = find_longest_... | 52 |
# Write a Pandas program to find out the alcohol consumption of a given year from the 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("\nThe world alcohol con... | 59 |
# Write a Python program to find missing and additional values in two lists.
list1 = ['a','b','c','d','e','f']
list2 = ['d','e','f','g','h']
print('Missing values in second list: ', ','.join(set(list1).difference(list2)))
print('Additional values in second list: ', ','.join(set(list2).difference(list1)))
| 34 |
# Write a Python program to insert an element at a specified position into a given list.
def insert_spec_position(x, n_list, pos):
return n_list[:pos-1]+[x]+n_list[pos-1:]
n_list = [1,1,2,3,4,4,5,1]
print("Original list:")
print(n_list)
kth_position = 3
x = 12
result = insert_spec_position(x, n_list, kth_positi... | 52 |
# Write a Pandas program to calculate the frequency counts of each unique value of a given series.
import pandas as pd
import numpy as np
num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40)))
print("Original Series:")
print(num_series)
print("Frequency of each unique value of the said s... | 47 |
# Write a Python program to find smallest window that contains all characters of a given string.
from collections import defaultdict
def find_sub_string(str):
str_len = len(str)
# Count all distinct characters.
dist_count_char = len(set([x for x in str]))
ctr, start_pos, start_pos_i... | 121 |
# Write a NumPy program to get the block-sum (block size is 5x5) from a given array of shape 25x25.
import numpy as np
arra1 = np.ones((25,25))
k = 5
print("Original arrays:")
print(arra1)
result = np.add.reduceat(np.add.reduceat(arra1, np.arange(0, arra1.shape[0], k), axis=0),
... | 51 |
# How to Build Web scraping bot in Python
# These are the imports to be made
import time
from selenium import webdriver
from datetime import datetime | 27 |
# Python Program to Find the Second Largest Number in a List Using Bubble Sort
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
... | 43 |
# Write a NumPy program to compute the line graph of a set of data.
import numpy as np
import matplotlib.pyplot as plt
arr = np.random.randint(1, 50, 10)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
| 40 |
# Write a Pandas program to create a histograms plot of opening, closing, high, low 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-9-30') ... | 75 |
# Create Pandas Series using NumPy functions in Python
# import pandas and numpy
import pandas as pd
import numpy as np
# series with numpy linspace()
ser1 = pd.Series(np.linspace(3, 33, 3))
print(ser1)
# series with numpy linspace()
ser2 = pd.Series(np.linspace(1, 100, 10))
print("\n", ser2)
| 45 |
# Write a Python program to find the index of the first element in the given list that satisfies the provided testing function.
def find_index(nums, fn):
return next(i for i, x in enumerate(nums) if fn(x))
print(find_index([1, 2, 3, 4], lambda n: n % 2 == 1))
| 46 |
# Write a Python program to remove a tag from a given tree of html document and destroy it and its contents.
from bs4 import BeautifulSoup
html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>'
soup = BeautifulSoup(html_content, "lxml")
print("Original Markup:")
a_tag = soup.a
print... | 47 |
# Write a Python program to append the same value /a list multiple times to a list/list-of-lists.
print("Add a value(7), 5 times, to a list:")
nums = []
nums += 5 * ['7']
print(nums)
nums1 = [1,2,3,4]
print("\nAdd 5, 6 times, to a list:")
nums1 += 6 * [5]
print(nums1)
print("\nAdd a list, 4 times, to a list of lists... | 88 |
# Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
def last(n):
return n[-1]
def sort(tuples):
return sorted(tuples, key=last)
a=input("Enter a list of tuples:")
print("Sorted:")
print(sort(a)) | 35 |
# Write a Python program to create a shallow copy of a given dictionary. Use copy.copy
import copy
nums_x = {"a":1, "b":2, 'cc':{"c":3}}
print("Original dictionary: ", nums_x)
nums_y = copy.copy(nums_x)
print("\nCopy of the said list:")
print(nums_y)
print("\nChange the value of an element of the original dictionary:... | 91 |
# Write a Python program to sort each sublist of strings in a given list of lists.
def sort_sublists(input_list):
result = list(map(sorted, input_list))
return result
color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]]
print("\nOriginal list:")
print(color1)
print("\nAfter sor... | 48 |
# Write a Pandas program to create a horizontal stacked bar plot of opening, closing 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-30')... | 74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.