Problem
stringlengths
4
623
Solution
stringlengths
18
8.48k
__index_level_0__
int64
0
3.31k
rite a Python program to find the first repeated word in a given string.
def first_repeated_word(str1): temp = set() for word in str1.split(): if word in temp: return word; else: temp.add(word) return 'None' print(first_repeated_word("ab ca bc ab")) print(first_repeated_word("ab ca bc ab ca ab bc")) print(first_repeated_word("ab ca bc ca ab bc")) print(first_repeated_word("ab ca bc"))
200
Create a dataframe of ten rows, four columns with random values. Convert some values to nan values. Write a Pandas program which will highlight the nan values.
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) def color_negative_red(val): color = 'red' if val < 0 else 'black' return 'color: %s' % color print("\nNegative numbers red and positive numbers black:") df.style.highlight_null(null_color='red')
201
Write a Python program to generate a number in a specified range except some specific numbers.
from random import choice def generate_random(start_range, end_range, nums): result = choice([i for i in range(start_range,end_range) if i not in nums]) return result start_range = 1 end_range = 10 nums = [2, 9, 10] print("\nGenerate a number in a specified range (1, 10) except [2, 9, 10]") print(generate_random(start_range,end_range,nums)) start_range = -5 end_range = 5 nums = [-5,0,4,3,2] print("\nGenerate a number in a specified range (-5, 5) except [-5,0,4,3,2]") print(generate_random(start_range,end_range,nums))
202
Write a Python program to add to a tag's contents in a given html document.
from bs4 import BeautifulSoup html_doc = '<a href="http://example.com/">HTML<i>w3resource.com</i></a>' soup = BeautifulSoup(html_doc, "lxml") print("\nOriginal Markup:") print(soup.a) soup.a.append("CSS") print("\nAfter append a text in the new link:") print(soup.a)
203
Write a NumPy program to create an array with 10^3 elements.
import numpy as np x = np.arange(1e3) print(x)
204
Write a NumPy program to suppresses the use of scientific notation for small numbers in NumPy array.
import numpy as np x=np.array([1.6e-10, 1.6, 1200, .235]) print("Original array elements:") print(x) print("Print array values with precision 3:") np.set_printoptions(suppress=True) print(x)
205
Write a Python program to join adjacent members of a given list.
def test(lst): result = [x + y for x, y in zip(lst[::2],lst[1::2])] return result nums = ['1','2','3','4','5','6','7','8'] print("Original list:") print(nums) print("\nJoin adjacent members of a given list:") print(test(nums)) nums = ['1','2','3'] print("\nOriginal list:") print(nums) print("\nJoin adjacent members of a given list:") print(test(nums))
206
Write a Python program to compare two unordered lists (not sets).
from collections import Counter def compare_lists(x, y): return Counter(x) == Counter(y) n1 = [20, 10, 30, 10, 20, 30] n2 = [30, 20, 10, 30, 20, 50] print(compare_lists(n1, n2))
207
Write a Pandas program to get the length of the string present of a given column in a DataFrame.
import pandas as pd df = pd.DataFrame({ 'company_code': ['Abcd','EFGF', 'skfsalf', 'sdfslew', 'safsdf'], '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("\nLength of the string in a column:") df['company_code_length'] = df['company_code'].apply(len) print(df)
208
Write a Python program to create a new Arrow object, representing the "floor" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute.
import arrow print(arrow.utcnow()) print("Hour ceiling:") print(arrow.utcnow().floor('hour')) print("\nMinute ceiling:") print(arrow.utcnow().floor('minute')) print("\nSecond ceiling:") print(arrow.utcnow().floor('second'))
209
Write a Python program to cast the provided value as a list if it's not one.
def cast_list(val): return list(val) if isinstance(val, (tuple, list, set, dict)) else [val] d1 = [1] print(type(d1)) print(cast_list(d1)) d2 = ('Red', 'Green') print(type(d2)) print(cast_list(d2)) d3 = {'Red', 'Green'} print(type(d3)) print(cast_list(d3)) d4 = {1: 'Red', 2: 'Green', 3: 'Black'} print(type(d4)) print(cast_list(d4))
210
Write a Python program to convert a list of dictionaries into a list of values corresponding to the specified key.
def test(lsts, key): return [x.get(key) for x in lsts] students = [ { 'name': 'Theodore', 'age': 18 }, { 'name': 'Mathew', 'age': 22 }, { 'name': 'Roxanne', 'age': 20 }, { 'name': 'David', 'age': 18 } ] print("Original list of dictionaries:") print(students) print("\nConvert a list of dictionaries into a list of values corresponding to the specified key:") print(test(students, 'age'))
211
Write a Python program to get the factorial of a non-negative integer.
def factorial(n): if n <= 1: return 1 else: return n * (factorial(n - 1)) print(factorial(5))
212
Write a Pandas program to create a Pivot table and find survival rate by gender, age wise of various classes.
import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table('survived', index=['sex','age'], columns='class') print(result)
213
Write a NumPy program to compute xy, element-wise where x, y are two given arrays.
import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[1, 2], [1, 2]]) print("Array1: ") print(x) print("Array1: ") print(y) print("Result- x^y:") r1 = np.power(x, y) print(r1)
214
Write a Python program to search the country name from given state name using Nominatim API and GeoPy package.
from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") state1 = "Uttar Pradesh" print("State Name:",state1) location = geolocator.geocode(state1) print("State Name/Country Name: ") print(location.address) state2 = " Illinois" print("\nState Name:",state2) location = geolocator.geocode(state2) print("State Name/Country Name: ") print(location.address) state3 = "Normandy" print("\nState Name:",state3) location = geolocator.geocode(state3) print("State Name/Country Name: ") print(location.address) state4 = "Jerusalem District" print("\nState Name:",state4) location = geolocator.geocode(state4) print("State Name/Country Name: ") print(location.address)
215
Write a Python program to append items from a specified list.
from array import * num_list = [1, 2, 6, -8] array_num = array('i', []) print("Items in the list: " + str(num_list)) print("Append items from the list: ") array_num.fromlist(num_list) print("Items in the array: "+str(array_num))
216
Write a NumPy program to create an array of the integers from 30 to70.
import numpy as np array=np.arange(30,71) print("Array of the integers from 30 to70") print(array)
217
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))
218
Write a NumPy program to generate a matrix product of two arrays.
import numpy as np x = [[1, 0], [1, 1]] y = [[3, 1], [2, 2]] print("Matrices and vectors.") print("x:") print(x) print("y:") print(y) print("Matrix product of above two arrays:") print(np.matmul(x, y))
219
Write a NumPy program to find elements within range from a given array of numbers.
import numpy as np a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29]) print("Original array:") print(a) result = np.where(np.logical_and(a>=7, a<=20)) print("\nElements within range: index position") print(result)
220
Write a Pandas program to find which years have all non-zero values and which years have any non-zero 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("\nFind which years have all non-zero values:") print(w_a_con.loc[:,w_a_con.all()]) print("\nFind which years have any non-zero values:") print(w_a_con.loc[:,w_a_con.any()])
221
Write a Pandas program to generate sequences of fixed-frequency dates and time spans intervals.
import pandas as pd print("Sequences of fixed-frequency dates and time spans (1 H):\n") r1 = pd.date_range('2030-01-01', periods=10, freq='H') print(r1) print("\nSequences of fixed-frequency dates and time spans (3 H):\n") r2 = pd.date_range('2030-01-01', periods=10, freq='3H') print(r2)
222
Write a Python program to display a number with a comma separator.
x = 3000000 y = 30000000 print("\nOriginal Number: ", x) print("Formatted Number with comma separator: "+"{:,}".format(x)); print("Original Number: ", y) print("Formatted Number with comma separator: "+"{:,}".format(y)); print()
223
Write a NumPy program to convert a given list into an array, then again convert it into a list. Check initial list and final list are equal or not.
import numpy as np a = [[1, 2], [3, 4]] x = np.array(a) a2 = x.tolist() print(a == a2)
224
Write a Python program to reverse a string.
def string_reverse(str1): rstr1 = '' index = len(str1) while index > 0: rstr1 += str1[ index - 1 ] index = index - 1 return rstr1 print(string_reverse('1234abcd'))
225
Write a Pandas program to find integer index of rows with missing data in a given dataframe.
import pandas as pd import numpy as np 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'], 'weight': [35, None, 33, 30, 31, None]}, index = ['t1', 't2', 't3', 't4', 't5', 't6']) print("Original DataFrame:") print(df) index = df['weight'].index[df['weight'].apply(np.isnan)] df_index = df.index.values.tolist() print("\nInteger index of rows with missing data in 'weight' column of the said dataframe:") print([df_index.index(i) for i in index])
226
Write a Python program to combine each line from first file with the corresponding line in second file.
with open('abc.txt') as fh1, open('test.txt') as fh2: for line1, line2 in zip(fh1, fh2): # line1 from abc.txt, line2 from test.txtg print(line1+line2)
227
Write a Python program to pair up the consecutive elements of a given list.
def pair_consecutive_elements(lst): result = [[lst[i], lst[i + 1]] for i in range(len(lst) - 1)] return result nums = [1,2,3,4,5,6] print("Original lists:") print(nums) print("Pair up the consecutive elements of the said list:") print(pair_consecutive_elements(nums)) nums = [1,2,3,4,5] print("\nOriginal lists:") print(nums) print("Pair up the consecutive elements of the said list:") print(pair_consecutive_elements(nums))
228
Write a Pandas program to create a Pivot table and find survival of both gender and class affected.
import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.groupby(['sex', 'class'])['survived'].aggregate('mean').unstack() print(result)
229
Write a Python program to find the maximum and minimum product from the pairs of tuple within a given list.
def tuple_max_val(nums): result_max = max([abs(x * y) for x, y in nums] ) result_min = min([abs(x * y) for x, y in nums] ) return result_max,result_min nums = [(2, 7), (2, 6), (1, 8), (4, 9)] print("The original list, tuple : ") print(nums) print("\nMaximum and minimum product from the pairs of the said tuple of list:") print(tuple_max_val(nums))
230
Write a Python program to interleave multiple lists of the same length. Use itertools module.
import itertools def interleave_multiple_lists(list1,list2,list3): result = list(itertools.chain(*zip(list1, list2, list3))) return result list1 = [100,200,300,400,500,600,700] list2 = [10,20,30,40,50,60,70] list3 = [1,2,3,4,5,6,7] print("Original list:") print("list1:",list1) print("list2:",list2) print("list3:",list3) print("\nInterleave multiple lists:") print(interleave_multiple_lists(list1,list2,list3))
231
Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix.
import numpy as np nums = np.random.randint(0,4,(6,3)) print("Original vector:") print(nums) new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1) result = nums[~new_nums] print("\nRows with unequal values:") print(result)
232
Write a Python script that takes input from the user and displays that input back in upper and lower cases.
user_input = input("What's your favourite language? ") print("My favourite language is ", user_input.upper()) print("My favourite language is ", user_input.lower())
233
Write a Python program to find the siblings of tags in a given html document.
from bs4 import BeautifulSoup html_doc = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>An example of HTML page</title> </head> <body> <h2>This is an example HTML page</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit, aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo. Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim elementum nunc, non elementum felis condimentum eu. In in turpis quis erat imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu, euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl euismod porta.</p> <p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from w3resource.com</a></p> <p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from w3resource.com</a></p> <a class="sister" href="http://example.com/lacie" id="link1">Lacie</a> <a class="sister" href="http://example.com/tillie" id="link2">Tillie</a> </body> </html> """ soup = BeautifulSoup(html_doc,"lxml") print("\nSiblings of tags:") print(soup.select("#link1 ~ .sister")) print(soup.select("#link1 + .sister"))
234
Write a Python program to extract and display all the image links from en.wikipedia.org/wiki/Peter_Jeffrey_(RAAF_officer).
import requests r = requests.get("https://analytics.usa.gov/data/live/browsers.json") print("90 days of visits broken down by browser for all sites:") print(r.json()['totals']['browser'])
235
Write a NumPy program to add a new row to an empty NumPy array.
import numpy as np arr = np.empty((0,3), int) print("Empty array:") print(arr) arr = np.append(arr, np.array([[10,20,30]]), axis=0) arr = np.append(arr, np.array([[40,50,60]]), axis=0) print("After adding two new arrays:") print(arr)
236
Write a Python program to find the href of the first <a> tag of a given html document.
from bs4 import BeautifulSoup html_doc = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>An example of HTML page</title> </head> <body> <h2>This is an example HTML page</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit, aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo. Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim elementum nunc, non elementum felis condimentum eu. In in turpis quis erat imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu, euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl euismod porta.</p> <p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from w3resource.com</a></p> <p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from w3resource.com</a></p> </body> </html> """ soup = BeautifulSoup(html_doc, 'html.parser') print("href of the first <a> tag:") print(soup.find('a').attrs['href'])
237
Write a Python program to convert an integer to binary keep leading zeros.
x = 12 print(format(x, '08b')) print(format(x, '010b'))
238
Write a Python program to reverse strings in a given list of string values using lambda.
def reverse_strings_list(string_list): result = list(map(lambda x: "".join(reversed(x)), string_list)) return result colors_list = ["Red", "Green", "Blue", "White", "Black"] print("\nOriginal lists:") print(colors_list) print("\nReverse strings of the said given list:") print(reverse_strings_list(colors_list))
239
Write a NumPy program to count the frequency of unique values in NumPy array.
import numpy as np a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] ) print("Original array:") print(a) unique_elements, counts_elements = np.unique(a, return_counts=True) print("Frequency of unique values of the said array:") print(np.asarray((unique_elements, counts_elements)))
240
Write a NumPy program to calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to a given array.
import numpy as np x = np.array([1, 3, 5, 7, 0]) print("Original array: ") print(x) r1 = np.ediff1d(x, to_begin=[0, 0], to_end=[200]) r2 = np.insert(np.append(np.diff(x), 200), 0, [0, 0]) assert np.array_equiv(r1, r2) print("Difference between neighboring elements, element-wise, and prepend [0, 0] and append[200] to the said array:") print(r2)
241
Write a Python program to calculate the area of the sector.
def sectorarea(): pi=22/7 radius = float(input('Radius of Circle: ')) angle = float(input('angle measure: ')) if angle >= 360: print("Angle is not possible") return sur_area = (pi*radius**2) * (angle/360) print("Sector Area: ", sur_area) sectorarea()
242
Write a NumPy program to print the full NumPy array, without truncation.
import numpy as np import sys nums = np.arange(2000) np.set_printoptions(threshold=sys.maxsize) print(nums)
243
Write a Python program to extract all the text 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("Text from the said page:") print(soup.get_text())
244
Write a Python program to convert given a dictionary to a list of tuples.
def test(d): return list(d.items()) d = {'Red': 1, 'Green': 3, 'White': 5, 'Black': 2, 'Pink': 4} print("Original Dictionary:") print(d) print("\nConvert the said dictionary to a list of tuples:") print(test(d))
245
Write a Pandas program to select rows by filtering on one or more column(s) in a multi-index 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'], 'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 37, 33, 30, 31, 32], 'tcode': ['t1', 't2', 't3', 't4', 't5', 't6']}) print("Original DataFrame:") print(df) print("\nCreate MultiIndex on 'tcode' and 'school_code':") df = df.set_index(['tcode', 'school_code']) print(df) print("\nSelect rows(s) from 'tcode' column:") print(df.query("tcode == 't2'")) print("\nSelect rows(s) from 'school_code' column:") print(df.query("school_code == 's001'")) print("\nSelect rows(s) from 'tcode' and 'scode' columns:") print(df.query(("tcode == 't1'") and ("school_code == 's001'")))
246
Write a Python program to find smallest and largest word in a given string.
def smallest_largest_words(str1): word = ""; all_words = []; str1 = str1 + " "; for i in range(0, len(str1)): if(str1[i] != ' '): word = word + str1[i]; else: all_words.append(word); word = ""; small = large = all_words[0]; #Find smallest and largest word in the str1 for k in range(0, len(all_words)): if(len(small) > len(all_words[k])): small = all_words[k]; if(len(large) < len(all_words[k])): large = all_words[k]; return small,large; str1 = "Write a Java program to sort an array of given integers using Quick sort Algorithm."; print("Original Strings:\n",str1) small, large = smallest_largest_words(str1) print("Smallest word: " + small); print("Largest word: " + large);
247
Write a Python program to find the length of a given dictionary values.
def test(dictt): result = {} for val in dictt.values(): result[val] = len(val) return result color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'} print("\nOriginal Dictionary:") print(color_dict) print("Length of dictionary values:") print(test(color_dict)) color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'} print("\nOriginal Dictionary:") print(color_dict) print("Length of dictionary values:") print(test(color_dict))
248
Write a Python program to extract year, month and date value from current datetime using arrow module.
import arrow a = arrow.utcnow() print("Year:") print(a.year) print("\nMonth:") print(a.month) print("\nDate:") print(a.day)
249
Write a Pandas program to extract words starting with capital 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 Avenue','92 N. Bishop Avenue','9910 Golden Star Avenue', '102 Dunbar St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def find_capital_word(str1): result = re.findall(r'\b[A-Z]\w+', str1) return result df['caps_word_in']=df['address'].apply(lambda cw : find_capital_word(cw)) print("\nExtract words starting with capital words from the sentences':") print(df)
250
Write a Python program to join one or more path components together and split a given path in directory and file.
import os path = r'g:\\testpath\\a.txt' print("Original path:") print(path) print("\nDir and file name of the said path:") print(os.path.split(path)) print("\nJoin one or more path components together:") print(os.path.join(r'g:\\testpath\\','a.txt'))
251
Write a Python program to randomize the order of the values of an list, returning a new list.
from copy import deepcopy from random import randint def shuffle_list(lst): temp_lst = deepcopy(lst) m = len(temp_lst) while (m): m -= 1 i = randint(0, m) temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst nums = [1, 2, 3, 4, 5, 6] print("Original list: ",nums) print("\nShuffle the elements of the said list:") print(shuffle_list(nums))
252
Write a Python program to count the same pair in three given lists.
def count_same_pair(nums1, nums2, nums3): result = sum(m == n == o for m, n, o in zip(nums1, nums2, nums3)) return result nums1 = [1,2,3,4,5,6,7,8] nums2 = [2,2,3,1,2,6,7,9] nums3 = [2,1,3,1,2,6,7,9] print("Original lists:") print(nums1) print(nums2) print(nums3) print("\nNumber of same pair of the said three given lists:") print(count_same_pair(nums1, nums2, nums3))
253
Write a Pandas program to create a Pivot table with multiple indexes from the data set of titanic.csv.
import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = pd.pivot_table(df, index = ["sex","age"], aggfunc=np.sum) print(result)
254
Write a Python program to get the volume of a sphere with radius 6.
pi = 3.1415926535897931 r= 6.0 V= 4.0/3.0*pi* r**3 print('The volume of the sphere is: ',V)
255
Write a Python program to traverse a given list in reverse order, also print the elements with original index.
color = ["red", "green", "white", "black"] print("Original list:") print(color) print("\nTraverse the said list in reverse order:") for i in reversed(color): print(i) print("\nTraverse the said list in reverse order with original index:") for i, el in reversed(list(enumerate(color))): print(i, el)
256
Write a NumPy program to create an array of zeros and three column types (integer, float, character).
import numpy as np x = np.zeros((3,), dtype=('i4,f4,a40')) new_data = [(1, 2., "Albert Einstein"), (2, 2., "Edmond Halley"), (3, 3., "Gertrude B. Elion")] x[:] = new_data print(x)
257
Write a NumPy program to stack 1-D arrays as row wise.
import numpy as np print("\nOriginal arrays:") x = np.array((1,2,3)) y = np.array((2,3,4)) print("Array-1") print(x) print("Array-2") print(y) new_array = np.row_stack((x, y)) print("\nStack 1-D arrays as rows wise:") print(new_array)
258
Write a Pandas program to add 100 days with reporting date of unidentified flying object (UFO).
import pandas as pd from datetime import timedelta df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) print("\nAdd 100 days with reporting date:") df['New_doc_dt'] = df['Date_time'] + timedelta(days=180) print(df)
259
Write a NumPy program to compute numerical negative value for all elements in a given array.
import numpy as np x = np.array([0, 1, -1]) print("Original array: ") print(x) r1 = np.negative(x) r2 = -x assert np.array_equal(r1, r2) print("Numerical negative value for all elements of the said array:") print(r1)
260
Write a Python program to sort each sublist of strings in a given list of lists using lambda.
def sort_sublists(input_list): result = [sorted(x, key = lambda x:x[0]) for x in input_list] return result color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]] print("\nOriginal list:") print(color1) print("\nAfter sorting each sublist of the said list of lists:") print(sort_sublists(color1))
261
Write a Python program to generate the combinations of n distinct objects taken from the elements of a given list.
def combination(n, n_list): if n<=0: yield [] return for i in range(len(n_list)): c_num = n_list[i:i+1] for a_num in combination(n-1, n_list[i+1:]): yield c_num + a_num n_list = [1,2,3,4,5,6,7,8,9] print("Original list:") print(n_list) n = 2 result = combination(n, n_list) print("\nCombinations of",n,"distinct objects:") for e in result: print(e)
262
Write a Python program to find all index positions of the maximum and minimum values in a given list of numbers.
def position_max_min(nums): max_val = max(nums) min_val = min(nums) max_result = [i for i, j in enumerate(nums) if j == max_val] min_result = [i for i, j in enumerate(nums) if j == min_val] return max_result,min_result nums = [12,33,23,10,67,89,45,667,23,12,11,10,54] print("Original list:") print(nums) result = position_max_min(nums) print("\nIndex positions of the maximum value of the said list:") print(result[0]) print("\nIndex positions of the minimum value of the said list:") print(result[1])
263
Write a NumPy program to get the powers of an array values element-wise.
import numpy as np x = np.arange(7) print("Original array") print(x) print("First array elements raised to powers from second array, element-wise:") print(np.power(x, 3))
264
Write a Python program to create a ctime formatted representation of the date and time using arrow module.
import arrow print("Ctime formatted representation of the date and time:") a = arrow.utcnow().ctime() print(a)
265
Write a NumPy program to create display every element of a NumPy array.
import numpy as np x = np.arange(12).reshape(3, 4) for x in np.nditer(x): print(x,end=' ') print()
266
Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees where hire_date> 01-01-07.
import pandas as pd import numpy as np df = pd.read_excel('E:\employee.xlsx') df[df['hire_date'] >='20070101']
267
Write a NumPy program to create a 2d array with 1 on the border and 0 inside.
import numpy as np x = np.ones((5,5)) print("Original array:") print(x) print("1 on the border and 0 inside in the array") x[1:-1,1:-1] = 0 print(x)
268
Write a NumPy program to get the n largest values of an array.
import numpy as np x = np.arange(10) print("Original array:") print(x) np.random.shuffle(x) n = 1 print (x[np.argsort(x)[-n:]])
269
Write a Python program to find numbers within a given range where every number is divisible by every digit it contains.
def divisible_by_digits(start_num, end_num): return [n for n in range(start_num, end_num+1) \ if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))] print(divisible_by_digits(1,22))
270
Write a Python program to extract h1 tag from example.com.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://en.wikipedia.org/wiki/Main_Page') bs = BeautifulSoup(html, "html.parser") titles = bs.find_all(['h1', 'h2','h3','h4','h5','h6']) print('List all the header tags :', *titles, sep='\n\n')
271
Write a Python program to remove a specified item using the index from an array.
from array import * array_num = array('i', [1, 3, 5, 7, 9]) print("Original array: "+str(array_num)) print("Remove the third item form the array:") array_num.pop(2) print("New array: "+str(array_num))
272
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))
273
Write a Python program to find the index position of the largest value smaller than a given number in a sorted list using Binary Search (bisect).
from bisect import bisect_left def Binary_Search(l, x): i = bisect_left(l, x) if i: return (i-1) else: return -1 nums = [1, 2, 3, 4, 8, 8, 10, 12] x = 5 num_position = Binary_Search(nums, x) if num_position == -1: print("Not found..!") else: print("Largest value smaller than ", x, " is at index ", num_position )
274
Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed.
import numpy as np result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) print("\nCopy of a matrix with the elements below the k-th diagonal zeroed:") print(result)
275
Write a Python program which iterates the integers from 1 to 50. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
for fizzbuzz in range(51): if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0: print("fizzbuzz") continue elif fizzbuzz % 3 == 0: print("fizz") continue elif fizzbuzz % 5 == 0: print("buzz") continue print(fizzbuzz)
276
Write a Python program to get a list with n elements removed from the left, right.
def drop_left_right(a, n = 1): return a[n:], a[:-n] nums = [1, 2, 3] print("Original list elements:") print(nums) result = drop_left_right(nums) print("Remove 1 element from left of the said list:") print(result[0]) print("Remove 1 element from right of the said list:") print(result[1]) nums = [1, 2, 3, 4] print("\nOriginal list elements:") print(nums) result = drop_left_right(nums,2) print("Remove 2 elements from left of the said list:") print(result[0]) print("Remove 2 elements from right of the said list:") print(result[1]) nums = [1, 2, 3, 4, 5, 6] print("\nOriginal list elements:") print(nums) result = drop_left_right(nums) print("Remove 7 elements from left of the said list:") print(result[0]) print("Remove 7 elements from right of the said list:") print(result[1])
277
Write a Python program to list the tables of given SQLite database file.
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 two tables 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);") cursorObj.execute("CREATE TABLE temp_agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);") print("List of tables:") cursorObj.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursorObj.fetchall()) conn.commit() sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
278
Write a Python program to split values into two groups, based on the result of the given filter list.
def bifurcate(colors, filter): return [ [x for x, flag in zip(colors, filter) if flag], [x for x, flag in zip(colors, filter) if not flag] ] print(bifurcate(['red', 'green', 'blue', 'pink'], [True, True, False, True]))
279
Write a Python program to store a given dictionary in a json file.
d = {"students":[{"firstName": "Nikki", "lastName": "Roysden"}, {"firstName": "Mervin", "lastName": "Friedland"}, {"firstName": "Aron ", "lastName": "Wilkins"}], "teachers":[{"firstName": "Amberly", "lastName": "Calico"}, {"firstName": "Regine", "lastName": "Agtarap"}]} print("Original dictionary:") print(d) print(type(d)) import json with open("dictionary", "w") as f: json.dump(d, f, indent = 4, sort_keys = True) print("\nJson file to dictionary:") with open('dictionary') as f: data = json.load(f) print(data)
280
Write a Python program to add two objects if both objects are an integer type.
def add_numbers(a, b): if not (isinstance(a, int) and isinstance(b, int)): return "Inputs must be integers!" return a + b print(add_numbers(10, 20)) print(add_numbers(10, 20.23)) print(add_numbers('5', 6)) print(add_numbers('5', '6'))
281
Write a Python program to count the number of items of a given doubly linked list.
class Node(object): # Singly 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 items = doubly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') items.append_item('SQL') print("Number of items of the Doubly linked list:",items.count)
282
Write a Pandas program to combine the columns of two potentially differently-indexed DataFrames into a single result DataFrame.
import pandas as pd data1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K2']) data2 = pd.DataFrame({'C': ['C0', 'C2', 'C3'], 'D': ['D0', 'D2', 'D3']}, index=['K0', 'K2', 'K3']) print("Original DataFrames:") print(data1) print("--------------------") print(data2) print("\nMerged Data (Joining on index):") result = data1.join(data2) print(result)
283
Write a Python program to count number of items in a dictionary value that is a list.
dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} ctr = sum(map(len, dict.values())) print(ctr)
284
Write a Python program to find the elements of a given list of strings that contain specific substring using lambda.
def find_substring(str1, sub_str): result = list(filter(lambda x: sub_str in x, str1)) return result colors = ["red", "black", "white", "green", "orange"] print("Original list:") print(colors) sub_str = "ack" print("\nSubstring to search:") print(sub_str) print("Elements of the said list that contain specific substring:") print(find_substring(colors, sub_str)) sub_str = "abc" print("\nSubstring to search:") print(sub_str) print("Elements of the said list that contain specific substring:") print(find_substring(colors, sub_str))
285
Write a Pandas program to generate holidays between two dates using the US federal holiday calendar.
import pandas as pd from pandas.tseries.holiday import * sdt = datetime(2021, 1, 1) edt = datetime(2030, 12, 31) print("Holidays between 2021-01-01 and 2030-12-31 using the US federal holiday calendar.") cal = USFederalHolidayCalendar() for dt in cal.holidays(start=sdt, end=edt): print (dt)
286
Write a NumPy program to get all 2D diagonals of a 3D NumPy array.
import numpy as np np_array = np.arange(3*4*5).reshape(3,4,5) print("Original Numpy array:") print(np_array) print("Type: ",type(np_array)) result = np.diagonal(np_array, axis1=1, axis2=2) print("\n2D diagonals: ") print(result) print("Type: ",type(result))
287
Write a Python program to solve the Fibonacci sequence using recursion.
def fibonacci(n): if n == 1 or n == 2: return 1 else: return (fibonacci(n - 1) + (fibonacci(n - 2))) print(fibonacci(7))
288
Write a NumPy program to access an array by column.
import numpy as np x= np.arange(9).reshape(3,3) print("Original array elements:") print(x) print("Access an array by column:") print("First column:") print(x[:,0]) print("Second column:") print(x[:,1]) print("Third column:") print(x[:,2])
289
Write a Python program to get the sum of a non-negative integer.
def sumDigits(n): if n == 0: return 0 else: return n % 10 + sumDigits(int(n / 10)) print(sumDigits(345)) print(sumDigits(45))
290
Write a NumPy program to create and display every element of a NumPy array in Fortran order.
import numpy as np x = np.arange(12).reshape(3, 4) print("Elements of the array in Fortan array:") for x in np.nditer(x, order="F"): print(x,end=' ') print("\n")
291
Write a Python program to check whether a specified list is sorted or not.
def is_sort_list(nums): result = all(nums[i] <= nums[i+1] for i in range(len(nums)-1)) return result nums1 = [1,2,4,6,8,10,12,14,16,17] print ("Original list:") print(nums1) print("\nIs the said list is sorted!") print(is_sort_list(nums1)) nums2 = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2] print ("\nOriginal list:") print(nums1) print("\nIs the said list is sorted!") print(is_sort_list(nums2))
292
Write a NumPy program to create a 3x3 identity matrix.
import numpy as np array_2D=np.identity(3) print('3x3 matrix:') print(array_2D)
293
Write a Python program to get string representing the date, controlled by an explicit format string.
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'))
294
Write a Python program to remove the first occurrence of a specified element from an array.
from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) print("Original array: "+str(array_num)) print("Remove the first occurrence of 3 from the said array:") array_num.remove(3) print("New array: "+str(array_num))
295
Write a Pandas program to extract word mention someone in tweets using @ from the specified column of a given DataFrame.
import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'tweets': ['@Obama says goodbye','Retweets for @cash','A political endorsement in @Indonesia', '1 dog = many #retweets', 'Just a simple #egg'] }) print("Original DataFrame:") print(df) def find_at_word(text): word=re.findall(r'(?<[email protected])\w+',text) return " ".join(word) df['at_word']=df['tweets'].apply(lambda x: find_at_word(x)) print("\Extracting @word from dataframe columns:") print(df)
296
Write a Python program to calculate the sum of the positive and negative numbers of a given list of numbers using lambda function.
nums = [2, 4, -6, -9, 11, -12, 14, -5, 17] print("Original list:",nums) total_negative_nums = list(filter(lambda nums:nums<0,nums)) total_positive_nums = list(filter(lambda nums:nums>0,nums)) print("Sum of the positive numbers: ",sum(total_negative_nums)) print("Sum of the negative numbers: ",sum(total_positive_nums))
297
Write a Pandas program to split the following dataframe into groups, group by month and year based on order date and find the total purchase amount year wise, month wise.
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-2013','08-17-2013','10-09-2013','07-27-2014','10-09-2012','10-10-2012','10-10-2012','06-17-2014','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("\nYear wise Month wise purchase amount:") result = df.groupby([df['ord_date'].dt.year, df['ord_date'].dt.month]).agg({'purch_amt':sum}) print(result)
298
Write a Python code to create a program for Bitonic Sort.
#License: https://bit.ly/2InTS3W # Python program for Bitonic Sort. Note that this program # works only when size of input is a power of 2. # The parameter dir indicates the sorting direction, ASCENDING # or DESCENDING; if (a[i] > a[j]) agrees with the direction, # then a[i] and a[j] are interchanged.*/ def compAndSwap(a, i, j, dire): if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]): a[i], a[j] = a[j], a[i] # It recursively sorts a bitonic sequence in ascending order, # if dir = 1, and in descending order otherwise (means dir=0). # The sequence to be sorted starts at index position low, # the parameter cnt is the number of elements to be sorted. def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) for i in range(low, low + k): compAndSwap(a, i, i + k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low + k, k, dire) # This funcion first produces a bitonic sequence by recursively # sorting its two halves in opposite sorting orders, and then # calls bitonicMerge to make them in the same order def bitonicSort(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) bitonicSort(a, low, k, 1) bitonicSort(a, low + k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N # in ASCENDING order def sort(a, N, up): bitonicSort(a, 0, N, up) # Driver code to test above a = [] print("How many numbers u want to enter?"); n = int(input()) print("Input the numbers:"); for i in range(n): a.append(int(input())) up = 1 sort(a, n, up) print("\n\nSorted array is:") for i in range(n): print("%d" % a[i])
299