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 output timestamp string would
# be recognizable by strptime() without
# format quantifers)
t_str = time.ctime(t)
# Converting the string to a time object
t_obj = time.strptime(t_str)
# Transforming the time object to a timestamp
# of ISO 8601 format
form_t = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)
# Since colon is an invalid character for a
# Windows file name Replacing colon with a
# similar looking symbol found in unicode
# Modified Letter Colon " " (U+A789)
form_t = form_t.replace(":", "꞉")
# Renaming the filename to its timestamp
os.rename(
f_path, os.path.split(f_path)[0] + '/' + form_t + os.path.splitext(f_path)[1]) | 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', 'year 1900', 'year 2200']
})
print("Original DataFrame:")
print(df)
def find_punctuations(text):
result = re.findall(r'[!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]*', text)
string="".join(result)
return list(string)
df['nonalpha']=df['company_code'].apply(lambda x: find_punctuations(x))
print("\nExtracting punctuation:")
print(df)
| 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)
# Insert last element at its correct position in sorted array.
last = arr[n - 1]
j = n - 2
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j >= 0 and arr[j] > last):
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = last
# Driver program to test insertion sort
if __name__ == '__main__':
A = [-7, 11, 6, 0, -3, 5, 10, 2]
n = len(A)
insertionSortRecursive(A, n)
print(A)
# Contributed by Harsh Valecha,
# Edited by Abraar Masud Nafiz. | 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
print(rx) | 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 set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set("aeiou")
# set() function convert empty
# dictionary into empty set
s = set({})
# looping through each
# character of the string
for char in string :
# Check for the character is present inside
# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels :
s.add(char)
else:
pass
# check the length of set s equal to length
# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels) :
print("Accepted")
else :
print("Not Accepted")
# Driver code
if __name__ == "__main__" :
string = "SEEquoiaL"
# calling function
check(string) | 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 Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'weight': [35, None, 33, 30, 31, None]},
index = ['t1', 't2', 't3', 't4', 't5', 't6'])
print("Original DataFrame:")
print(df)
index = df['weight'].index[df['weight'].apply(np.isnan)]
df_index = df.index.values.tolist()
print("\nInteger index of rows with missing data in 'weight' column of the said dataframe:")
print([df_index.index(i) for i in index])
| 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(s.std())
| 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/2002','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print("Original DataFrame:")
print(df)
df[["first", "middle", "last"]] = df["name"].str.split(" ", expand = True)
print("\nNew DataFrame:")
print(df)
| 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))
print(all_repeat('xyz', 2))
print(all_repeat('abcd', 4))
| 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)
# initializing sub list
sub_list = ["best", "all"]
# Remove substring list from String
# Using loop + replace()
for sub in sub_list:
test_str = test_str.replace(' ' + sub + ' ', ' ')
# printing result
print("The string after substring removal : " + test_str) | 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))
# initializing List elements
add_list = ['Gfg', 'is', 'best']
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
for e in ele:
res.append((idx, e))
# printing result
print("Matrix after conversion : " + str(res)) | 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 which is greater than",n,"in the said list:")
print(first_index(nums,n))
n = 21
print("\nIndex of the first element which is greater than",n,"in the said list:")
print(first_index(nums,n))
n = 80
print("\nIndex of the first element which is greater than",n,"in the said list:")
print(first_index(nums,n))
n = 55
print("\nIndex of the first element which is greater than",n,"in the said list:")
print(first_index(nums,n))
| 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
dict=Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same)>2:
print('No')
elif len (same)==2 and same[1]-same[0]>1:
print('No')
else:
print('Yes')
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == "__main__":
input = 'xxxyyzzt'
allSame(input) | 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().rounding = decimal.ROUND_HALF_EVEN
print(decimal.Decimal(10) / decimal.Decimal(4))
| 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.5, 22, 23]
})
print("Original DataFrame:")
print(df)
print("\nAfter capitalizing name column:")
df['name'] = list(map(lambda x: x.capitalize(), df['name']))
print(df)
| 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.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
print("\nDataframe - table style and border around the table and not around the rows:")
df.style.set_table_styles([{'selector':'','props':[('border','4px solid #7a7')]}])
| 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(string str)
{
// Make own character set
regex regx("[@_!#$%^&*()<>?/|}{~:]");
// Pass the string in regex_search
// method
if(regex_search(str, regx) == 0)
cout << "String is accepted";
else
cout << "String is not accepted.";
}
// Driver Code
int main()
{
// Enter the string
string str = "Geeks$For$Geeks";
// Calling run function
run(str);
return 0;
}
// This code is contributed by Yash_R | 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
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList)) | 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_rev).__eq__(sub_str[inn]): sub_str1.append(sub_str[inn]) print(sub_str1[p]) p +=1 flag = 1len2 = pif flag==1: min = len(sub_str1[0]) for inn in range(0,len2): len1 = len(sub_str1[inn]) if len1 < min: min=len1 minInd=inn print("Smallest palindrome Substring is ",sub_str1[minInd])else: print("No palindrome Found") | 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()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 3)
print("\nNew array :")
print(new_array) | 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), columns=list('BCDE'))],
axis=1)
print("Original array:")
print(df)
print("\nDataframe - Heatmap style:")
cm = sns.light_palette("red", as_cmap=True)
df.style.background_gradient(cmap='viridis')
| 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 create a 2-D array
// from to 1 to N*2
int A[N][N];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
A[i][j] = K;
K++;
}
}
// If found even we reverse
// the alternate row elements
// to get all diagonal elements
// as all even or all odd
if(N % 2 == 0)
{
for(int i = 0; i < N; i++)
{
if(i % 2 == 1)
{
int s = 0;
int l = N - 1;
// Reverse the row
while(s < l)
{
swap(A[i][s],
A[i][l]);
s++;
l--;
}
}
}
}
// Print the formed array
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
}
// Driver code
int main()
{
int N = 4;
// Function call
sub_mat_even(N);
}
// This code is contributed by mishrapriyanshu557 | 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
for perm in list(permList):
print (''.join(perm))
# Driver program
if __name__ == "__main__":
str = 'ABC'
allPermutations(str) | 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=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
def highlight_max(s):
'''
highlight the maximum in a Series green.
'''
is_max = s == s.max()
return ['background-color: green' if v else '' for v in is_max]
print("\nHighlight the maximum value in last two columns:")
df.style.apply(highlight_max,subset=pd.IndexSlice[:, ['D', 'E']])
| 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)
print("Deque before rotation:")
print(dq_object)
# Rotate once in positive direction
dq_object.rotate()
print("\nDeque after 1 positive rotation:")
print(dq_object)
# Rotate twice in positive direction
dq_object.rotate(2)
print("\nDeque after 2 positive rotations:")
print(dq_object)
| 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:",
np.mean(arr))
print("Using nanmean function:", np.nanmean(arr)) | 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_list))
# using dictionary comprehension for iteration
res = {idx + 1 : test_list[idx] for idx in range(len(test_list))}
# printing result
print("The constructed dictionary : " + str(res)) | 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)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).items()]
# printing results
print("Frequency Tuple list : " + str(res)) | 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:")
print(z)
| 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 original list is : " + str(test_list))
# flattening
temp = [ele for sub in test_list for ele in sub]
# joining to form column pairs
res = list(zip(*temp))
# printing result
print("The converted tuple list : " + str(res)) | 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__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, value):
# Append an item
new_item = Node(value, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.value
current = current.next
yield item_val
def print_foward(self):
for node in self.iter():
print(node)
def search_item(self, val):
for node in self.iter():
if val == node:
return True
return False
def delete(self, value):
# Delete a specific item
current = self.head
node_deleted = False
if current is None:
node_deleted = False
elif current.value == value:
self.head = current.next
self.head.prev = None
node_deleted = True
elif self.tail.value == value:
self.tail = self.tail.prev
self.tail.next = None
node_deleted = True
else:
while current:
if current.value == value:
current.prev.next = current.next
current.next.prev = current.prev
node_deleted = True
current = current.next
if node_deleted:
self.count -= 1
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
items.append_item('SQL')
print("Original list:")
items.print_foward()
items.delete("Java")
items.delete("Python")
print("\nList after deleting two items:")
items.print_foward()
| 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() + sum()
res = sum(list(test_tup))
# printing result
print("The summation of tuple elements are : " + str(res)) | 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 requests.exceptions.RequestException as e:
print(e)
print("\ntimeout = 1.0")
try:
r = requests.get('https://github.com/', timeout = 1.0)
print("Connected....!")
except requests.exceptions.RequestException as e:
print(e)
| 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':[np.nan,270.65,65.26,np.nan,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,np.nan],
'ord_date': [np.nan,'2012-09-10',np.nan,np.nan,'2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17',np.nan],
'customer_id':[np.nan,3001,3001,np.nan,3002,3001,3001,3004,3003,3002,3001,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("\nKeep the said DataFrame with valid entries:")
result = df.dropna(inplace=False)
print(result)
| 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], arr[i]
return arr
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
odd_even_transposition(nums)
print("Sorted order is:", nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
odd_even_transposition(nums)
print("Sorted order is:", nums)
| 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 list : " + str(test_list))
# using str() to convert each element to string
res = [[str(ele) for ele in sub] for sub in test_list]
# printing result
print("The data type converted Matrix : " + str(res)) | 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.05'):
return x
else:
return x - remainder
# Test code.
for x in range(80, 120):
y = Decimal(x) / Decimal('1E2')
print("{0} rounds to {1}".format(y, round_to_10_cents(y)))
| 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,
# and has no duplicate elements.
# "".join() --> It joins two adjacent elements in
# iterable with any symbol defined in
# "" ( double quotes ) and returns a
# single string
return "".join(set(str))
# Function to remove all duplicates from string
# and keep the order of characters same
def removeDupWithOrder(str):
return "".join(OrderedDict.fromkeys(str))
# Driver program
if __name__ == "__main__":
str = "geeksforgeeks"
print ("Without Order = ",removeDupWithoutOrder(str))
print ("With Order = ",removeDupWithOrder(str)) | 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 original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res)) | 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[List[int]]
"""
triplets = []
if len(nums) < 3:
return triplets
num_freq = Counter(nums)
nums = sorted(num_freq) # Sorted unique numbers
max_num = nums[-1]
for i, v in enumerate(nums):
if num_freq[v] >= 2:
complement = -2 * v
if complement in num_freq:
if complement != v or num_freq[v] >= 3:
triplets.append([v] * 2 + [complement])
# When all 3 numbers are different.
if v < 0: # Only when v is the smallest
two_sum = -v
# Lower/upper bound of the smaller of remainingtwo.
lb = bisect_left(nums, two_sum - max_num, i + 1)
ub = bisect(nums, two_sum // 2, lb)
for u in nums[lb : ub]:
complement = two_sum - u
if complement in num_freq and u != complement:
triplets.append([v, u, complement])
return triplets
nums = [-20, 0, 20, 40, -20, -40, 80]
s = Solution()
result = s.three_Sum(nums)
print(result)
nums = [1, 2, 3, 4, 5, -6]
result = s.three_Sum(nums)
print(result)
| 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 the array elements: ")
arra_nums = list(map(int, input().split()))
print("Original unsorted array:")
print(arra_nums)
print("The said array after applying Wiggle sort:")
print(wiggle_sort(arra_nums))
| 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 Sunday.'''
return 6 == date(y, 12, 25).weekday()
# main :: IO ()
def main():
'''Years between 2000 and 2150 with 25 December on a Sunday'''
xs = list(filter(
xmasIsSunday,
enumFromTo(2000)(2150)
))
total = len(xs)
print(
fTable(main.__doc__ + ':\n\n' + '(Total ' + str(total) + ')\n')(
lambda i: str(1 + i)
)(str)(index(xs))(
enumFromTo(0)(total - 1)
)
)
# GENERIC -------------------------------------------------
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
# index (!!) :: [a] -> Int -> a
def index(xs):
'''Item at given (zero-based) index.'''
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, "__getitem__")
) else next(islice(xs, n, None))
)
# unlines :: [String] -> String
def unlines(xs):
'''A single string formed by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
# FORMATTING ---------------------------------------------
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# MAIN --
if __name__ == '__main__':
main()
| 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 list:")
print(text)
print("\nBigram sequence of the said list:")
print(bigram_sequence(text))
| 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 lazy dog"))
| 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."""
vertex = Vertex(key)
self.vertices[key] = vertex
def get_vertex(self, key):
"""Return vertex object with the corresponding key."""
return self.vertices[key]
def __contains__(self, key):
return key in self.vertices
def add_edge(self, src_key, dest_key, weight=1):
"""Add edge from src_key to dest_key with given weight."""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
def does_edge_exist(self, src_key, dest_key):
"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
def add_undirected_edge(self, v1_key, v2_key, weight=1):
"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)
def does_undirected_edge_exist(self, v1_key, v2_key):
"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key
def add_neighbour(self, dest, weight):
"""Make this vertex point to dest with given edge weight."""
self.points_to[dest] = weight
def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
def get_weight(self, dest):
"""Get weight of edge from this vertex to dest."""
return self.points_to[dest]
def does_it_point_to(self, dest):
"""Return True if this vertex points to dest."""
return dest in self.points_to
def label_all_reachable(vertex, component, label):
"""Set component[v] = label for all v in the component containing vertex."""
label_all_reachable_helper(vertex, set(), component, label)
def label_all_reachable_helper(vertex, visited, component, label):
"""Set component[v] = label for all v in the component containing
vertex. Uses set visited to keep track of nodes alread visited."""
visited.add(vertex)
component[vertex] = label
for dest in vertex.get_neighbours():
if dest not in visited:
label_all_reachable_helper(dest, visited, component, label)
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('components')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_undirected_edge_exist(src, dest):
g.add_undirected_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'components':
component = dict.fromkeys(g, None)
label = 1
for v in g:
if component[v] is None:
label_all_reachable(v, component, label)
label += 1
max_label = label
for label in range(1, max_label):
print('Component {}:'.format(label),
[v.get_key() for v in component if component[v] == label])
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation == 'quit':
break | 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), 200), 0, [0, 0])
assert np.array_equiv(r1, r2)
print("Difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to the said array:")
print(r2)
| 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:")
print(df_data)
print("\nOriginal Series:")
print(sr_data)
print("\nCheck for inequality of the said series & dataframe:")
print(df_data.ne(sr_data, axis = 0))
| 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)
parsed_csv = list(reader)
print("\nList representation of the CSV file:")
print(parsed_csv)
| 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.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def remove(self):
parent = self.parent
index = parent.children.index(self)
parent.children.remove(self)
for child in reversed(self.children):
parent.children.insert(index, child)
child.parent = parent
def bfs_display(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')
tree = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('remove <data>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
new_node.parent = ref_node
ref_node.add(new_node)
elif operation == 'remove':
data = int(do[1])
to_remove = tree.search(data)
if tree == to_remove:
if tree.children == []:
tree = None
else:
leaf = tree.children[0]
while leaf.children != []:
leaf = leaf.children[0]
leaf.parent.children.remove(leaf)
leaf.parent = None
leaf.children = tree.children
tree = leaf
else:
to_remove.remove()
elif operation == 'display':
if tree is not None:
print('BFS traversal display: ', end='')
tree.bfs_display()
print()
else:
print('Tree is empty.')
elif operation == 'quit':
break | 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 sample data:")
print(w_a_con.head())
print("\nThe world alcohol consumption details: average consumption of \nbeverages per person >=4 and Beverage Types is Beer:")
print(w_a_con[(w_a_con['Display Value'] >= 4) & ((w_a_con['Beverage Types'] == 'Beer') | (w_a_con['Beverage Types'] == 'Wine')| (w_a_con['Beverage Types'] == 'Spirits'))].head(10))
| 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 fh:
# reads each line and trims of extra the spaces
# and gives only the valid words
command, description = line.strip().split(None, 1)
dict1[command] = description.strip()
# creating json file
# the JSON file is named as test1
out_file = open("test1.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)
out_file.close() | 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)))
print("\nGenerate a random alphabetical string:")
max_length = 255
s = ""
for i in range(random.randint(1, max_length)):
s += random.choice(string.ascii_letters)
print(s)
print("Generate a random value between two integers, inclusive:")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print("Generate a random multiple of 7 between 0 and 70:")
print(random.randint(0, 10) * 7)
| 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)
print('\nIntersection (taking positive minimums):')
print(c1 & c2)
print('\nUnion (taking maximums):')
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_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': ['2012-10-05','2012-09-10','2012-10-05','2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print("Original Orders DataFrame:")
print(orders_data)
print("\nGroup by two columns and count by each row:")
result = orders_data.groupby(['salesman_id','customer_id']).size().reset_index().groupby(['salesman_id','customer_id'])[[0]].max()
print(result)
| 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("Subtract one polynomial from another:")
print(P.polysub(x,y))
print("Multiply one polynomial by another:")
print(P.polymul(x,y))
print("Divide one polynomial by another:")
print(P.polydiv(x,y))
| 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, other):
return self[-1] == other[-1]
def patience_sort(collection: list) -> list:
stacks = []
# sort into stacks
for element in collection:
new_stacks = Stack([element])
i = bisect_left(stacks, new_stacks)
if i != len(stacks):
stacks[i].append(element)
else:
stacks.append(new_stacks)
# use a heap-based merge to merge stack efficiently
collection[:] = merge(*[reversed(stack) for stack in stacks])
return collection
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
patience_sort(nums)
print("Sorted order is:", nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
patience_sort(nums)
print("Sorted order is:", nums)
| 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 : " + test_str)
# initializing right rot
r_rot = 7
# initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = (test_str * 3)[len(test_str) + r_rot - l_rot :
2 * len(test_str) + r_rot - l_rot]
# printing result
print("The string after rotation is : " + str(res)) | 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 dictionary
print("The original dictionary is : " + str(test_dict))
max_val = 0
max_key = None
for sub in test_dict:
# test for length using len()
# converted to set for duplicates removal
if len(set(test_dict[sub])) > max_val:
max_val = len(set(test_dict[sub]))
max_key = sub
# printing result
print("Key with maximum unique values : " + str(max_key)) | 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)
else:
ctr = ctr + 1
return result
nums = [3,10,4,7,5,7,8,3,3,4,5,9,3,4,9,8,5]
N = 4
print("Original list:")
print(nums)
print("\nRemove first 4 even numbers from the said list:")
print(remove_items_con(nums, N))
| 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.")
print(np.sort_complex(complex_num))
| 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,np.nan,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("\nDrop the rows where at least one element is missing:")
result = df.dropna()
print(result)
| 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("Original tuple values:")
print(tuple_str)
print("\nNew tuple values:")
print(tuple_int_str(tuple_str))
| 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("\nConfigure the rounding to round down:")
decimal.getcontext().prec = 3
decimal.getcontext().rounding = decimal.ROUND_DOWN
print(decimal.Decimal(30) / decimal.Decimal(4))
print("\nConfigure the rounding to round up:")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP))
print("\nConfigure the rounding to round down:")
print(decimal.Decimal('8.325').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN))
| 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_tup:
res += test_tup[0]
# assigning inner tuple as original
test_tup = test_tup[1]
# printing result
print("Summation of 1st positions : " + str(res)) | 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):
if(ctr[ord(str1[j]) - 97] == 0):
dist_ctr += 1
ctr[ord(str1[j]) - 97] += 1
if(dist_ctr == k):
result += 1
if(dist_ctr > k):
break
return result
str1 = input("Input a string (lowercase alphabets):")
k = int(input("Input k: "))
print("Number of substrings with exactly", k, "distinct characters : ", end = "")
print(count_k_dist(str1, k))
| 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 1 element from right of the said list:")
print(result[1])
nums = [1, 2, 3, 4]
print("\nOriginal list elements:")
print(nums)
result = drop_left_right(nums,2)
print("Remove 2 elements from left of the said list:")
print(result[0])
print("Remove 2 elements from right of the said list:")
print(result[1])
nums = [1, 2, 3, 4, 5, 6]
print("\nOriginal list elements:")
print(nums)
result = drop_left_right(nums)
print("Remove 7 elements from left of the said list:")
print(result[0])
print("Remove 7 elements from right of the said list:")
print(result[1])
| 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,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("Using median in purch_amt to replace NaN:")
df['purch_amt'].fillna(df['purch_amt'].median(), inplace=True)
print(df)
print("Using mean to replace NaN:")
df['sale_amt'].fillna(int(df['sale_amt'].mean()), inplace=True)
print(df)
| 66 |
Subsets and Splits