code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to Mirror Image of String
# Python3 code to demonstrate working of
# Mirror Image of String
# Using Mirror Image of String
# initializing strings
test_str = 'void'
# printing original string
print("The original string is : " + str(test_str))
# initializing mirror dictionary
mir_dict... | 104 |
# Find the power of a number using recursion
def Power(num1,num2): if num2==0: return 1 return num1*Power(num1, num2-1)num1=int(input("Enter the base value:"))num2=int(input("Enter the power value:"))print("Power of Number Using Recursion is:",Power(num1,num2)) | 29 |
# Write a Python program to get a datetime or timestamp representation from current datetime.
import arrow
a = arrow.utcnow()
print("Datetime representation:")
print(a.datetime)
b = a.timestamp
print("\nTimestamp representation:")
print(b)
| 29 |
# Write a Python program to Creating DataFrame from dict of narray/lists
# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd
# initialise data of lists.
data = {'Category':['Array', 'Stack', 'Queue'],
'Marks':[20, 21, 19]}
# Create DataFram... | 57 |
# Write a Pandas program to create a Pivot table and count the manager wise sale and mean value of sale amount.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index=["Manager"],values=["Sale_amt"],aggfunc=[np.mean,len]))
| 34 |
# Write a Python program to check whether a list contains a sublist.
def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n = 1
while (n < len(s)) and (l[i+n] == s[n])... | 85 |
# Write a Python program to Convert Matrix to Custom Tuple Matrix
# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
... | 103 |
# Write a Python program to check a dictionary is empty or not.
my_dict = {}
if not bool(my_dict):
print("Dictionary is empty")
| 22 |
# Write a NumPy program to extract first and second elements of the first and second rows 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 and second elements of the first and second rows ")
print(arra_da... | 48 |
# Write a Python program to remove duplicate words from a given string.
def unique_list(text_str):
l = text_str.split()
temp = []
for x in l:
if x not in temp:
temp.append(x)
return ' '.join(temp)
text_str = "Python Exercises Practice Solution Exercises"
print("Original String:")... | 53 |
# Write a Python program to execute a string containing Python code.
mycode = 'print("hello world")'
code = """
def mutiply(x,y):
return x*y
print('Multiply of 2 and 3 is: ',mutiply(2,3))
"""
exec(mycode)
exec(code)
| 33 |
# Write a python program to access environment variables and value of the environment variable.
import os
print("Access all environment variables:")
print('*----------------------------------*')
print(os.environ)
print('*----------------------------------*')
print("Access a particular environment variable:")
print(o... | 41 |
# Check whether a given number is Friendly pair or not
'''Write
a Python program to check whether a given number is Friendly pair or
not. or
Write a program to check whether
a given number is Friendly pair or not
using Python '''
print("Enter two numbers:")
num1=int(input())
num2=int(input())
sum1=0
sum2=0
fo... | 77 |
# Change Data Type for one or more columns in Pandas Dataframe in Python
# importing pandas as pd
import pandas as pd
# sample dataframe
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [1.1, '1.0', '1.3', 2, 5] })
# converting all columns to string type
df = df.astype(... | 59 |
# Write a NumPy program to sum and compute the product of a NumPy array elements.
import numpy as np
x = np.array([10, 20, 30], float)
print("Original array:")
print(x)
print("Sum of the array elements:")
print(x.sum())
print("Product of the array elements:")
print(x.prod())
| 41 |
# Write a Pandas program to create a Pivot table and find number of survivors and average rate grouped by gender and class.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index='sex', columns='class', aggfunc={'survived':sum, 'fare':'mean'})
print(result)
| 41 |
# Write a Python program to Filter dictionary values in heterogeneous dictionary
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# p... | 108 |
# Write a Python program to Update each element in tuple list
# Python3 code to demonstrate working of
# Update each element in tuple list
# Using list comprehension
# initialize list
test_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
# printing original list
print("The original list : " + str(test_list))
# init... | 98 |
# Write a Python program to Elements Frequency in Mixed Nested Tuple
# Python3 code to demonstrate working of
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
# helper_fnc
def flatten(test_tuple):
for tup in test_tuple:
if isinstance(tup, tuple):
yield from flatten(tup)
... | 112 |
# Write a Python program to Find all close matches of input string from a list
# Function to find all close matches of
# input string in given list of possible strings
from difflib import get_close_matches
def closeMatches(patterns, word):
print(get_close_matches(word, patterns))
# Driver program
if __nam... | 60 |
# Write a Python program to generate 26 text files named A.txt, B.txt, and so on up to Z.txt.
import string, os
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_uppercase:
with open(letter + ".txt", "w") as f:
f.writelines(letter)
| 38 |
# Write a NumPy program to stack 1-D arrays as columns wise.
import numpy as np
print("\nOriginal arrays:")
x = np.array((1,2,3))
y = np.array((2,3,4))
print("Array-1")
print(x)
print("Array-2")
print(y)
new_array = np.column_stack((x, y))
print("\nStack 1-D arrays as columns wise:")
print(new_array)
| 39 |
# Write a Python program to remove all duplicate elements from a given array and returns a new array.
import array as arr
def test(nums):
return sorted(set(nums),key=nums.index)
array_num = arr.array('i', [1, 3, 5, 1, 3, 7, 9])
print("Original array:")
for i in range(len(array_num)):
print(array_num[i],... | 102 |
# Write a Pandas program to extract the column labels, shape and data types of the dataset (titanic.csv).
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
print("List of columns:")
print(df.columns)
print("\nShape of the Dataset:")
print(df.shape)
print("\nData types of the Dataset:")
print(df.... | 44 |
# Creating a Pandas dataframe using list of tuples in Python
# import pandas to use pandas DataFrame
import pandas as pd
# data in the form of list of tuples
data = [('Peter', 18, 7),
('Riff', 15, 6),
('John', 17, 8),
('Michel', 18, 7),
('Sheli', 17, 5) ]
# create DataFrame us... | 62 |
#
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
def f(n):
if n==0:
return 0
else:
return f(n-1)+100
n=int(raw_input())
print f(n)
| 31 |
# Write a Pandas program to find average consumption of wine per person greater than 2 in world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(w_a_con.head())
print("\nAverage consumpti... | 57 |
# Write a Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# count will contain all the word counts
count = {}
# insert words of string A to hash
for word in A.split()... | 116 |
# Write a Python program to get all possible combinations of the elements of a given list.
def combinations_list(colors):
if len(colors) == 0:
return [[]]
result = []
for el in combinations_list(colors[1:]):
result += [el, el+[colors[0]]]
return result
colors = ['orange', 'red', 'gree... | 56 |
# Write a Python program to find if a given string starts with a given character using Lambda.
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Python'))
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Java'))
| 38 |
# Write a NumPy program to create an array of the integers from 30 to70.
import numpy as np
array=np.arange(30,71)
print("Array of the integers from 30 to70")
print(array)
| 28 |
# Write a Python program to extract and display all the header tags from en.wikipedia.org/wiki/Main_Page.
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen('https://en.wikipedia.org/wiki/Peter_Jeffrey_(RAAF_officer)')
bs = BeautifulSoup(html, 'html.parser')
images = bs.... | 41 |
# How to get the indices of the sorted array using NumPy in Python
import numpy as np
# Original array
array = np.array([10, 52, 62, 16, 16, 54, 453])
print(array)
# Indices of the sorted elements of a
# given array
indices = np.argsort(array)
print(indices) | 46 |
# Write a Python program to add a number to each element in a given list of numbers.
def add_val_to_list(lst, add_val):
result = lst
result = [x+add_val for x in result]
return result
nums = [3,8,9,4,5,0,5,0,3]
print("Original lists:")
print(nums)
add_val = 3
print("\nAdd",add_val,"to each element... | 69 |
# Write a Python function to find the maximum and minimum numbers from a sequence of numbers.
def max_min(data):
l = data[0]
s = data[0]
for num in data:
if num> l:
l = num
elif num< s:
s = num
return l, s
print(max_min([0, 10, 15, 40, -5, 42, 17, 28, 75]))
| 53 |
# Write a Python program to Frequency of numbers in String
# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + len()
import re
# initializing string
test_str = "geeks4feeks is No. 1 4 geeks"
# printing original string
print("The original string is : " + test_str)
... | 81 |
# Write a Python program to get the weighted average of two or more numbers.
def weighted_average(nums, weights):
return sum(x * y for x, y in zip(nums, weights)) / sum(weights)
nums1 = [10, 50, 40]
nums2 = [2, 5, 3]
print("Original list elements:")
print(nums1)
print(nums2)
print("\nWeighted average of the said ... | 84 |
# Program to find square root of a number
import math
num=int(input("Enter the Number:"))
print("Square root of ",num," is : ",math.sqrt(num)) | 21 |
# Write a NumPy program to convert a given list into an array, then again convert it into a list. Check initial list and final list are equal or not.
import numpy as np
a = [[1, 2], [3, 4]]
x = np.array(a)
a2 = x.tolist()
print(a == a2)
| 49 |
# Write a Python program to split a given dictionary of lists into list of dictionaries using map function.
def list_of_dicts(marks):
result = map(dict, zip(*[[(key, val) for val in value] for key, value in marks.items()]))
return list(result)
marks = {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80... | 64 |
# Write a Python program to swap two variables.
a = 30
b = 20
print("\nBefore swap a = %d and b = %d" %(a, b))
a, b = b, a
print("\nAfter swaping a = %d and b = %d" %(a, b))
print()
| 43 |
# Write a Python program to reverse strings in a given list of string values.
def reverse_strings_list(string_list):
result = [x[::-1] for x in string_list]
return result
colors_list = ["Red", "Green", "Blue", "White", "Black"]
print("\nOriginal lists:")
print(colors_list)
print("\nReverse strings of the sa... | 44 |
# Find the most frequent value in a NumPy array in Python
import numpy as np
# create array
x = np.array([1,2,3,4,5,1,2,1,1,1])
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.bincount(x).argmax()) | 33 |
# Write a Python program to sort a list of elements using Bogosort sort.
import random
def bogosort(nums):
def isSorted(nums):
if len(nums) < 2:
return True
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return False
return True
whil... | 62 |
# A Python Dictionary contains List as value. Write a Python program to clear the list values in the said dictionary.
def test(dictionary):
for key in dictionary:
dictionary[key].clear()
return dictionary
dictionary = {
'C1' : [10,20,30],
'C2' : [20,30,40],
... | 55 |
# Write a NumPy program to search the index of a given array in another given array.
import numpy as np
np_array = np.array([[1,2,3], [4,5,6] , [7,8,9], [10, 11, 12]])
test_array = np.array([4,5,6])
print("Original Numpy array:")
print(np_array)
print("Searched array:")
print(test_array)
print("Index of the searched... | 52 |
# Write a Python program to convert a given heterogeneous list of scalars into a string.
def heterogeneous_list_to_str(lst):
result = ','.join(str(x) for x in lst)
return result
h_data = ["Red", 100, -50, "green", "w,3,r", 12.12, False]
print("Original list:")
print(h_data)
print("\nConvert the heterogeneous... | 49 |
# How to change background color of Tkinter OptionMenu widget in Python
# Python program to change menu background
# color of Tkinter's Option Menu
# Import the library tkinter
from tkinter import *
# Create a GUI app
app = Tk()
# Give title to your GUI app
app.title("Vinayak App")
# Construct the label i... | 152 |
# Program to Find subtraction 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([int(j) fo... | 111 |
# Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(m)
| 25 |
# Write a Python program to create a time object with the same hour, minute, second, microsecond and timezone info.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nTime object with the same hour, minute, second, microsecond and timezone info.:")
print(arrow.utcnow().timetz())
| 41 |
# Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard pattern.
import numpy as np
x = np.ones((3,3))
print("Checkerboard pattern:")
x = np.zeros((8,8),dtype=int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x)
| 36 |
# Write a Pandas program to find the sum, mean, max, min value of 'Production (short tons)' column of coalpublic2013.xlsx file.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
print("Sum: ",df["Production"].sum())
print("Mean: ",df["Production"].mean())
print("Maximum: ",df["Prod... | 40 |
# Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.
:
Solution
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
for k in d.keys():
print k
printDict()
| 52 |
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
print("\n")
| 32 |
# Write a Python program to generate the running maximum, minimum value of the elements of an iterable.
from itertools import accumulate
def running_max_product(iters):
return accumulate(iters, max)
#List
result = running_max_product([1,3,2,7,9,8,10,11,12,14,11,12,7])
print("Running maximum value of a list:")
fo... | 92 |
# Write a Python program to reverse the content of a file and store it in another file
# Open the file in write mode
f1 = open("output1.txt", "w")
# Open the input file and get
# the content into a variable data
with open("file.txt", "r") as myfile:
data = myfile.read()
# For Full Reversing we will store t... | 110 |
# Write a Pandas program to filter those records where WHO region matches with multiple values (Africa, Eastern Mediterranean, Europe) 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 da... | 60 |
# Write a Python program to Loop through files of certain extensions
# importing the library
import os
# giving directory name
dirname = 'D:\\AllData'
# giving file extension
ext = ('.exe', 'jpg')
# iterating over all files
for files in os.listdir(dirname):
if files.endswith(ext):
print(files) #... | 54 |
# Write a Python program to count Even and Odd numbers in a List
# Python program to count Even
# and Odd numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
... | 85 |
# Write a Pandas program to create a time-series with two index labels and random values. Also print the type of the index.
import pandas as pd
import numpy as np
import datetime
from datetime import datetime, date
dates = [datetime(2011, 9, 1), datetime(2011, 9, 2)]
print("Time-series with two index labels:")
time_... | 61 |
# Write a Python program to split a variable length string into variables.
var_list = ['a', 'b', 'c']
x, y, z = (var_list + [None] * 3)[:3]
print(x, y, z)
var_list = [100, 20.25]
x, y = (var_list + [None] * 2)[:2]
print(x, y)
| 44 |
# How to scrape multiple pages using Selenium in Python
# importing necessary packages
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# for holding the resultant list
element_list = []
for page in range(1, 3, 1):
page_url = "https://webscraper.io/test-sites/e-co... | 71 |
# Write a Python program to invert a given dictionary with non-unique hashable values.
from collections import defaultdict
def test(students):
obj = defaultdict(list)
for key, value in students.items():
obj[value].append(key)
return dict(obj)
students = {
'Ora Mckinney': 8,
'Theodore Hollandl': 7,
... | 51 |
# Concatenated string with uncommon characters in Python
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# take intersection of two sets to get list of
# co... | 119 |
# Write a Pandas program to create a period index represent all monthly boundaries of a given year. Also print start and end time for each period object in the said index.
import pandas as pd
import datetime
from datetime import datetime, date
sdt = datetime(2020, 1, 1)
edt = datetime(2020, 12, 31)
dateset = pd.peri... | 86 |
# Convert a NumPy array into a csv file in Python
# import necessary libraries
import pandas as pd
import numpy as np
# create a dummy array
arr = np.arange(1,11).reshape(2,5)
# display the array
print(arr)
# convert array into dataframe
DF = pd.DataFrame(arr)
# save the dataframe as a csv file
DF.to_csv(... | 53 |
# Write a Python program to Matrix Row subset
# Python3 code to demonstrate working of
# Matrix Row subset
# Using any() + all() + list comprehension
# initializing lists
test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
# printing original list
print("The original list is : " + str(test_list))
# initializing c... | 107 |
# Write a Pandas program to create a Pivot table with multiple indexes from a given excel sheet (Salesdata.xlsx).
import pandas as pd
df = pd.read_excel('E:\SaleData.xlsx')
print(df)
pd.pivot_table(df,index=["Region","SalesMan"])
| 28 |
# Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))
| 41 |
# Write a Python program to Reverse Row sort in Lists of List
# Python3 code to demonstrate
# Reverse Row sort in Lists of List
# using loop
# initializing list
test_list = [[4, 1, 6], [7, 8], [4, 10, 8]]
# printing original list
print ("The original list is : " + str(test_list))
# Reverse Row sort in List... | 86 |
# Write a NumPy program to find the number of rows and columns of a given matrix.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
print("Original matrix:")
print(m)
print("Number of rows and columns of the said matrix:")
print(m.shape)
| 37 |
# Write a Python program to move a specified element in a given list.
def group_similar_items(seq,el):
seq.append(seq.pop(seq.index(el)))
return seq
colors = ['red','green','white','black','orange']
print("Original list:")
print(colors)
el = "white"
print("Move",el,"at the end of the said list:")
print(gro... | 73 |
# Write a Pandas program to create a Pivot table and find survival rate by gender on various classes.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index='sex', columns='class')
print(result)
| 36 |
# Write a Python program to join adjacent members of a given list.
def test(lst):
result = [x + y for x, y in zip(lst[::2],lst[1::2])]
return result
nums = ['1','2','3','4','5','6','7','8']
print("Original list:")
print(nums)
print("\nJoin adjacent members of a given list:")
print(test(nums))
nums = ['1','... | 55 |
# Write a Pandas program to create a TimeSeries to display all the Sundays of given year.
import pandas as pd
result = pd.Series(pd.date_range('2020-01-01', periods=52, freq='W-SUN'))
print("All Sundays of 2019:")
print(result)
| 31 |
# Write a Python program to read a given CSV file as a dictionary.
import csv
data = csv.DictReader(open("departments.csv"))
print("CSV file as a dictionary:\n")
for row in data:
print(row)
| 29 |
# Write a Python program to remove duplicate words from a given list of strings.
def unique_list(l):
temp = []
for x in l:
if x not in temp:
temp.append(x)
return temp
text_str = ["Python", "Exercises", "Practice", "Solution", "Exercises"]
print("Original String:")
print(text_str)
pr... | 53 |
# Write a NumPy program to get the memory usage by NumPy arrays.
import numpy as np
from sys import getsizeof
x = [0] * 1024
y = np.array(x)
print(getsizeof(x))
| 30 |
# Write a Python program to Row-wise element Addition in Tuple Matrix
# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing ori... | 109 |
# Write a NumPy program to reverse an array (first element becomes last).
import numpy as np
import numpy as np
x = np.arange(12, 38)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x)
| 34 |
# Remove all the occurrences of an element from a list in Python
# Python 3 code to demonstrate
# the removal of all occurrences of a
# given item using list comprehension
def remove_items(test_list, item):
# using list comprehension to perform the task
res = [i for i in test_list if i != item]
... | 124 |
# Program to print square star pattern
print("Enter the row and column size:");
row_size=int(input())
for out in range(0,row_size):
for i in range(0,row_size):
print("*")
print("\r")
| 24 |
# Write a Pandas program to convert Series of lists to one Series.
import pandas as pd
s = pd.Series([
['Red', 'Green', 'White'],
['Red', 'Black'],
['Yellow']])
print("Original Series of list")
print(s)
s = s.apply(pd.Series).stack().reset_index(drop=True)
print("One Series")
print(s)
| 37 |
# Write a Pandas program to find the index of a substring of DataFrame with beginning and end position.
import pandas as pd
df = pd.DataFrame({
'name_code': ['c0001','1000c','b00c2', 'b2c02', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.... | 63 |
# Write a NumPy program to create a 5x5x5 cube of 1's.
import numpy as np
x = np.zeros((5, 5, 5)).astype(int) + 1
print(x)
| 24 |
# Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists.
def grouping_dictionary(l):
result = {}
for k, v in l:
result.setdefault(k, []).append(v)
return result
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]... | 61 |
# Write a Python program to get a dictionary from an object's fields.
class dictObj(object):
def __init__(self):
self.x = 'red'
self.y = 'Yellow'
self.z = 'Green'
def do_nothing(self):
pass
test = dictObj()
print(test.__dict__)
| 33 |
# Write a Python program to Check if String Contain Only Defined Characters using Regex
# _importing module
import re
def check(str, pattern):
# _matching the strings
if re.search(pattern, str):
print("Valid String")
else:
print("Invalid String")
# _driver code
pattern = re.c... | 45 |
# Write a Python program to print all permutations of a given string (including duplicates).
def permute_string(str):
if len(str) == 0:
return ['']
prev_list = permute_string(str[1:len(str)])
next_list = []
for i in range(0,len(prev_list)):
for j in range(0,len(str)):
new_... | 49 |
# Write a Python program to find numbers divisible by nineteen or thirteen from a list of numbers using Lambda.
nums = [19, 65, 57, 39, 152, 639, 121, 44, 90, 190]
print("Orginal list:")
print(nums)
result = list(filter(lambda x: (x % 19 == 0 or x % 13 == 0), nums))
print("\nNumbers of the above list divisible by ... | 62 |
# Write a Python program to Change column names and row indexes in Pandas DataFrame
# first import the libraries
import pandas as pd
# Create a dataFrame using dictionary
df=pd.DataFrame({"Name":['Tom','Nick','John','Peter'],
"Age":[15,26,17,28]})
# Creates a dataFrame with
# 2 columns and 4 r... | 44 |
# Write a Python program to move all spaces to the front of a given string in single traversal.
def moveSpaces(str1):
no_spaces = [char for char in str1 if char!=' ']
space= len(str1) - len(no_spaces)
# Create string with spaces
result = ' '*space
return result + ''.join(no_spaces)
s1 ... | 62 |
# Write a Python program to get the daylight savings time adjustment using arrow module.
import arrow
print("Daylight savings time adjustment:")
a = arrow.utcnow().dst()
print(a)
| 25 |
# Write a Python program to count the frequency in a given dictionary.
from collections import Counter
def test(dictt):
result = Counter(dictt.values())
return result
dictt = {
'V': 10,
'VI': 10,
'VII': 40,
'VIII': 20,
'IX': 70,
'X': 80,
'XI': 40,
'XII': 20,
}
print("\nOriginal Dictionary... | 55 |
# Write a Pandas program to extract the day name from a specified date. Add 2 days and 1 business day with the specified date.
import pandas as pd
newday = pd.Timestamp('2020-02-07')
print("First date:")
print(newday)
print("\nThe day name of the said date:")
print(newday.day_name())
print("\nAdd 2 days with the sai... | 66 |
# Python Program to Select the ith Largest Element from a List in Expected Linear Time
def select(alist, start, end, i):
"""Find ith largest element in alist[start... end-1]."""
if end - start <= 1:
return alist[start]
pivot = partition(alist, start, end)
# number of elements in alist[pivot.... | 179 |
# Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees where hire_date between two specific month and year.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\employee.xlsx')
result = df[(df['hire_date'] >='Jan-2005') & (df['hire_date'] <= 'Dec-... | 49 |
# Write a Python program to calculate the distance between London and New York city.
from geopy import distance
london = ("51.5074° N, 0.1278° W")
newyork = ("40.7128° N, 74.0060° W")
print("Distance between London and New York city (in km):")
print(distance.distance(london, newyork).km," kms")
| 43 |
# How to build an array of all combinations of two NumPy arrays in Python
# importing Numpy package
import numpy as np
# creating 2 numpy arrays
array_1 = np.array([1, 2])
array_2 = np.array([4, 6])
print("Array-1")
print(array_1)
print("\nArray-2")
print(array_2)
# combination of elements of array_1 and ... | 59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.