Problem
stringlengths
4
623
Solution
stringlengths
18
8.48k
__index_level_0__
int64
0
3.31k
Write a NumPy program to repeat elements of an array.
import numpy as np x = np.repeat(3, 4) print(x) x = np.array([[1,2],[3,4]]) print(np.repeat(x, 2))
0
Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).
def printValues(): l = list() for i in range(1,31): l.append(i**2) print(l) printValues()
1
Write a Python program to remove duplicates from a list of lists.
import itertools num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]] print("Original List", num) num.sort() new_num = list(num for num,_ in itertools.groupby(num)) print("New List", new_num)
2
Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib.
import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.2) y = np.sin(x) print("Plot the points using matplotlib:") plt.plot(x, y) plt.show()
3
Write a Python program to alter 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() cursorObj.execute("CREATE TABLE agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);") print("\nagent_master file has created.") # adding a new column in the agent_master table cursorObj.execute(""" ALTER TABLE agent_master ADD COLUMN FLAG BOOLEAN; """) print("\nagent_master file altered.") conn.commit() sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
4
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))
5
Write a Python program to create Fibonacci series upto n using Lambda.
from functools import reduce fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1]) print("Fibonacci series upto 2:") print(fib_series(2)) print("\nFibonacci series upto 5:") print(fib_series(5)) print("\nFibonacci series upto 6:") print(fib_series(6)) print("\nFibonacci series upto 9:") print(fib_series(9))
6
Write a Python program to sort unsorted numbers using Strand sort.
#Ref:https://bit.ly/3qW9FIX import operator def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution lst = [4, 3, 5, 1, 2] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst)) lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst)) lst = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(lst) print("After applying Strand sort the said list becomes:") print(strand_sort(lst))
7
Write a Python program to insert a specified element in a given list after every nth element.
def inset_element_list(lst, x, n): i = n while i < len(lst): lst.insert(i, x) i+= n+1 return lst nums = [1, 3, 5, 7, 9, 11,0, 2, 4, 6, 8, 10,8,9,0,4,3,0] print("Original list:") print(nums) x = 20 n = 4 print("\nInsert",x,"in said list after every",n,"th element:") print(inset_element_list(nums, x, n)) chars = ['s','d','f','j','s','a','j','d','f','d'] print("\nOriginal list:") print(chars) x = 'Z' n = 3 print("\nInsert",x,"in said list after every",n,"th element:") print(inset_element_list(chars, x, n))
8
rite a Pandas program to create a Pivot table and find the maximum and minimum sale value of the items.
import pandas as pd import numpy as np df = pd.read_excel('E:\SaleData.xlsx') table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=[np.max, np.min]) print(table)
9
Write a NumPy program to extract upper triangular part of a NumPy matrix.
import numpy as np num = np.arange(18) arr1 = np.reshape(num, [6, 3]) print("Original array:") print(arr1) result = arr1[np.triu_indices(3)] print("\nExtract upper triangular part of the said array:") print(result) result = arr1[np.triu_indices(2)] print("\nExtract upper triangular part of the said array:") print(result)
10
Write a Python program to find the maximum occurring character in a given string.
def get_max_occuring_char(str1): ASCII_SIZE = 256 ctr = [0] * ASCII_SIZE max = -1 ch = '' for i in str1: ctr[ord(i)]+=1; for i in str1: if max < ctr[ord(i)]: max = ctr[ord(i)] ch = i return ch print(get_max_occuring_char("Python: Get file creation and modification date/times")) print(get_max_occuring_char("abcdefghijkb"))
11
Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
num = int(input("Enter a number: ")) mod = num % 2 if mod > 0: print("This is an odd number.") else: print("This is an even number.")
12
Write a NumPy program to create a new vector with 2 consecutive 0 between two values of a given vector.
import numpy as np nums = np.array([1,2,3,4,5,6,7,8]) print("Original array:") print(nums) p = 2 new_nums = np.zeros(len(nums) + (len(nums)-1)*(p)) new_nums[::p+1] = nums print("\nNew array:") print(new_nums)
13
Write a Python program to count the occurrences of each word in a given sentence.
def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.'))
14
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))
15
Write a Pandas program to insert a column at a specific index in a given DataFrame.
import pandas as pd 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'], 'weight': [35, 32, 33, 30, 31, 32]}, index = [1, 2, 3, 4, 5, 6]) print("Original DataFrame with single index:") print(df) date_of_birth = ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'] idx = 3 print("\nInsert 'date_of_birth' column in 3rd position of the said DataFrame:") df.insert(loc=idx, column='date_of_birth', value=date_of_birth) print(df)
16
Write a Python program to remove the last N number of elements from a given list.
def remove_last_n(nums, N): result = nums[:len(nums)-N] return result nums = [2,3,9,8,2,0,39,84,2,2,34,2,34,5,3,5] print("Original lists:") print(nums) N = 3 print("\nRemove the last",N,"elements from the said list:") print(remove_last_n(nums, N)) N = 5 print("\nRemove the last",N,"elements from the said list:") print(remove_last_n(nums, N)) N = 1 print("\nRemove the last",N,"element from the said list:") print(remove_last_n(nums, N))
17
Write a Python program to find index position and value of the maximum and minimum values in a given list of numbers using lambda.
def position_max_min(nums): max_result = max(enumerate(nums), key=(lambda x: x[1])) min_result = min(enumerate(nums), key=(lambda x: x[1])) return max_result,min_result nums = [12,33,23,10.11,67,89,45,66.7,23,12,11,10.25,54] print("Original list:") print(nums) result = position_max_min(nums) print("\nIndex position and value of the maximum value of the said list:") print(result[0]) print("\nIndex position and value of the minimum value of the said list:") print(result[1])
18
Write a NumPy program to find the k smallest values of a given NumPy array.
import numpy as np array1 = np.array([1, 7, 8, 2, 0.1, 3, 15, 2.5]) print("Original arrays:") print(array1) k = 4 result = np.argpartition(array1, k) print("\nk smallest values:") print(array1[result[:k]])
19
Write a NumPy program to add one polynomial to another, subtract one polynomial from another, multiply one polynomial by another and divide one polynomial by another.
from numpy.polynomial import polynomial as P x = (10,20,30) y = (30,40,50) print("Add one polynomial to another:") print(P.polyadd(x,y)) print("Subtract one polynomial from another:") print(P.polysub(x,y)) print("Multiply one polynomial by another:") print(P.polymul(x,y)) print("Divide one polynomial by another:") print(P.polydiv(x,y))
20
Write a Python program to check common elements between two given list are in same order or not.
def same_order(l1, l2): common_elements = set(l1) & set(l2) l1 = [e for e in l1 if e in common_elements] l2 = [e for e in l2 if e in common_elements] return l1 == l2 color1 = ["red","green","black","orange"] color2 = ["red","pink","green","white","black"] color3 = ["white","orange","pink","black"] print("Original lists:") print(color1) print(color2) print(color3) print("\nTest common elements between color1 and color2 are in same order?") print(same_order(color1, color2)) print("\nTest common elements between color1 and color3 are in same order?") print(same_order(color1, color3)) print("\nTest common elements between color2 and color3 are in same order?") print(same_order(color2, color3))
21
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 nineteen or thirteen:") print(result)
22
Write a NumPy program to multiply two given arrays of same size element-by-element.
import numpy as np nums1 = np.array([[2, 5, 2], [1, 5, 5]]) nums2 = np.array([[5, 3, 4], [3, 2, 5]]) print("Array1:") print(nums1) print("Array2:") print(nums2) print("\nMultiply said arrays of same size element-by-element:") print(np.multiply(nums1, nums2))
23
Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
def last(n): return n[-1] def sort_list_last(tuples): return sorted(tuples, key=last) print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
24
Write a Pandas program to replace the missing values with the most frequent values present in each column of a given DataFrame.
import pandas as pd import numpy as np pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013], 'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6], 'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6], 'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001], 'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]}) print("Original Orders DataFrame:") print(df) print("\nReplace the missing values with the most frequent values present in each column:") result = df.fillna(df.mode().iloc[0]) print(result)
25
Write a NumPy program to split an array of 14 elements into 3 arrays, each of which has 2, 4, and 8 elements in the original order.
import numpy as np x = np.arange(1, 15) print("Original array:",x) print("After splitting:") print(np.split(x, [2, 6]))
26
Write a Python program to create a deep copy of a given dictionary. Use copy.copy
import copy nums_x = {"a":1, "b":2, 'cc':{"c":3}} print("Original dictionary: ", 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 dictionary:") nums_x["cc"]["c"] = 10 print(nums_x) print("\nSecond dictionary (Deep copy):") print(nums_y) nums = {"x":1, "y":2, 'zz':{"z":3}} nums_copy = copy.deepcopy(nums) print("\nOriginal dictionary :") print(nums) print("\nDeep copy of the said list:") print(nums_copy) print("\nChange the value of an element of the original dictionary:") nums["zz"]["z"] = 10 print("\nFirst dictionary:") print(nums) print("\nSecond dictionary (Deep copy):") print(nums_copy)
27
Write a Pandas program to create a subset of a given series based on value and condition.
import pandas as pd s = pd.Series([0, 1,2,3,4,5,6,7,8,9,10]) print("Original Data Series:") print(s) print("\nSubset of the above Data Series:") n = 6 new_s = s[s < n] print(new_s)
28
Write a Python program to get the items from a given list with specific condition.
def first_index(l1): return sum(1 for i in l1 if (i> 45 and i % 2 == 0)) nums = [12,45,23,67,78,90,45,32,100,76,38,62,73,29,83] print("Original list:") print(nums) n = 45 print("\nNumber of Items of the said list which are even and greater than",n) print(first_index(nums))
29
Write a Python program to read a file line by line store it into a variable.
def file_read(fname): with open (fname, "r") as myfile: data=myfile.readlines() print(data) file_read('test.txt')
30
Write a Python program to get the current value of the recursion limit.
import sys print() print("Current value of the recursion limit:") print(sys.getrecursionlimit()) print()
31
Write a Python program to swap cases of a given string.
def swap_case_string(str1): result_str = "" for item in str1: if item.isupper(): result_str += item.lower() else: result_str += item.upper() return result_str print(swap_case_string("Python Exercises")) print(swap_case_string("Java")) print(swap_case_string("NumPy"))
32
Write a Python program to convert an address (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).
import requests geo_url = 'http://maps.googleapis.com/maps/api/geocode/json' my_address = {'address': '21 Ramkrishana Road, Burdwan, East Burdwan, West Bengal, India', 'language': 'en'} response = requests.get(geo_url, params = my_address) results = response.json()['results'] my_geo = results[0]['geometry']['location'] print("Longitude:",my_geo['lng'],"\n","Latitude:",my_geo['lat'])
33
Write a Python program to create a datetime from a given timezone-aware datetime using arrow module.
import arrow from datetime import datetime from dateutil import tz print("\nCreate a date from a given date and a given time zone:") d1 = arrow.get(datetime(2018, 7, 5), 'US/Pacific') print(d1) print("\nCreate a date from a given date and a time zone object from a string representation:") d2 = arrow.get(datetime(2017, 7, 5), tz.gettz('America/Chicago')) print(d2) d3 = arrow.get(datetime.now(tz.gettz('US/Pacific'))) print("\nCreate a date using current datetime and a specified time zone:") print(d3)
34
Write a Python program to create a two-dimensional list from given list of lists.
def two_dimensional_list(nums): return list(zip(*nums)) print(two_dimensional_list([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])) print(two_dimensional_list([[1, 2], [4, 5]]))
35
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 NumPy program to access last two columns of a multidimensional columns.
import numpy as np arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arra) result = arra[:,[1,2]] print(result)
37
Write a Python program to create Cartesian product of two or more given lists using itertools.
import itertools def cartesian_product(lists): return list(itertools.product(*lists)) ls = [[1,2],[3,4]] print("Original Lists:",ls) print("Cartesian product of the said lists: ",cartesian_product(ls)) ls = [[1,2,3],[3,4,5]] print("\nOriginal Lists:",ls) print("Cartesian product of the said lists: ",cartesian_product(ls)) ls = [[],[1,2,3]] print("\nOriginal Lists:",ls) print("Cartesian product of the said lists: ",cartesian_product(ls)) ls = [[1,2],[]] print("\nOriginal Lists:",ls) print("Cartesian product of the said lists: ",cartesian_product(ls))
38
Write a NumPy program to find the first Monday in May 2017.
import numpy as np print("First Monday in May 2017:") print(np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon'))
39
Write a Python program to get the number of people visiting a U.S. government website right now.
#https://bit.ly/2lVhlLX import requests from lxml import html url = 'https://www.us-cert.gov/ncas/alerts' doc = html.fromstring(requests.get(url).text) print("The number of security alerts issued by US-CERT in the current year:") print(len(doc.cssselect('.item-list li')))
40
Write a NumPy program to remove the leading and trailing whitespaces 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) stripped = np.char.strip(x) print("\nRemove the leading and trailing whitespaces: ", stripped)
41
Write a Python program to find the first repeated character of a given string where the index of first occurrence is smallest.
def first_repeated_char_smallest_distance(str1): temp = {} for ch in str1: if ch in temp: return ch, str1.index(ch); else: temp[ch] = 0 return 'None' print(first_repeated_char_smallest_distance("abcabc")) print(first_repeated_char_smallest_distance("abcb")) print(first_repeated_char_smallest_distance("abcc")) print(first_repeated_char_smallest_distance("abcxxy")) print(first_repeated_char_smallest_distance("abc"))))
42
Write a Python program to create a table and insert some records in that table. Finally selects all rows from the table and display the records.
import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) 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); """) conn.commit() cursorObj.execute("SELECT * FROM salesman") rows = cursorObj.fetchall() print("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.")
43
Write a Pandas program to calculate the number of characters in each word in a given series.
import pandas as pd series1 = pd.Series(['Php', 'Python', 'Java', 'C#']) print("Original Series:") print(series1) result = series1.map(lambda x: len(x)) print("\nNumber of characters in each word in the said series:") print(result)
44
Write a NumPy program to broadcast on different shapes of arrays where p(3,3) + q(3).
import numpy as np p = np.array([[0, 0, 0], [1, 2, 3], [4, 5, 6]]) q= np.array([10, 11, 12]) print("Original arrays:") print("Array-1") print(p) print("Array-2") print(q) print("\nNew Array:") new_array1 = p + q print(new_array1)
45
Write a Python program to check if a given function returns True for at least one element in the list.
def some(lst, fn = lambda x: x): return any(map(fn, lst)) print(some([0, 1, 2, 0], lambda x: x >= 2 )) print(some([5, 10, 20, 10], lambda x: x < 2 ))
46
Write a NumPy program to create an array using generator function that generates 15 integers.
import numpy as np def generate(): for n in range(15): yield n nums = np.fromiter(generate(),dtype=float,count=-1) print("New array:") print(nums)
47
Write a Python program to find four elements from a given array of integers whose sum is equal to a given number. The solution set must not contain duplicate quadruplets.
#Source: https://bit.ly/2SSoyhf from bisect import bisect_left class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ N = 4 quadruplets = [] if len(nums) < N: return quadruplets nums = sorted(nums) quadruplet = [] # Let top[i] be the sum of largest i numbers. top = [0] for i in range(1, N): top.append(top[i - 1] + nums[-i]) # Find range of the least number in curr_n (0,...,N) # numbers that sum up to curr_target, then find range # of 2nd least number and so on by recursion. def sum_(curr_target, curr_n, lo=0): if curr_n == 0: if curr_target == 0: quadruplets.append(quadruplet[:]) return next_n = curr_n - 1 max_i = len(nums) - curr_n max_i = bisect_left( nums, curr_target // curr_n, lo, max_i) min_i = bisect_left( nums, curr_target - top[next_n], lo, max_i) for i in range(min_i, max_i + 1): if i == min_i or nums[i] != nums[i - 1]: quadruplet.append(nums[i]) next_target = curr_target - nums[i] sum_(next_target, next_n, i + 1) quadruplet.pop() sum_(target, N) return quadruplets s = Solution() nums = [-2, -1, 1, 2, 3, 4, 5, 6] target = 10 result = s.fourSum(nums, target) print("\nArray values & target value:",nums,"&",target) print("Solution Set:\n", result)
48
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))
49
Write a Python program to count the number of times a specific element presents in a deque object.
import collections nums = (2,9,0,8,2,4,0,9,2,4,8,2,0,4,2,3,4,0) nums_dq = collections.deque(nums) print("Number of 2 in the sequence") print(nums_dq.count(2)) print("Number of 4 in the sequence") print(nums_dq.count(4))
50
Write a Pandas program to check the empty values of UFO (unidentified flying object) Dataframe.
import pandas as pd df = pd.read_csv(r'ufo.csv') print(df.isnull().sum())
51
Create a dataframe of ten rows, four columns with random values. Write a Pandas program to make a gradient color on all the values of the said dataframe.
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 - Gradient color:") df.style.background_gradient()
52
Write a Python program to find the difference between consecutive numbers in a given list.
def diff_consecutive_nums(nums): result = [b-a for a, b in zip(nums[:-1], nums[1:])] return result nums1 = [1, 1, 3, 4, 4, 5, 6, 7] print("Original list:") print(nums1) print("Difference between consecutive numbers of the said list:") print(diff_consecutive_nums(nums1)) nums2 = [4, 5, 8, 9, 6, 10] print("\nOriginal list:") print(nums2) print("Difference between consecutive numbers of the said list:") print(diff_consecutive_nums(nums2))
53
Write a Pandas program to extract only words 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 Ave.','92 N. Bishop Ave.','9910 Golden Star Ave.', '102 Dunbar St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def search_words(text): result = re.findall(r'\b[^\d\W]+\b', text) return " ".join(result) df['only_words']=df['address'].apply(lambda x : search_words(x)) print("\nOnly words:") print(df)
54
Write a Python program to replace hour, minute, day, month, year and timezone with specified value of current datetime using arrow.
import arrow a = arrow.utcnow() print("Current date and time:") print(a) print("\nReplace hour and minute with 5 and 35:") print(a.replace(hour=5, minute=35)) print("\nReplace day with 2:") print(a.replace(day=2)) print("\nReplace year with 2021:") print(a.replace(year=2021)) print("\nReplace month with 11:") print(a.replace(month=11)) print("\nReplace timezone with 'US/Pacific:") print(a.replace(tzinfo='US/Pacific'))
55
Write a Python program that invoke a given function after specific milliseconds.
from time import sleep import math def delay(fn, ms, *args): sleep(ms / 1000) return fn(*args) print("Square root after specific miliseconds:") print(delay(lambda x: math.sqrt(x), 100, 16)) print(delay(lambda x: math.sqrt(x), 1000, 100)) print(delay(lambda x: math.sqrt(x), 2000, 25100))
56
Write a Pandas program to find and drop the missing values from 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("\nMissing values:") print(w_a_con.isnull()) print("\nDropping the missing values:") print(w_a_con.dropna())
57
Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number.
def sieve_of_Eratosthenes(num): limitn = num+1 not_prime_num = set() prime_nums = [] for i in range(2, limitn): if i in not_prime_num: continue for f in range(i*2, limitn, i): not_prime_num.add(f) prime_nums.append(i) return prime_nums print(sieve_of_Eratosthenes(100));
58
Write a Python program to create non-repeated combinations of Cartesian product of four given list of numbers.
import itertools as it mums1 = [1, 2, 3, 4] mums2 = [5, 6, 7, 8] mums3 = [9, 10, 11, 12] mums4 = [13, 14, 15, 16] print("Original lists:") print(mums1) print(mums2) print(mums3) print(mums4) print("\nSum of the specified range:") for i in it.product([tuple(mums1)], it.permutations(mums2), it.permutations(mums3), it.permutations(mums4)): print(i)
59
Write a Python program to find the values of length six in a given list using Lambda.
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] days = filter(lambda day: day if len(day)==6 else '', weekdays) for d in days: print(d)
60
Write a Pandas program to replace NaNs with the value from the previous row or the next row in a given DataFrame.
import pandas as pd import numpy as np pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013], 'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6], 'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6], 'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001], 'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]}) print("Original Orders DataFrame:") print(df) print("\nReplacing NaNs with the value from the previous row (purch_amt):") df['purch_amt'].fillna(method='pad', inplace=True) print(df) print("\nReplacing NaNs with the value from the next row (sale_amt):") df['sale_amt'].fillna(method='bfill', inplace=True) print(df)
61
Write a Python program to sort a list of elements using the merge sort algorithm.
def mergeSort(nlist): print("Splitting ",nlist) if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): nlist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): nlist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",nlist) nlist = [14,46,43,27,57,41,45,21,70] mergeSort(nlist) print(nlist)
62
latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map.
from lxml import html import requests response = requests.get('http://catalog.data.gov/dataset?q=&sort=metadata_created+desc') doc = html.fromstring(response.text) title = doc.cssselect('h3.dataset-heading')[0].text_content() print("The name of the most recently added dataset on data.gov:") print(title.strip())
63
Write a NumPy program to create an array of ones and an array of zeros.
import numpy as np print("Create an array of zeros") x = np.zeros((1,2)) print("Default type is float") print(x) print("Type changes to int") x = np.zeros((1,2), dtype = np.int) print(x) print("Create an array of ones") y= np.ones((1,2)) print("Default type is float") print(y) print("Type changes to int") y = np.ones((1,2), dtype = np.int) print(y)
64
Write a Python program to find the value of the first element in the given list that satisfies the provided testing function.
def find(lst, fn): return next(x for x in lst if fn(x)) print(find([1, 2, 3, 4], lambda n: n % 2 == 1)) print(find([1, 2, 3, 4], lambda n: n % 2 == 0))
65
Write a Python program to remove duplicates from Dictionary.
student_data = {'id1': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id2': {'name': ['David'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id3': {'name': ['Sara'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, 'id4': {'name': ['Surya'], 'class': ['V'], 'subject_integration': ['english, math, science'] }, } result = {} for key,value in student_data.items(): if value not in result.values(): result[key] = value print(result)
66
Write a Python program to find the list in a list of lists whose sum of elements is the highest.
num = [[1,2,3], [4,5,6], [10,11,12], [7,8,9]] print(max(num, key=sum))
67
Write a Python program to get the top stories from Google news.
import bs4 from bs4 import BeautifulSoup as soup from urllib.request import urlopen news_url="https://news.google.com/news/rss" Client=urlopen(news_url) xml_page=Client.read() Client.close() soup_page=soup(xml_page,"xml") news_list=soup_page.findAll("item") # Print news title, url and publish date for news in news_list: print(news.title.text) print(news.link.text) print(news.pubDate.text) print("-"*60)
68
Write a Python program to check all values are same in a dictionary.
def value_check(students, n): result = all(x == n for x in students.values()) return result students = {'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12} print("Original Dictionary:") print(students) n = 12 print("\nCheck all are ",n,"in the dictionary.") print(value_check(students, n)) n = 10 print("\nCheck all are ",n,"in the dictionary.") print(value_check(students, n))
69
Write a Python program to compare two given lists and find the indices of the values present in both lists.
def matched_index(l1, l2): l2 = set(l2) return [i for i, el in enumerate(l1) if el in l2] nums1 = [1, 2, 3, 4, 5 ,6] nums2 = [7, 8, 5, 2, 10, 12] print("Original lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2)) nums1 = [1, 2, 3, 4, 5 ,6] nums2 = [7, 8, 5, 7, 10, 12] print("\nOriginal lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2)) nums1 = [1, 2, 3, 4, 15 ,6] nums2 = [7, 8, 5, 7, 10, 12] print("\nOriginal lists:") print(nums1) print(nums2) print("Compare said two lists and get the indices of the values present in both lists:") print(matched_index(nums1, nums2))
70
Write a Python program to create a 24-hour time format (HH:MM ) using 4 given digits. Display the latest time and do not use any digit more than once.
import itertools def max_time(nums): for i in range(len(nums)): nums[i] *= -1 nums.sort() for hr1, hr2, m1, m2 in itertools.permutations(nums): hrs = -(10*hr1 + hr2) mins = -(10*m1 + m2) if 60> mins >=0 and 24 > hrs >=0: result = "{:02}:{:02}".format(hrs, mins) break return result nums = [1,2,3,4] print("Original array:",nums) print("Latest time: ",max_time(nums)) nums = [1,2,4,5] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [2,2,4,5] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [2,2,4,3] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums)) nums = [0,2,4,3] print("\nOriginal array:",nums) print("Latest time: ",max_time(nums))
71
Sum a list of numbers. Write a Python program to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.
#Source: shorturl.at/csxLM def test(list1): result = [(x + y) / 2.0 for (x, y) in zip(list1[:-1], list1[1:])] return list(result) nums = [1,2,3,4,5,6,7] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums)) nums = [0,1,-3,3,7,-5,6,7,11] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums))
72
Write a Python program to test whether all numbers of a list is greater than a certain number.
num = [2, 3, 4, 5] print() print(all(x > 1 for x in num)) print(all(x > 4 for x in num)) print()
73
Write a NumPy program to test whether a given 2D array has null columns or not.
import numpy as np print("Original array:") nums = np.random.randint(0,3,(4,10)) print(nums) print("\nTest whether the said array has null columns or not:") print((~nums.any(axis=0)).any())
74
Write a NumPy program to convert angles from degrees to radians for all elements in a given array.
import numpy as np x = np.array([-180., -90., 90., 180.]) r1 = np.radians(x) r2 = np.deg2rad(x) assert np.array_equiv(r1, r2) print(r1)
75
Write a Python program to find all anagrams of a string in a given list of strings using lambda.
from collections import Counter texts = ["bcda", "abce", "cbda", "cbea", "adcb"] str = "abcd" print("Orginal list of strings:") print(texts) result = list(filter(lambda x: (Counter(str) == Counter(x)), texts)) print("\nAnagrams of 'abcd' in the above string: ") print(result)
76
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)
77
Write a NumPy program to extract all numbers from a given array which are less and greater than a specified number.
import numpy as np nums = np.array([[5.54, 3.38, 7.99], [3.54, 4.38, 6.99], [1.54, 2.39, 9.29]]) print("Original array:") print(nums) n = 5 print("\nElements of the said array greater than",n) print(nums[nums > n]) n = 6 print("\nElements of the said array less than",n) print(nums[nums < n])
78
Write a NumPy program to extract second and fourth elements of the second and fourth 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: Second and fourth elements of the second and fourth rows ") print(arra_data[1::2, 1::2])
79
Write a NumPy program to split a given array into multiple sub-arrays vertically (row-wise).
import numpy as np print("\nOriginal arrays:") x = np.arange(16.0).reshape(4, 4) print(x) new_array1 = np.vsplit(x, 2) print("\nSplit an array into multiple sub-arrays vertically:") print(new_array1)
80
Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters.
def count_k_dist(str1, k): str_len = len(str1) result = 0 ctr = [0] * 27 for i in range(0, str_len): dist_ctr = 0 ctr = [0] * 27 for j in range(i, str_len): if(ctr[ord(str1[j]) - 97] == 0): dist_ctr += 1 ctr[ord(str1[j]) - 97] += 1 if(dist_ctr == k): result += 1 if(dist_ctr > k): break return result str1 = input("Input a string (lowercase alphabets):") k = int(input("Input k: ")) print("Number of substrings with exactly", k, "distinct characters : ", end = "") print(count_k_dist(str1, k))
81
Write a Python program to create a list reflecting the run-length encoding from a given list of integers or a given list of characters.
from itertools import groupby def encode_list(s_list): return [[len(list(group)), key] for key, group in groupby(s_list)] n_list = [1,1,2,3,4,4.3,5, 1] print("Original list:") print(n_list) print("\nList reflecting the run-length encoding from the said list:") print(encode_list(n_list)) n_list = 'automatically' print("\nOriginal String:") print(n_list) print("\nList reflecting the run-length encoding from the said string:") print(encode_list(n_list))
82
Write a Pandas program to check whether only numeric values present in a given column of a DataFrame.
import pandas as pd df = pd.DataFrame({ 'company_code': ['Company','Company a001', '2055', 'abcd', '123345'], '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("\nNumeric values present in company_code column:") df['company_code_is_digit'] = list(map(lambda x: x.isdigit(), df['company_code'])) print(df)
83
Write a Python program to check if a specific Key and a value exist in a dictionary.
def test(dictt, key, value): if any(sub[key] == value for sub in dictt): return True return False students = [ {'student_id': 1, 'name': 'Jean Castro', 'class': 'V'}, {'student_id': 2, 'name': 'Lula Powell', 'class': 'V'}, {'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'}, {'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'}, {'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'} ] print("\nOriginal dictionary:") print(students) print("\nCheck if a specific Key and a value exist in the said dictionary:") print(test(students,'student_id', 1)) print(test(students,'name', 'Brian Howell')) print(test(students,'class', 'VII')) print(test(students,'class', 'I')) print(test(students,'name', 'Brian Howelll')) print(test(students,'student_id', 11))
84
Write a Pandas program to split a given dataset using group by on multiple columns and drop last n rows of from each group.
import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013], 'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6], 'ord_date': ['2012-10-05','2012-09-10','2012-10-05','2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[3002,3001,3001,3003,3002,3002,3001,3004,3003,3002,3003,3001], 'salesman_id':[5002,5003,5001,5003,5002,5001,5001,5003,5003,5002,5003,5001]}) print("Original Orders DataFrame:") print(df) print("\nSplit the said data on 'salesman_id', 'customer_id' wise:") result = df.groupby(['salesman_id', 'customer_id']) for name,group in result: print("\nGroup:") print(name) print(group) n = 2 #result1 = df.groupby(['salesman_id', 'customer_id']).tail(n).index, axis=0) print("\nDroping last two records:") result1 = df.drop(df.groupby(['salesman_id', 'customer_id']).tail(n).index, axis=0) print(result1)
85
Write a NumPy program to find point by point distances of a random vector with shape (10,2) representing coordinates.
import numpy as np a= np.random.random((10,2)) x,y = np.atleast_2d(a[:,0], a[:,1]) d = np.sqrt( (x-x.T)**2 + (y-y.T)**2) print(d)
86
Write a Python program to create the next bigger number by rearranging the digits of a given number.
def rearrange_bigger(n): #Break the number into digits and store in a list nums = list(str(n)) for i in range(len(nums)-2,-1,-1): if nums[i] < nums[i+1]: z = nums[i:] y = min(filter(lambda x: x > z[0], z)) z.remove(y) z.sort() nums[i:] = [y] + z return int("".join(nums)) return False n = 12 print("Original number:",n) print("Next bigger number:",rearrange_bigger(n)) n = 10 print("\nOriginal number:",n) print("Next bigger number:",rearrange_bigger(n)) n = 201 print("\nOriginal number:",n) print("Next bigger number:",rearrange_bigger(n)) n = 102 print("\nOriginal number:",n) print("Next bigger number:",rearrange_bigger(n)) n = 445 print("\nOriginal number:",n) print("Next bigger number:",rearrange_bigger(n))
87
Write a Python program to filter a dictionary based on values.
marks = {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190} print("Original Dictionary:") print(marks) print("Marks greater than 170:") result = {key:value for (key, value) in marks.items() if value >= 170} print(result)
88
Write a Python program to count the frequency of the elements of a given unordered list.
from itertools import groupby uno_list = [2,1,3,8,5,1,4,2,3,4,0,8,2,0,8,4,2,3,4,2] print("Original list:") print(uno_list) uno_list.sort() print(uno_list) print("\nSort the said unordered list:") print(uno_list) print("\nFrequency of the elements of the said unordered list:") result = [len(list(group)) for key, group in groupby(uno_list)] print(result)
89
Write a Pandas program to find out the alcohol consumption details in the year '1987' or '1989' from the 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("\nThe world alcohol consumption details where year is 1987 or 1989:") print((w_a_con[(w_a_con['Year']==1987) | (w_a_con['Year']==1989)]).head(10))
90
Write a Python program to count the number of even and odd numbers from a series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 print("Number of even numbers :",count_even) print("Number of odd numbers :",count_odd)
91
Write a Python code to send some sort of data in the URL's query string.
import requests payload = {'key1': 'value1', 'key2': 'value2'} print("Parameters: ",payload) r = requests.get('https://httpbin.org/get', params=payload) print("Print the url to check the URL has been correctly encoded or not!") print(r.url) print("\nPass a list of items as a value:") payload = {'key1': 'value1', 'key2': ['value2', 'value3']} print("Parameters: ",payload) r = requests.get('https://httpbin.org/get', params=payload) print("Print the url to check the URL has been correctly encoded or not!") print(r.url)
92
Write a Pandas program to split the following dataframe into groups and calculate monthly purchase amount.
import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013], 'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6], 'ord_date': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'], 'customer_id':[3001,3001,3005,3001,3005,3001,3005,3001,3005,3001,3005,3005], 'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]}) print("Original Orders DataFrame:") print(df) df['ord_date']= pd.to_datetime(df['ord_date']) print("\nMonth wise purchase amount:") result = df.set_index('ord_date').groupby(pd.Grouper(freq='M')).agg({'purch_amt':sum}) print(result)
93
Write a Pandas program to add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit.
import pandas as pd nums = {'amount': ['10', '250', '3000', '40000', '500000']} print("Original dataframe:") df = pd.DataFrame(nums) print(df) print("\nAdd leading zeros:") df['amount'] = list(map(lambda x: x.zfill(10), df['amount'])) print(df)
94
Write a NumPy program to compute the reciprocal for all elements in a given array.
import numpy as np x = np.array([1., 2., .2, .3]) print("Original array: ") print(x) r1 = np.reciprocal(x) r2 = 1/x assert np.array_equal(r1, r2) print("Reciprocal for all elements of the said array:") print(r1)
95
Write a NumPy program to calculate the QR decomposition of a given matrix.
import numpy as np m = np.array([[1,2],[3,4]]) print("Original matrix:") print(m) result = np.linalg.qr(m) print("Decomposition of the said matrix:") print(result)
96
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_data[0:2, 0:2])
97
Write a Python program to compute sum of digits of a given string.
def sum_digits_string(str1): sum_digit = 0 for x in str1: if x.isdigit() == True: z = int(x) sum_digit = sum_digit + z return sum_digit print(sum_digits_string("123abcd45")) print(sum_digits_string("abcd1234"))
98
Create a dataframe of ten rows, four columns with random values. Write a Pandas program to make a gradient color mapping on a specified column.
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) print("Original array:") print(df) print("\nDataframe - Gradient color:") df.style.background_gradient(subset=['C'])
99

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
8
Add dataset card