code
stringlengths
63
8.54k
code_length
int64
11
747
# Convert Temperature from degree Celsius to Fahrenheit celsius=float(input("Enter degree in celsius: ")) fahrenheit=(celsius*(9/5))+32 print("Degree in Fahrenheit is",fahrenheit)
18
# Write a Python program to count the same pair in two given lists. use map() function. from operator import eq def count_same_pair(nums1, nums2): result = sum(map(eq, nums1, nums2)) return result nums1 = [1,2,3,4,5,6,7,8] nums2 = [2,2,3,1,2,6,7,9] print("Original lists:") print(nums1) print(nums2) print("\nNumber of same pair of the said two given lists:") print(count_same_pair(nums1, nums2))
53
# Check Armstrong number using recursion sum=0def check_ArmstrongNumber(num):    global sum    if (num!=0):        sum+=pow(num%10,3)        check_ArmstrongNumber(num//10)    return sumnum=int(input("Enter a number:"))if (check_ArmstrongNumber(num) == num):    print("It is an Armstrong Number.")else:    print("It is not an Armstrong Number.")
32
# Write a Python program to Modulo of tuple elements # Python3 code to demonstrate working of # Tuple modulo # using zip() + generator expression    # initialize tuples test_tup1 = (10, 4, 5, 6) test_tup2 = (5, 6, 7, 5)    # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))    # Tuple modulo # using zip() + generator expression res = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2))    # printing result print("The modulus tuple : " + str(res))
91
# Python Program to Implement Heapsort def heapsort(alist): build_max_heap(alist) for i in range(len(alist) - 1, 0, -1): alist[0], alist[i] = alist[i], alist[0] max_heapify(alist, index=0, size=i)   def parent(i): return (i - 1)//2   def left(i): return 2*i + 1   def right(i): return 2*i + 2   def build_max_heap(alist): length = len(alist) start = parent(length - 1) while start >= 0: max_heapify(alist, index=start, size=length) start = start - 1   def max_heapify(alist, index, size): l = left(index) r = right(index) if (l < size and alist[l] > alist[index]): largest = l else: largest = index if (r < size and alist[r] > alist[largest]): largest = r if (largest != index): alist[largest], alist[index] = alist[index], alist[largest] max_heapify(alist, largest, size)     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] heapsort(alist) print('Sorted list: ', end='') print(alist)
134
# Write a Python program to access only unique key value of a Python object. import json python_obj = '{"a": 1, "a": 2, "a": 3, "a": 4, "b": 1, "b": 2}' print("Original Python object:") print(python_obj) json_obj = json.loads(python_obj) print("\nUnique Key in a JSON object:") print(json_obj)
45
# Write a Python program that will accept the base and height of a triangle and compute the area. b = int(input("Input the base : ")) h = int(input("Input the height : ")) area = b*h/2 print("area = ", area)
40
# Write a Pandas program to find the Indexes of missing values 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("\nMissing values in purch_amt column:") result = df['ord_no'].isnull().to_numpy().nonzero() print(result)
53
# Write a Python program to get the symmetric difference between two lists, after applying the provided function to each list element of both. def symmetric_difference_by(a, b, fn): (_a, _b) = (set(map(fn, a)), set(map(fn, b))) return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a] from math import floor print(symmetric_difference_by([2.1, 1.2], [2.3, 3.4], floor))
66
# Print array elements in reverse order arr=[] size = int(input("Enter the size of the array: ")) print("Enter the Element of the array:") for i in range(0,size):     num = int(input())     arr.append(num) temp=size while(temp>=0):     for k in range(0,temp-1,1):         temp2=arr[k]         arr[k]=arr[k+1]         arr[k+1]=temp2     temp-=1 print("After reversing array is :") for i in range(0, size):     print(arr[i],end=" ")
53
# Write a NumPy program to save as text a matrix which has in each row 2 float and 1 string at the end. import numpy as np matrix = [[1, 0, 'aaa'], [0, 1, 'bbb'], [0, 1, 'ccc']] np.savetxt('test', matrix, delimiter=' ', header='string', comments='', fmt='%s')
46
# Write a Python program to sort a list of tuples alphabetically # Python program to sort a # list of tuples alphabetically       # Function to sort the list of # tuples    def SortTuple(tup):            # Getting the length of list      # of tuples     n = len(tup)            for i in range(n):         for j in range(n-i-1):                            if tup[j][0] > tup[j + 1][0]:                 tup[j], tup[j + 1] = tup[j + 1], tup[j]                        return tup        # Driver's code    tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),         ("Nikhil", 21), ("B", "C")]            print(SortTuple(tup))
87
# 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')
28
# Write a Python program to convert Set into Tuple and Tuple into Set #   program to convert set to tuple # create set s = {'a', 'b', 'c', 'd', 'e'}    # print set print(type(s), " ", s)    # call tuple() method  # this method convert set to tuple t = tuple(s)    # print tuple print(type(t), " ", t)
59
# Write a Python program to count the frequency of words in a file. from collections import Counter def word_count(fname): with open(fname) as f: return Counter(f.read().split()) print("Number of words in the file :",word_count("test.txt"))
33
# Write a Python program to find the minimum window in a given string which will contain all the characters of another given string. import collections def min_window(str1, str2): result_char, missing_char = collections.Counter(str2), len(str2) i = p = q = 0 for j, c in enumerate(str1, 1): missing_char -= result_char[c] > 0 result_char[c] -= 1 if not missing_char: while i < q and result_char[str1[i]] < 0: result_char[str1[i]] += 1 i += 1 if not q or j - i <= q - p: p, q = i, j return str1[p:q] str1 = "PRWSOERIUSFK" str2 = "OSU" print("Original Strings:\n",str1,"\n",str2) print("Minimum window:") print(min_window(str1,str2))
101
# Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. : Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[-5:] printList()
48
# Write a Pandas program to stack two given series vertically and horizontally. import pandas as pd series1 = pd.Series(range(10)) series2 = pd.Series(list('pqrstuvwxy')) print("Original Series:") print(series1) print(series2) series1.append(series2) df = pd.concat([series1, series2], axis=1) print("\nStack two given series vertically and horizontally:") print(df)
41
# Write a NumPy program to check whether the dimensions of two given arrays are same or not. import numpy as np def test_array_dimensions(ar1,ar2): try: ar1 + ar2 except ValueError: return "Different dimensions" else: return "Same dimensions" ar1 = np.arange(20).reshape(4,5) ar2 = np.arange(20).reshape(4,5) print(test_array_dimensions(ar1, ar2)) ar1 = np.arange(20).reshape(5,4) ar2 = np.arange(20).reshape(4,5) print(test_array_dimensions(ar1, ar2))
53
# Write a Pandas program to create a time-series from a given list of dates as strings. import pandas as pd import numpy as np import datetime from datetime import datetime, date dates = ['2014-08-01','2014-08-02','2014-08-03','2014-08-04'] time_series = pd.Series(np.random.randn(4), dates) print(time_series)
40
# Python Program for Depth First Binary Tree Search using Recursion class BinaryTree: def __init__(self, key=None): self.key = key self.left = None self.right = None   def set_root(self, key): self.key = key   def insert_left(self, new_node): self.left = new_node   def insert_right(self, new_node): self.right = new_node   def search(self, key): if self.key == key: return self if self.left is not None: temp = self.left.search(key) if temp is not None: return temp if self.right is not None: temp = self.right.search(key) return temp return None   def depth_first(self): print('entering {}...'.format(self.key)) if self.left is not None: self.left.depth_first() print('at {}...'.format(self.key)) if self.right is not None: self.right.depth_first() print('leaving {}...'.format(self.key))     btree = None   print('Menu (this assumes no duplicate keys)') print('insert <data> at root') print('insert <data> left of <data>') print('insert <data> right of <data>') print('dfs') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'insert': data = int(do[1]) new_node = BinaryTree(data) suboperation = do[2].strip().lower() if suboperation == 'at': btree = new_node else: position = do[4].strip().lower() key = int(position) ref_node = None if btree is not None: ref_node = btree.search(key) if ref_node is None: print('No such key.') continue if suboperation == 'left': ref_node.insert_left(new_node) elif suboperation == 'right': ref_node.insert_right(new_node)   elif operation == 'dfs': print('depth-first search traversal:') if btree is not None: btree.depth_first() print()   elif operation == 'quit': break
213
# 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)
68
# Write a Python program to count the number of groups of non-zero numbers separated by zeros of a given list of numbers. def test(lst): previous_digit = 0 ctr = 0 for digit in lst: if previous_digit==0 and digit!=0: ctr+=1 previous_digit = digit return ctr nums = [3,4,6,2,0,0,0,0,0,0,6,7,6,9,10,0,0,0,0,0,5,9,9,7,4,4,0,0,0,0,0,0,5,3,2,9,7,1] print("\nOriginal list:") print(nums) print("\nNumber of groups of non-zero numbers separated by zeros of the said list:") print(test(nums))
65
# How to check which Button was clicked in Tkinter in Python # Python program to determine which # button was pressed in tkinter    # Import the library tkinter from tkinter import *    # Create a GUI app app = Tk()    # Create a function with one paramter, i.e., of  # the text you want to show when button is clicked def which_button(button_press):     # Printing the text when a button is clicked     print(button_press)       # Creating and displaying of button b1 b1 = Button(app, text="Apple",             command=lambda m="It is an apple": which_button(m))    b1.grid(padx=10, pady=10)    # Creating and displaying of button b2 b2 = Button(app, text="Banana",             command=lambda m="It is a banana": which_button(m)) b2.grid(padx=10, pady=10)    # Make the infinite loop for displaying the app app.mainloop()
121
# 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)
53
# Write a Pandas program to interpolate the missing values using the Linear Interpolation method 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("\nInterpolate the missing values using the Linear Interpolation method (purch_amt):") df['purch_amt'].interpolate(method='linear', direction = 'forward', inplace=True) print(df)
63
# Write a Python program to find out, if the given number is abundant. def is_abundant(n): fctr_sum = sum([fctr for fctr in range(1, n) if n % fctr == 0]) return fctr_sum > n print(is_abundant(12)) print(is_abundant(13))
36
# Write a Python program to Remove empty tuples from a list # Python program to remove empty tuples from a  # list of tuples function to remove empty tuples  # using list comprehension def Remove(tuples):     tuples = [t for t in tuples if t]     return tuples    # Driver Code tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),            ('krishna', 'akbar', '45'), ('',''),()] print(Remove(tuples))
62
# numpy.where() in Python # Python program explaining  # where() function     import numpy as np    np.where([[True, False], [True, True]],          [[1, 2], [3, 4]], [[5, 6], [7, 8]])
27
# Write a Python code to remove all characters except a specified character in a given string. def remove_characters(str1,c): return ''.join([el for el in str1 if el == c]) text = "Python Exercises" print("Original string") print(text) except_char = "P" print("Remove all characters except",except_char,"in the said string:") print(remove_characters(text,except_char)) text = "google" print("\nOriginal string") print(text) except_char = "g" print("Remove all characters except",except_char,"in the said string:") print(remove_characters(text,except_char)) text = "exercises" print("\nOriginal string") print(text) except_char = "e" print("Remove all characters except",except_char,"in the said string:") print(remove_characters(text,except_char))
81
# Write a Pandas program to check whether only lower case or upper case is present in a given column of a DataFrame. import pandas as pd df = pd.DataFrame({ 'company_code': ['ABCD','EFGF', 'hhhh', 'abcd', 'EAWQaaa'], '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("\nIs lower (company_code)?") df['company_code_ul_cases'] = list(map(lambda x: x.islower(), df['company_code'])) print(df) print("\nIs Upper (company_code)?") df['company_code_ul_cases'] = list(map(lambda x: x.isupper(), df['company_code'])) print(df)
67
# Write a NumPy program to make the length of each element 15 of a given array and the string centered / left-justified / right-justified with paddings of _. import numpy as np x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str) print("Original Array:") print(x) centered = np.char.center(x, 15, fillchar='_') left = np.char.ljust(x, 15, fillchar='_') right = np.char.rjust(x, 15, fillchar='_') print("\nCentered =", centered) print("Left =", left) print("Right =", right)
68
# Program to print the Full Pyramid Star Pattern row_size=int(input("Enter the row size:")) star_print=1 for out in range(0,row_size):     for inn in range(row_size-1,out,-1):         print(" ",end="")     for p in range(0,star_print):         print("*",end="")     star_print+=2     print("\r")
31
# Copy one string to another using recursion def Copy_String(str, str1,i):    str1[i]=str[i]    if (str[i] == '\0'):        return    Copy_String(str, str1, i + 1)str=input("Enter your String:")str+='\0'str1=[0]*(len(str))Copy_String(str, str1,0)print("Copy Done...")print("Copy string is:","".join(str1))
28
# 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)
66
# 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()
41
# 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)
82
# How to Extract Wikipedia Data in Python import wikipedia wikipedia.summary("Python (programming language)")
13
# Write a Python program to count the frequency of consecutive duplicate elements in a given list of numbers. def count_dups(nums): element = [] freque = [] if not nums: return element running_count = 1 for i in range(len(nums)-1): if nums[i] == nums[i+1]: running_count += 1 else: freque.append(running_count) element.append(nums[i]) running_count = 1 freque.append(running_count) element.append(nums[i+1]) return element,freque nums = [1,2,2,2,4,4,4,5,5,5,5] print("Original lists:") print(nums) print("\nConsecutive duplicate elements and their frequency:") print(count_dups(nums))
69
# 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))
85
# Write a NumPy program to create a Cartesian product of two arrays into single array of 2D points. import numpy as np x = np.array([1,2,3]) y = np.array([4,5]) result = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))]) print(result)
36
# Python Program to Minimize Lateness using Greedy Algorithm def minimize_lateness(ttimes, dtimes): """Return minimum max lateness and the schedule to obtain it.   (min_lateness, schedule) is returned.   Lateness of a request i is L(i) = finish time of i - deadline of if request i finishes after its deadline. The maximum lateness is the maximum value of L(i) over all i. min_lateness is the minimum value of the maximum lateness that can be achieved by optimally scheduling the requests.   schedule is a list that contains the indexes of the requests ordered such that minimum maximum lateness is achieved.   ttime[i] is the time taken to complete request i. dtime[i] is the deadline of request i. """ # index = [0, 1, 2, ..., n - 1] for n requests index = list(range(len(dtimes))) # sort according to deadlines index.sort(key=lambda i: dtimes[i])   min_lateness = 0 start_time = 0 for i in index: min_lateness = max(min_lateness, (ttimes[i] + start_time) - dtimes[i]) start_time += ttimes[i]   return min_lateness, index     n = int(input('Enter number of requests: ')) ttimes = input('Enter the time taken to complete the {} request(s) in order: ' .format(n)).split() ttimes = [int(tt) for tt in ttimes] dtimes = input('Enter the deadlines of the {} request(s) in order: ' .format(n)).split() dtimes = [int(dt) for dt in dtimes]   min_lateness, schedule = minimize_lateness(ttimes, dtimes) print('The minimum maximum lateness:', min_lateness) print('The order in which the requests should be scheduled:', schedule)
231
# Write a Python program to find the missing number in a given array of numbers between 10 and 20. import array as arr def test(nums): return sum(range(10, 21)) - sum(list(nums)) array_num = arr.array('i', [10, 11, 12, 13, 14, 16, 17, 18, 19, 20]) print("Original array:") for i in range(len(array_num)): print(array_num[i], end=' ') print("\nMissing number in the said array (10-20): ",test(array_num)) array_num = arr.array('i', [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) print("\nOriginal array:") for i in range(len(array_num)): print(array_num[i], end=' ') print("\nMissing number in the said array (10-20): ",test(array_num))
91
# Write a Python program to find the nested lists elements, which are present in another list using lambda. def intersection_nested_lists(l1, l2): result = [list(filter(lambda x: x in l1, sublist)) for sublist in l2] return result nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] nums2 = [[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]] print("\nOriginal lists:") print(nums1) print(nums2) print("\nIntersection of said nested lists:") print(intersection_nested_lists(nums1, nums2))
81
# 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)
99
# Write a Python program to create an array contains six integers. Also print all the members of the array. from array import array my_array = array('i', [10, 20, 30, 40, 50]) for i in my_array: print(i)
37
# Write a NumPy program to save a given array to a text file and load it. import numpy as np import os x = np.arange(12).reshape(4, 3) print("Original array:") print(x) header = 'col1 col2 col3' np.savetxt('temp.txt', x, fmt="%d", header=header) print("After loading, content of the text file:") result = np.loadtxt('temp.txt') print(result)
50
# Selenium – Search for text on page in Python # import webdriver  from selenium import webdriver    # create webdriver object  driver = webdriver.Chrome()    # URL of the website  url = "https://www.geeksforgeeks.org/"    # Opening the URL  driver.get(url)     # Getting current URL source code  get_source = driver.page_source    # Text you want to search search_text = "Floor"    # print True if text is present else False print(search_text in get_source)
67
# Write a Python program to add two given lists of different lengths, start from right , using itertools module. from itertools import zip_longest def elementswise_right_join(l1, l2): result = [a + b for a,b in zip_longest(reversed(l1), reversed(l2), fillvalue=0)][::-1] return result nums1 = [2, 4, 7, 0, 5, 8] nums2 = [3, 3, -1, 7] print("\nOriginal lists:") print(nums1) print(nums2) print("\nAdd said two lists from right:") print(elementswise_right_join(nums1, nums2)) nums3 = [1, 2, 3, 4, 5, 6] nums4 = [2, 4, -3] print("\nOriginal lists:") print(nums3) print(nums4) print("\nAdd said two lists from right:") print(elementswise_right_join(nums3, nums4))
91
# Write a Python program to find the index of an item in a specified list. num =[10, 30, 4, -6] print(num.index(30))
22
# Write a Python program to get the difference between the two lists. list1 = [1, 3, 5, 7, 9] list2=[1, 2, 4, 6, 7, 8] diff_list1_list2 = list(set(list1) - set(list2)) diff_list2_list1 = list(set(list2) - set(list1)) total_diff = diff_list1_list2 + diff_list2_list1 print(total_diff)
42
# Write a Python program to Remove keys with Values Greater than K ( Including mixed values ) # Python3 code to demonstrate working of  # Remove keys with Values Greater than K ( Including mixed values ) # Using loop + isinstance()    # initializing dictionary test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}     # printing original dictionary print("The original dictionary is : " + str(test_dict))    # initializing K  K = 6    # using loop to iterate keys of dictionary res = {} for key in test_dict:          # testing for data type and then condition, order is imp.     if not (isinstance(test_dict[key], int) and test_dict[key] > K):         res[key] = test_dict[key]            # printing result  print("The constructed dictionary : " + str(res)) 
128
# Write a Python program to find the index position of the last occurrence of a given number in a sorted list using Binary Search (bisect). from bisect import bisect_right def BinarySearch(a, x): i = bisect_right(a, x) if i != len(a)+1 and a[i-1] == x: return (i-1) else: return -1 nums = [1, 2, 3, 4, 8, 8, 10, 12] x = 8 num_position = BinarySearch(nums, x) if num_position == -1: print("not presetn!") else: print("Last occurrence of", x, "is present at", num_position)
82
# Write a Pandas program to create a new DataFrame based on existing series, using specified argument and override the existing columns names. import pandas as pd s1 = pd.Series([0, 1, 2, 3], name='col1') s2 = pd.Series([0, 1, 2, 3]) s3 = pd.Series([0, 1, 4, 5], name='col3') df = pd.concat([s1, s2, s3], axis=1, keys=['column1', 'column2', 'column3']) print(df)
57
# How to check if a string starts with a substring using regex in Python # import library import re    # define a function  def find(string, sample) :        # check substring present    # in a string or not   if (sample in string):          y = "^" + sample          # check if string starts        # with the substring       x = re.search(y, string)          if x :           print("string starts with the given substring")          else :           print("string doesn't start with the given substring")      else :       print("entered string isn't a substring")       # Driver code string = "geeks for geeks makes learning fun"   sample = "geeks"    # function call find(string, sample)    sample = "makes"    # function call find(string, sample)
112
# Write a Python program to perform a deep flattens a list. from collections.abc import Iterable def deep_flatten(lst): return ([a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]) nums = [1, [2], [[3], [4], 5], 6] print("Original list elements:") print(nums) print() print("Deep flatten the said list:") print(deep_flatten(nums)) nums = [[[1, 2, 3], [4, 5]], 6] print("\nOriginal list elements:") print(nums) print() print("Deep flatten the said list:") print(deep_flatten(nums))
71
# Write a NumPy program to compute the histogram of nums against the bins. import numpy as np import matplotlib.pyplot as plt nums = np.array([0.5, 0.7, 1.0, 1.2, 1.3, 2.1]) bins = np.array([0, 1, 2, 3]) print("nums: ",nums) print("bins: ",bins) print("Result:", np.histogram(nums, bins)) plt.hist(nums, bins=bins) plt.show()
46
# Write a NumPy program to compute the covariance matrix of two given arrays. import numpy as np x = np.array([0, 1, 2]) y = np.array([2, 1, 0]) print("\nOriginal array1:") print(x) print("\nOriginal array1:") print(y) print("\nCovariance matrix of the said arrays:\n",np.cov(x, y))
41
# Write a Python program to Check if a Substring is Present in a Given String # function to check if small string is  # there in big string def check(string, sub_str):     if (string.find(sub_str) == -1):         print("NO")     else:         print("YES")              # driver code string = "geeks for geeks" sub_str ="geek" check(string, sub_str)
51
# Write a Python program to find largest number in a list # Python program to find largest # number in a list    # list of numbers list1 = [10, 20, 4, 45, 99]    # sorting the list list1.sort()    # printing the last element print("Largest element is:", list1[-1])
48
# Write a Pandas program to filter all records starting from the 'Year' column, access every other column 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("\nFrom the 'Year' column, access every other column:") print(w_a_con.loc[:,'Year'::2].head(10)) print("\nAlternate solution:") print(w_a_con.iloc[:,0::2].head(10))
53
# 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)
49
# Write a Python Program to Reverse the Content of a File using Stack # Python3 code to reverse the lines # of a file using Stack.            # Creating Stack class (LIFO rule) class Stack:            def __init__(self):                    # Creating an empty stack         self._arr = []                # Creating push() method.     def push(self, val):         self._arr.append(val)         def is_empty(self):                    # Returns True if empty         return len(self._arr) == 0        # Creating Pop method.     def pop(self):                    if self.is_empty():             print("Stack is empty")             return                    return self._arr.pop()    # Creating a function which will reverse # the lines of a file and Overwrites the  # given file with its contents line-by-line # reversed def reverse_file(filename):             S = Stack()     original = open(filename)            for line in original:         S.push(line.rstrip("\n"))            original.close()                     output = open(filename, 'w')            while not S.is_empty():         output.write(S.pop()+"\n")            output.close()       # Driver Code filename = "GFG.txt"    # Calling the reverse_file function reverse_file(filename)     # Now reading the content of the file with open(filename) as file:         for f in file.readlines():             print(f, end ="")
157
# 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())
28
# Write a Python program to sort unsorted numbers using Multi-key quicksort. #Ref.https://bit.ly/36fvcEw def quick_sort_3partition(sorting: list, left: int, right: int) -> None: if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 elif sorting[i] > pivot: sorting[b], sorting[i] = sorting[i], sorting[b] b -= 1 else: i += 1 quick_sort_3partition(sorting, left, a - 1) quick_sort_3partition(sorting, b + 1, right) def three_way_radix_quicksort(sorting: list) -> list: if len(sorting) <= 1: return sorting return ( three_way_radix_quicksort([i for i in sorting if i < sorting[0]]) + [i for i in sorting if i == sorting[0]] + three_way_radix_quicksort([i for i in sorting if i > sorting[0]]) ) nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_3partition(nums, 0, len(nums)-1) print(nums) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) print("After applying Multi-key quicksort the said list becomes:") quick_sort_3partition(nums, 0, len(nums)-1) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Multi-key quicksort the said list becomes:") quick_sort_3partition(nums, 0, len(nums)-1) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Multi-key quicksort the said list becomes:") quick_sort_3partition(nums, 1, len(nums)-1) print(nums) nums = ['z','a','y','b','x','c'] print("\nOriginal list:") print(nums) print("After applying Multi-key quicksort the said list becomes:") quick_sort_3partition(nums, 0, len(nums)-1) print(nums) nums = ['z','a','y','b','x','c'] print("\nOriginal list:") print(nums) print("After applying Multi-key quicksort the said list becomes:") quick_sort_3partition(nums, 2, len(nums)-1) print(nums)
261
# Write a Python program to Consecutive characters frequency # Python3 code to demonstrate working of  # Consecutive characters frequency # Using list comprehension + groupby() from itertools import groupby    # initializing string test_str = "geekksforgggeeks"    # printing original string print("The original string is : " + test_str)    # Consecutive characters frequency # Using list comprehension + groupby() res = [len(list(j)) for _, j in groupby(test_str)]    # printing result  print("The Consecutive characters frequency : " + str(res)) 
77
# Write a Python program to print all negative numbers in a range # Python program to print negative Numbers in given range    start, end = -4, 19    # iterating each number in list for num in range(start, end + 1):            # checking condition     if num < 0:         print(num, end = " ")
53
# Write a Python program to check if a given value is a method of a user-defined class. Use types.MethodType() import types class C: def x(): return 1 def y(): return 1 def b(): return 2 print(isinstance(C().x, types.MethodType)) print(isinstance(C().y, types.MethodType)) print(isinstance(b, types.MethodType)) print(isinstance(max, types.MethodType)) print(isinstance(abs, types.MethodType))
46
# Write a Python program to get the length of an array. from array import array num_array = array('i', [10,20,30,40,50]) print("Length of the array is:") print(len(num_array))
26
# Write a Python program to make two given strings (lower case, may or may not be of the same length) anagrams removing any characters from any of the strings. def make_map(s): temp_map = {} for char in s: if char not in temp_map: temp_map[char] = 1 else: temp_map[char] +=1 return temp_map def make_anagram(str1, str2): str1_map1 = make_map(str1) str2_map2 = make_map(str2) ctr = 0 for key in str2_map2.keys(): if key not in str1_map1: ctr += str2_map2[key] else: ctr += max(0, str2_map2[key]-str1_map1[key]) for key in str1_map1.keys(): if key not in str2_map2: ctr += str1_map1[key] else: ctr += max(0, str1_map1[key]-str2_map2[key]) return ctr str1 = input("Input string1: ") str2 = input("Input string2: ") print(make_anagram(str1, str2))
112
# 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())
24
# Write a Python program to check if there are duplicate values in a given flat list. def has_duplicates(lst): return len(lst) != len(set(lst)) nums = [1, 2, 3, 4, 5, 6, 7] print("Original list:") print(nums) print("Check if there are duplicate values in the said given flat list:") print(has_duplicates(nums)) nums = [1, 2, 3, 3, 4, 5, 5, 6, 7] print("\nOriginal list:") print(nums) print("Check if there are duplicate values in the said given flat list:") print(has_duplicates(nums))
75
# 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)
50
# Write a Pandas program to create a DataFrame using intervals as an index. import pandas as pd print("Create an Interval Index using IntervalIndex.from_breaks:") df_interval = pd.DataFrame({"X":[1, 2, 3, 4, 5, 6, 7]}, index = pd.IntervalIndex.from_breaks( [0, 0.5, 1.0, 1.5, 2.0, 2.5, 3, 3.5])) print(df_interval) print(df_interval.index) print("\nCreate an Interval Index using IntervalIndex.from_tuples:") df_interval = pd.DataFrame({"X":[1, 2, 3, 4, 5, 6, 7]}, index = pd.IntervalIndex.from_tuples( [(0, .5), (.5, 1), (1, 1.5), (1.5, 2), (2, 2.5), (2.5, 3), (3, 3.5)])) print(df_interval) print(df_interval.index) print("\nCreate an Interval Index using IntervalIndex.from_arrays:") df_interval = pd.DataFrame({"X":[1, 2, 3, 4, 5, 6, 7]}, index = pd.IntervalIndex.from_arrays( [0, .5, 1, 1.5, 2, 2.5, 3], [.5, 1, 1.5, 2, 2.5, 3, 3.5])) print(df_interval) print(df_interval.index)
114
# Program to find the sum of series 1/1+1/2+1/3..+1/N print("Enter the range of number:") n=int(input()) print("Enter the value of x:"); x=int(input()) sum=0 i=1 while(i<=n):     sum+=pow(x,i)     i+=2 print("The sum of the series = ",sum)
33
# Write a Python program to Records with Value at K index # Python3 code to demonstrate working of # Records with Value at K index # Using loop    # initialize list  test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]    # printing original list print("The original list is : " + str(test_list))    # initialize ele  ele = 3    # initialize K  K = 1    # Records with Value at K index # Using loop # using y for K = 1  res = [] for x, y, z in test_list:     if y == ele:         res.append((x, y, z))    # printing result print("The tuples of element at Kth position : " + str(res))
120
# Write a Python program to create a histogram from a given list of integers. def histogram( items ): for n in items: output = '' times = n while( times > 0 ): output += '*' times = times - 1 print(output) histogram([2, 3, 6, 5])
47
# 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)
29
# Write a Python program to find the shortest distance from a specified character in a given string. Return the shortest distances through a list and use itertools module to solve the problem. import itertools as it def char_shortest_distancer(str1, char1): result = [len(str1)] * len(str1) prev_char = -len(str1) for i in it.chain(range(len(str1)),reversed(range(len(str1)))): if str1[i] == char1: prev_char = i result[i] = min(result[i], abs(i-prev_char)) return result str1 = "w3resource" chr1='r' print("Original string:",str1,": Specified character:",chr1) print(char_shortest_distancer(str1,chr1)) str1 = "python exercises" chr1='e' print("\nOriginal string:",str1,": Specified character:",chr1) print(char_shortest_distancer(str1,chr1)) str1 = "JavaScript" chr1='S' print("\nOriginal string:",str1,": Specified character:",chr1) print(char_shortest_distancer(str1,chr1))
93
# Write a Python program to find the maximum and minimum values in a given heterogeneous list. def max_min_val(list_val): max_val = max(i for i in list_val if isinstance(i, int)) min_val = min(i for i in list_val if isinstance(i, int)) return(max_val, min_val) list_val = ['Python', 3, 2, 4, 5, 'version'] print("Original list:") print(list_val) print("\nMaximum and Minimum values in the said list:") print(max_min_val(list_val))
61
# Write a Python program to split a given list into two parts where the length of the first part of the list is given. def split_two_parts(n_list, L): return n_list[:L], n_list[L:] n_list = [1,1,2,3,4,4,5, 1] print("Original list:") print(n_list) first_list_length = 3 print("\nLength of the first part of the list:",first_list_length) print("\nSplited the said list into two parts:") print(split_two_parts(n_list, first_list_length))
58
# Write a Python program to Test substring order # Python3 code to demonstrate working of  # Test substring order # Using join() + in operator + generator expression    # initializing string test_str = 'geeksforgeeks'    # printing original string print("The original string is : " + str(test_str))    # initializing substring K = 'seek'    # concatenating required characters  temp = lambda sub: ''.join(chr for chr in sub if chr in set(K))    # checking in order res = K in temp(test_str)    # printing result  print("Is substring in order : " + str(res)) 
90
# Write a Python program to count the frequency of consecutive duplicate elements in a given list of numbers. Use itertools module. from itertools import groupby def count_same_pair(nums): result = [sum(1 for _ in group) for _, group in groupby(nums)] return result nums = [1,1,2,2,2,4,4,4,5,5,5,5] print("Original lists:") print(nums) print("\nFrequency of the consecutive duplicate elements:") print(count_same_pair(nums))
55
# Write a Python program to remove the specific item from a given list of lists. import copy def remove_list_of_lists(color, N): for x in color: del x[N] return color nums = [ ["Red","Maroon","Yellow","Olive"], ["#FF0000", "#800000", "#FFFF00", "#808000"], ["rgb(255,0,0)","rgb(128,0,0)","rgb(255,255,0)","rgb(128,128,0)"] ] nums1 = copy.deepcopy(nums) nums2 = copy.deepcopy(nums) nums3 = copy.deepcopy(nums) print("Original list of lists:") print(nums) N = 0 print("\nRemove 1st item from the said list of lists:") print(remove_list_of_lists(nums1, N)) N = 1 print("\nRemove 2nd item from the said list of lists:") print(remove_list_of_lists(nums2, N)) N = 3 print("\nRemove 4th item from the said list of lists:") print(remove_list_of_lists(nums3, N))
95
# Write a Pandas program to get the day of month, day of year, week number and day of week from a given series of date strings. import pandas as pd from dateutil.parser import parse date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20']) print("Original Series:") print(date_series) date_series = date_series.map(lambda x: parse(x)) print("Day of month:") print(date_series.dt.day.tolist()) print("Day of year:") print(date_series.dt.dayofyear.tolist()) print("Week number:") print(date_series.dt.weekofyear.tolist()) print("Day of week:") print(date_series.dt.weekday_name.tolist())
68
# Find the length of each string element in the Numpy array in Python # importing the numpy library as np import numpy as np    # Create a numpy array arr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])    # Print the array print(arr)
42
# Write a Python program to get the frequency of the tuples in a given list. from collections import Counter nums = [(['1', '4'], ['4', '1'], ['3', '4'], ['2', '7'], ['6', '8'], ['5','8'], ['6','8'], ['5','7'], ['2','7'])] print("Original list of tuples:") print(nums) result = Counter(tuple(sorted(i)) for i in nums[0]) print("\nTuples"," ","frequency") for key,val in result.items(): print(key," ", val)
57
# Convert a decimal number to hexadecimal using recursion str3=""def DecimalToHexadecimal(n):    global str3    if(n!=0):        rem = n % 16        if (rem < 10):            str3 += (chr)(rem + 48) # 48 Ascii = 0        else:            str3 += (chr)(rem + 55) #55 Ascii = 7        DecimalToHexadecimal(n // 16)    return str3n=int(input("Enter the Decimal Value:"))str=DecimalToHexadecimal(n)print("Hexadecimal Value of Decimal number is:",''.join(reversed(str)))
56
# Write a Python program to Convert dictionary to K sized dictionaries # Python3 code to demonstrate working of  # Convert dictionary to K Keys dictionaries # Using loop    # initializing dictionary test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}    # printing original dictionary print("The original dictionary is : " + str(test_dict))    # initializing K  K = 2    res = [] count = 0 flag = 0 indict = dict() for key in test_dict:     indict[key] = test_dict[key]             count += 1            # checking for K size and avoiding empty dict using flag     if count % K == 0 and flag:         res.append(indict)                    # reinitializing dictionary         indict = dict()         count = 0     flag = 1           # printing result  print("The converted list : " + str(res)) 
134
# 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))
75
# Write a Python program to find the latitude and longitude of a given location using Nominatim API and GeoPy package. from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") ladd1 = "27488 Stanford Avenue, North Dakota" print("Location address:",ladd1) location = geolocator.geocode(ladd1) print("Latitude and Longitude of the said address:") print((location.latitude, location.longitude)) ladd2 = "380 New York St, Redlands, CA 92373" print("\nLocation address:",ladd2) location = geolocator.geocode(ladd2) print("Latitude and Longitude of the said address:") print((location.latitude, location.longitude)) ladd3 = "1600 Pennsylvania Avenue NW" print("\nLocation address:",ladd3) location = geolocator.geocode(ladd3) print("Latitude and Longitude of the said address:") print((location.latitude, location.longitude))
92
# Write a Python program to find Indices of Overlapping Substrings # Import required module import re       # Function to depict use of finditer() method def CntSubstr(pattern, string):        # Array storing the indices     a = [m.start() for m in re.finditer(pattern, string)]     return a       # Driver Code string = 'geeksforgeeksforgeeks' pattern = 'geeksforgeeks'    # Printing index values of non-overlapping pattern print(CntSubstr(pattern, string))
61
# Write a NumPy program to convert (in sequence depth wise (along third axis)) two 1-D arrays into a 2-D array. import numpy as np a = np.array([[10],[20],[30]]) b = np.array([[40],[50],[60]]) c = np.dstack((a, b)) print(c)
36
# 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]))
122
# Write a Python program to run an operating system command using the os module. import os if os.name == "nt": command = "dir" else: command = "ls -l" os.system(command)
30
# Python Program to Implement Shell Sort def gaps(size): # uses the gap sequence 2^k - 1: 1, 3, 7, 15, 31, ... length = size.bit_length() for k in range(length - 1, 0, -1): yield 2**k - 1     def shell_sort(alist): def insertion_sort_with_gap(gap): for i in range(gap, len(alist)): temp = alist[i] j = i - gap while (j >= 0 and temp < alist[j]): alist[j + gap] = alist[j] j = j - gap alist[j + gap] = temp   for g in gaps(len(alist)): insertion_sort_with_gap(g)     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] shell_sort(alist) print('Sorted list: ', end='') print(alist)
104
# Write a Python program to add more number of elements to a deque object from an iterable object. import collections even_nums = (2, 4, 6, 8, 10) even_deque = collections.deque(even_nums) print("Even numbers:") print(even_deque) more_even_nums = (12, 14, 16, 18, 20) even_deque.extend(more_even_nums) print("More even numbers:") print(even_deque)
46
# Write a Python program to Sort Tuples by their Maximum element # Python3 code to demonstrate working of  # Sort Tuples by Maximum element # Using max() + sort()    # helper function def get_max(sub):     return max(sub)    # initializing list test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]    # printing original list print("The original list is : " + str(test_list))    # sort() is used to get sorted result # reverse for sorting by max - first element's tuples test_list.sort(key = get_max, reverse = True)    # printing result  print("Sorted Tuples : " + str(test_list))
101
# Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. : Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 print d printDict()
40
# Write a Python program to Ways to find length of list # Python code to demonstrate # length of list # using naive method    # Initializing list  test_list = [ 1, 4, 5, 7, 8 ]    # Printing test_list print ("The list is : " + str(test_list))    # Finding length of list  # using loop # Initializing counter counter = 0 for i in test_list:            # incrementing counter     counter = counter + 1    # Printing length of list  print ("Length of list using naive method is : " + str(counter))
91