code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Pandas program to select rows by filtering on one or more column(s) in a multi-index dataframe.
import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan 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, 37, 33, 30, 31, 32],
'tcode': ['t1', 't2', 't3', 't4', 't5', 't6']})
print("Original DataFrame:")
print(df)
print("\nCreate MultiIndex on 'tcode' and 'school_code':")
df = df.set_index(['tcode', 'school_code'])
print(df)
print("\nSelect rows(s) from 'tcode' column:")
print(df.query("tcode == 't2'"))
print("\nSelect rows(s) from 'school_code' column:")
print(df.query("school_code == 's001'"))
print("\nSelect rows(s) from 'tcode' and 'scode' columns:")
print(df.query(("tcode == 't1'") and ("school_code == 's001'")))
| 106 |
# Get n-smallest values from a particular column in Pandas DataFrame in Python
# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
df.head(10) | 29 |
# Program to convert Days into years, months and Weeks
days=int(input("Enter Day:"))
years =(int) (days / 365)
weeks =(int) (days / 7)
months =(int) (days / 30)
print("Days to Years:",years)
print("Days to Weeks:",weeks)
print("Days to Months:",months) | 36 |
# Write a Python program to find tags by CSS class in a given html document.
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a class="sister" href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from
w3resource.com</a></p>
<a class="sister" href="http://example.com/lacie" id="link1">Lacie</a>
<a class="sister" href="http://example.com/tillie" id="link2">Tillie</a>
</body>
</html>
"""
soup = BeautifulSoup(html_doc,"lxml")
print("\nTags by CSS class:")
print(soup.select(".sister"))
| 173 |
# Write a Pandas program to create a Pivot table and calculate how many women and men were in a particular cabin class.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index=['sex'], columns=['pclass'], values='survived', aggfunc='count')
print(result)
| 41 |
# Python Program to Check Whether a Given Year is a Leap Year
year=int(input("Enter year to be checked:"))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!)
else:
print("The year isn't a leap year!) | 36 |
# Write a Pandas program create a series with a PeriodIndex which represents all the calendar month periods in 2029 and 2031. Also print the values for all periods in 2030.
import pandas as pd
import numpy as np
pi = pd.Series(np.random.randn(36),
pd.period_range('1/1/2029',
'12/31/2031', freq='M'))
print("PeriodIndex which represents all the calendar month periods in 2029 and 2030:")
print(pi)
print("\nValues for all periods in 2030:")
print(pi['2030'])
| 65 |
# Write a Python program to remove duplicates from a list of lists.
import itertools
num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
print("Original List", num)
num.sort()
new_num = list(num for num,_ in itertools.groupby(num))
print("New List", new_num)
| 41 |
# Write a Python program to count number of occurrences of each value in a given array of non-negative integers.
import numpy as np
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7]
print("Original array:")
print(array1)
print("Number of occurrences of each value in array: ")
print(np.bincount(array1))
| 48 |
# Write a Python program to print the index of the character in a string.
str1 = "w3resource"
for index, char in enumerate(str1):
print("Current character", char, "position at", index )
| 30 |
# Write a Python program to remove all strings from a given list of tuples.
def test(list1):
result = [tuple(v for v in i if not isinstance(v, str)) for i in list1]
return list(result)
marks = [(100, 'Math'), (80, 'Math'), (90, 'Math'), (88, 'Science', 89), (90, 'Science', 92)]
print("\nOriginal list:")
print(marks)
print("\nRemove all strings from the said list of tuples:")
print(test(marks))
| 61 |
# Write a Python program to Removing duplicates from tuple
# Python3 code to demonstrate working of
# Removing duplicates from tuple
# using tuple() + set()
# initialize tuple
test_tup = (1, 3, 5, 2, 3, 5, 1, 1, 3)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Removing duplicates from tuple
# using tuple() + set()
res = tuple(set(test_tup))
# printing result
print("The tuple after removing duplicates : " + str(res)) | 78 |
# Write a Python program to combine two given sorted lists using heapq module.
from heapq import merge
nums1 = [1, 3, 5, 7, 9, 11]
nums2 = [0, 2, 4, 6, 8, 10]
print("Original sorted lists:")
print(nums1)
print(nums2)
print("\nAfter merging the said two sorted lists:")
print(list(merge(nums1, nums2)))
| 48 |
# Python Program to Check if a Substring is Present in a Given String
string=raw_input("Enter string:")
sub_str=raw_input("Enter word:")
if(string.find(sub_str)==-1):
print("Substring not found in string!")
else:
print("Substring in string!") | 28 |
# Split a column in Pandas dataframe and get part of it in Python
import pandas as pd
import numpy as np
df = pd.DataFrame({'Geek_ID':['Geek1_id', 'Geek2_id', 'Geek3_id',
'Geek4_id', 'Geek5_id'],
'Geek_A': [1, 1, 3, 2, 4],
'Geek_B': [1, 2, 3, 4, 6],
'Geek_R': np.random.randn(5)})
# Geek_A Geek_B Geek_ID Geek_R
# 0 1 1 Geek1_id random number
# 1 1 2 Geek2_id random number
# 2 3 3 Geek3_id random number
# 3 2 4 Geek4_id random number
# 4 4 6 Geek5_id random number
print(df.Geek_ID.str.split('_').str[0]) | 84 |
# Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
:
Solution
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print squaredNumbers
| 32 |
# Write a NumPy program to generate a matrix product of two arrays.
import numpy as np
x = [[1, 0], [1, 1]]
y = [[3, 1], [2, 2]]
print("Matrices and vectors.")
print("x:")
print(x)
print("y:")
print(y)
print("Matrix product of above two arrays:")
print(np.matmul(x, y))
| 44 |
# Write a Pandas program to create a plot to visualize daily percentage returns of Alphabet Inc. stock price 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')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Adj Close']]
df3 = df2.set_index('Date')
daily_changes = df3.pct_change(periods=1)
daily_changes['Adj Close'].plot(figsize=(10,7),legend=True,linestyle='--',marker='o')
plt.suptitle('Daily % return of Alphabet Inc. stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()
| 80 |
# Write a Python program to create a new Arrow object, representing the "ceiling" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute.
import arrow
print(arrow.utcnow())
print("Hour ceiling:")
print(arrow.utcnow().ceil('hour'))
print("\nMinute ceiling:")
print(arrow.utcnow().ceil('minute'))
print("\nSecond ceiling:")
print(arrow.utcnow().ceil('second'))
| 51 |
# Write a Pandas program to print a DataFrame without index.
import pandas as pd
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', '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, 32, 33, 30, 31, 32]},
index = [1, 2, 3, 4, 5, 6])
print("Original DataFrame with single index:")
print(df)
print("\nDataFrame without index:")
print(df.to_string(index=False))
| 65 |
# Print the Full Pyramid Alphabet Pattern
row_size=int(input("Enter the row size:"))np=1for out in range(0,row_size): for inn in range(row_size-1,out,-1): print(" ",end="") for p in range(0, np): print(chr(out+65),end="") np+=2 print("\r") | 28 |
# Write a NumPy program to extract first, third and fifth elements of the third and fifth rows from a given (6x6) array.
import numpy as np
arra_data = np.arange(0,36).reshape((6, 6))
print("Original array:")
print(arra_data)
print("\nExtracted data: First, third and fifth elements of the third and fifth rows")
print(arra_data[2::2, ::2])
| 49 |
# Dictionary and counter in Python to find winner of election
# Function to find winner of an election where votes
# are represented as candidate names
from collections import Counter
def winner(input):
# convert list of candidates into dictionary
# output will be likes candidates = {'A':2, 'B':4}
votes = Counter(input)
# create another dictionary and it's key will
# be count of votes values will be name of
# candidates
dict = {}
for value in votes.values():
# initialize empty list to each key to
# insert candidate names having same
# number of votes
dict[value] = []
for (key,value) in votes.items():
dict[value].append(key)
# sort keys in descending order to get maximum
# value of votes
maxVote = sorted(dict.keys(),reverse=True)[0]
# check if more than 1 candidates have same
# number of votes. If yes, then sort the list
# first and print first element
if len(dict[maxVote])>1:
print (sorted(dict[maxVote])[0])
else:
print (dict[maxVote][0])
# Driver program
if __name__ == "__main__":
input =['john','johnny','jackie','johnny',
'john','jackie','jamie','jamie',
'john','johnny','jamie','johnny',
'john']
winner(input) | 166 |
# Write a NumPy program to compute the mean, standard deviation, and variance of a given array along the second axis.
import numpy as np
x = np.arange(6)
print("\nOriginal array:")
print(x)
r1 = np.mean(x)
r2 = np.average(x)
assert np.allclose(r1, r2)
print("\nMean: ", r1)
r1 = np.std(x)
r2 = np.sqrt(np.mean((x - np.mean(x)) ** 2 ))
assert np.allclose(r1, r2)
print("\nstd: ", 1)
r1= np.var(x)
r2 = np.mean((x - np.mean(x)) ** 2 )
assert np.allclose(r1, r2)
print("\nvariance: ", r1)
| 76 |
# Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.
import numpy as np
x = np.diagflat([4, 5, 6, 8])
print(x)
| 31 |
# 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):
self.head = None
self.tail = None
self.__nodes = []
# method to insert node at beginning
def InsertAtStart(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.head.npx = id(node) ^ self.head.npx
node.npx = id(self.head)
self.head = node
self.__nodes.append(node)
# method to insert node at end
def InsertAtEnd(self, value):
node = Node(value)
if self.head is None: # If list is empty
self.head = node
self.tail = node
else:
self.tail.npx = id(node) ^ self.tail.npx
node.npx = id(self.tail)
self.tail = node
self.__nodes.append(node)
# method to remove node at beginning
def DeleteAtStart(self):
if self.isEmpty(): # If list is empty
return "List is empty !"
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif (0 ^ self.head.npx) == id(self.tail): # If list has 2 nodes
self.head = self.tail
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
res = self.head.value
x = self.__type_cast(0 ^ self.head.npx) # Address of next node
y = (id(self.head) ^ x.npx) # Address of next of next node
self.head = x
self.head.npx = 0 ^ y
return res
# method to remove node at end
def DeleteAtEnd(self):
if self.isEmpty(): # If list is empty
return "List is empty !"
elif self.head == self.tail: # If list has 1 node
self.head = self.tail = None
elif self.__type_cast(0 ^ self.head.npx) == (self.tail): # If list has 2 nodes
self.tail = self.head
self.head.npx = self.tail.npx = 0
else: # If list has more than 2 nodes
prev_id = 0
node = self.head
next_id = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
res = node.value
x = self.__type_cast(prev_id).npx ^ id(node)
y = self.__type_cast(prev_id)
y.npx = x ^ 0
self.tail = y
return res
# method to traverse linked list
def Print(self):
"""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list."""
if self.head != None:
prev_id = 0
node = self.head
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print("List is empty !")
# method to traverse linked list in reverse order
def ReversePrint(self):
# Print Values is reverse order.
"""We are printing values rather than returning it bacause
for returning we have to append all values in a list
and it takes extra memory to save all values in a list."""
if self.head != None:
prev_id = 0
node = self.tail
next_id = 1
print(node.value, end=' ')
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
print(node.value, end=' ')
else:
return
else:
print("List is empty !")
# method to get length of linked list
def Length(self):
if not self.isEmpty():
prev_id = 0
node = self.head
next_id = 1
count = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
count += 1
else:
return count
else:
return 0
# method to get node data value by index
def PrintByIndex(self, index):
prev_id = 0
node = self.head
for i in range(index):
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
else:
return "Value dosn't found index out of range."
return node.value
# method to check if the liked list is empty or not
def isEmpty(self):
if self.head is None:
return True
return False
# method to return a new instance of type
def __type_cast(self, id):
return ctypes.cast(id, ctypes.py_object).value
# Driver Code
# create object
obj = XorLinkedList()
# insert nodes
obj.InsertAtEnd(2)
obj.InsertAtEnd(3)
obj.InsertAtEnd(4)
obj.InsertAtStart(0)
obj.InsertAtStart(6)
obj.InsertAtEnd(55)
# display length
print("\nLength:", obj.Length())
# traverse
print("\nTraverse linked list:")
obj.Print()
print("\nTraverse in reverse order:")
obj.ReversePrint()
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print("Data value at index", i, 'is', obj.PrintByIndex(i))
# removing nodes
print("\nDelete Last Node: ", obj.DeleteAtEnd())
print("\nDelete First Node: ", obj.DeleteAtStart())
# new length
print("\nUpdated length:", obj.Length())
# display data values by index
print('\nNodes:')
for i in range(obj.Length()):
print("Data value at index", i, 'is', obj.PrintByIndex(i))
# traverse
print("\nTraverse linked list:")
obj.Print()
print("\nTraverse in reverse order:")
obj.ReversePrint() | 744 |
# Write a Python program to Stack using Doubly Linked List
# A complete working Python program to demonstrate all
# stack operations using a doubly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.prev = None # Initialize prev as null
# Stack class contains a Node object
class Stack:
# Function to initialize head
def __init__(self):
self.head = None
# Function to add an element data in the stack
def push(self, data):
if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
self.head.prev = new_node
new_node.next = self.head
new_node.prev = None
self.head = new_node
# Function to pop top element and return the element from the stack
def pop(self):
if self.head is None:
return None
elif self.head.next is None:
temp = self.head.data
self.head = None
return temp
else:
temp = self.head.data
self.head = self.head.next
self.head.prev = None
return temp
# Function to return top element in the stack
def top(self):
return self.head.data
# Function to return the size of the stack
def size(self):
temp = self.head
count = 0
while temp is not None:
count = count + 1
temp = temp.next
return count
# Function to check if the stack is empty or not
def isEmpty(self):
if self.head is None:
return True
else:
return False
# Function to print the stack
def printstack(self):
print("stack elements are:")
temp = self.head
while temp is not None:
print(temp.data, end ="->")
temp = temp.next
# Code execution starts here
if __name__=='__main__':
# Start with the empty stack
stack = Stack()
# Insert 4 at the beginning. So stack becomes 4->None
print("Stack operations using Doubly LinkedList")
stack.push(4)
# Insert 5 at the beginning. So stack becomes 4->5->None
stack.push(5)
# Insert 6 at the beginning. So stack becomes 4->5->6->None
stack.push(6)
# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
stack.push(7)
# Print the stack
stack.printstack()
# Print the top element
print("\nTop element is ", stack.top())
# Print the stack size
print("Size of the stack is ", stack.size())
# pop the top element
stack.pop()
# pop the top element
stack.pop()
# two elements are popped
# Print the stack
stack.printstack()
# Print True if the stack is empty else False
print("\nstack is empty:", stack.isEmpty())
#This code is added by Suparna Raut | 392 |
# Write a Python program to sort a given list of strings(numbers) numerically.
def sort_numeric_strings(nums_str):
result = [int(x) for x in nums_str]
result.sort()
return result
nums_str = ['4','12','45','7','0','100','200','-12','-500']
print("Original list:")
print(nums_str)
print("\nSort the said list of strings(numbers) numerically:")
print(sort_numeric_strings(nums_str))
| 39 |
# Write a Python program to create a list with infinite elements.
import itertools
c = itertools.count()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
| 22 |
# Write a Python program to create a floating-point representation of the Arrow object, in UTC time using arrow module.
import arrow
a = arrow.utcnow()
print("Current Datetime:")
print(a)
print("\nFloating-point representation of the said Arrow object:")
f = arrow.utcnow().float_timestamp
print(f)
| 39 |
# Write a program to print the alphabet pattern
print("Enter the row and column size:");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),ord(row_size)+1):
print(chr(i),end=" ")
print("\r")
| 27 |
# Write a NumPy program to sort pairs of first name and last name return their indices. (first by last name, then by first name).
import numpy as np
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
x = np.lexsort((first_names, last_names))
print(x)
| 48 |
# Write a NumPy program to interchange two axes of an array.
import numpy as np
x = np.array([[1,2,3]])
print(x)
y = np.swapaxes(x,0,1)
print(y)
| 24 |
# Write a NumPy program to create an array using generator function that generates 15 integers.
import numpy as np
def generate():
for n in range(15):
yield n
nums = np.fromiter(generate(),dtype=float,count=-1)
print("New array:")
print(nums)
| 34 |
# Write a Python program to find the siblings of tags in a given html document.
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from
w3resource.com</a></p>
<a class="sister" href="http://example.com/lacie" id="link1">Lacie</a>
<a class="sister" href="http://example.com/tillie" id="link2">Tillie</a>
</body>
</html>
"""
soup = BeautifulSoup(html_doc,"lxml")
print("\nSiblings of tags:")
print(soup.select("#link1 ~ .sister"))
print(soup.select("#link1 + .sister"))
| 176 |
# Reset Index in Pandas Dataframe in Python
# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
'Age':[27, 24, 22, 32, 15],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'] }
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
df | 56 |
# Write a Python program to find the parent's process id, real user ID of the current process and change real user ID.
import os
print("Parent’s process id:",os.getppid())
uid = os.getuid()
print("\nUser ID of the current process:", uid)
uid = 1400
os.setuid(uid)
print("\nUser ID changed")
print("User ID of the current process:", os.getuid())
| 52 |
# Map function and Lambda expression in Python to replace characters
# Function to replace a character c1 with c2
# and c2 with c1 in a string S
def replaceChars(input,c1,c2):
# create lambda to replace c1 with c2, c2
# with c1 and other will remain same
# expression will be like "lambda x:
# x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2"
# and map it onto each character of string
newChars = map(lambda x: x if (x!=c1 and x!=c2) else \
c1 if (x==c2) else c2,input)
# now join each character without space
# to print resultant string
print (''.join(newChars))
# Driver program
if __name__ == "__main__":
input = 'grrksfoegrrks'
c1 = 'e'
c2 = 'r'
replaceChars(input,c1,c2) | 123 |
# Write a Python program to print a list of space-separated elements.
num = [1, 2, 3, 4, 5]
print(*num)
| 20 |
# How to randomly select rows from Pandas DataFrame in Python
# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
'Age':[27, 24, 22, 32, 15],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# select all columns
df | 62 |
# Matrix Multiplication in NumPy in Python
# importing the module
import numpy as np
# creating two matrices
p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)
# computing product
result = np.dot(p, q)
# printing the result
print("The matrix multiplication is :")
print(result) | 56 |
# Write a NumPy program to print the full NumPy array, without truncation.
import numpy as np
import sys
nums = np.arange(2000)
np.set_printoptions(threshold=sys.maxsize)
print(nums)
| 24 |
# Write a Python program to print negative numbers in a list
# Python program to print negative Numbers in a List
# list of numbers
list1 = [11, -21, 0, 45, 66, -93]
# iterating each number in list
for num in list1:
# checking condition
if num < 0:
print(num, end = " ") | 56 |
# Write a Pandas program to create a plot to present the number of unidentified flying object (UFO) reports per year.
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nPlot to present the number unidentified flying objects (ufo) found year wise:")
df["Year"] = df.Date_time.dt.year
df.Year.value_counts().sort_index().plot(x="Year")
| 50 |
# Write a NumPy program to replace "PHP" with "Python" in the element of a given array.
import numpy as np
x = np.array(['PHP Exercises, Practice, Solution'], dtype=np.str)
print("\nOriginal Array:")
print(x)
r = np.char.replace(x, "PHP", "Python")
print("\nNew array:")
print(r)
| 39 |
# Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically).
items = input("Input comma separated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
| 40 |
# Ranking Rows of Pandas DataFrame in Python
# import the required packages
import pandas as pd
# Define the dictionary for converting to dataframe
movies = {'Name': ['The Godfather', 'Bird Box', 'Fight Club'],
'Year': ['1972', '2018', '1999'],
'Rating': ['9.2', '6.8', '8.8']}
df = pd.DataFrame(movies)
print(df) | 46 |
# Write a Pandas program to split the following given dataframe into groups based on single column and multiple columns. Find the size of the grouped data.
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = 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'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(student_data)
print('\nSplit the said data on school_code wise:')
grouped_single = student_data.groupby(['school_code'])
print("Size of the grouped data - single column")
print(grouped_single.size())
print('\nSplit the said data on school_code and class wise:')
grouped_mul = student_data.groupby(['school_code', 'class'])
print("Size of the grouped data - multiple columns:")
print(grouped_mul.size())
| 139 |
# How to calculate the element-wise absolute value of NumPy array in Python
# import library
import numpy as np
# create a numpy 1d-array
array = np.array([1, -2, 3])
print("Given array:\n", array)
# find element-wise
# absolute value
rslt = np.absolute(array)
print("Absolute array:\n", rslt) | 45 |
# Write a NumPy program compare two given arrays.
import numpy as np
a = np.array([1, 2])
b = np.array([4, 5])
print("Array a: ",a)
print("Array b: ",b)
print("a > b")
print(np.greater(a, b))
print("a >= b")
print(np.greater_equal(a, b))
print("a < b")
print(np.less(a, b))
print("a <= b")
print(np.less_equal(a, b))
| 47 |
# Write a Python program to check whether a specified list is sorted or not.
def is_sort_list(nums):
result = all(nums[i] <= nums[i+1] for i in range(len(nums)-1))
return result
nums1 = [1,2,4,6,8,10,12,14,16,17]
print ("Original list:")
print(nums1)
print("\nIs the said list is sorted!")
print(is_sort_list(nums1))
nums2 = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2]
print ("\nOriginal list:")
print(nums1)
print("\nIs the said list is sorted!")
print(is_sort_list(nums2))
| 56 |
# Write a NumPy program to generate an array of 15 random numbers from a standard normal distribution.
import numpy as np
rand_num = np.random.normal(0,1,15)
print("15 random numbers from a standard normal distribution:")
print(rand_num)
| 34 |
# Write a Python program to convert a given number (integer) to a list of digits.
def digitize(n):
return list(map(int, str(n)))
print(digitize(123))
print(digitize(1347823))
| 23 |
# Write a NumPy program to calculate cumulative product of the elements along a given axis, sum over rows for each of the 3 columns and product over columns for each of the 2 rows of a given 3x3 array.
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
print("Original array: ")
print(x)
print("Cumulative product of the elements along a given axis:")
r = np.cumprod(x)
print(r)
print("\nProduct over rows for each of the 3 columns:")
r = np.cumprod(x,axis=0)
print(r)
print("\nProduct over columns for each of the 2 rows:")
r = np.cumprod(x,axis=1)
print(r)
| 91 |
# Write a Pandas program to get the positions of items of a given series in another given series.
import pandas as pd
series1 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
series2 = pd.Series([1, 3, 5, 7, 10])
print("Original Series:")
print(series1)
print(series2)
result = [pd.Index(series1).get_loc(i) for i in series2]
print("Positions of items of series2 in series1:")
print(result)
| 61 |
# Program to print series 6,9,14,21,30,41,54...N
print("Enter the range of number(Limit):")
n=int(input())
i=1
j=3
value=6
while(i<=n):
print(value,end=" ")
value+=j
j+=2
i+=1 | 21 |
# Print only consonants in a string
str=input("Enter the String:")
print("All the consonants in the string are:")
for i in range(len(str)):
if str[i] == 'a' or str[i] == 'A' or str[i] == 'e' or str[i] == 'E' or str[i] == 'i'or str[i] == 'I' or str[i] == 'o' or str[i] == 'O' or str[i] == 'u' or str[i] == 'U':
continue
else:
print(str[i],end=" ") | 64 |
# Write a NumPy program to extract all the rows from a given array where a specific column starts with a given character.
import numpy as np
np.set_printoptions(linewidth=100)
student = np.array([['01', 'V', 'Debby Pramod'],
['02', 'V', 'Artemiy Ellie'],
['03', 'V', 'Baptist Kamal'],
['04', 'V', 'Lavanya Davide'],
['05', 'V', 'Fulton Antwan'],
['06', 'V', 'Euanthe Sandeep'],
['07', 'V', 'Endzela Sanda'],
['08', 'V', 'Victoire Waman'],
['09', 'V', 'Briar Nur'],
['10', 'V', 'Rose Lykos']])
print("Original array:")
print(student)
char='E'
result = student[np.char.startswith(student[:,2], char)]
print("\nStudent name starting with",char,":")
print(result)
char='1'
result = student[np.char.startswith(student[:,0], char)]
print("\nStudent id starting with",char,":")
print(result)
| 93 |
# Write a Python program to Convert List to List of dictionaries
# Python3 code to demonstrate working of
# Convert List to List of dictionaries
# Using dictionary comprehension + loop
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
# printing original list
print("The original list : " + str(test_list))
# initializing key list
key_list = ["name", "number"]
# loop to iterate through elements
# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
# printing result
print("The constructed dictionary list : " + str(res)) | 110 |
# Write a Python program to join one or more path components together and split a given path in directory and file.
import os
path = r'g:\\testpath\\a.txt'
print("Original path:")
print(path)
print("\nDir and file name of the said path:")
print(os.path.split(path))
print("\nJoin one or more path components together:")
print(os.path.join(r'g:\\testpath\\','a.txt'))
| 47 |
# How to Scrape all PDF files in a Website in Python
# for get the pdf files or url
import requests
# for tree traversal scraping in webpage
from bs4 import BeautifulSoup
# for input and output operations
import io
# For getting information about the pdfs
from PyPDF2 import PdfFileReader | 52 |
# Write a Python program to split and join a string
# Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(' ')
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-'.join(list_string)
return string
# Driver Function
if __name__ == '__main__':
string = 'Geeks for Geeks'
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string) | 87 |
# Write a Python program to skip the headers of a given CSV file. Use csv.reader
import csv
f = open("employees.csv", "r")
reader = csv.reader(f)
next(reader)
for row in reader:
print(row)
| 31 |
# Python Program to Generate Gray Codes using Recursion
def get_gray_codes(n):
"""Return n-bit Gray code in a list."""
if n == 0:
return ['']
first_half = get_gray_codes(n - 1)
second_half = first_half.copy()
first_half = ['0' + code for code in first_half]
second_half = ['1' + code for code in reversed(second_half)]
return first_half + second_half
n = int(input('Enter the number of bits: '))
codes = get_gray_codes(n)
print('All {}-bit Gray Codes:'.format(n))
print(codes) | 70 |
# Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l[:5])
print(l[-5:])
printValues()
| 43 |
# Write a Python program to find the occurrences of 10 most common words in a given text.
from collections import Counter
import re
text = """The Python Software Foundation (PSF) is a 501(c)(3) non-profit
corporation that holds the intellectual property rights behind
the Python programming language. We manage the open source licensing
for Python version 2.1 and later and own and protect the trademarks
associated with Python. We also run the North American PyCon conference
annually, support other Python conferences around the world, and
fund Python related development with our grants program and by funding
special projects."""
words = re.findall('\w+',text)
print(Counter(words).most_common(10))
| 102 |
# Write a Python program to check all values are same in a dictionary.
def value_check(students, n):
result = all(x == n for x in students.values())
return result
students = {'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12}
print("Original Dictionary:")
print(students)
n = 12
print("\nCheck all are ",n,"in the dictionary.")
print(value_check(students, n))
n = 10
print("\nCheck all are ",n,"in the dictionary.")
print(value_check(students, n))
| 67 |
# Reshape a pandas DataFrame using stack,unstack and melt method in Python
# import pandas module
import pandas as pd
# making dataframe
df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
# it was print the first 5-rows
print(df.head()) | 34 |
# How to convert a list and tuple into NumPy arrays in Python
import numpy as np
# list
list1 = [3, 4, 5, 6]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.asarray(list1)
print(type(array1))
print(array1)
print()
# tuple
tuple1 = ([8, 4, 6], [1, 2, 3])
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.asarray(tuple1)
print(type(array2))
print(array2) | 56 |
# Python Program to Count the Number of Occurrences of an Element in the Linked List using Recursion
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
def count(self, key):
return self.count_helper(self.head, key)
def count_helper(self, current, key):
if current is None:
return 0
if current.data == key:
return 1 + self.count_helper(current.next, key)
else:
return self.count_helper(current.next, key)
a_llist = LinkedList()
for data in [7, 3, 7, 4, 7, 11, 4, 0, 3, 7]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()
key = int(input('Enter data item: '))
count = a_llist.count(key)
print('{0} occurs {1} time(s) in the list.'.format(key, count)) | 146 |
# Write a Python program to reverse words in a string.
def reverse_string_words(text):
for line in text.split('\n'):
return(' '.join(line.split()[::-1]))
print(reverse_string_words("The quick brown fox jumps over the lazy dog."))
print(reverse_string_words("Python Exercises."))
| 30 |
# Write a Python program to find the elements of a given list of strings that contain specific substring using lambda.
def find_substring(str1, sub_str):
result = list(filter(lambda x: sub_str in x, str1))
return result
colors = ["red", "black", "white", "green", "orange"]
print("Original list:")
print(colors)
sub_str = "ack"
print("\nSubstring to search:")
print(sub_str)
print("Elements of the said list that contain specific substring:")
print(find_substring(colors, sub_str))
sub_str = "abc"
print("\nSubstring to search:")
print(sub_str)
print("Elements of the said list that contain specific substring:")
print(find_substring(colors, sub_str))
| 80 |
# Write a Python program to convert a given list of strings into list of lists.
def strings_to_listOflists(colors):
result = [list(word) for word in colors]
return result
colors = ["Red", "Maroon", "Yellow", "Olive"]
print('Original list of strings:')
print(colors)
print("\nConvert the said list of strings into list of lists:")
print(strings_to_listOflists(colors))
| 49 |
# Write a Python program to get an array buffer information.
from array import array
a = array("I", (12,25))
print("Array buffer start address in memory and number of elements.")
print(a.buffer_info())
| 30 |
# Write a Python program to print the names of all HTML tags of a given web page going through the document tree.
import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print("\nNames of all HTML tags (https://www.python.org):\n")
for child in soup.recursiveChildGenerator():
if child.name:
print(child.name)
| 52 |
# Write a NumPy program to combine a one and a two dimensional array together and display their elements.
import numpy as np
x = np.arange(4)
print("One dimensional array:")
print(x)
y = np.arange(8).reshape(2,4)
print("Two dimensional array:")
print(y)
for a, b in np.nditer([x,y]):
print("%d:%d" % (a,b),)
| 45 |
# Write a Python program to check if a given element occurs at least n times in a list.
def check_element_in_list(lst, x, n):
t = 0
try:
for _ in range(n):
t = lst.index(x, t) + 1
return True
except ValueError:
return False
nums = [0,1,3,5,0,3,4,5,0,8,0,3,6,0,3,1,1,0]
print("Original list:")
print(nums)
x = 3
n = 4
print("\nCheck if",x,"occurs at least",n,"times in a list:")
print(check_element_in_list(nums,x,n))
x = 0
n = 5
print("\nCheck if",x,"occurs at least",n,"times in a list:")
print(check_element_in_list(nums,x,n))
x = 8
n = 3
print("\nCheck if",x,"occurs at least",n,"times in a list:")
print(check_element_in_list(nums,x,n))
| 91 |
# Write a Python program that reads a CSV file and remove initial spaces, quotes around each entry and the delimiter.
import csv
csv.register_dialect('csv_dialect',
delimiter='|',
skipinitialspace=True,
quoting=csv.QUOTE_ALL)
with open('temp.csv', 'r') as csvfile:
reader = csv.reader(csvfile, dialect='csv_dialect')
for row in reader:
print(row)
| 41 |
# Convert JSON to CSV in Python
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close() | 110 |
# Write a NumPy program to split a given text into lines and split the single line into array values.
import numpy as np
student = """01 V Debby Pramod
02 V Artemiy Ellie
03 V Baptist Kamal
04 V Lavanya Davide
05 V Fulton Antwan
06 V Euanthe Sandeep
07 V Endzela Sanda
08 V Victoire Waman
09 V Briar Nur
10 V Rose Lykos"""
print("Original text:")
print(student)
text_lines = student.splitlines()
text_lines = [r.split('\t') for r in text_lines]
result = np.array(text_lines, dtype=np.str)
print("\nArray from the said text:")
print(result)
| 89 |
# Write a Python program to check if a specific Key and a value exist in a dictionary.
def test(dictt, key, value):
if any(sub[key] == value for sub in dictt):
return True
return False
students = [
{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'},
{'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
{'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'},
{'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'},
{'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
]
print("\nOriginal dictionary:")
print(students)
print("\nCheck if a specific Key and a value exist in the said dictionary:")
print(test(students,'student_id', 1))
print(test(students,'name', 'Brian Howell'))
print(test(students,'class', 'VII'))
print(test(students,'class', 'I'))
print(test(students,'name', 'Brian Howelll'))
print(test(students,'student_id', 11))
| 103 |
# Write a Python program to get a list of elements that exist in both lists, after applying the provided function to each list element of both.
def intersection_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) in _b]
from math import floor
print(intersection_by([2.1, 1.2], [2.3, 3.4], floor))
| 54 |
# What is a clean, Pythonic way to have multiple constructors in Python
class example:
def __init__(self):
print("One")
def __init__(self):
print("Two")
def __init__(self):
print("Three")
e = example() | 27 |
# Write a Python program to extract the nth element from a given list of tuples using lambda.
def extract_nth_element(test_list, n):
result = list(map (lambda x:(x[n]), test_list))
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print ("Original list:")
print(students)
n = 0
print("\nExtract nth element ( n =",n,") from the said list of tuples:")
print(extract_nth_element(students, n))
n = 2
print("\nExtract nth element ( n =",n,") from the said list of tuples:")
print(extract_nth_element(students, n))
| 85 |
# How to search and replace text in a file in Python
# creating a variable and storing the text
# that we want to search
search_text = "dummy"
# creating a variable and storing the text
# that we want to add
replace_text = "replaced"
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt', 'r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = file.read()
# Searching and replacing the text
# using the replace() function
data = data.replace(search_text, replace_text)
# Opening our text file in write only
# mode to write the replaced content
with open(r'SampleFile.txt', 'w') as file:
# Writing the replaced data in our
# text file
file.write(data)
# Printing Text replaced
print("Text replaced") | 140 |
# Write a Python program to flatten a given nested list structure.
def flatten_list(n_list):
result_list = []
if not n_list: return result_list
stack = [list(n_list)]
while stack:
c_num = stack.pop()
next = c_num.pop()
if c_num: stack.append(c_num)
if isinstance(next, list):
if next: stack.append(list(next))
else: result_list.append(next)
result_list.reverse()
return result_list
n_list = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
print("Original list:")
print(n_list)
print("\nFlatten list:")
print(flatten_list(n_list))
| 68 |
# Write a Python program to get the least common multiple (LCM) of two positive integers.
def lcm(x, y):
if x > y:
z = x
else:
z = y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
| 55 |
# Convert Lowercase to Uppercase using the inbuilt function
str=input("Enter the String(Lower case):")
print("Upper case String is:", str.upper()) | 18 |
# Kill a Process by name using Python
import os, signal
def process():
# Ask user for the name of process
name = input("Enter process Name: ")
try:
# iterating through each instance of the process
for line in os.popen("ps ax | grep " + name + " | grep -v grep"):
fields = line.split()
# extracting Process ID from the output
pid = fields[0]
# terminating process
os.kill(int(pid), signal.SIGKILL)
print("Process Successfully terminated")
except:
print("Error Encountered while running script")
process() | 80 |
# Write a Python program to Remove Reduntant Substrings from Strings List
# Python3 code to demonstrate working of
# Remove Reduntant Substrings from Strings List
# Using enumerate() + join() + sort()
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate for each string
test_list.sort(key = len)
res = []
for idx, val in enumerate(test_list):
# concatenating all next values and checking for existence
if val not in ', '.join(test_list[idx + 1:]):
res.append(val)
# printing result
print("The filtered list : " + str(res)) | 105 |
# Write a Python program to insert spaces between words starting with capital letters.
import re
def capital_words_spaces(str1):
return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)
print(capital_words_spaces("Python"))
print(capital_words_spaces("PythonExercises"))
print(capital_words_spaces("PythonExercisesPracticeSolution"))
| 26 |
# Write a Python program to find the most common elements and their counts of a specified text.
from collections import Counter
s = 'lkseropewdssafsdfafkpwe'
print("Original string: "+s)
print("Most common three characters of the said string:")
print(Counter(s).most_common(3))
| 37 |
# Write a Python program to Remove after substring in String
# Python3 code to demonstrate working of
# Remove after substring in String
# Using index() + len() + slicing
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing sub string
sub_str = "best"
# slicing off after length computation
res = test_str[:test_str.index(sub_str) + len(sub_str)]
# printing result
print("The string after removal : " + str(res)) | 82 |
# Write a Python program to count and display the vowels of a given text.
def vowel(text):
vowels = "aeiuoAEIOU"
print(len([letter for letter in text if letter in vowels]))
print([letter for letter in text if letter in vowels])
vowel('w3resource');
| 39 |
# Write a Python program to get the n minimum elements from a given list of numbers.
def min_n_nums(nums, n = 1):
return sorted(nums, reverse = False)[:n]
nums = [1, 2, 3]
print("Original list elements:")
print(nums)
print("Minimum values of the said list:", min_n_nums(nums))
nums = [1, 2, 3]
print("\nOriginal list elements:")
print(nums)
print("Two minimum values of the said list:", min_n_nums(nums,2))
nums = [-2, -3, -1, -2, -4, 0, -5]
print("\nOriginal list elements:")
print(nums)
print("Threee minimum values of the said list:", min_n_nums(nums,3))
nums = [2.2, 2, 3.2, 4.5, 4.6, 5.2, 2.9]
print("\nOriginal list elements:")
print(nums)
print("Two minimum values of the said list:", min_n_nums(nums, 2))
| 103 |
# Rename a folder of images using Tkinter in Python
# Python 3 code to rename multiple image
# files in a directory or folder
import os
from tkinter import messagebox
import cv2
from tkinter import filedialog
from tkinter import *
height1 = 0
width1 = 0
# Function to select folder to rename images
def get_folder_path():
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
return folder_selected
# Function to rename multiple files
def submit():
source = src_dir.get()
src_dir.set("")
global width1
global height1
input_folder = get_folder_path()
i = 0
for img_file in os.listdir(input_folder):
file_name = os.path.splitext(img_file)[0]
extension = os.path.splitext(img_file)[1]
if extension == '.jpg':
src = os.path.join(input_folder, img_file)
img = cv2.imread(src)
h, w, c = img.shape
dst = source + '-' + str(i) + '-' + str(w) + "x" + str(h) + ".jpg"
dst = os.path.join(input_folder, dst)
# rename() function will rename all the files
os.rename(src, dst)
i += 1
messagebox.showinfo("Done", "All files renamed successfully !!")
# Driver Code
if __name__ == '__main__':
top = Tk()
top.geometry("450x300")
top.title("Image Files Renamer")
top.configure(background ="Dark grey")
# For Input Label
input_path = Label(top,
text ="Enter Name to Rename files:",
bg ="Dark grey").place(x = 40, y = 60)
# For Input Textbox
src_dir = StringVar()
input_path_entry_area = Entry(top,
textvariable = src_dir,
width = 50).place(x = 40, y = 100)
# For submit button
submit_button = Button(top,
text ="Submit",
command = submit).place(x = 200, y = 150)
top.mainloop() | 231 |
# Write a Python program to Inversion in nested dictionary
# Python3 code to demonstrate working of
# Inversion in nested dictionary
# Using loop + recursion
# utility function to get all paths till end
def extract_path(test_dict, path_way):
if not test_dict:
return [path_way]
temp = []
for key in test_dict:
temp.extend(extract_path(test_dict[key], path_way + [key]))
return temp
# function to compute inversion
def hlper_fnc(test_dict):
all_paths = extract_path(test_dict, [])
res = {}
for path in all_paths:
front = res
for ele in path[::-1]:
if ele not in front :
front[ele] = {}
front = front[ele]
return res
# initializing dictionary
test_dict = {"a" : {"b" : {"c" : {}}},
"d" : {"e" : {}},
"f" : {"g" : {"h" : {}}}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# calling helper function for task
res = hlper_fnc(test_dict)
# printing result
print("The inverted dictionary : " + str(res)) | 151 |
# Input a string through the keyboard and Print the same
arr=[]
size = int(input("Enter the size of the array: "))
for i in range(0,size):
word = (input())
arr.append(word)
for i in range(0,size):
print(arr[i],end="") | 34 |
# Python Program to Reverse a String Using Recursion
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a)) | 32 |
# Convert Octal to decimal using recursion
decimal=0sem=0def OctalToDecimal(n): global sem,decimal if(n!=0): decimal+=(n%10)*pow(8,sem) sem+=1 OctalToDecimal(n // 10) return decimaln=int(input("Enter the Octal Value:"))print("Decimal Value of Octal number is:",OctalToDecimal(n)) | 27 |
Subsets and Splits