Problem
stringlengths 4
623
| Solution
stringlengths 18
8.48k
⌀ | __index_level_0__
int64 0
3.31k
|
---|---|---|
Write a Python program to find the nth Hamming number. User itertools module. | import itertools
from heapq import merge
def nth_hamming_number(n):
def num_recur():
last = 1
yield last
x, y, z = itertools.tee(num_recur(), 3)
for n in merge((2 * i for i in x), (3 * i for i in y), (5 * i for i in z)):
if n != last:
yield n
last = n
result = itertools.islice(num_recur(), n)
return list(result)[-1]
print(nth_hamming_number(8))
print(nth_hamming_number(14))
print(nth_hamming_number(17))
| 100 |
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 list:")
print(last_occurrence(chars, ch))
ch = 'c'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'k'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'w'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
| 101 |
Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4. | import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print("Original String:")
print(j_str)
print("\nJSON data:")
print(json.dumps(j_str, sort_keys=True, indent=4))
| 102 |
Write a Python program to create the combinations of 3 digit combo. | numbers = []
for num in range(1000):
num=str(num).zfill(3)
print(num)
numbers.append(num)
| 103 |
Write a Python program to create an iterator to get specified number of permutations of elements. | import itertools as it
def permutations_data(iter, length):
return it.permutations(iter, length)
#List
result = permutations_data(['A','B','C','D'], 3)
print("\nIterator to get specified number of permutations of elements:")
for i in result:
print(i)
#String
result = permutations_data("Python", 2)
print("\nIterator to get specified number of permutations of elements:")
for i in result:
print(i)
| 104 |
Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string. | def first_three(str):
return str[:3] if len(str) > 3 else str
print(first_three('ipy'))
print(first_three('python'))
print(first_three('py'))
| 105 |
Write a Python program to get hourly datetime between two hours. | import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nString representing the date, controlled by an explicit format string:")
print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S'))
print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
| 106 |
Write a Python program to display formatted text (width=50) as output. | 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.
'''
print()
print(textwrap.fill(sample_text, width=50))
print()
| 107 |
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]))
| 108 |
Write a Pandas program to create a sequence of durations increasing by an hour. | import pandas as pd
date_range = pd.timedelta_range(0, periods=49, freq='H')
print("Hourly range of perods 49:")
print(date_range)
| 109 |
Write a NumPy program to sort the specified number of elements from beginning of a given array. | import numpy as np
nums = np.random.rand(10)
print("Original array:")
print(nums)
print("\nSorted first 5 elements:")
print(nums[np.argpartition(nums,range(5))])
| 110 |
Write a Python program to extract year, month, date and time using Lambda. | import datetime
now = datetime.datetime.now()
print(now)
year = lambda x: x.year
month = lambda x: x.month
day = lambda x: x.day
t = lambda x: x.time()
print(year(now))
print(month(now))
print(day(now))
print(t(now))
| 111 |
Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no common letters print "No common characters". | from collections import Counter
def common_chars(str1,str2):
d1 = Counter(str1)
d2 = Counter(str2)
common_dict = d1 & d2
if len(common_dict) == 0:
return "No common characters."
# list of common elements
common_chars = list(common_dict.elements())
common_chars = sorted(common_chars)
return ''.join(common_chars)
str1 = 'Python'
str2 = 'PHP'
print("Two strings: "+str1+' : '+str2)
print(common_chars(str1, str2))
str1 = 'Java'
str2 = 'PHP'
print("Two strings: "+str1+' : '+str2)
print(common_chars(str1, str2))
| 112 |
Write a Python program to remove a newline in Python. | str1='Python Exercises\n'
print(str1)
print(str1.rstrip())
| 113 |
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.dtypes)
| 114 |
Write a Pandas program to replace arbitrary values with other values in a given DataFrame. | import pandas as pd
df = pd.DataFrame({
'company_code': ['A','B', 'C', 'D', 'A'],
'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("\nReplace A with c:")
df = df.replace("A", "C")
print(df)
| 115 |
Write a NumPy program to calculate mean across dimension, in a 2D numpy array. | import numpy as np
x = np.array([[10, 30], [20, 60]])
print("Original array:")
print(x)
print("Mean of each column:")
print(x.mean(axis=0))
print("Mean of each row:")
print(x.mean(axis=1))
| 116 |
Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Add the fare as a dimension of columns and partition fare column into 2 categories based on the values present in fare columns. | import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
fare = pd.qcut(df['fare'], 2)
age = pd.cut(df['age'], [0, 10, 30, 60, 80])
result = df.pivot_table('survived', index=['sex', age], columns=[fare, 'pclass'])
print(result)
| 117 |
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 get(d, selectors):
return reduce(getitem, selectors, d)
users = {
'freddy': {
'name': {
'first': 'Fateh',
'last': 'Harwood'
},
'postIds': [1, 2, 3]
}
}
print(get(users, ['freddy', 'name', 'last']))
print(get(users, ['freddy', 'postIds', 1]))
| 118 |
Write a Python program to sort unsorted numbers using Recursive Bubble Sort. | #Ref.https://bit.ly/3oneU2l
def bubble_sort(list_data: list, length: int = 0) -> list:
length = length or len(list_data)
swapped = False
for i in range(length - 1):
if list_data[i] > list_data[i + 1]:
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
swapped = True
return list_data if not swapped else bubble_sort(list_data, length - 1)
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Insertion Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = [1.1, 1, 0, -1, -1.1, .1]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
nums = ['z','a','y','b','x','c']
print("\nOriginal list:")
print(nums)
print("After applying Recursive Bubble Sort the said list becomes:")
bubble_sort(nums, len(nums))
print(nums)
| 119 |
Write a Python program to count the values associated with key in a dictionary. | student = [{'id': 1, 'success': True, 'name': 'Lary'},
{'id': 2, 'success': False, 'name': 'Rabi'},
{'id': 3, 'success': True, 'name': 'Alex'}]
print(sum(d['id'] for d in student))
print(sum(d['success'] for d in student))
| 120 |
Write a NumPy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2). | import numpy as np
nums1 = np.ones((2,2,3))
nums2 = 3*np.ones((2,2))
print("Original array:")
print(nums1)
new_array = nums1 * nums2[:,:,None]
print("\nNew array:")
print(new_array)
| 121 |
Write a NumPy program to swap rows and columns of a given array in reverse order. | import numpy as np
nums = np.array([[[1, 2, 3, 4],
[0, 1, 3, 4],
[90, 91, 93, 94],
[5, 0, 3, 2]]])
print("Original array:")
print(nums)
print("\nSwap rows and columns of the said array in reverse order:")
new_nums = print(nums[::-1, ::-1])
print(new_nums)
| 122 |
Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array. | import numpy as np
array_nums = np.arange(0, 40, 2)
print("Original array:")
print(array_nums)
print("\nNew array of shape(5, 4):")
new_array = array_nums.reshape(5, 4)
print(new_array)
print("\nRestore the reshaped array into a 1-D array:")
print(new_array.flatten())
| 123 |
Write a Python program to sort a list of elements using Tree sort. | # License https://bit.ly/2InTS3W
# Tree_sort algorithm
# Build a BST and in order traverse.
class node():
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self,val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive travesal
if root:
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
def treesort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1,len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root,res)
return res
print(treesort([7,1,5,2,19,14,17]))
| 124 |
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("Comparison - equal:")
print(np.equal(x, y))
print("Comparison - equal within a tolerance:")
print(np.allclose(x, y))
| 125 |
Write a Pandas program to split a given dataframe into groups with multiple aggregations. | import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s001'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(df)
print("\nGroup by with multiple aggregations:")
result = df.groupby(['school_code','class']).agg({'height': ['max', 'mean'],
'weight': ['sum','min','count']})
print(result)
| 126 |
Write a NumPy program to find a matrix or vector norm. | import numpy as np
v = np.arange(7)
result = np.linalg.norm(v)
print("Vector norm:")
print(result)
m = np.matrix('1, 2; 3, 4')
result1 = np.linalg.norm(m)
print("Matrix norm:")
print(result1)
| 127 |
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
self.head = None
self.count = 0
def append_item(self, data):
#Append items on the list
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.count += 1
def delete_item(self, data):
# Delete an item from the list
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.count -= 1
return
prev = current
current = current.next
def iterate_item(self):
# Iterate the list.
current_item = self.tail
while current_item:
val = current_item.data
current_item = current_item.next
yield val
items = singly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print("Original list:")
for val in items.iterate_item():
print(val)
print("\nAfter removing the first item from the list:")
items.delete_item('PHP')
for val in items.iterate_item():
print(val)
| 128 |
Write a Python program to find the difference between two list including duplicate elements. Use collections module. | from collections import Counter
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print("Original lists:")
c1 = Counter(l1)
c2 = Counter(l2)
diff = c1-c2
print(list(diff.elements()))
| 129 |
Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number. | def sum_of_cubes(n):
n -= 1
total = 0
while n > 0:
total += n * n * n
n -= 1
return total
print("Sum of cubes smaller than the specified number: ",sum_of_cubes(3))
| 130 |
Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a Pandas dataframe and find a list of specified customers by name. | import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
df.query('Mine_Name == ["Shoal Creek Mine", "Piney Woods Preparation Plant"]').head()
| 131 |
Write a Python program to create a new Arrow object, cloned from the current one. | import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
cloned = a.clone()
print("\nCloned datetime:")
print(cloned)
| 132 |
Write a NumPy program to create a 3-D array with ones on a diagonal and zeros elsewhere. | import numpy as np
x = np.eye(3)
print(x)
| 133 |
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 row ")
print(arra_data[[1,3], [0,3]])
| 134 |
Write a Python program to get date and time properties from datetime function using arrow module. | import arrow
a = arrow.utcnow()
print("Current date:")
print(a.date())
print("\nCurrent time:")
print(a.time())
| 135 |
Write a Python program to get the size of a file. | import os
file_size = os.path.getsize("abc.txt")
print("\nThe size of abc.txt is :",file_size,"Bytes")
print()
| 136 |
Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display bar charts in dataframe on specified columns. | import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
print("\nBar charts in dataframe:")
df.style.bar(subset=['B', 'C'], color='#d65f5f')
| 137 |
Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) sighted by month. | 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.month
months_data = df.ufo_yr.value_counts()
months_index = months_data.index # x ticks
months_values = months_data.get_values()
plt.figure(figsize=(15,8))
plt.xticks(rotation = 60)
plt.title('UFO sighted by Month')
plt.xlabel("Months")
plt.ylabel("Number of sighting")
months_plot = sns.barplot(x=months_index[:60],y=months_values[:60], palette = "Oranges")
| 138 |
Write a Python program to sort unsorted numbers using Recursive Quick Sort. | def quick_sort(nums: list) -> list:
if len(nums) <= 1:
return nums
else:
return (
quick_sort([el for el in nums[1:] if el <= nums[0]])
+ [nums[0]]
+ quick_sort([el for el in nums[1:] if el > nums[0]])
)
nums = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Quick Sort the said list becomes:")
print(quick_sort(nums))
nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Quick Sort the said list becomes:")
print(quick_sort(nums))
nums = [1.1, 1, 0, -1, -1.1, .1]
print("\nOriginal list:")
print(nums)
print("After applying Recursive Quick Sort the said list becomes:")
print(quick_sort(nums))
| 139 |
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/Pacific'))
| 140 |
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("\nDifference between two said list including duplicate elements):")
print(list_difference(l1,l2))
| 141 |
Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in Heatmap style. | import pandas as pd
import numpy as np
import seaborn as sns
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
print("Original array:")
print(df)
print("\nDataframe - Heatmap style:")
cm = sns.light_palette("red", as_cmap=True)
df.style.background_gradient(cmap='viridis')
| 142 |
Write a Python program to remove a tag from a given tree of html document and destroy it and its contents. | 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:")
a_tag = soup.a
print(a_tag)
new_tag = soup.a.decompose()
print("After decomposing:")
print(new_tag)
| 143 |
Write a Python program to convert a given number (integer) to a list of digits. | def digitize(n):
return list(map(int, str(n)))
print(digitize(123))
print(digitize(1347823))
| 144 |
rite a Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output (all characters in lower case). | lines = []
while True:
l = input()
if l:
lines.append(l.upper())
else:
break;
for l in lines:
print(l)
| 145 |
Write a Python program to remove a tag or string from a given tree of html document and replace it with the given tag or string. | from bs4 import BeautifulSoup
html_markup= '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>'
soup = BeautifulSoup(html_markup, "lxml")
print("Original markup:")
a_tag = soup.a
print(a_tag)
new_tag = soup.new_tag("b")
new_tag.string = "PHP"
b_tag = a_tag.i.replace_with(new_tag)
print("New Markup:")
print(a_tag)
| 146 |
Write a Pandas program to extract the unique sentences from a given column of a given DataFrame. | import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],
'address': ['9910 Surrey Avenue\n9910 Surrey Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.\n102 Dunbar St.', '17 West Livingston Court']
})
print("Original DataFrame:")
print(df)
def find_unique_sentence(str1):
result = re.findall(r'(?sm)(^[^\r\n]+$)(?!.*^\1$)', str1)
return result
df['unique_sentence']=df['address'].apply(lambda st : find_unique_sentence(st))
print("\nExtract unique sentences :")
print(df)
| 147 |
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())
| 148 |
Write a Pandas program to extract elements in the given positional indices along an axis of a dataframe. | import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale3', 'sale3', 'sale2', 'sale2', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print("\nConstruct a Dataframe using the said MultiIndex levels:")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)
print("\nSelect 1st, 2nd and 3rd row of the said DataFrame:")
positions = [1, 2, 5]
print(df.take([1, 2, 5]))
print("\nTake elements at indices 1 and 2 along the axis 1 (column selection):")
print(df.take([1, 2], axis=1))
print("\nTake elements at indices 4 and 3 using negative integers along the axis 1 (column selection):")
print(df.take([-1, -2], axis=1))
| 149 |
Write a Python program to find a pair with highest product from a given array of integers. | def max_Product(arr):
arr_len = len(arr)
if (arr_len < 2):
print("No pairs exists")
return
# Initialize max product pair
x = arr[0]; y = arr[1]
# Traverse through every possible pair
for i in range(0, arr_len):
for j in range(i + 1, arr_len):
if (arr[i] * arr[j] > x * y):
x = arr[i]; y = arr[j]
return x,y
nums = [1, 2, 3, 4, 7, 0, 8, 4]
print("Original array:", nums)
print("Maximum product pair is:", max_Product(nums))
nums = [0, -1, -2, -4, 5, 0, -6]
print("\nOriginal array:", nums)
print("Maximum product pair is:", max_Product(nums))
| 150 |
Write a Python program to move all zero digits to end of a given list of numbers. | def test(lst):
result = sorted(lst, key=lambda x: not x)
return result
nums = [3,4,0,0,0,6,2,0,6,7,6,0,0,0,9,10,7,4,4,5,3,0,0,2,9,7,1]
print("\nOriginal list:")
print(nums)
print("\nMove all zero digits to end of the said list of numbers:")
print(test(nums))
| 151 |
Write a NumPy program to compute cross-correlation of two given arrays. | import numpy as np
x = np.array([0, 1, 3])
y = np.array([2, 4, 5])
print("\nOriginal array1:")
print(x)
print("\nOriginal array1:")
print(y)
print("\nCross-correlation of the said arrays:\n",np.cov(x, y))
| 152 |
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))
| 153 |
Write a Python program to extract the nth element from a given list of tuples using lambda. | def extract_nth_element(test_list, n):
result = list(map (lambda x:(x[n]), test_list))
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print ("Original list:")
print(students)
n = 0
print("\nExtract nth element ( n =",n,") from the said list of tuples:")
print(extract_nth_element(students, n))
n = 2
print("\nExtract nth element ( n =",n,") from the said list of tuples:")
print(extract_nth_element(students, n))
| 154 |
Write a NumPy program to add an extra column to a NumPy array. | import numpy as np
x = np.array([[10,20,30], [40,50,60]])
y = np.array([[100], [200]])
print(np.append(x, y, axis=1))
| 155 |
Write a Python program to calculate the product of a given list of numbers using lambda. | import functools
def remove_duplicates(nums):
result = functools.reduce(lambda x, y: x * y, nums, 1)
return result
nums1 = [1,2,3,4,5,6,7,8,9,10]
nums2 = [2.2,4.12,6.6,8.1,8.3]
print("list1:", nums1)
print("Product of the said list numbers:")
print(remove_duplicates(nums1))
print("\nlist2:", nums2)
print("Product of the said list numbers:")
print(remove_duplicates(nums2))
| 156 |
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())
| 157 |
Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable. | import numpy as np
x = np.random.rand(10, 4)
print("Original array: ")
print(x)
y= x[:5, :]
print("First 5 rows of the above array:")
print(y)
| 158 |
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 consumption of wine per person greater than 2:")
print(w_a_con[(w_a_con['Beverage Types'] == 'Wine') & (w_a_con['Display Value'] > .2)].count())
| 159 |
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)
| 160 |
Write a Python program to sort a list of elements using Time sort. | # License https://bit.ly/2InTS3W
def binary_search(lst, item, start, end):
if start == end:
if lst[start] > item:
return start
else:
return start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index+1:]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def time_sort(lst):
runs, sorted_runs = [], []
length = len(lst)
new_run = [lst[0]]
sorted_array = []
for i in range(1, length):
if i == length - 1:
new_run.append(lst[i])
runs.append(new_run)
break
if lst[i] < lst[i - 1]:
if not new_run:
runs.append([lst[i - 1]])
new_run.append(lst[i])
else:
runs.append(new_run)
new_run = []
else:
new_run.append(lst[i])
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(time_sort(nums))
| 161 |
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/Pacific'))
| 162 |
Write a NumPy program to subtract the mean of each row of a given matrix. | import numpy as np
print("Original matrix:\n")
X = np.random.rand(5, 10)
print(X)
print("\nSubtract the mean of each row of the said matrix:\n")
Y = X - X.mean(axis=1, keepdims=True)
print(Y)
| 163 |
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))
| 164 |
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]))
| 165 |
Write a Python program to select all the Sundays of a specified year. | from datetime import date, timedelta
def all_sundays(year):
# January 1st of the given year
dt = date(year, 1, 1)
# First Sunday of the given year
dt += timedelta(days = 6 - dt.weekday())
while dt.year == year:
yield dt
dt += timedelta(days = 7)
for s in all_sundays(2020):
print(s)
| 166 |
Write a Pandas program to print a concise summary of the dataset (titanic.csv). | import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.info()
print(result)
| 167 |
Write a Python program to create an object for writing and iterate over the rows to print the values. | import csv
import sys
with open('temp.csv', 'wt') as f:
writer = csv.writer(f)
writer.writerow(('id1', 'id2', 'date'))
for i in range(3):
row = (
i + 1,
chr(ord('a') + i),
'01/{:02d}/2019'.format(i + 1),)
writer.writerow(row)
print(open('temp.csv', 'rt').read())
| 168 |
Write a Python program to remove duplicate dictionary from a given list. | def remove_duplicate_dictionary(list_color):
result = [dict(e) for e in {tuple(d.items()) for d in list_color}]
return result
list_color = [{'Green': '#008000'}, {'Black': '#000000'}, {'Blue': '#0000FF'}, {'Green': '#008000'}]
print ("Original list with duplicate dictionary:")
print(list_color)
print("\nAfter removing duplicate dictionary of the said list:")
print(remove_duplicate_dictionary(list_color))
| 169 |
Write a Pandas program to create a Pivot table and compute survival totals of all classes along each group. | import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table('survived', index='sex', columns='class', margins=True)
print(result)
| 170 |
Write a Python program to remove first specified number of elements from a given list satisfying a condition. | def condition_match(x):
return ((x % 2) == 0)
def remove_items_con(data, N):
ctr = 1
result = []
for x in data:
if ctr > N or not condition_match(x):
result.append(x)
else:
ctr = ctr + 1
return result
nums = [3,10,4,7,5,7,8,3,3,4,5,9,3,4,9,8,5]
N = 4
print("Original list:")
print(nums)
print("\nRemove first 4 even numbers from the said list:")
print(remove_items_con(nums, N))
| 171 |
Write a Python program to convert a list of multiple integers into a single integer. | L = [11, 33, 50]
print("Original List: ",L)
x = int("".join(map(str, L)))
print("Single Integer: ",x)
| 172 |
Write a Python program to find the value of the last element in the given list that satisfies the provided testing function. | def find_last(lst, fn):
return next(x for x in lst[::-1] if fn(x))
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 1))
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 0))
| 173 |
Write a Python program to change the position of every n-th value with the (n+1)th in a list. | from itertools import zip_longest, chain, tee
def replace2copy(lst):
lst1, lst2 = tee(iter(lst), 2)
return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))
n = [0,1,2,3,4,5]
print(replace2copy(n))
| 174 |
Write a Python program to multiply all the numbers in a given list using lambda. | from functools import reduce
def mutiple_list(nums):
result = reduce(lambda x, y: x*y, nums)
return result
nums = [4, 3, 2, 2, -1, 18]
print ("Original list: ")
print(nums)
print("Mmultiply all the numbers of the said list:",mutiple_list(nums))
nums = [2, 4, 8, 8, 3, 2, 9]
print ("\nOriginal list: ")
print(nums)
print("Mmultiply all the numbers of the said list:",mutiple_list(nums))
| 175 |
Write a Python program to remove unwanted characters from a given string. | def remove_chars(str1, unwanted_chars):
for i in unwanted_chars:
str1 = str1.replace(i, '')
return str1
str1 = "Pyth*^on Exercis^es"
str2 = "A%^!B#*CD"
unwanted_chars = ["#", "*", "!", "^", "%"]
print ("Original String : " + str1)
print("After removing unwanted characters:")
print(remove_chars(str1, unwanted_chars))
print ("\nOriginal String : " + str2)
print("After removing unwanted characters:")
print(remove_chars(str2, unwanted_chars))
| 176 |
Write a Python program to compute the average of n | import itertools as it
nums = [[0, 1, 2],
[2, 3, 4],
[3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14]]
print("Original list:")
print(nums)
def get_avg(x):
x = [i for i in x if i is not None]
return sum(x, 0.0) / len(x)
result = map(get_avg, it.zip_longest(*nums))
print("\nAverage of n-th elements in the said list of lists with different lengths:")
print(list(result))
| 177 |
Write a Python program to find the details of a given zip code using Nominatim API and GeoPy package. | from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")
zipcode1 = "99501"
print("\nZipcode:",zipcode1)
location = geolocator.geocode(zipcode1)
print("Details of the said pincode:")
print(location.address)
zipcode2 = "CA9 3HX"
print("\nZipcode:",zipcode2)
location = geolocator.geocode(zipcode2)
print("Details of the said pincode:")
print(location.address)
zipcode3 = "61000"
print("\nZipcode:",zipcode3)
location = geolocator.geocode(zipcode3)
print("Details of the said pincode:")
print(location.address)
zipcode4 = "713101"
print("\nZipcode:",zipcode4)
location = geolocator.geocode(zipcode4)
print("Details of the said pincode:")
print(location.address)
| 178 |
Write a NumPy program to insert a space between characters of all the elements of a given array. | import numpy as np
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
print("Original Array:")
print(x)
r = np.char.join(" ", x)
print(r)
| 179 |
Write a Python program to merge some list items in given list using index value. | def merge_some_chars(lst,merge_from,merge_to):
result = lst
result[merge_from:merge_to] = [''.join(result[merge_from:merge_to])]
return result
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print("Original lists:")
print(chars)
merge_from = 2
merge_to = 4
print("\nMerge items from",merge_from,"to",merge_to,"in the said List:")
print(merge_some_chars(chars,merge_from,merge_to))
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
merge_from = 3
merge_to = 7
print("\nMerge items from",merge_from,"to",merge_to,"in the said List:")
print(merge_some_chars(chars,merge_from,merge_to))
| 180 |
Write a Python function to check whether a number is perfect or not. | def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(6))
| 181 |
Write a Pandas program to split a given dataset, group by two columns and convert other columns of the dataframe into a dictionary with column header as key. | import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(df)
dict_data_list = list()
for gg, dd in df.groupby(['school_code','class']):
group = dict(zip(['school_code','class'], gg))
ocolumns_list = list()
for _, data in dd.iterrows():
data = data.drop(labels=['school_code','class'])
ocolumns_list.append(data.to_dict())
group['other_columns'] = ocolumns_list
dict_data_list.append(group)
print(dict_data_list)
| 182 |
Write a Python program to find the most common elements and their counts of a specified text. | from collections import Counter
s = 'lkseropewdssafsdfafkpwe'
print("Original string: "+s)
print("Most common three characters of the said string:")
print(Counter(s).most_common(3))
| 183 |
Write a NumPy program to round array elements to the given number of decimals. | import numpy as np
x = np.round([1.45, 1.50, 1.55])
print(x)
x = np.round([0.28, .50, .64], decimals=1)
print(x)
x = np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
print(x)
| 184 |
Write a Pandas program to find the index of the first occurrence of the smallest and largest value of a given series. | import pandas as pd
nums = pd.Series([1, 3, 7, 12, 88, 23, 3, 1, 9, 0])
print("Original Series:")
print(nums)
print("Index of the first occurrence of the smallest and largest value of the said series:")
print(nums.idxmin())
print(nums.idxmax())
| 185 |
Write a NumPy program to generate a random number between 0 and 1. | import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1:")
print(rand_num)
| 186 |
Write a Python program to count number of unique sublists within a given list. | def unique_sublists(input_list):
result ={}
for l in input_list:
result.setdefault(tuple(l), list()).append(1)
for a, b in result.items():
result[a] = sum(b)
return result
list1 = [[1, 3], [5, 7], [1, 3], [13, 15, 17], [5, 7], [9, 11]]
print("Original list:")
print(list1)
print("Number of unique lists of the said list:")
print(unique_sublists(list1))
color1 = [["green", "orange"], ["black"], ["green", "orange"], ["white"]]
print("\nOriginal list:")
print(color1)
print("Number of unique lists of the said list:")
print(unique_sublists(color1))
| 187 |
Write a Python program to calculate the time runs (difference between start and current time) of a program. | from timeit import default_timer
def timer(n):
start = default_timer()
# some code here
for row in range(0,n):
print(row)
print(default_timer() - start)
timer(5)
timer(15)
| 188 |
Write a Python program to concatenate element-wise three given lists. | def concatenate_lists(l1,l2,l3):
return [i + j + k for i, j, k in zip(l1, l2, l3)]
l1 = ['0','1','2','3','4']
l2 = ['red','green','black','blue','white']
l3 = ['100','200','300','400','500']
print("Original lists:")
print(l1)
print(l2)
print(l3)
print("\nConcatenate element-wise three said lists:")
print(concatenate_lists(l1,l2,l3))
| 189 |
Write a Python program to delete a specific row from a given SQLite 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("\nDelete Salesman of ID 5003:")
s_id = 5003
cursorObj.execute("""
DELETE FROM salesman
WHERE salesman_id = ?
""", (s_id,))
conn.commit()
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.")
| 190 |
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_length = min(len(x) for x in input_list )
min_list = min(input_list, key = lambda i: len(i))
return(min_length, min_list)
list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]]
print("Original list:")
print(list1)
print("\nList with maximum length of lists:")
print(max_length_list(list1))
print("\nList with minimum length of lists:")
print(min_length_list(list1))
| 191 |
Write a Python program to convert a given string to camelcase. | from re import sub
def camel_case(s):
s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
return ''.join([s[0].lower(), s[1:]])
print(camel_case('JavaScript'))
print(camel_case('Foo-Bar'))
print(camel_case('foo_bar'))
print(camel_case('--foo.bar'))
print(camel_case('Foo-BAR'))
print(camel_case('fooBAR'))
print(camel_case('foo bar'))
| 192 |
Write a Python program to find common items from two lists. | color1 = "Red", "Green", "Orange", "White"
color2 = "Black", "Green", "White", "Pink"
print(set(color1) & set(color2))
| 193 |
Write a Python program to create a doubly linked list, append some items and iterate through the list (print forward). | 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(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
def print_foward(self):
for node in self.iter():
print(node)
def iter(self):
# Iterate the list
current = self.head
while current:
item_val = current.data
current = current.next
yield item_val
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
print("Items in the Doubly linked list: ")
items.print_foward()
| 194 |
Write a NumPy program to rearrange the dimensions of a given array. | import numpy as np
x = np.arange(24).reshape((6,4))
print("Original arrays:")
print(x)
new_array = np.transpose(x)
print("After reverse the dimensions:")
print(new_array)
| 195 |
Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns. | import pandas as pd
df = pd.DataFrame({'year': [2018, 2019, 2020],
'month': [2, 3, 4],
'day': [4, 5, 6],
'hour': [2, 3, 4]})
print("Original dataframe:")
print(df)
result = pd.to_datetime(df)
print("\nSeries of Timestamps from the said dataframe:")
print(result)
print("\nSeries of Timestamps using specified columns:")
print(pd.to_datetime(df[['year', 'month', 'day']]))
| 196 |
Write a Python program to create datetime from integers, floats and strings timestamps using arrow module. | import arrow
i = arrow.get(1857900545)
print("Date from integers: ")
print(i)
f = arrow.get(1857900545.234323)
print("\nDate from floats: ")
print(f)
s = arrow.get('1857900545')
print("\nDate from Strings: ")
print(s)
| 197 |
Write a Python program to merge two or more lists into a list of lists, combining elements from each of the input lists based on their positions. | def merge_lists(*args, fill_value = None):
max_length = max([len(lst) for lst in args])
result = []
for i in range(max_length):
result.append([
args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))
])
return result
print("After merging lists into a list of lists:")
print(merge_lists(['a', 'b'], [1, 2], [True, False]))
print(merge_lists(['a'], [1, 2], [True, False]))
print(merge_lists(['a'], [1, 2], [True, False], fill_value = '_'))
| 198 |
Write a NumPy program to stack arrays in sequence horizontally (column wise). | import numpy as np
print("\nOriginal arrays:")
x = np.arange(9).reshape(3,3)
y = x*3
print("Array-1")
print(x)
print("Array-2")
print(y)
new_array = np.hstack((x,y))
print("\nStack arrays in sequence horizontally:")
print(new_array)
| 199 |