code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python function to get the city, state and country name of a specified latitude and longitude using Nominatim API and Geopy package.
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")
def city_state_country(coord):
location = geolocator.reverse(coord, exactly_one=True)
address = location.raw['address']
city = address.get('city', '')
state = address.get('state', '')
country = address.get('country', '')
return city, state, country
print(city_state_country("47.470706, -99.704723"))
| 59 |
# Print the Hollow Half Pyramid Number Pattern
row_size=int(input("Enter the row size:"))print_control_x=row_size//2+1for out in range(1,row_size+1): for inn in range(1,row_size+1): if inn==1 or out==inn or out==row_size: print(out,end="") else: print(" ", end="") print("\r") | 31 |
# Write a Python program to remove key values pairs from a list of dictionaries.
original_list = [{'key1':'value1', 'key2':'value2'}, {'key1':'value3', 'key2':'value4'}]
print("Original List: ")
print(original_list)
new_list = [{k: v for k, v in d.items() if k != 'key1'} for d in original_list]
print("New List: ")
print(new_list)
| 46 |
# Write a Pandas program to find the index of a given substring of a DataFrame column.
import pandas as pd
df = pd.DataFrame({
'name_code': ['c001','c002','c022', 'c2002', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})
print("Original DataFrame:")
print(df)
print("\nCount occurrence of 22 in date_of_birth column:")
df['Index'] = list(map(lambda x: x.find('22'), df['name_code']))
print(df)
| 55 |
# Write a Python program to get the actual module object for a given object.
from inspect import getmodule
from math import sqrt
print(getmodule(sqrt))
| 24 |
# Write a Python program to sort a list of elements using Heap sort.
def heap_data(nums, index, heap_size):
largest_num = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and nums[left_index] > nums[largest_num]:
largest_num = left_index
if right_index < heap_size and nums[right_index] > nums[largest_num]:
largest_num = right_index
if largest_num != index:
nums[largest_num], nums[index] = nums[index], nums[largest_num]
heap_data(nums, largest_num, heap_size)
def heap_sort(nums):
n = len(nums)
for i in range(n // 2 - 1, -1, -1):
heap_data(nums, i, n)
for i in range(n - 1, 0, -1):
nums[0], nums[i] = nums[i], nums[0]
heap_data(nums, 0, i)
return nums
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
heap_sort(nums)
print(nums)
| 122 |
# Write a Python program to Successive Characters Frequency
# Python3 code to demonstrate working of
# Successive Characters Frequency
# Using count() + loop + re.findall()
import re
# initializing string
test_str = 'geeksforgeeks is best for geeks. A geek should take interest.'
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using count() + loop + re.findall()
temp = []
for sub in re.findall(que_word + '.', test_str):
temp.append(sub[-1])
res = {que_word : temp.count(que_word) for que_word in temp}
# printing result
print("The Characters Frequency is : " + str(res)) | 104 |
# Write a Python program to extract specified size of strings from a give list of string values using lambda.
def extract_string(str_list1, l):
result = list(filter(lambda e: len(e) == l, str_list1))
return result
str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
print("Original list:")
print(str_list1)
l = 8
print("\nlength of the string to extract:")
print(l)
print("\nAfter extracting strings of specified length from the said list:")
print(extract_string(str_list1 , l))
| 66 |
# Write a Python program to remove sublists from a given list of lists, which contains an element outside a given range.
#Source bit.ly/33MAeHe
def remove_list_range(input_list, left_range, rigth_range):
result = [i for i in input_list if (min(i)>=left_range and max(i)<=rigth_range)]
return result
list1 = [[2], [0], [1, 2, 3], [0, 1, 2, 3, 6, 7], [9, 11], [13, 14, 15, 17]]
left_range = 13
rigth_range = 17
print("Original list:")
print(list1)
print("\nAfter removing sublists from a given list of lists, which contains an element outside the given range:")
print(remove_list_range(list1, left_range, rigth_range))
| 89 |
# Write a Python program to convert JSON encoded data into Python objects.
import json
jobj_dict = '{"name": "David", "age": 6, "class": "I"}'
jobj_list = '["Red", "Green", "Black"]'
jobj_string = '"Python Json"'
jobj_int = '1234'
jobj_float = '21.34'
python_dict = json.loads(jobj_dict)
python_list = json.loads(jobj_list)
python_str = json.loads(jobj_string)
python_int = json.loads(jobj_int)
python_float = json.loads(jobj_float)
print("Python dictionary: ", python_dict)
print("Python list: ", python_list)
print("Python string: ", python_str)
print("Python integer: ", python_int)
print("Python float: ", python_float)
| 73 |
# Write a Python program to Sort by Frequency of second element in Tuple List
# Python3 code to demonstrate working of
# Sort by Frequency of second element in Tuple List
# Using sorted() + loop + defaultdict() + lambda
from collections import defaultdict
# initializing list
test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
# printing original list
print("The original list is : " + str(test_list))
# constructing mapping
freq_map = defaultdict(int)
for idx, val in test_list:
freq_map[val] += 1
# performing sort of result
res = sorted(test_list, key = lambda ele: freq_map[ele[1]], reverse = True)
# printing results
print("Sorted List of tuples : " + str(res)) | 115 |
# Write a Python program to get the smallest number from a list.
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
| 39 |
# Write a Pandas program to filter all records where the average consumption of beverages per person from .5 to 2.50 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("\nFilter all records where the average consumption of beverages per person from .5 to 2.50.:")
print(w_a_con[(w_a_con['Display Value'] < 2.5) & (w_a_con['Display Value']>.5)].head())
| 66 |
# Write a Python program to Test if List contains elements in Range
# Python3 code to demonstrate
# Test if List contains elements in Range
# using loop
# Initializing loop
test_list = [4, 5, 6, 7, 3, 9]
# printing original list
print("The original list is : " + str(test_list))
# Initialization of range
i, j = 3, 10
# Test if List contains elements in Range
# using loop
res = True
for ele in test_list:
if ele < i or ele >= j :
res = False
break
# printing result
print ("Does list contain all elements in range : " + str(res)) | 107 |
# Python Program to Find the Area of a Triangle Given All Three Sides
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2)) | 36 |
# Write a Python program to extract specified size of strings from a give list of string values.
def extract_string(str_list1, l):
result = [e for e in str_list1 if len(e) == l]
return result
str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution']
print("Original list:")
print(str_list1)
l = 8
print("\nlength of the string to extract:")
print(l)
print("\nAfter extracting strings of specified length from the said list:")
print(extract_string(str_list1 , l))
| 67 |
# Write a Pandas program to get the difference (in days) between documented date and reporting date of unidentified flying object (UFO).
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
df['date_documented'] = df['date_documented'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nDifference (in days) between documented date and reporting date of UFO:")
df['Difference'] = (df['date_documented'] - df['Date_time']).dt.days
print(df)
| 55 |
# rite a Python program to find numbers between 100 and 400 (both included) where each digit of a number is an even number. The numbers obtained should be printed in a comma-separated sequence.
items = []
for i in range(100, 401):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0):
items.append(s)
print( ",".join(items))
| 54 |
# Write a Python program to find the greatest common divisor (gcd) of two integers.
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))
| 43 |
# Write a Python program to find a tuple, the smallest second index value from a list of tuples.
x = [(4, 1), (1, 2), (6, 0)]
print(min(x, key=lambda n: (n[1], -n[0])))
| 32 |
# Write a Pandas program to convert a specified character column in upper/lower cases 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': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
df1 = 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': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]
})
print("Original DataFrame:")
print(df)
print("\nUpper cases in comapny_code:")
df['upper_company_code'] = list(map(lambda x: x.upper(), df['company_code']))
print(df)
print("\nLower cases in comapny_code:")
df1['lower_company_code'] = list(map(lambda x: x.lower(), df1['company_code']))
print(df1)
| 81 |
# Write a NumPy program to create an array of 10 zeros,10 ones, 10 fives.
import numpy as np
array=np.zeros(10)
print("An array of 10 zeros:")
print(array)
array=np.ones(10)
print("An array of 10 ones:")
print(array)
array=np.ones(10)*5
print("An array of 10 fives:")
print(array)
| 40 |
# Program to Find the area and perimeter of a circle
radius=int(input("Enter the radius of a circle :"))
area=3.14*radius*radius
perimeter=2*3.14*radius
print("Area =",area)
print("Perimeter =",perimeter)
| 24 |
# How to Remove columns in Numpy array that contains non-numeric values in Python
# Importing Numpy module
import numpy as np
# Creating 2X3 2-D Numpy array
n_arr = np.array([[10.5, 22.5, np.nan],
[41, 52.5, np.nan]])
print("Given array:")
print(n_arr)
print("\nRemove all columns containing non-numeric elements ")
print(n_arr[:, ~np.isnan(n_arr).any(axis=0)]) | 48 |
# Flatten a Matrix in Python using NumPy
# importing numpy as np
import numpy as np
# declare matrix with np
gfg = np.array([[2, 3], [4, 5]])
# using array.flatten() method
flat_gfg = gfg.flatten()
print(flat_gfg) | 36 |
# Sorting a CSV object by dates in Python
import pandas as pd | 13 |
# Write a Pandas program to compute the minimum, 25th percentile, median, 75th, and maximum of a given series.
import pandas as pd
import numpy as np
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
print("Original Series:")
print(num_series)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
print("\nMinimum, 25th percentile, median, 75th, and maximum of a given series:")
print(result)
| 58 |
# Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
print( "%s %s"%(color_list[0],color_list[-1]))
| 23 |
# Write a Python program to create a deep copy of a given list. Use copy.copy
import copy
nums_x = [1, [2, 3, 4]]
print("Original list: ", nums_x)
nums_y = copy.deepcopy(nums_x)
print("\nDeep copy 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_x)
print("\nCopy of the second list (Deep copy):")
print(nums_y)
nums = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(nums)
print("\nOriginal list:")
print(nums)
print("\nDeep copy of the said list:")
print(deep_copy)
print("\nChange the value of some elements of the original list:")
nums[0][2] = 55
nums[1][1] = 77
print("\nOriginal list:")
print(nums)
print("\nSecond list (Deep copy):")
print(deep_copy)
| 105 |
# Combining a one and a two-dimensional NumPy Array in Python
# importing Numpy package
import numpy as np
num_1d = np.arange(5)
print("One dimensional array:")
print(num_1d)
num_2d = np.arange(10).reshape(2,5)
print("\nTwo dimensional array:")
print(num_2d)
# Combine 1-D and 2-D arrays and display
# their elements using numpy.nditer()
for a, b in np.nditer([num_1d, num_2d]):
print("%d:%d" % (a, b),) | 56 |
# Write a Python program that prints each item and its corresponding type from the following list.
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))
| 42 |
# Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.
items=[n for n in input().split('-')]
items.sort()
print('-'.join(items))
| 33 |
# Write a NumPy program to rearrange columns of a given NumPy 2D array using given index positions.
import numpy as np
array1 = np.array([[11, 22, 33, 44, 55],
[66, 77, 88, 99, 100]])
print("Original arrays:")
print(array1)
i = [1,3,0,4,2]
result = array1[:,i]
print("New array:")
print(result)
| 46 |
# Write a Pandas program to create a plot of Open, High, Low, Close, Adjusted Closing prices and Volume 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-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
stock_data.plot(subplots = True, figsize = (8, 8));
plt.legend(loc = 'best')
plt.suptitle('Open,High,Low,Close,Adj Close prices & Volume of Alphabet Inc., From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()
| 84 |
# Write a Python program to Remove duplicate lists in tuples (Preserving Order)
# Python3 code to demonstrate working of
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
# Initializing tuple
test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
temp = set()
res = [ele for ele in test_tup if not(tuple(ele) in temp or temp.add(tuple(ele)))]
# printing result
print("The unique lists tuple is : " + str(res)) | 106 |
# Write a Python program to Exceptional Split in String
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using loop + split()
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using loop + split()
temp = ''
res = []
check = 0
for ele in test_str:
if ele == '(':
check += 1
elif ele == ')':
check -= 1
if ele == ', ' and check == 0:
if temp.strip():
res.append(temp)
temp = ''
else:
temp += ele
if temp.strip():
res.append(temp)
# printing result
print("The string after exceptional split : " + str(res)) | 120 |
# Write a Python program to sort a given list of lists by length and value using lambda.
def sort_sublists(input_list):
result = sorted(input_list, key=lambda l: (len(l), l))
return result
list1 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]
print("Original list:")
print(list1)
print("\nSort the list of lists by length and value:")
print(sort_sublists(list1))
| 55 |
# Program to Print K using Alphabets in Python
// C++ Program to design the
// above pattern of K using alphabets
#include<bits/stdc++.h>
using namespace std;
// Function to print
// the above Pattern
void display(int n)
{
int v = n;
// This loop is used
// for rows and prints
// the alphabets in
// decreasing order
while (v >= 0)
{
int c = 65;
// This loop is used
// for columns
for(int j = 0; j < v + 1; j++)
{
// chr() function converts the
// number to alphabet
cout << char(c + j) << " ";
}
v--;
cout << endl;
}
// This loop is again used
// to rows and prints the
// half remaining pattern in
// increasing order
for(int i = 0; i < n + 1; i++)
{
int c = 65;
for(int j = 0; j < i + 1; j++)
{
cout << char(c + j) << " ";
}
cout << endl;
}
}
// Driver code
int main()
{
int n = 5;
display(n);
return 0;
}
// This code is contributed by divyeshrabadiya07 | 191 |
# Write a Python program to get a string which is n (non-negative integer) copies of a given string.
def larger_string(str, n):
result = ""
for i in range(n):
result = result + str
return result
print(larger_string('abc', 2))
print(larger_string('.py', 3))
| 40 |
# Flattening JSON objects in Python
# for a array value of a key
unflat_json = {'user' :
{'Rachel':
{'UserID':1717171717,
'Email': 'rachel1999@gmail.com',
'friends': ['John', 'Jeremy', 'Emily']
}
}
}
# Function for flattening
# json
def flatten_json(y):
out = {}
def flatten(x, name =''):
# If the Nested key-value
# pair is of dict type
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
# If the Nested key-value
# pair is of list type
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out
# Driver code
print(flatten_json(unflat_json)) | 111 |
# Write a Python program to compute the sum of digits of each number of a given list of positive integers.
from itertools import chain
def sum_of_digits(nums):
return sum(int(y) for y in (chain(*[str(x) for x in nums])))
nums = [10,2,56]
print("Original tuple: ")
print(nums)
print("Sum of digits of each number of the said list of integers:")
print(sum_of_digits(nums))
nums = [10,20,4,5,70]
print("\nOriginal tuple: ")
print(nums)
print("Sum of digits of each number of the said list of integers:")
print(sum_of_digits(nums))
| 77 |
# Write a Python program to Remove nested records from tuple
# Python3 code to demonstrate working of
# Remove nested records
# using isinstance() + enumerate() + loop
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Remove nested records
# using isinstance() + enumerate() + loop
res = tuple()
for count, ele in enumerate(test_tup):
if not isinstance(ele, tuple):
res = res + (ele, )
# printing result
print("Elements after removal of nested records : " + str(res)) | 93 |
# Write a Python program to convert a given list of strings into list of lists using map function.
def strings_to_listOflists(str):
result = map(list, str)
return list(result)
colors = ["Red", "Green", "Black", "Orange"]
print('Original list of strings:')
print(colors)
print("\nConvert the said list of strings into list of lists:")
print(strings_to_listOflists(colors))
| 49 |
#
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
n=int(raw_input())
sum=0.0
for i in range(1,n+1):
sum += float(float(i)/(i+1))
print sum
| 26 |
# Write a Python program to retrieve children of the html tag from a given web page.
import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print("\nChildren of the html tag (https://www.python.org):\n")
root = soup.html
root_childs = [e.name for e in root.children if e.name is not None]
print(root_childs)
| 55 |
# Write a Pandas program to filter words from a given series that contain atleast two vowels.
import pandas as pd
from collections import Counter
color_series = pd.Series(['Red', 'Green', 'Orange', 'Pink', 'Yellow', 'White'])
print("Original Series:")
print(color_series)
print("\nFiltered words:")
result = mask = color_series.map(lambda c: sum([Counter(c.lower()).get(i, 0) for i in list('aeiou')]) >= 2)
print(color_series[result])
| 53 |
# Write a Python program to Replace index elements with elements in Other List
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print ("The lists after index elements replacements is : " + str(res)) | 111 |
# Write a NumPy program to test whether two arrays are element-wise equal within a tolerance.
import numpy as np
print("Test if two arrays are element-wise equal within a tolerance:")
print(np.allclose([1e10,1e-7], [1.00001e10,1e-8]))
print(np.allclose([1e10,1e-8], [1.00001e10,1e-9]))
print(np.allclose([1e10,1e-8], [1.0001e10,1e-9]))
print(np.allclose([1.0, np.nan], [1.0, np.nan]))
print(np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True))
| 45 |
# Python Program to Implement Bucket Sort
def bucket_sort(alist):
largest = max(alist)
length = len(alist)
size = largest/length
buckets = [[] for _ in range(length)]
for i in range(length):
j = int(alist[i]/size)
if j != length:
buckets[j].append(alist[i])
else:
buckets[length - 1].append(alist[i])
for i in range(length):
insertion_sort(buckets[i])
result = []
for i in range(length):
result = result + buckets[i]
return result
def insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
j = i - 1
while (j >= 0 and temp < alist[j]):
alist[j + 1] = alist[j]
j = j - 1
alist[j + 1] = temp
alist = input('Enter the list of (nonnegative) numbers: ').split()
alist = [int(x) for x in alist]
sorted_list = bucket_sort(alist)
print('Sorted list: ', end='')
print(sorted_list) | 122 |
# Write a Python program to generate combinations of a given length of given iterable.
import itertools as it
def combinations_data(iter, length):
return it.combinations(iter, length)
#List
result = combinations_data(['A','B','C','D'], 1)
print("\nCombinations of an given iterable of length 1:")
for i in result:
print(i)
#String
result = combinations_data("Python", 1)
print("\nCombinations of an given iterable of length 1:")
for i in result:
print(i)
#List
result = combinations_data(['A','B','C','D'], 2)
print("\nCombinations of an given iterable of length 2:")
for i in result:
print(i)
#String
result = combinations_data("Python", 2)
print("\nCombinations of an given iterable of length 2:")
for i in result:
print(i)
| 97 |
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and display the last ten rows.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.tail(n=10)
| 33 |
# Write a Pandas program to display most frequent value in a given series and replace everything else as 'Other' in the series.
import pandas as pd
import numpy as np
np.random.RandomState(100)
num_series = pd.Series(np.random.randint(1, 5, [15]))
print("Original Series:")
print(num_series)
print("Top 2 Freq:", num_series.value_counts())
result = num_series[~num_series.isin(num_series.value_counts().index[:1])] = 'Other'
print(num_series)
| 50 |
# Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
def new_string(str):
if len(str) >= 2 and str[:2] == "Is":
return str
return "Is" + str
print(new_string("Array"))
print(new_string("IsEmpty"))
| 53 |
# Calculate the Euclidean distance using NumPy in Python
# Python code to find Euclidean distance
# using linalg.norm()
import numpy as np
# initializing points in
# numpy arrays
point1 = np.array((1, 2, 3))
point2 = np.array((1, 1, 1))
# calculating Euclidean distance
# using linalg.norm()
dist = np.linalg.norm(point1 - point2)
# printing Euclidean distance
print(dist) | 57 |
# Write a Pandas program to convert unix/epoch time to a regular time stamp in UTC. Also convert the said timestamp in to a given time zone.
import pandas as pd
epoch_t = 1621132355
time_stamp = pd.to_datetime(epoch_t, unit='s')
# UTC (Coordinated Universal Time) is one of the well-known names of UTC+0 time zone which is 0h.
# By default, time series objects of pandas do not have an assigned time zone.
print("Regular time stamp in UTC:")
print(time_stamp)
print("\nConvert the said timestamp in to US/Pacific:")
print(time_stamp.tz_localize('UTC').tz_convert('US/Pacific'))
print("\nConvert the said timestamp in to Europe/Berlin:")
print(time_stamp.tz_localize('UTC').tz_convert('Europe/Berlin'))
| 93 |
# Write a Python program to check whether it follows the sequence given in the patterns array.
def is_samePatterns(colors, patterns):
if len(colors) != len(patterns):
return False
sdict = {}
pset = set()
sset = set()
for i in range(len(patterns)):
pset.add(patterns[i])
sset.add(colors[i])
if patterns[i] not in sdict.keys():
sdict[patterns[i]] = []
keys = sdict[patterns[i]]
keys.append(colors[i])
sdict[patterns[i]] = keys
if len(pset) != len(sset):
return False
for values in sdict.values():
for i in range(len(values) - 1):
if values[i] != values[i+1]:
return False
return True
print(is_samePatterns(["red",
"green",
"green"], ["a",
"b",
"b"]))
print(is_samePatterns(["red",
"green",
"greenn"], ["a",
"b",
"b"]))
| 92 |
# Write a Python program to parse a string representing a time according to a format.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\ntime.struct_time, in the current timezone:")
print(arrow.utcnow().timetuple())
| 30 |
# Scrape and Save Table Data in CSV file using Selenium in Python
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
import pandas as pd
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import csv | 45 |
# Write a NumPy program to create a 10x4 array filled with random floating point number values with and set the array values with specified precision.
import numpy as np
nums = np.random.randn(10, 4)
print("Original arrays:")
print(nums)
print("Set the array values with specified precision:")
np.set_printoptions(precision=4)
print(nums)
| 46 |
# Write a program to calculate simple Interest
principle=float(input("Enter a principle:"))
rate=float(input("Enter a rate:"))
time=float(input("Enter a time(year):"))
simple_interest=(principle*rate*time)/100;
print("Simple Interest:",simple_interest) | 20 |
# Menu driven Python program to execute Linux commands
# importing the module
import os
# sets the text colour to green
os.system("tput setaf 2")
print("Launching Terminal User Interface")
# sets the text color to red
os.system("tput setaf 1")
print("\t\tWELCOME TO Terminal User Interface\t\t\t")
# sets the text color to white
os.system("tput setaf 7")
print("\t-------------------------------------------------")
print("Entering local device")
while True:
print("""
1.Print date
2.Print cal
3.Configure web
4.Configure docker
5.Add user
6.Delete user
7.Create a file
8.Create a folder
9.Exit""")
ch=int(input("Enter your choice: "))
if(ch == 1):
os.system("date")
elif ch == 2:
os.system("cal")
elif ch == 3:
os.system("yum install httpd -y")
os.system("systemctl start httpd")
os.system("systemctl status httpd")
elif ch == 4:
os.system("yum install docker-ce -y")
os.system("systemctl start docker")
os.system("systemctl status docker")
elif ch == 5:
new_user=input("Enter the name of new user: ")
os.system("sudo useradd {}".format(new_user))
os.system("id -u {}".format(new_user) )
elif ch == 6:
del_user=input("Enter the name of the user to delete: ")
os.system("sudo userdel {}".format(del_user))
elif ch == 7:
filename=input("Enter the filename: ")
f=os.system("sudo touch {}".format(filename))
if f!=0:
print("Some error occurred")
else:
print("File created successfully")
elif ch == 8:
foldername=input("Enter the foldername: ")
f=os.system("sudo mkdir {}".format(foldername))
if f!=0:
print("Some error occurred")
else:
print("Folder created successfully")
elif ch == 9:
print("Exiting application")
exit()
else:
print("Invalid entry")
input("Press enter to continue")
os.system("clear") | 210 |
# Write a Python program to read a file line by line and store it into a list.
def file_read(fname):
with open(fname) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
print(content_list)
file_read(\'test.txt\')
| 38 |
# Write a Pandas program to split the following dataframe into groups based on first column and set other column values into a list of values.
import pandas as pd
df = pd.DataFrame( {'X' : [10, 10, 10, 20, 30, 30, 10],
'Y' : [10, 15, 11, 20, 21, 12, 14],
'Z' : [22, 20, 18, 20, 13, 10, 0]})
print("Original DataFrame:")
print(df)
result= df.groupby('X').aggregate(lambda tdf: tdf.unique().tolist())
print(result)
| 68 |
# Write a Python program to invert a dictionary with unique hashable values.
def test(students):
return { value: key for key, value in students.items() }
students = {
'Theodore': 10,
'Mathew': 11,
'Roxanne': 9,
}
print(test(students))
| 36 |
# Write a Pandas program to compute difference of differences between consecutive numbers of a given series.
import pandas as pd
series1 = pd.Series([1, 3, 5, 8, 10, 11, 15])
print("Original Series:")
print(series1)
print("\nDifference of differences between consecutive numbers of the said series:")
print(series1.diff().tolist())
print(series1.diff().diff().tolist())
| 45 |
# Program to print series 1,22,333,4444...n
n=int(input("Enter the range of number(Limit):"))for out in range(n+1): for i in range(out): print(out,end="") print(end=" ") | 21 |
# Get row numbers of NumPy array having element larger than X in Python
# importing library
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[10, -3, 30, 4, 5],
[3, 2, 5, -4, 5],
[9, 7, 3, 6, 5]
])
# declare specified value
X = 6
# view array
print("Given Array:\n", arr)
# finding out the row numbers
output = numpy.where(numpy.any(arr > X,
axis = 1))
# view output
print("Result:\n", output) | 78 |
# Write a Python program to sort a list of elements using the selection sort algorithm.
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
| 46 |
# Write a Python program to access a function inside a function.
def test(a):
def add(b):
nonlocal a
a += 1
return a+b
return add
func= test(4)
print(func(4))
| 28 |
# Write a Python program to remove the contents of a tag in a given html document.
from bs4 import BeautifulSoup
html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>'
soup = BeautifulSoup(html_content, "lxml")
print("Original Markup:")
print(soup.a)
tag = soup.a
tag = tag.clear()
print("\nAfter clearing the contents in the tag:")
print(soup.a)
| 47 |
# Program to Find the nth Automorphic number
rangenumber=int(input("Enter an Nth Number:"))
c = 0
letest = 0
num = 1
while c != rangenumber:
num1 = num
sqr = num1 * num1
flag = 0
while num1>0:
if num1%10 != sqr%10:
flag = -1
break
num1 = num1 // 10
sqr = sqr // 10
if flag==0:
c+=1
letest = num
num = num + 1
print(rangenumber,"th Automorphic number is ",letest) | 72 |
# Write a Python program to How to search for a string in text files
string1 = 'coding'
# opening a text file
file1 = open("geeks.txt", "r")
# setting flag and index to 0
flag = 0
index = 0
# Loop through the file line by line
for line in file1:
index + = 1
# checking string is present in line or not
if string1 in line:
flag = 1
break
# checking condition for string found or not
if flag == 0:
print('String', string1 , 'Not Found')
else:
print('String', string1, 'Found In Line', index)
# closing text file
file1.close() | 102 |
# Write a Python program to print the Inverted heart pattern
# determining the size of the heart
size = 15
# printing the inverted triangle
for a in range(0, size):
for b in range(a, size):
print(" ", end = "")
for b in range(1, (a * 2)):
print("*", end = "")
print("")
# printing rest of the heart
for a in range(size, int(size / 2) - 1 , -2):
# printing the white space right-triangle
for b in range(1, size - a, 2):
print(" ", end = "")
# printing the first trapezium
for b in range(1, a + 1):
print("*", end = "")
# printing the white space triangle
for b in range(1, (size - a) + 1):
print(" ", end = "")
# printing the second trapezium
for b in range(1, a):
print("*", end = "")
# new line
print("") | 143 |
# Write a Python program to Sort Dictionary key and values List
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
'is': [2, 10, 3],
'best': [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
res[key] = sorted(test_dict[key])
# printing result
print("The sorted dictionary : " + str(res)) | 93 |
# Write a Python program to Group similar elements into Matrix
# Python3 code to demonstrate working of
# Group similar elements into Matrix
# Using list comprehension + groupby()
from itertools import groupby
# initializing list
test_list = [1, 3, 5, 1, 3, 2, 5, 4, 2]
# printing original list
print("The original list : " + str(test_list))
# Group similar elements into Matrix
# Using list comprehension + groupby()
res = [list(val) for key, val in groupby(sorted(test_list))]
# printing result
print("Matrix after grouping : " + str(res)) | 89 |
# Scientific GUI Calculator using Tkinter in Python
from tkinter import *
import math
import tkinter.messagebox | 16 |
# Program to print series 1 9 17 33 49 73 97 ...N
n=int(input("Enter the range of number(Limit):"))i=1pr=0while i<=n: if(i%2==0): pr=2*pow(i, 2) +1 print(pr,end=" ") else: pr = 2*pow(i, 2) - 1 print(pr, end=" ") i+=1 | 36 |
# Print anagrams together in Python using List and Dictionary
# Function to return all anagrams together
def allAnagram(input):
# empty dictionary which holds subsets
# of all anagrams together
dict = {}
# traverse list of strings
for strVal in input:
# sorted(iterable) method accepts any
# iterable and rerturns list of items
# in ascending order
key = ''.join(sorted(strVal))
# now check if key exist in dictionary
# or not. If yes then simply append the
# strVal into the list of it's corresponding
# key. If not then map empty list onto
# key and then start appending values
if key in dict.keys():
dict[key].append(strVal)
else:
dict[key] = []
dict[key].append(strVal)
# traverse dictionary and concatenate values
# of keys together
output = ""
for key,value in dict.items():
output = output + ' '.join(value) + ' '
return output
# Driver function
if __name__ == "__main__":
input=['cat', 'dog', 'tac', 'god', 'act']
print (allAnagram(input)) | 154 |
# rite a Python program to display the current date and time.
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
| 27 |
# Write a Pandas program to construct a DataFrame using the MultiIndex levels as the column and index.
import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
print("Create a MultiIndex:")
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print(sales_tuples)
print("\nConstruct a Dataframe using the said MultiIndex levels: ")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)
| 71 |
# Write a Python program to set the indentation of the first line.
import textwrap
sample_text ='''
Python is a widely used high-level, general-purpose, interpreted, dynamic
programming language. Its design philosophy emphasizes code readability,
and its syntax allows programmers to express concepts in fewer lines of
code than possible in languages such as C++ or Java.
'''
text1 = textwrap.dedent(sample_text).strip()
print()
print(textwrap.fill(text1,
initial_indent='',
subsequent_indent=' ' * 4,
width=80,
))
print()
| 70 |
# Write a Python program to print the following integers with zeros on the left of specified width.
x = 3
y = 123
print("\nOriginal Number: ", x)
print("Formatted Number(left padding, width 2): "+"{:0>2d}".format(x));
print("Original Number: ", y)
print("Formatted Number(left padding, width 6): "+"{:0>6d}".format(y));
print()
| 45 |
# Write a Pandas program to create a plot of stock price and trading volume 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-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
top_plt = plt.subplot2grid((5,4), (0, 0), rowspan=3, colspan=4)
top_plt.plot(stock_data.index, stock_data["Close"])
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]')
bottom_plt = plt.subplot2grid((5,4), (3,0), rowspan=1, colspan=4)
bottom_plt.bar(stock_data.index, stock_data['Volume'])
plt.title('\nAlphabet Inc. Trading Volume', y=-0.60)
plt.gcf().set_size_inches(12,8)
| 87 |
# Write a Python program to Create Nested Dictionary using given List
# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using loop + zip()
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
# using zip() and loop to perform
# combining and assignment respectively.
res = {}
for key, ele in zip(test_list, test_dict.items()):
res[key] = dict([ele])
# printing result
print("The mapped dictionary : " + str(res)) | 106 |
# Write a Python program to Uncommon elements in Lists of List
# Python 3 code to demonstrate
# Uncommon elements in List
# using naive method
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
# printing both lists
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
# using naive method
# Uncommon elements in List
res_list = []
for i in test_list1:
if i not in test_list2:
res_list.append(i)
for i in test_list2:
if i not in test_list1:
res_list.append(i)
# printing the uncommon
print ("The uncommon of two lists is : " + str(res_list)) | 119 |
# Write a Python program to update a specific column value of a given table and select all rows before and after updating the said table.
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));")
# Insert records
cursorObj.executescript("""
INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);
INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("Agent details:")
for row in rows:
print(row)
print("\nUpdate commission .15 to .45 where id is 5003:")
sql_update_query = """Update salesman set commission = .45 where salesman_id = 5003"""
cursorObj.execute(sql_update_query)
conn.commit()
print("Record Updated successfully ")
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("\nAfter updating Agent details:")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
print("\nThe SQLite connection is closed.")
| 172 |
# Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) Sightings year.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
df["ufo_yr"] = df.Date_time.dt.year
years_data = df.ufo_yr.value_counts()
years_index = years_data.index # x ticks
years_values = years_data.get_values()
plt.figure(figsize=(15,8))
plt.xticks(rotation = 60)
plt.title('UFO Sightings by Year')
plt.xlabel("Year")
plt.ylabel("Number of reports")
years_plot = sns.barplot(x=years_index[:60],y=years_values[:60], palette = "Reds")
| 68 |
# Write a Python Program to Reverse Every Kth row in a Matrix
# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using reversed() + loop
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2],
[3, 6], [3, 7, 4], [2, 9]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = []
for idx, ele in enumerate(test_list):
# checking for K multiple
if (idx + 1) % K == 0:
# reversing using reversed
res.append(list(reversed(ele)))
else:
res.append(ele)
# printing result
print("After reversing every Kth row: " + str(res)) | 109 |
# Insertion sort using recursion
def InsertionSort(arr,n): if(n<=1): return InsertionSort(arr, n-1) temp = arr[n - 1] i = n - 2 while (i >= 0 and arr[i] > temp): arr[ i +1] = arr[ i] i=i-1 arr[i+1] = temparr=[]n = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,n): num = int(input()) arr.append(num)print("Before Sorting Array Element are: ",arr)InsertionSort(arr, n)print("After Sorting Array Elements are:",arr) | 69 |
# 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(0, np):
print(np,end="")
np+=2
print("\r")
| 32 |
# Write a Python program to drop empty Items from a given Dictionary.
dict1 = {'c1': 'Red', 'c2': 'Green', 'c3':None}
print("Original Dictionary:")
print(dict1)
print("New Dictionary after dropping empty items:")
dict1 = {key:value for (key, value) in dict1.items() if value is not None}
print(dict1)
| 43 |
# Write a Python program to calculate the sum of a list, after mapping each element to a value using the provided function.
def sum_by(lst, fn):
return sum(map(fn, lst))
print(sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
| 49 |
# Write a Python program to compute average of two given lists.
def average_two_lists(nums1, nums2):
result = sum(nums1 + nums2) / len(nums1 + nums2)
return result
nums1 = [1, 1, 3, 4, 4, 5, 6, 7]
nums2 = [0, 1, 2, 3, 4, 4, 5, 7, 8]
print("Original list:")
print(nums1)
print(nums2)
print("\nAverage of two lists:")
print(average_two_lists(nums1, nums2))
| 57 |
# Python Program to Append, Delete and Display Elements of a List Using Classes
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)
obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List: ",obj.dis())
elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())
elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print() | 76 |
# Python Program to Form a New String where the First Character and the Last Character have been Exchanged
def change(string):
return string[-1:] + string[1:-1] + string[:1]
string=raw_input("Enter string:")
print("Modified string:")
print(change(string)) | 32 |
# Write a Python program to sort a list of elements using Comb sort.
def comb_sort(nums):
shrink_fact = 1.3
gaps = len(nums)
swapped = True
i = 0
while gaps > 1 or swapped:
gaps = int(float(gaps) / shrink_fact)
swapped = False
i = 0
while gaps + i < len(nums):
if nums[i] > nums[i+gaps]:
nums[i], nums[i+gaps] = nums[i+gaps], nums[i]
swapped = True
i += 1
return nums
num1 = input('Input comma separated numbers:\n').strip()
nums = [int(item) for item in num1.split(',')]
print(comb_sort(nums))
| 82 |
# Write a Python program to find shortest list of values with the keys in a given dictionary.
def test(dictt):
min_value=1
result = [k for k, v in dictt.items() if len(v) == (min_value)]
return result
dictt = {
'V': [10, 12],
'VI': [10],
'VII': [10, 20, 30, 40],
'VIII': [20],
'IX': [10,30,50,70],
'X': [80]
}
print("\nOriginal Dictionary:")
print(dictt)
print("\nShortest list of values with the keys of the said dictionary:")
print(test(dictt))
| 70 |
# Write a Python program to extract a given number of randomly selected elements from a given list.
import random
def random_select_nums(n_list, n):
return random.sample(n_list, n)
n_list = [1,1,2,3,4,4,5,1]
print("Original list:")
print(n_list)
selec_nums = 3
result = random_select_nums(n_list, selec_nums)
print("\nSelected 3 random numbers of the above list:")
print(result)
| 48 |
# Write a Python function to check whether a number is divisible by another number. Accept two integers values form the user.
def multiple(m, n):
return True if m % n == 0 else False
print(multiple(20, 5))
print(multiple(7, 2))
| 39 |
# rogram to display the name of the most recently added dataset on data.gov.
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.example.com/')
bsh = BeautifulSoup(html.read(), 'html.parser')
print(bsh.h1)
| 30 |