code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to Convert Key-Value list Dictionary to List of Lists
# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using loop + items()
# initializing Dictionary
test_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]}
# printing original dicti... | 101 |
# Reverse words in a given String in Python
# Function to reverse words of string
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# f... | 64 |
# Write a NumPy program to sort an given array by the n
import numpy as np
print("Original array:\n")
nums = np.random.randint(0,10,(3,3))
print(nums)
print("\nSort the said array by the nth column: ")
print(nums[nums[:,1].argsort()])
| 33 |
# Write a Python program to create a ctime formatted representation of the date and time using arrow module.
import arrow
print("Ctime formatted representation of the date and time:")
a = arrow.utcnow().ctime()
print(a)
| 33 |
# Write a Pandas program to extract word mention someone in tweets using @ 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({
'tweets': ['@Obama says goodbye','Retweets for @cash','A political endorsement in @Indonesia'... | 74 |
# Write a Python program to Avoid Spaces in string length
# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()
# initializing string
test_str = 'geeksforgeeks 33 is best'
# printing original string
print("The original string is : " + str(test_str))
# is... | 79 |
# Write a Pandas program to select a specific row of given series/dataframe by integer index.
import pandas as pd
ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8])
print("Original Series:")
print(ds)
print("\nPrint specified row from the said series using location based indexing:")
print("\nThird row:")
... | 99 |
# Program to print Fibonacci series in Python | C | C++ | Java
print("Enter the range of number(Limit):")
n=int(input())
i=1
a=0
b=1
c=a+b
while(i<=n):
print(c,end=" ")
c = a + b
a = b
b = c
i+=1 | 39 |
# Python Program to Solve Matrix-Chain Multiplication using Dynamic Programming with Memoization
def matrix_product(p):
"""Return m and s.
m[i][j] is the minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j).
s[i][j] is the index of the matrix... | 415 |
# Write a Python program to Maximum frequency character in String
# Python 3 code to demonstrate
# Maximum frequency character in String
# naive method
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print ("The original string is : " + test_str)
# using naive method to get
# M... | 97 |
# Write a NumPy program to swap columns in a given array.
import numpy as np
my_array = np.arange(12).reshape(3, 4)
print("Original array:")
print(my_array)
my_array[:,[0, 1]] = my_array[:,[1, 0]]
print("\nAfter swapping arrays:")
print(my_array)
| 32 |
# Write a Python program to find the Strongest Neighbour
# define a function for finding
# the maximum for adjacent
# pairs in the array
def maximumAdjacent(arr1, n):
# array to store the max
# value between adjacent pairs
arr2 = []
# iterate from 1 to n - 1
for i in range(1, n):
... | 113 |
# Write a Python program to Find common elements in three sorted arrays by dictionary intersection
# Function to find common elements in three
# sorted arrays
from collections import Counter
def commonElement(ar1,ar2,ar3):
# first convert lists into dictionary
ar1 = Counter(ar1)
ar2 = Counter(ar2)
... | 115 |
# Write a NumPy program to convert numpy datetime64 to Timestamp.
import numpy as np
from datetime import datetime
dt = datetime.utcnow()
print("Current date:")
print(dt)
dt64 = np.datetime64(dt)
ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
print("Timestamp:")
print(ts)
print("UTC fro... | 42 |
# Program to print series 1,3,7,15,31...N
n=int(input("Enter the range of number(Limit):"))i=1pr=0while i<=n: pr = (pr * 2) + 1 print(pr,end=" ") i+=1 | 22 |
# Write a NumPy program to find unique rows in a NumPy array.
import numpy as np
x = np.array([[20, 20, 20, 0],
[0, 20, 20, 20],
[0, 20, 20, 20],
[20, 20, 20, 0],
[10, 20, 20,20]])
print("Original array:")
print(x)
y = np.ascontiguousarray(x).view(np.dtype((np.... | 62 |
# Write a Python program to get unique values from a list.
my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
| 38 |
# Write a Python program to read last n lines of a file.
import sys
import os
def file_read_from_tail(fname,lines):
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open(fname) as f:
if bufsize > fsize:
bufsize = fsize-1
... | 59 |
# Write a NumPy program to compute the Kronecker product of two given mulitdimension arrays.
import numpy as np
a = np.array([1,2,3])
b = np.array([0,1,0])
print("Original 1-d arrays:")
print(a)
print(b)
result = np.kron(a, b)
print("Kronecker product of the said arrays:")
print(result)
x = np.arange(9).reshape(3, ... | 66 |
# Write a Python program to find the type of IP Address using Regex
# Python program to find the type of Ip address
# re module provides support
# for regular expressions
import re
# Make a regular expression
# for validating an Ipv4
ipv4 = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4]... | 143 |
# Write a Python program to Odd Frequency Characters
# Python3 code to demonstrate working of
# Odd Frequency Characters
# Using list comprehension + defaultdict()
from collections import defaultdict
# helper_function
def hlper_fnc(test_str):
cntr = defaultdict(int)
for ele in test_str:
cntr[ele] ... | 104 |
# Write a Python program to convert an array to an ordinary list with the same items.
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
print("Original array: "+str(array_num))
num_list = array_num.tolist()
print("Convert the said array to an ordinary list with the same items:")
print(num_list)
| 51 |
# Write a Python program to create a shallow copy of a given list. Use copy.copy
import copy
nums_x = [1, [2, 3, 4]]
print("Original list: ", nums_x)
nums_y = copy.copy(nums_x)
print("\nCopy of the said list:")
print(nums_y)
print("\nChange the value of an element of the original list:")
nums_x[1][1] = 10
print(nums_... | 89 |
# Write a Pandas program to remove the html tags within the specified column of a given DataFrame.
import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
... | 72 |
# Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
def sum(x, y, z):
if x == y or y == z or x==z:
sum = 0
else:
sum = x + y + z
return sum
print(sum(2, 1, 2))
print(sum(3, 2, 2))
print(sum(2, 2, 2))
print(sum(1, 2, 3))
| 60 |
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight dataframe's specific columns with different colors.
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)... | 116 |
# Write a Python program to get the size of a file.
import os
file_size = os.path.getsize("abc.txt")
print("\nThe size of abc.txt is :",file_size,"Bytes")
print()
| 24 |
# Python Program to Find the LCM of Two Numbers
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if(a>b):
min1=a
else:
min1=b
while(1):
if(min1%a==0 and min1%b==0):
print("LCM is:",min1)
break
min1=min1+1 | 30 |
# Write a Python program to find middle of a linked list using one traversal
# Python 3 program to find the middle of a
# given linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data
self.next = None
class Link... | 127 |
# Write a Pandas program to extract only phone number from the specified column of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
'company_phone_no': ['Company1-Phone no. 46951683... | 69 |
# Write a Python program to find the length of the text of the first <h2> tag of 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... | 176 |
# Write a Python program to find common items from two lists.
color1 = "Red", "Green", "Orange", "White"
color2 = "Black", "Green", "White", "Pink"
print(set(color1) & set(color2))
| 27 |
# Write a NumPy program to normalize a 3x3 random matrix.
import numpy as np
x= np.random.random((3,3))
print("Original Array:")
print(x)
xmax, xmin = x.max(), x.min()
x = (x - xmin)/(xmax - xmin)
print("After normalization:")
print(x)
| 35 |
# Python Program to Put Even and Odd elements in a List into Two Different Lists
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even li... | 44 |
# Write a NumPy program to get the unique elements of an array.
import numpy as np
x = np.array([10, 10, 20, 20, 30, 30])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x))
x = np.array([[1, 1], [2, 3]])
print("Original array:")
print(x)
print("Unique elements of the a... | 51 |
# Program to compute the area and perimeter of Rhombus
print("Enter the two Diagonals Value:")
p=int(input())
q=int(input())
a=int(input("Enter the length of the side value:"))
area=(p*q)/2.0
perimeter=(4*a)
print("Area of the Rhombus = ",area)
print("Perimeter of the Rhombus = ",perimeter)
| 38 |
# How to iterate over rows in Pandas Dataframe in Python
# importing pandas
import pandas as pd
# list of dicts
input_df = [{'name':'Sujeet', 'age':10},
{'name':'Sameer', 'age':11},
{'name':'Sumit', 'age':12}]
df = pd.DataFrame(input_df)
print('Original DataFrame: \n', df)
print('\... | 50 |
# Find the average of an unknown number of inputs in Python
# function that takes arbitary
# number of inputs
def avgfun(*n):
sums = 0
for t in n:
sums = sums + t
avg = sums / len(n)
return avg
# Driver Code
result1 = avgfun(1, 2, 3)
result2 = avgfun(2, 6, 4, 8)
# Pr... | 66 |
# numpy.percentile() in python
# Python Program illustrating
# numpy.percentile() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print("arr : ", arr)
print("50th percentile of arr : ",
np.percentile(arr, 50))
print("25th percentile of arr : ",
np.percentile(arr, 25))
print("75th pe... | 53 |
# Write a NumPy program to remove the first dimension from a given array of shape (1,3,4).
import numpy as np
nums = np.array([[[1, 2, 3, 4],
[0, 1, 3, 4],
[5, 0, 3, 2]]])
print('Shape of the said array:')
print(nums.shape)
print("\nAfter removing the first dimension of the shape of th... | 53 |
# Write a Python program to Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
# Python program to Find the Number
# Occurring Odd Number of Times
# using Lambda expression and reduce function
from functools import reduce
def oddTimes(input):
# write lambda expressio... | 113 |
# Reindexing in Pandas DataFrame in Python
# import numpy and pandas module
import pandas as pd
import numpy as np
column=['a','b','c','d','e']
index=['A','B','C','D','E']
# create a dataframe of random values of array
df1 = pd.DataFrame(np.random.rand(5,5),
columns=column, index=index)
print(df1)
... | 48 |
# Write a Python program to sort unsorted numbers using Strand sort.
#Ref:https://bit.ly/3qW9FIX
import operator
def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list:
_operator = operator.lt if reverse else operator.gt
solution = solution or []
if not arr:
return solut... | 158 |
# Write a Python program to interleave two given list into another list randomly.
import random
def randomly_interleave(nums1, nums2):
result = [x.pop(0) for x in random.sample([nums1]*len(nums1) + [nums2]*len(nums2), len(nums1)+len(nums2))]
return result
nums1 = [1,2,7,8,3,7]
nums2 = [4,3,8,9,4,3,8,9]
prin... | 51 |
# Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm
def find_max_subarray(alist, start, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end."""
max_ending_at_i = max_seen_so_fa... | 149 |
# Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.
:
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[5:]
printList()
| 51 |
# Write a Pandas program to merge two given datasets using multiple join keys.
import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
d... | 76 |
# Write a Python program to find palindromes in a given list of strings using Lambda.
texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"]
print("Orginal list of strings:")
print(texts)
result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
print("\nList of palindromes:")
print(result)
| 41 |
# LRU Cache in Python using OrderedDict
from collections import OrderedDict
class LRUCache:
# initialising capacity
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
# we return the value of the key
# that is queried in O(1) and return -1 if w... | 208 |
# Write a Python program to sum two or more lists, the lengths of the lists may be different.
def sum_lists_diff_length(test_list):
result = [sum(x) for x in zip(*map(lambda x:x+[0]*max(map(len, test_list)) if len(x)<max(map(len, test_list)) else x, test_list))]
return result
nums = [[1,2,4],[2,4,4],[1,2]]... | 64 |
# Python Program to Implement Radix Sort
def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return ((alist[index]//(base**digit)) % base)
return key
largest = max(alist)
exp = 0
while base**exp <= larg... | 155 |
# Program to print the Full Pyramid Number Pattern
row_size=int(input("Enter the row size:"))
np=1
for out in range(0,row_size):
for in1 in range(row_size-1,out,-1):
print(" ",end="")
for in2 in range(1, np+1):
print(in2,end="")
np+=2
print("\r")
| 32 |
# Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))
print() | 28 |
# Python Program to Print nth Fibonacci Number using Dynamic Programming with Memoization
def fibonacci(n):
"""Return the nth Fibonacci number."""
# r[i] will contain the ith Fibonacci number
r = [-1]*(n + 1)
return fibonacci_helper(n, r)
def fibonacci_helper(n, r):
"""Return the nth Fibonacci... | 105 |
# Write a NumPy program to sort an along the first, last axis of an array.
import numpy as np
a = np.array([[4, 6],[2, 1]])
print("Original array: ")
print(a)
print("Sort along the first axis: ")
x = np.sort(a, axis=0)
print(x)
print("Sort along the last axis: ")
y = np.sort(x, axis=1)
print(y)
| 51 |
# Check whether a Numpy array contains a specified row in Python
# importing package
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]
])
# view array
prin... | 81 |
# Write a NumPy program to move the specified axis backwards, until it lies in a given position.
import numpy as np
x = np.ones((2,3,4,5))
print(np.rollaxis(x, 3, 1).shape)
| 28 |
# Write a Python program to generate all possible permutations of n different objects.
import itertools
def permutations_all(l):
for values in itertools.permutations(l):
print(values)
permutations_all([1])
print("\n")
permutations_all([1,2])
print("\n")
permutations_all([1,2,3])
| 28 |
# Count distinct elements in an array
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
size = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,size):
num = int(input())
arr.append(num)
for i in range(0, size):
if(arr[i]>=max):
max=arr[i]
for i in r... | 70 |
# Write a Python program to get the items from a given list with specific condition.
def first_index(l1):
return sum(1 for i in l1 if (i> 45 and i % 2 == 0))
nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83]
print("Original list:")
print(nums)
n = 45
print("\nNumber of Items of the said list which are even... | 56 |
# Write a Python program to List product excluding duplicates
# Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ... | 104 |
# Write a Python program to search a date from a given string using arrow module.
import arrow
print("\nSearch a date from a string:")
d1 = arrow.get('David was born in 11 June 2003', 'DD MMMM YYYY')
print(d1)
| 37 |
# Write a Python program to create datetime from integers, floats and strings timestamps using arrow module.
import arrow
i = arrow.get(1857900545)
print("Date from integers: ")
print(i)
f = arrow.get(1857900545.234323)
print("\nDate from floats: ")
print(f)
s = arrow.get('1857900545')
print("\nDate from Strings: ")... | 43 |
# Write a Python program to shift last element to first position and first element to last position in a given list.
def shift_first_last(lst):
x = lst.pop(0)
y = lst.pop()
lst.insert(0, y)
lst.insert(len(lst), x)
return lst
nums = [1,2,3,4,5,6,7]
print("Original list:")
print(nums)
print("Shift... | 82 |
# Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.
def substring_copy(str, n):
flen = 2
if flen > len(str):
flen = len(str)
substr = str[:flen]
result = ""
for i in ran... | 70 |
# Write a Python program to Flatten a 2d numpy array into 1d array
# Python code to demonstrate
# flattening a 2d numpy array
# into 1d array
import numpy as np
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
# printing initial arrays
print("initial array", str(ini_array1))
# Multiplying arrays
r... | 65 |
# Write a Python program to create a time object with the same hour, minute, second, microsecond and a timestamp representation of the Arrow object, in UTC time.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nTime object with the same hour, minute, second, microsecond:")
print(arrow.utc... | 56 |
# Write a NumPy program to change the dimension of an array.
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
print("6 rows and 0 columns")
print(x.shape)
y = np.array([[1, 2, 3],[4, 5, 6],[7,8,9]])
print("(3, 3) -> 3 rows and 3 columns ")
print(y)
x = np.array([1,2,3,4,5,6,7,8,9])
print("Change array shape to ... | 68 |
# How to get all 2D diagonals of a 3D NumPy array in Python
# Import the numpy package
import numpy as np
# Create 3D-numpy array
# of 4 rows and 4 columns
arr = np.arange(3 * 4 * 4).reshape(3, 4, 4)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
... | 65 |
# Program to Find the multiplication of two matrices
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the 1st matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([in... | 118 |
# Write a NumPy program to create display every element of a NumPy array.
import numpy as np
x = np.arange(12).reshape(3, 4)
for x in np.nditer(x):
print(x,end=' ')
print()
| 29 |
# Write a Pandas program to add 100 days with reporting date of unidentified flying object (UFO).
import pandas as pd
from datetime import timedelta
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nAdd 100 days with reporti... | 46 |
# Python Program to Find the Length of 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... | 105 |
# Write a Python program to build flashcard using class in Python
class flashcard:
def __init__(self, word, meaning):
self.word = word
self.meaning = meaning
def __str__(self):
#we will return a string
return self.word+' ( '+self.meaning+' )'
flash = []
print... | 111 |
# Write a NumPy program to create an array of all the even integers from 30 to 70.
import numpy as np
array=np.arange(30,71,2)
print("Array of all the even integers from 30 to 70")
print(array)
| 34 |
# Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series.
import pandas as pd
import numpy as np
num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = np.argwhere(num_series % 5==0)
print("Positions of numbers that are mult... | 50 |
# Write a NumPy program to compute pearson product-moment correlation coefficients of two given arrays.
import numpy as np
x = np.array([0, 1, 3])
y = np.array([2, 4, 5])
print("\nOriginal array1:")
print(x)
print("\nOriginal array1:")
print(y)
print("\nPearson product-moment correlation coefficients of the said arr... | 44 |
# Write a NumPy program to test whether each element of a 1-D array is also present in a second array.
import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [0, 40]
print("Array2: ",array2)
print("Compare each element of array1 and array2")
print(np.in1d(array1, array2))
| 49 |
# Write a Python program to Creating a Pandas dataframe column based on a given condition
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011',
'11/11/2011', '11/12/2011'],
'... | 50 |
# Write a Python program to Extract tuples having K digit elements
# Python3 code to demonstrate working of
# Extract K digit Elements Tuples
# Using all() + list comprehension
# initializing list
test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )]
# printing original list
print("The original list is :... | 102 |
# Write a Python program to Convert a set into dictionary
# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
# Converting set to dictionary
res = dict.fro... | 66 |
# Write a Python program to calculate surface volume and area of a sphere.
pi=22/7
radian = float(input('Radius of sphere: '))
sur_area = 4 * pi * radian **2
volume = (4/3) * (pi * radian ** 3)
print("Surface Area is: ", sur_area)
print("Volume is: ", volume)
| 47 |
# Write a Python program to print number with commas as thousands separators(from right side).
print("{:,}".format(1000000))
print("{:,}".format(10000))
| 17 |
# Write a Python program to count integer in a given mixed list.
def count_integer(list1):
ctr = 0
for i in list1:
if isinstance(i, int):
ctr = ctr + 1
return ctr
list1 = [1, 'abcd', 3, 1.2, 4, 'xyz', 5, 'pqr', 7, -5, -12.22]
print("Original list:")
print(list1)
print("\nNumber of ... | 57 |
# Write a Python program to decapitalize the first letter of a given string.
def decapitalize_first_letter(s, upper_rest = False):
return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])
print(decapitalize_first_letter('Java Script'))
print(decapitalize_first_letter('Python'))
| 29 |
# Python Program to Print all the Paths from the Root to the Leaf in a Tree
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key... | 189 |
# Program to display a lower triangular matrix
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([int(j) for j... | 71 |
# Write a Python program to chunk a given list into n smaller lists.
from math import ceil
def chunk_list_into_n(nums, n):
size = ceil(len(nums) / n)
return list(
map(lambda x: nums[x * size:x * size + size],
list(range(n)))
)
print(chunk_list_into_n([1, 2, 3, 4, 5, 6, 7], 4))
| 47 |
# Write a Python program to get all unique combinations of two Lists
# python program to demonstrate
# unique combination of two lists
# using zip() and permutation of itertools
# import itertools package
import itertools
from itertools import permutations
# initialize lists
list_1 = ["a", "b", "c","d"]
list_2 = ... | 108 |
# How To Automate Google Chrome Using Foxtrot and Python
# Import the required modules
from selenium import webdriver
import time
# Main Function
if __name__ == '__main__':
# Provide the email and password
email = ''
password = ''
options = webdriver.ChromeOptions()
options.add_argument("... | 163 |
# Write a Pandas program to split a given dataset using group by on specified column into two labels and ranges.
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({
'salesman_id': [5001,5002,5003,5004,5005,5006,5007,5008,5009,5... | 68 |
# Select row with maximum and minimum value in Pandas dataframe in Python
# importing pandas and numpy
import pandas as pd
import numpy as np
# data of 2018 drivers world championship
dict1 ={'Driver':['Hamilton', 'Vettel', 'Raikkonen',
'Verstappen', 'Bottas', 'Ricciardo',
'Hulk... | 104 |
# Get the index of minimum value in DataFrame column 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) | 28 |
# Write a Python program to sort a list of elements using Gnome sort.
def gnome_sort(nums):
if len(nums) <= 1:
return nums
i = 1
while i < len(nums):
if nums[i-1] <= nums[i]:
i += 1
else:
nums[i-1], nums[i] = nums[i], nums[i-1]
i ... | 69 |
# Limited rows selection with given column in Pandas | Python
# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
... | 63 |
# Program to print the Inverted V Star Pattern
row_size=int(input("Enter the row size:"))
print_control_x=row_size
print_control_y=row_size
for out in range(1,row_size+1):
for in1 in range(1,row_size*2+1):
if in1==print_control_x or in1==print_control_y:
print("*",end="")
else:
... | 35 |
# Write a Python program to split an iterable and generate iterables specified number of times.
import itertools as it
def tee_data(iter, n):
return it.tee(iter, n)
#List
result = tee_data(['A','B','C','D'], 5)
print("Generate iterables specified number of times:")
for i in result:
print(list(i))
#String
re... | 59 |
# Program to convert decimal to octal using while loop
sem=1
octal=0
print("Enter the Decimal Number:")
number=int(input())
while(number !=0):
octal=octal+(number%8)*sem
number=number//8
sem=int(sem*10)
print("Octal Number is ",octal)
| 26 |
# Write a Python program to add to a tag's contents in a given html document.
from bs4 import BeautifulSoup
html_doc = '<a href="http://example.com/">HTML<i>w3resource.com</i></a>'
soup = BeautifulSoup(html_doc, "lxml")
print("\nOriginal Markup:")
print(soup.a)
soup.a.append("CSS")
print("\nAfter append a text in th... | 41 |
# Write a Python program to find the numbers of a given string and store them in a list, display the numbers which are bigger than the length of the list in sorted form. Use lambda function to solve the problem.
str1 = "sdf 23 safs8 5 sdfsd8 sdfs 56 21sfs 20 5"
print("Original string: ",str1)
str_num=[i for i in str... | 81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.