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',... | 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 ... | 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',
... | 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:")
p... | 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 dupli... | 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... | 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') ... | 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')... | 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 Parke... | 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")
prin... | 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}
vot... | 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... | 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):
... | 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.n... | 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 lis... | 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_... | 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 ips... | 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'],
'... | 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 curr... | 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:
... | 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', 'No... | 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 ... | 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 unidentif... | 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.DataF... | 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',... | 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... | 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 o... | 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 seri... | 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':
... | 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'... | 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 o... | 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:... | 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):
# J... | 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 ... | 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 o... | 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 = ... | 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)
p... | 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)... | 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(color... | 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 ... | 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"... | 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]... | 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 c... | 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 wri... | 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 Ly... | 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 ... | 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], fl... | 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)... | 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 op... | 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, ... | 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"):
... | 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
prin... | 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("PythonExercisesPracticeSol... | 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_... | 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 li... | 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
... | 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 k... | 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
No community queries yet
The top public SQL queries from the community will appear here once available.