code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to create a doubly linked list and print nodes from current position to first node.
class Node(object):
# Doubly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(obje... | 141 |
# Write a Pandas program to split a given dataframe into groups and display target column as a list of unique values.
import pandas as pd
df = pd.DataFrame( {'id' : ['A','A','A','A','A','A','B','B','B','B','B'],
'type' : [1,1,1,1,2,2,1,1,1,2,2],
'book' : ['Math','Math','Engl... | 69 |
# 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 Pandas program to split a given dataset, group by one column and apply an aggregate function to few columns and another aggregate function to the rest of the columns of the dataframe.
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df = pd.DataFrame({
... | 219 |
# Write a Python program to assess if a file is closed or not.
f = open('abc.txt','r')
print(f.closed)
f.close()
print(f.closed)
| 20 |
# Write a Python program to get the proleptic Gregorian ordinal of a given date.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nProleptic Gregorian ordinal of the date:")
print(arrow.utcnow().toordinal())
| 30 |
# Write a NumPy program to extract first element of the second row and fourth element of fourth row from a given (4x4) array.
import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print("Original array:")
print(arra_data)
print("\nExtracted data: First element of the second row and fourth element of fourth ... | 52 |
# Write a Python program to sort a list of elements using Pancake sort.
def pancake_sort(nums):
arr_len = len(nums)
while arr_len > 1:
mi = nums.index(max(nums[0:arr_len]))
nums = nums[mi::-1] + nums[mi+1:len(nums)]
nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]
arr_len ... | 57 |
# Write a NumPy program to Create a 1-D array of 30 evenly spaced elements between 2.5. and 6.5, inclusive.
import numpy as np
x = np.linspace(2.5, 6.5, 30)
print(x)
| 30 |
# Write a Python program to print a dictionary in table format.
my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}
for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
print(*row)
| 27 |
# Write a Python program to get every element that exists in any of the two given lists once, after applying the provided function to each element of both.
def union_by_el(x, y, fn):
_x = set(map(fn, x))
return list(set(x + [item for item in y if fn(item) not in _x]))
from math import floor
print(union_by_el([4... | 58 |
# Write a Python program to generate a 3*4*6 3D array whose each element is *.
array = [[ ['*' for col in range(6)] for col in range(4)] for row in range(3)]
print(array)
| 33 |
# Write a Pandas program to find the all the business quarterly begin and end dates of a specified year.
import pandas as pd
q_start_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQS-JUN')
q_end_dates = pd.date_range('2020-01-01', '2020-12-31', freq='BQ-JUN')
print("All the business quarterly begin dates o... | 52 |
# Lambda with if but without else in Python
# Lambda function with if but without else.
square = lambda x : x*x if(x > 0)
print(square(6)) | 27 |
# Write a Python program to create a list of random integers and randomly select multiple items from the said list. Use random.sample()
import random
print("Create a list of random integers:")
population = range(0, 100)
nums_list = random.sample(population, 10)
print(nums_list)
no_elements = 4
print("\nRandomly sele... | 70 |
# a href="#EDITOR">Go to the editor</a>
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
| 28 |
# Write a Python program to find the last occurrence of a specified item in a given list.
def last_occurrence(l1, ch):
return ''.join(l1).rindex(ch)
chars = ['s','d','f','s','d','f','s','f','k','o','p','i','w','e','k','c']
print("Original list:")
print(chars)
ch = 'f'
print("Last occurrence of",ch,"in the said ... | 73 |
# Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number.
def sieve_of_Eratosthenes(num):
limitn = num+1
not_prime_num = set()
prime_nums = []
for i in range(2, limitn):
if i in not_prime_num:
continue
for f in ran... | 50 |
# Write a Python program to create a deque from an existing iterable object.
import collections
even_nums = (2, 4, 6)
print("Original tuple:")
print(even_nums)
print(type(even_nums))
even_nums_deque = collections.deque(even_nums)
print("\nOriginal deque:")
print(even_nums_deque)
even_nums_deque.append(8)
even_nums_d... | 44 |
# Write a Python program to display half diamond pattern of numbers with star border
# function to display the pattern up to n
def display(n):
print("*")
for i in range(1, n+1):
print("*", end="")
# for loop to display number up to i
for j in range(1, i+1):
... | 125 |
# Ways to remove i’th character from string in Python
# Python code to demonstrate
# method to remove i'th character
# Naive Method
# Initializing String
test_str = "GeeksForGeeks"
# Printing original string
print ("The original string is : " + test_str)
# Removing char at pos 3
# using loop
new_str = ""
... | 85 |
# Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
:
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print evenNumbers
| 38 |
# Write a Python program to Remove Tuples of Length K
# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using list comprehension
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print("The original list : " + str(test_list))
# init... | 102 |
# How to switch to new window in Selenium for Python
# import modules
from selenium import webdriver
import time
# provide the path for chromedriver
PATH = "C:/chromedriver.exe"
# pass on the path to driver for working
driver = webdriver.Chrome(PATH) | 41 |
# Write a Python program to round every number of a given list of numbers and print the total sum multiplied by the length of the list.
nums = [22.4, 4.0, -16.22, -9.10, 11.00, -12.22, 14.20, -5.20, 17.50]
print("Original list: ", nums)
print("Result:")
lenght=len(nums)
print(sum(list(map(round,nums))* lenght))
| 46 |
# Write a Python program to Replace all occurrences of a substring in a string
# Python3 code to demonstrate working of
# Swap Binary substring
# Using translate()
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Swap Binary substrin... | 72 |
# How to compute numerical negative value for all elements in a given NumPy array in Python
# importing library
import numpy as np
# creating a array
x = np.array([-1, -2, -3,
1, 2, 3, 0])
print("Printing the Original array:",
x)
# converting array elements to
# its corresponding negative va... | 64 |
# Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length using lambda.
def check_string(str1):
messg = [
lambda str1: any(x.isupper() for x in str1) or 'String must have 1 upper case character.',
lambda str1: any(x.islower() fo... | 116 |
# Write a Python program to Flatten Tuples List to String
# Python3 code to demonstrate working of
# Flatten Tuples List to String
# using join() + list comprehension
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
# printing original tuples list
print("The original... | 95 |
# Write a NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays.
import numpy as np
x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100])
y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001])
print("Original numbers:")
print(x)
print(y)
print("C... | 64 |
# Python Program To Find the Smallest and Largest Elements in the Binary Search Tree
class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left i... | 233 |
# Write a NumPy program to convert 1-D arrays as columns into a 2-D array.
import numpy as np
a = np.array((10,20,30))
b = np.array((40,50,60))
c = np.column_stack((a, b))
print(c)
| 30 |
# How to get the floor, ceiling and truncated values of the elements of a numpy array in Python
# Import the numpy library
import numpy as np
# Initialize numpy array
a = np.array([1.2])
# Get floor value
a = np.floor(a)
print(a) | 43 |
# Write a Python program to get all values from an enum class.
from enum import IntEnum
class Country(IntEnum):
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
country_code_list = list(map(int, Country))
print(country_code_list)
| 42 |
# Simple Diamond Pattern in Python
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size//2+2):
for j in range(size):
# condition to left space
# condit... | 121 |
# Write a Python program to find the second smallest number in a list.
def second_smallest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] == numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
... | 71 |
# Write a Pandas program to create a line plot of the opening, closing stock prices of Alphabet Inc. between two specific dates.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-30') ... | 75 |
# Write a Python program to convert timezone from local to utc, utc to local or specified zones.
import arrow
utc = arrow.utcnow()
print("utc:")
print(utc)
print("\nutc to local:")
print(utc.to('local'))
print("\nlocal to utc:")
print(utc.to('local').to('utc'))
print("\nutc to specific location:")
print(utc.to('US/P... | 38 |
# Write a NumPy program to extract all the elements of the first and fourth columns from a given (4x4) array.
import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print("Original array:")
print(arra_data)
print("\nExtracted data: All the elements of the first and fourth columns ")
print(arra_data[:, [0,3]]... | 46 |
# Write a Pandas program to extract only 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'],
'address': ['7277 Surrey Ave.','920 N. Bishop Ave.','99... | 72 |
# Program to Find gcd or hcf of two numbers
print("Enter two number to find G.C.D")
num1=int(input())
num2=int(input())
while(num1!=num2):
if (num1 > num2):
num1 = num1 - num2
else:
num2= num2 - num1
print("G.C.D is",num1)
| 35 |
# Write a Python program to retrieve the value of the nested key indicated by the given selector list from a dictionary or list.
from functools import reduce
from operator import getitem
def test(d, selectors):
return reduce(getitem, selectors, d)
users = {
'Carla ': {
'name': {
'first': 'Carla ',
... | 71 |
# Write a Python Dictionary to find mirror characters in a string
# function to mirror characters of a string
def mirrorChars(input,k):
# create dictionary
original = 'abcdefghijklmnopqrstuvwxyz'
reverse = 'zyxwvutsrqponmlkjihgfedcba'
dictChars = dict(zip(original,reverse))
# separate out st... | 91 |
# Write a Pandas program to swap the cases of a specified character column in a given DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12... | 53 |
# Write a Python program to find the difference between two list including duplicate elements.
def list_difference(l1,l2):
result = list(l1)
for el in l2:
result.remove(el)
return result
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print("Original lists:")
print(l1)
print(l2)
print("\nDifferenc... | 46 |
# Write a Python program to Filter Range Length Tuples
# Python3 code to demonstrate working of
# Filter Range Length Tuples
# Using list comprehension + len()
# Initializing list
test_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
# printing original list
print("The original list is : " + str(test_lis... | 107 |
# Compute the Kronecker product of two multidimension NumPy arrays in Python
# Importing required modules
import numpy
# Creating arrays
array1 = numpy.array([[1, 2], [3, 4]])
print('Array1:\n', array1)
array2 = numpy.array([[5, 6], [7, 8]])
print('\nArray2:\n', array2)
# Computing the Kronecker Product
kroneck... | 50 |
# Write a Python program to Minimum number of subsets with distinct elements using Counter
# Python program to find Minimum number of
# subsets with distinct elements using Counter
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
def minSubsets(input):
... | 85 |
# Write a Python program to construct an infinite iterator that returns evenly spaced values starting with a specified number and step.
import itertools as it
start = 10
step = 1
print("The starting number is ", start, "and step is ",step)
my_counter = it.count(start, step)
# Following loop will run for ever
print(... | 64 |
# Conditional operation on Pandas DataFrame columns in Python
# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':['Umbrella', 'Matress', 'Badminton', 'Shuttle'],
'Last Pr... | 51 |
# Write a Python program to generate a random integer between 0 and 6 - excluding 6, random integer between 5 and 10 - excluding 10, random integer between 0 and 10, with a step of 3 and random date between two dates. Use random.randrange()
import random
import datetime
print("Generate a random integer between 0 and ... | 116 |
# Write a NumPy program to add two arrays A and B of sizes (3,3) and (,3).
import numpy as np
A = np.ones((3,3))
B = np.arange(3)
print("Original array:")
print("Array-1")
print(A)
print("Array-2")
print(B)
print("A + B:")
new_array = A + B
print(new_array)
| 42 |
# Write a Python program to remove the characters which have odd index values of a given string.
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))
| 42 |
# Write a Python program to Swap elements in String list
# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
# printing original lists
print("The original list is : " + str(test_list))
# Swa... | 85 |
# Write a Pandas program to calculate all the sighting days of the unidentified flying object (ufo) from current date.
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
now = pd.to_datetime('today')
print("Original Dataframe:")
print(df.head())
print("\nCurre... | 39 |
# Write a Pandas program to split the following dataframe into groups based on all columns and calculate Groupby value counts on the dataframe.
import pandas as pd
df = pd.DataFrame( {'id' : [1, 2, 1, 1, 2, 1, 2],
'type' : [10, 15, 11, 20, 21, 12, 14],
'book' : ['Math','Engl... | 62 |
# numpy.var() in Python
# Python Program illustrating
# numpy.var() method
import numpy as np
# 1D array
arr = [20, 2, 7, 1, 34]
print("arr : ", arr)
print("var of arr : ", np.var(arr))
print("\nvar of arr : ", np.var(arr, dtype = np.float32))
print("\nvar of arr : ", np.var(arr, dtype = np.float... | 53 |
# Write a Python program to detect the number of local variables declared in a function.
def abc():
x = 1
y = 2
str1= "w3resource"
print("Python Exercises")
print(abc.__code__.co_nlocals)
| 29 |
# How to check if a Python variable exists
def func():
# defining local variable
a_variable = 0
# using locals() function
# for checking existence in symbol table
is_local_var = "a_variable" in locals()
# printing result
print(is_local_var)
# driver code
func() | 42 |
# Write a Pandas program to add summation to a row of the given excel file.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
sum_row=df[["Production", "Labor_Hours"]].sum()
df_sum=pd.DataFrame(data=sum_row).T
df_sum=df_sum.reindex(columns=df.columns)
df_sum
| 32 |
# Write a NumPy program to generate a uniform, non-uniform random sample from a given 1-D array with and without replacement.
import numpy as np
print("Generate a uniform random sample with replacement:")
print(np.random.choice(7, 5))
print("\nGenerate a uniform random sample without replacement:")
print(np.rando... | 77 |
# Write a Python program to Get Function Signature
from inspect import signature
# declare a function gfg with some
# parameter
def gfg(x:str, y:int):
pass
# with the help of signature function
# store signature of the function in
# variable t
t = signature(gfg)
# print the signature of the function
p... | 78 |
# Program to check if a string contains any special character in Python
// C++ program to check if a string
// contains any special character
// import required packages
#include <iostream>
#include <regex>
using namespace std;
// Function checks if the string
// contains any special character
void run(str... | 113 |
# Write a Pandas program to create a heatmap (rectangular data as a color-encoded matrix) for comparison of the top 10 years in which the UFO was sighted vs each Month.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Source: https://bit.ly/1l9yjm9
df = pd.read_csv(r'ufo.csv')
df['Date_time... | 93 |
# Write a Python program to Get list of running processes
import wmi
# Initializing the wmi constructor
f = wmi.WMI()
# Printing the header for the later columns
print("pid Process name")
# Iterating through all the running processes
for process in f.Win32_Process():
# Displaying the P_ID and P_Name... | 54 |
# Write a Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
# Python code to find if we can make first string
# from second by deleting some characters from
# second and rearranging remaining characters.
from collections import Counter
def makeString(str1,str2):
... | 132 |
# Write a Python program to delete the first item from a singly linked list.
class Node:
# Singly linked node
def __init__(self, data=None):
self.data = data
self.next = None
class singly_linked_list:
def __init__(self):
# Createe an empty list
self.tail = None
sel... | 168 |
# Write a Python program to calculate the sum of the numbers in a list between the indices of a specified range.
def sum_Range_list(nums, m, n): ... | 61 |
# Lambda expression in Python to rearrange positive and negative numbers
# Function to rearrange positive and negative elements
def Rearrange(arr):
# First lambda expression returns list of negative numbers
# in arr.
# Second lambda expression returns list of positive numbers
# in arr.
return [... | 85 |
# Write a python program to check whether two lists are circularly identical.
list1 = [10, 10, 0, 0, 10]
list2 = [10, 10, 10, 0, 0]
list3 = [1, 10, 10, 0, 0]
print('Compare list1 and list2')
print(' '.join(map(str, list2)) in ' '.join(map(str, list1 * 2)))
print('Compare list1 and list3')
print(' '.join(map(str, li... | 60 |
# Write a Python program to Filter Strings combination of K substrings
# Python3 code to demonstrate working of
# Filter Strings combination of K substrings
# Using permutations() + map() + join() + set() + loop
from itertools import permutations
# initializing list
test_list = ["geeks4u", "allbest", "abcdef"]
... | 119 |
# Write a Python program to get all possible two digit letter combinations from a digit (1 to 9) string.
def letter_combinations(digits):
if digits == "":
return []
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",... | 84 |
# Write a Python program to insert an element at the beginning of a given OrderedDictionary.
from collections import OrderedDict
color_orderdict = OrderedDict([('color1', 'Red'), ('color2', 'Green'), ('color3', 'Blue')])
print("Original OrderedDict:")
print(color_orderdict)
print("Insert an element at the beginning... | 49 |
# Difference of two columns in Pandas dataframe in Python
import pandas as pd
# Create a DataFrame
df1 = { 'Name':['George','Andrea','micheal',
'maggie','Ravi','Xien','Jalpa'],
'score1':[62,47,55,74,32,77,86],
'score2':[45,78,44,89,66,49,72]}
df1 = pd.DataFrame(df1,columns= ['Nam... | 48 |
# Write a Python program to create non-repeated combinations of Cartesian product of four given list of numbers.
import itertools as it
mums1 = [1, 2, 3, 4]
mums2 = [5, 6, 7, 8]
mums3 = [9, 10, 11, 12]
mums4 = [13, 14, 15, 16]
print("Original lists:")
print(mums1)
print(mums2)
print(mums3)
print(mums4)
print("\nSum ... | 65 |
# Write a NumPy program to compute the determinant of a given square array.
import numpy as np
from numpy import linalg as LA
a = np.array([[1, 0], [1, 2]])
print("Original 2-d array")
print(a)
print("Determinant of the said 2-D array:")
print(np.linalg.det(a))
| 41 |
# Write a Python Dictionary | Check if binary representations of two numbers are anagram
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1,num2):
# convert numbers into in binary
# and remove first two characters of
# ou... | 130 |
# Write a NumPy program to find the closest value (to a given scalar) in an array.
import numpy as np
x = np.arange(100)
print("Original array:")
print(x)
a = np.random.uniform(0,100)
print("Value to compare:")
print(a)
index = (np.abs(x-a)).argmin()
print(x[index])
| 38 |
# Program to find the transpose of a 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 in... | 89 |
# Write a Python program to get the last part of a string before a specified character.
str1 = 'https://www.w3resource.com/python-exercises/string'
print(str1.rsplit('/', 1)[0])
print(str1.rsplit('-', 1)[0])
| 24 |
# Write a Pandas program to filter those records which not appears in a given list from world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
new_w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(new_w_a_con.head())
print("\nSelect all ... | 60 |
# Write a Python program to build a list, using an iterator function and an initial seed value.
def unfold(fn, seed):
def fn_generator(val):
while True:
val = fn(val[1])
if val == False: break
yield val[0]
return [i for i in fn_generator([None, seed])]
f = lambda n: False if n > 40 else [-... | 58 |
# Program to Find the sum of series 3+33+333.....+N
n=int(input("Enter the range of number:"))sum=0p=3for i in range(1,n+1): sum += p p=(p*10)+3print("The sum of the series = ",sum) | 27 |
# Write a NumPy program to create a three-dimension array with shape (300,400,5) and set to a variable. Fill the array elements with values using unsigned integer (0 to 255).
import numpy as np
np.random.seed(32)
nums = np.random.randint(low=0, high=256, size=(300, 400, 5), dtype=np.uint8)
print(nums)
| 44 |
# Write a Python program to randomize the order of the values of an list, returning a new list.
from copy import deepcopy
from random import randint
def shuffle_list(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst... | 70 |
# Write a Python program to create a table and insert some records in that table. Finally selects all rows from the table and display the records.
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error... | 131 |
# Program to find the sum of series 1+X+X^2/2!+X^3/3!...+X^N/N!
print("Enter the range of number:")
n=int(input())
print("Enter the value of x:")
x=int(input())
sum=1.0
i=1
while(i<=n):
fact=1
for j in range(1,i+1):
fact*=j
sum+=pow(x,i)/fact
i+=1
print("The sum of the series = ",sum) | 39 |
# Write a Pandas program to create a time series using three months frequency.
import pandas as pd
time_series = pd.date_range('1/1/2021', periods = 36, freq='3M')
print("Time series using three months frequency:")
print(time_series)
| 32 |
# Write a Python program to find the list with maximum and minimum length using lambda.
def max_length_list(input_list):
max_length = max(len(x) for x in input_list )
max_list = max(input_list, key = lambda i: len(i))
return(max_length, max_list)
def min_length_list(input_list):
min_lengt... | 85 |
# Write a Python program to check if a string has at least one letter and one number
def checkString(str):
# intializing flag variable
flag_l = False
flag_n = False
# checking for letter and numbers in
# given string
for i in str:
# if string has letter
if... | 83 |
# Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise, sales man wise.
import numpy as np
import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=["Region","Manager","SalesMan"], values="Sale_amt", aggfunc=np.sum))
| 37 |
# Write a Python program to create a naïve (without time zone) datetime representation of the Arrow object.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
r = arrow.now('US/Mountain')
print("\nNaive datetime representation:")
print(r.naive)
| 33 |
# Python Program to Read a Number n and Compute n+nn+nnn
n=int(input("Enter a number n: "))
temp=str(n)
t1=temp+temp
t2=temp+temp+temp
comp=n+int(t1)+int(t2)
print("The value is:",comp) | 23 |
# Write a Python program to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters.
from itertools import groupby
def modified_encode(alist):
def ctr_ele(el):
if len(el)>1: return [len(el), el[0]]
else: return el[0]
... | 84 |
# Write a Python program to get all possible combinations of the elements of a given list using itertools module.
import itertools
def combinations_list(list1):
temp = []
for i in range(0,len(list1)+1):
temp.append(list(itertools.combinations(list1,i)))
return temp
colors = ['orange', 'red', 'gr... | 52 |
# Write a NumPy program to find the first Monday in May 2017.
import numpy as np
print("First Monday in May 2017:")
print(np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon'))
| 26 |
# Convert String to Set in Python
# create a string str
string = "geeks"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string... | 56 |
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot where each bar will represent one of the top 10 production.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel('E:\coalpublic2013.xlsx')
sorted_by_production = df.sort_valu... | 51 |
# Write a Python program to find four elements from a given array of integers whose sum is equal to a given number. The solution set must not contain duplicate quadruplets.
#Source: https://bit.ly/2SSoyhf
from bisect import bisect_left
class Solution:
def fourSum(self, nums, target):
"""
:type nu... | 227 |
# Write a NumPy program to find the nearest value from a given value in an array.
import numpy as np
x = np.random.uniform(1, 12, 5)
v = 4
n = x.flat[np.abs(x - v).argmin()]
print(n)
| 35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.