code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to search a specific item in a given doubly linked list and return true if the item is found otherwise return false. 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 def iter(self): # Iterate the list current = self.head while current: item_val = current.data current = current.next yield item_val def print_foward(self): for node in self.iter(): print(node) def search_item(self, val): for node in self.iter(): if val == node: return True return False 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("Original list:") items.print_foward() print("\n") if items.search_item('SQL'): print("True") else: print("False") if items.search_item('C+'): print("True") else: print("False")
159
# Write a Python program to create a time object with the same hour, minute, second, microsecond and timezone info. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nTime object with the same hour, minute, second, microsecond and timezone info.:") print(arrow.utcnow().timetz())
41
# Write a NumPy program to find the number of weekdays in March 2017. import numpy as np print("Number of weekdays in March 2017:") print(np.busday_count('2017-03', '2017-04'))
26
# Write a Python program to Adding Tuple to List and vice – versa # Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # Using += operator (list + tuple) # initializing list test_list = [5, 6, 7] # printing original list print("The original list is : " + str(test_list)) # initializing tuple test_tup = (9, 10) # Adding Tuple to List and vice - versa # Using += operator (list + tuple) test_list += test_tup # printing result print("The container after addition : " + str(test_list))
94
# Scraping Indeed Job Data Using Python # import module import requests from bs4 import BeautifulSoup       # user define function # Scrape the data # and get in string def getdata(url):     r = requests.get(url)     return r.text    # Get Html code using parse def html_code(url):        # pass the url     # into getdata function     htmldata = getdata(url)     soup = BeautifulSoup(htmldata, 'html.parser')        # return html code     return(soup)    # filter job data using # find_all function def job_data(soup):          # find the Html tag     # with find()     # and convert into string     data_str = ""     for item in soup.find_all("a", class_="jobtitle turnstileLink"):         data_str = data_str + item.get_text()     result_1 = data_str.split("\n")     return(result_1)    # filter company_data using # find_all function       def company_data(soup):        # find the Html tag     # with find()     # and convert into string     data_str = ""     result = ""     for item in soup.find_all("div", class_="sjcl"):         data_str = data_str + item.get_text()     result_1 = data_str.split("\n")        res = []     for i in range(1, len(result_1)):         if len(result_1[i]) > 1:             res.append(result_1[i])     return(res)       # driver nodes/main function if __name__ == "__main__":        # Data for URL     job = "data+science+internship"     Location = "Noida%2C+Uttar+Pradesh"     url = "https://in.indeed.com/jobs?q="+job+"&l="+Location        # Pass this URL into the soup     # which will return     # html string     soup = html_code(url)        # call job and company data     # and store into it var     job_res = job_data(soup)     com_res = company_data(soup)        # Traverse the both data     temp = 0     for i in range(1, len(job_res)):         j = temp         for j in range(temp, 2+temp):             print("Company Name and Address : " + com_res[j])            temp = j         print("Job : " + job_res[i])         print("-----------------------------")
254
# Write a Python program to generate all permutations of a list in Python. import itertools print(list(itertools.permutations([1,2,3])))
17
# Write a Python program to count the elements in a list until an element is a tuple. num = [10,20,30,(10,20),40] ctr = 0 for n in num: if isinstance(n, tuple): break ctr += 1 print(ctr)
36
# Write a Pandas program to select random number of rows, fraction of random rows 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("\nSelect random number of rows:") print(w_a_con.sample(5)) print("\nSelect fraction of randome rows:") print(w_a_con.sample(frac=0.02))
50
# Write a Python program for nth Catalan Number. def catalan_number(num): if num <=1: return 1 res_num = 0 for i in range(num): res_num += catalan_number(i) * catalan_number(num-i-1) return res_num for n in range(10): print(catalan_number(n))
35
# Write a Python program to Get number of characters, words, spaces and lines in a file # Python implementation to compute # number of characters, words, spaces # and lines in a file    # Function to count number  # of characters, words, spaces  # and lines in a file def counter(fname):        # variable to store total word count     num_words = 0            # variable to store total line count     num_lines = 0            # variable to store total character count     num_charc = 0            # variable to store total space count     num_spaces = 0            # opening file using with() method     # so that file gets closed      # after completion of work     with open(fname, 'r') as f:                    # loop to iterate file         # line by line         for line in f:                            # incrementing value of              # num_lines with each              # iteration of loop to             # store total line count              num_lines += 1                            # declaring a variable word             # and assigning its value as Y             # because every file is              # supposed to start with              # a word or a character             word = 'Y'                            # loop to iterate every             # line letter by letter             for letter in line:                                    # condition to check                  # that the encountered character                 # is not white space and a word                 if (letter != ' ' and word == 'Y'):                                            # incrementing the word                     # count by 1                     num_words += 1                                            # assigning value N to                      # variable word because until                     # space will not encounter                     # a word can not be completed                     word = 'N'                                        # condition to check                  # that the encountered character                 # is a white space                 elif (letter == ' '):                                            # incrementing the space                     # count by 1                     num_spaces += 1                                            # assigning value Y to                     # variable word because after                     # white space a word                     # is supposed to occur                     word = 'Y'                                        # loop to iterate every                  # letter character by                  # character                 for i in letter:                                            # condition to check                      # that the encountered character                      # is not  white space and not                     # a newline character                     if(i !=" " and i !="\n"):                                                    # incrementing character                         # count by 1                         num_charc += 1                                # printing total word count      print("Number of words in text file: ", num_words)            # printing total line count     print("Number of lines in text file: ", num_lines)            # printing total character count     print('Number of characters in text file: ', num_charc)            # printing total space count     print('Number of spaces in text file: ', num_spaces)        # Driver Code:  if __name__ == '__main__':      fname = 'File1.txt'     try:          counter(fname)      except:          print('File not found')
427
# Write a Python program to write (without writing separate lines between rows) and read a CSV file with specified delimiter. Use csv.reader import csv fw = open("test.csv", "w", newline='') writer = csv.writer(fw, delimiter = ",") writer.writerow(["a","b","c"]) writer.writerow(["d","e","f"]) writer.writerow(["g","h","i"]) fw.close() fr = open("test.csv", "r") csv = csv.reader(fr, delimiter = ",") for row in csv: print(row) fr.close()
56
# Write a Python program to initialize and fills a list with the specified value. def initialize_list_with_values(n, val = 0): return [val for x in range(n)] print(initialize_list_with_values(7)) print(initialize_list_with_values(8,3)) print(initialize_list_with_values(5,-2)) print(initialize_list_with_values(5, 3.2))
31
# Write a NumPy program to get the indices of the sorted elements of a given array. import numpy as np student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]) print("Original array:") print(student_id) i = np.argsort(student_id) print("Indices of the sorted elements of a given array:") print(i)
46
# Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. import itertools from functools import partial X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] T = 70 def check_sum_array(N, *nums): if sum(x for x in nums) == N: return (True, nums) else: return (False, nums) pro = itertools.product(X,Y,Z) func = partial(check_sum_array, T) sums = list(itertools.starmap(func, pro)) result = set() for s in sums: if s[0] == True and s[1] not in result: result.add(s[1]) print(result)
104
# Write a Python program to Convert List to List of dictionaries # Python3 code to demonstrate working of  # Convert List to List of dictionaries # Using dictionary comprehension + loop    # initializing lists test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]    # printing original list print("The original list : " + str(test_list))    # initializing key list  key_list = ["name", "number"]    # loop to iterate through elements # using dictionary comprehension # for dictionary construction n = len(test_list) res = [] for idx in range(0, n, 2):     res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})    # printing result  print("The constructed dictionary list : " + str(res))
110
# Write a Python program to convert a given list of dictionaries into a list of values corresponding to the specified key. def pluck(lst, key): return [x.get(key) for x in lst] simpsons = [ { 'name': 'Areeba', 'age': 8 }, { 'name': 'Zachariah', 'age': 36 }, { 'name': 'Caspar', 'age': 34 }, { 'name': 'Presley', 'age': 10 } ] print(pluck(simpsons, 'age'))
61
# Write a Python program to convert unix timestamp string to readable date # Python program to illustrate the # convertion of unix timestamp string # to its readable date # Importing datetime module import datetime # Calling the fromtimestamp() function to # extract datetime from the given timestamp # Calling the strftime() function to convert # the extracted datetime into its string format print(datetime.datetime.fromtimestamp(int("1294113662"))       .strftime('%Y-%m-%d %H:%M:%S'))
67
# Python Program to Solve 0-1 Knapsack Problem using Dynamic Programming with Memoization def knapsack(value, weight, capacity): """Return the maximum value of items that doesn't exceed capacity.   value[i] is the value of item i and weight[i] is the weight of item i for 1 <= i <= n where n is the number of items.   capacity is the maximum weight. """ n = len(value) - 1   # m[i][w] will store the maximum value that can be attained with a maximum # capacity of w and using only the first i items m = [[-1]*(capacity + 1) for _ in range(n + 1)]   return knapsack_helper(value, weight, m, n, capacity)     def knapsack_helper(value, weight, m, i, w): """Return maximum value of first i items attainable with weight <= w.   m[i][w] will store the maximum value that can be attained with a maximum capacity of w and using only the first i items This function fills m as smaller subproblems needed to compute m[i][w] are solved.   value[i] is the value of item i and weight[i] is the weight of item i for 1 <= i <= n where n is the number of items. """ if m[i][w] >= 0: return m[i][w]   if i == 0: q = 0 elif weight[i] <= w: q = max(knapsack_helper(value, weight, m, i - 1 , w - weight[i]) + value[i], knapsack_helper(value, weight, m, i - 1 , w)) else: q = knapsack_helper(value, weight, m, i - 1 , w) m[i][w] = q return q     n = int(input('Enter number of items: ')) value = input('Enter the values of the {} item(s) in order: ' .format(n)).split() value = [int(v) for v in value] value.insert(0, None) # so that the value of the ith item is at value[i] weight = input('Enter the positive weights of the {} item(s) in order: ' .format(n)).split() weight = [int(w) for w in weight] weight.insert(0, None) # so that the weight of the ith item is at weight[i] capacity = int(input('Enter maximum weight: '))   ans = knapsack(value, weight, capacity) print('The maximum value of items that can be carried:', ans)
343
# How to Scrape Multiple Pages of a Website Using Python import requests from bs4 import BeautifulSoup as bs    URL = 'https://www.geeksforgeeks.org/page/1/'    req = requests.get(URL) soup = bs(req.text, 'html.parser')    titles = soup.find_all('div',attrs = {'class','head'})    print(titles[4].text)
35
# Write a NumPy program to find the missing data in a given array. import numpy as np nums = np.array([[3, 2, np.nan, 1], [10, 12, 10, 9], [5, np.nan, 1, np.nan]]) print("Original array:") print(nums) print("\nFind the missing data of the said array:") print(np.isnan(nums))
44
# Write a NumPy program to find the roots of the following polynomials. import numpy as np print("Roots of the first polynomial:") print(np.roots([1, -2, 1])) print("Roots of the second polynomial:") print(np.roots([1, -12, 10, 7, -10]))
35
# Write a Python script to merge two Python dictionaries. d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(d)
27
# Check whether a given matrix is an identity matrix or not # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) # check Diagonal elements are 1 and rest elements are 0 point=0 for i in range(len(matrix)): for j in range(len(matrix[0])): # check for diagonals element if i == j and matrix[i][j] != 1: point=1 break #check for rest elements elif i!=j and matrix[i][j]!=0: point=1 break if point==1: print("Given Matrix is not an identity matrix.") else: print("Given Matrix is an identity matrix.")
113
# Write a Python program to find tag(s) directly beneath other tag(s) 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> </body> </html> """ soup = BeautifulSoup(html_doc,"lxml") print("\nBeneath directly head tag:") print(soup.select("head > title")) print() print("\nBeneath directly p tag:") print(soup.select("p > a"))
175
# numpy string operations | lower() function in Python # Python Program explaining # numpy.char.lower() function     import numpy as geek        in_arr = geek.array(['P4Q R', '4Q RP', 'Q RP4', 'RP4Q']) print ("input array : ", in_arr)    out_arr = geek.char.lower(in_arr) print ("output lowercased array :", out_arr)
44
# Write a Python program to get the current memory address and the length in elements of the buffer used to hold an array's contents and also find the size of the memory buffer in bytes. from array import * array_num = array('i', [1, 3, 5, 7, 9]) print("Original array: "+str(array_num)) print("Current memory address and the length in elements of the buffer: "+str(array_num.buffer_info())) print("The size of the memory buffer in bytes: "+str(array_num.buffer_info()[1] * array_num.itemsize))
74
# Python Program to Implement Comb Sort def comb_sort(alist): def swap(i, j): alist[i], alist[j] = alist[j], alist[i]   gap = len(alist) shrink = 1.3   no_swap = False while not no_swap: gap = int(gap/shrink)   if gap < 1: gap = 1 no_swap = True else: no_swap = False   i = 0 while i + gap < len(alist): if alist[i] > alist[i + gap]: swap(i, i + gap) no_swap = False i = i + 1     alist = input('Enter the list of numbers: ').split() alist = [int(x) for x in alist] comb_sort(alist) print('Sorted list: ', end='') print(alist)
94
# Write a Python program to find the location address of a specified latitude and longitude using Nominatim API and Geopy package. from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") lald = "47.470706, -99.704723" print("Latitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location) lald = "34.05728435, -117.194132331602" print("\nLatitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location) lald = "38.8976998, -77.0365534886228" print("\nLatitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location) lald = "55.7558° N, 37.6173° E" print("\nLatitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location) lald = "35.6762° N, 139.6503° E" print("\nLatitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location) lald = "41.9185° N, 45.4777° E" print("\nLatitude and Longitude:",lald) location = geolocator.geocode(lald) print("Location address of the said Latitude and Longitude:") print(location)
149
# Remove duplicate words from string str=input("Enter Your String:")sub_str=str.split(" ")len1=len(sub_str)print("After removing duplicate words from a given String is:")for inn in range(len1):    out=inn+1    while out<len1:        if sub_str[out].__eq__(sub_str[inn]):            for p in range(out,len1+1):                if p >= p + 1:                    sub_str[p]=sub_str[p+1]            len1-=1        else:            out+=1for inn in range(len1):    print(sub_str[inn],end=" ")
45
# Write a Python program to filter a list of integers using Lambda. nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("Original list of integers:") print(nums) print("\nEven numbers from the said list:") even_nums = list(filter(lambda x: x%2 == 0, nums)) print(even_nums) print("\nOdd numbers from the said list:") odd_nums = list(filter(lambda x: x%2 != 0, nums)) print(odd_nums)
60
# Write a Python program to convert the values of RGB components to a hexadecimal color code. def rgb_to_hex(r, g, b): return ('{:02X}' * 3).format(r, g, b) print(rgb_to_hex(255, 165, 1)) print(rgb_to_hex(255, 255, 255)) print(rgb_to_hex(0, 0, 0)) print(rgb_to_hex(0, 0, 128)) print(rgb_to_hex(192, 192, 192))
42
# Write a Python program to count the number of rows of a given SQLite table. import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) def sql_table(conn): cursorObj = conn.cursor() # Create the table cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));") print("Number of records before inserting rows:") cursor = cursorObj.execute('select * from salesman;') print(len(cursor.fetchall())) # Insert records cursorObj.executescript(""" INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15); INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25); INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15); INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35); INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45); """) conn.commit() print("\nNumber of records after inserting rows:") cursor = cursorObj.execute('select * from salesman;') print(len(cursor.fetchall())) sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
132
# Write a Python program to Numpy matrix.max() # import the important module in python import numpy as np            # make matrix with numpy gfg = np.matrix('[64, 1; 12, 3]')            # applying matrix.max() method geeks = gfg.max()      print(geeks)
38
# Python Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String string=raw_input("Enter string:") count1=0 count2=0 for i in string: if(i.islower()): count1=count1+1 elif(i.isupper()): count2=count2+1 print("The number of lowercase characters is:") print(count1) print("The number of uppercase characters is:") print(count2)
44
# 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:]])
30
# Write a Pandas program to join the two given dataframes along rows and merge with another dataframe along the common column id. import pandas as pd student_data1 = pd.DataFrame({ 'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'], 'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'], 'marks': [200, 210, 190, 222, 199]}) student_data2 = pd.DataFrame({ 'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'], 'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'], 'marks': [201, 200, 198, 219, 201]}) exam_data = pd.DataFrame({ 'student_id': ['S1', 'S2', 'S3', 'S4', 'S5', 'S7', 'S8', 'S9', 'S10', 'S11', 'S12', 'S13'], 'exam_id': [23, 45, 12, 67, 21, 55, 33, 14, 56, 83, 88, 12]}) print("Original DataFrames:") print(student_data1) print(student_data2) print(exam_data) print("\nJoin first two said dataframes along rows:") result_data = pd.concat([student_data1, student_data2]) print(result_data) print("\nNow join the said result_data and df_exam_data along student_id:") final_merged_data = pd.merge(result_data, exam_data, on='student_id') print(final_merged_data)
140
# Multiply two numbers without using multiplication(*) operator num1=int(input("Enter the First numbers :")) num2=int(input("Enter the Second number:")) sum=0 for i in range(1,num1+1):     sum=sum+num2 print("The multiplication of ",num1," and ",num2," is ",sum)
31
# Write a Python program to get the every nth element in a given list. def every_nth(nums, nth): return nums[nth - 1::nth] print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) print(every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6))
66
# Find the size of a Tuple in Python import sys    # sample Tuples Tuple1 = ("A", 1, "B", 2, "C", 3) Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu") Tuple3 = ((1, "Lion"), ( 2, "Tiger"), (3, "Fox"), (4, "Wolf"))    # print the sizes of sample Tuples print("Size of Tuple1: " + str(sys.getsizeof(Tuple1)) + "bytes") print("Size of Tuple2: " + str(sys.getsizeof(Tuple2)) + "bytes") print("Size of Tuple3: " + str(sys.getsizeof(Tuple3)) + "bytes")
72
# Write a Python program to remove unwanted characters from a given string. def remove_chars(str1, unwanted_chars): for i in unwanted_chars: str1 = str1.replace(i, '') return str1 str1 = "Pyth*^on Exercis^es" str2 = "A%^!B#*CD" unwanted_chars = ["#", "*", "!", "^", "%"] print ("Original String : " + str1) print("After removing unwanted characters:") print(remove_chars(str1, unwanted_chars)) print ("\nOriginal String : " + str2) print("After removing unwanted characters:") print(remove_chars(str2, unwanted_chars))
66
# Program to print the Solid Diamond Alphabet Pattern row_size=int(input("Enter the row size:"))x=0for out in range(row_size,-(row_size+1),-1):    for inn in range(1,abs(out)+1):        print(" ",end="")    for p in range(row_size,abs(out)-1,-1):        print((chr)(x+65),end=" ")    if out > 0:        x +=1    else:        x -=1    print("\r")
38
# Write a NumPy program to add a border (filled with 0's) around an existing array. import numpy as np x = np.ones((3,3)) print("Original array:") print(x) print("0 on the border and 1 inside in the array") x = np.pad(x, pad_width=1, mode='constant', constant_values=0) print(x)
43
# Write a Python code to send some sort of data in the URL's query string. import requests payload = {'key1': 'value1', 'key2': 'value2'} print("Parameters: ",payload) r = requests.get('https://httpbin.org/get', params=payload) print("Print the url to check the URL has been correctly encoded or not!") print(r.url) print("\nPass a list of items as a value:") payload = {'key1': 'value1', 'key2': ['value2', 'value3']} print("Parameters: ",payload) r = requests.get('https://httpbin.org/get', params=payload) print("Print the url to check the URL has been correctly encoded or not!") print(r.url)
79
# Convert nested JSON to CSV in Python import json       def read_json(filename: str) -> dict:        try:         with open(filename, "r") as f:             data = json.loads(f.read())     except:         raise Exception(f"Reading {filename} file encountered an error")        return data       def normalize_json(data: dict) -> dict:        new_data = dict()     for key, value in data.items():         if not isinstance(value, dict):             new_data[key] = value         else:             for k, v in value.items():                 new_data[key + "_" + k] = v        return new_data       def generate_csv_data(data: dict) -> str:        # Defining CSV columns in a list to maintain     # the order     csv_columns = data.keys()        # Generate the first row of CSV      csv_data = ",".join(csv_columns) + "\n"        # Generate the single record present     new_row = list()     for col in csv_columns:         new_row.append(str(data[col]))        # Concatenate the record with the column information      # in CSV format     csv_data += ",".join(new_row) + "\n"        return csv_data       def write_to_file(data: str, filepath: str) -> bool:        try:         with open(filepath, "w+") as f:             f.write(data)     except:         raise Exception(f"Saving data to {filepath} encountered an error")       def main():     # Read the JSON file as python dictionary     data = read_json(filename="article.json")        # Normalize the nested python dict     new_data = normalize_json(data=data)        # Pretty print the new dict object     print("New dict:", new_data)        # Generate the desired CSV data      csv_data = generate_csv_data(data=new_data)        # Save the generated CSV data to a CSV file     write_to_file(data=csv_data, filepath="data.csv")       if __name__ == '__main__':     main()
215
# Write a Python program to get the total length of all values of a given dictionary with string values. def test(dictt): result = sum((len(values) for values in dictt.values())) return result color = {'#FF0000':'Red', '#800000':'Maroon', '#FFFF00':'Yellow', '#808000':'Olive'} print("\nOriginal dictionary:") print(color) print("\nTotal length of all values of the said dictionary with string values:") print(test(color))
53
# Write a Python program to create a file where all letters of English alphabet are listed by specified number of letters on each line. import string def letters_file_line(n): with open("words1.txt", "w") as f: alphabet = string.ascii_uppercase letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet), n)] f.writelines(letters) letters_file_line(3)
52
# Write a Python program to find the sum of all items in a dictionary # Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(myDict):           list = []     for i in myDict:         list.append(myDict[i])     final = sum(list)           return final # Driver Function dict = {'a': 100, 'b':200, 'c':300} print("Sum :", returnSum(dict))
60
# Write a Python program to calculate the harmonic sum of n-1. def harmonic_sum(n): if n < 2: return 1 else: return 1 / n + (harmonic_sum(n - 1)) print(harmonic_sum(7)) print(harmonic_sum(4))
31
# Write a NumPy program to test equal, not equal, greater equal, greater and less test of all the elements of two given arrays. import numpy as np x1 = np.array(['Hello', 'PHP', 'JS', 'examples', 'html'], dtype=np.str) x2 = np.array(['Hello', 'php', 'Java', 'examples', 'html'], dtype=np.str) print("\nArray1:") print(x1) print("Array2:") print(x2) print("\nEqual test:") r = np.char.equal(x1, x2) print(r) print("\nNot equal test:") r = np.char.not_equal(x1, x2) print(r) print("\nLess equal test:") r = np.char.less_equal(x1, x2) print(r) print("\nGreater equal test:") r = np.char.greater_equal(x1, x2) print(r) print("\nLess test:") r = np.char.less(x1, x2) print(r)
86
# Write a Python program to count number of substrings with same first and last characters of a given string. def no_of_substring_with_equalEnds(str1): result = 0; n = len(str1); for i in range(n): for j in range(i, n): if (str1[i] == str1[j]): result = result + 1 return result str1 = input("Input a string: ") print(no_of_substring_with_equalEnds(str1))
55
# Find a pair with given sum in the array 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)sum=int(input("Enter the Sum Value:"))flag=0for i in range(0,size-1):    for j in range(i+1, size):        if arr[i]+arr[j]==sum:            flag=1            print("Given sum pairs of elements are ", arr[i]," and ", arr[j],".\n")if flag==0:  print("Given sum Pair is not Present.")
63
# Write a Pandas program to create a Pivot table and find the region wise, item wise unit sold. import numpy as np import pandas as pd df = pd.read_excel('E:\SaleData.xlsx') print(pd.pivot_table(df,index=["Region", "Item"], values="Units", aggfunc=np.sum))
34
# Convert string to datetime in Python with timezone # Python3 code to demonstrate # Getting datetime object using a date_string    # importing datetime module import datetime    # datestring for which datetime_obj required date_string = '2021-09-01 15:27:05.004573 +0530' print("string datetime: ") print(date_string) print("datestring class is :", type(date_string))    # using strptime() to get datetime object datetime_obj = datetime.datetime.strptime(     date_string, '%Y-%m-%d %H:%M:%S.%f %z')    print("converted to datetime:")    # Printing datetime print(datetime_obj)    # Checking class of datetime_obj. print("datetime_obj class is :", type(datetime_obj))
78
# Write a Pandas program to create a scatter plot of the trading volume/stock prices of Alphabet Inc. stock between two specific dates. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-9-30') df['Date'] = pd.to_datetime(df['Date']) new_df = (df['Date']>= start_date) & (df['Date']<= end_date) df1 = df.loc[new_df] df2 = df1.set_index('Date') x= ['Close']; y = ['Volume'] plt.figure(figsize=[15,10]) df2.plot.scatter(x, y, s=50); plt.grid(True) plt.title('Trading Volume/Price of Alphabet Inc. stock,\n01-04-2020 to 30-09-2020', fontsize=14, color='black') plt.xlabel("Stock Price",fontsize=12, color='black') plt.ylabel("Trading Volume", fontsize=12, color='black') plt.show()
84
# Write a Python program to sort a list of lists by a given index of the inner list using lambda. def index_on_inner_list(list_data, index_no): result = sorted(list_data, key=lambda x: x[index_no]) return result students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] print ("Original list:") print(students) index_no = 0 print("\nSort the said list of lists by a given index","( Index = ",index_no,") of the inner list") print(index_on_inner_list(students, index_no)) index_no = 2 print("\nSort the said list of lists by a given index","( Index = ",index_no,") of the inner list") print(index_on_inner_list(students, index_no))
98
# Write a Python program to chose specified number of colours from three different colours and generate the unique combinations. from itertools import combinations def unique_combinations_colors(list_data, n): return [" and ".join(items) for items in combinations(list_data, r=n)] colors = ["Red","Green","Blue"] print("Original List: ",colors) n=1 print("\nn = 1") print(list(unique_combinations_colors(colors, n))) n=2 print("\nn = 2") print(list(unique_combinations_colors(colors, n))) n=3 print("\nn = 3") print(list(unique_combinations_colors(colors, n)))
60
# Write a Python program to find smallest number in a list # Python program to find smallest # number in a list # list of numbers list1 = [10, 20, 4, 45, 99] # sorting the list list1.sort() # printing the first element print("Smallest element is:", *list1[:1])
48
# Write a NumPy program to calculate round, floor, ceiling, truncated and round (to the given number of decimals) of the input, element-wise of a given array. import numpy as np x = np.array([3.1, 3.5, 4.5, 2.9, -3.1, -3.5, -5.9]) print("Original array: ") print(x) r1 = np.around(x) r2 = np.floor(x) r3 = np.ceil(x) r4 = np.trunc(x) r5 = [round(elem) for elem in x] print("\naround: ", r1) print("floor: ",r2) print("ceil: ",r3) print("trunc: ",r4) print("round: ",r5)
74
# Write a Python program to count the occurrence of each element of a given list. from collections import Counter colors = ['Green', 'Red', 'Blue', 'Red', 'Orange', 'Black', 'Black', 'White', 'Orange'] print("Original List:") print(colors) print("Count the occurrence of each element of the said list:") result = Counter(colors) print(result) nums = [3,5,0,3,9,5,8,0,3,8,5,8,3,5,8,1,0,2] print("\nOriginal List:") print(nums) print("Count the occurrence of each element of the said list:") result = Counter(nums) print(result)
68
# Write a Python program to sort one list based on another list containing the desired indexes. def sort_by_indexes(lst, indexes, reverse=False): return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \ x[0], reverse=reverse)] l1 = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk'] l2 = [3, 2, 6, 4, 1, 5] print(sort_by_indexes(l1, l2)) print(sort_by_indexes(l1, l2, True))
55
# Write a NumPy program to test element-wise of a given array for finiteness (not infinity or not Not a Number), positive or negative infinity, for NaN, for NaT (not a time), for negative infinity, for positive infinity. import numpy as np print("\nTest element-wise for finiteness (not infinity or not Not a Number):") print(np.isfinite(1)) print(np.isfinite(0)) print(np.isfinite(np.nan)) print("\nTest element-wise for positive or negative infinity:") print(np.isinf(np.inf)) print(np.isinf(np.nan)) print(np.isinf(np.NINF)) print("Test element-wise for NaN:") print(np.isnan([np.log(-1.),1.,np.log(0)])) print("Test element-wise for NaT (not a time):") print(np.isnat(np.array(["NaT", "2016-01-01"], dtype="datetime64[ns]"))) print("Test element-wise for negative infinity:") x = np.array([-np.inf, 0., np.inf]) y = np.array([2, 2, 2]) print(np.isneginf(x, y)) print("Test element-wise for positive infinity:") x = np.array([-np.inf, 0., np.inf]) y = np.array([2, 2, 2]) print(np.isposinf(x, y))
115
# Write a Python program to insert values to a table from user input. import sqlite3 conn = sqlite3 . connect ( 'mydatabase.db' ) cursor = conn.cursor () #create the salesman table cursor.execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city char(35), commission decimal(7,2));") s_id = input('Salesman ID:') s_name = input('Name:') s_city = input('City:') s_commision = input('Commission:') cursor.execute(""" INSERT INTO salesman(salesman_id, name, city, commission) VALUES (?,?,?,?) """, (s_id, s_name, s_city, s_commision)) conn.commit () print ( 'Data entered successfully.' ) conn . close () if (conn): conn.close() print("\nThe SQLite connection is closed.")
89
# Find the sum of all elements in a 2D Array # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) # Calculate sum of given matrix Elements sum=0 for i in range(0,row_size): for j in range(0,col_size): sum+=matrix[i][j] # Display The Sum Of Given Matrix Elements print("Sum of the Given Matrix Elements is: ",sum)
83
# Write a NumPy program to calculate averages without NaNs along a given array. import numpy as np arr1 = np.array([[10, 20 ,30], [40, 50, np.nan], [np.nan, 6, np.nan], [np.nan, np.nan, np.nan]]) print("Original array:") print(arr1) temp = np.ma.masked_array(arr1,np.isnan(arr1)) result = np.mean(temp, axis=1) print("Averages without NaNs along the said array:") print(result.filled(np.nan))
50
# Write a Python program to write a string to a buffer and retrieve the value written, at the end discard buffer memory. import io # Write a string to a buffer output = io.StringIO() output.write('Python Exercises, Practice, Solution') # Retrieve the value written print(output.getvalue()) # Discard buffer memory output.close()
50
# 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())
40
# Python Program to Compute the Value of Euler's Number e. Use the Formula: e = 1 + 1/1! + 1/2! + …… 1/n! import math n=int(input("Enter the number of terms: ")) sum1=1 for i in range(1,n+1): sum1=sum1+(1/math.factorial(i)) print("The sum of series is",round(sum1,2))
43
# Calculate average values of two given NumPy arrays in Python # import library import numpy as np    #  create a numpy 1d-arrays arr1 = np.array([3, 4]) arr2 = np.array([1, 0])    # find average of NumPy arrays avg = (arr1 + arr2) / 2    print("Average of NumPy arrays:\n",       avg)
49
# Write a Pandas program to extract the sentences where a specific word is present in 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 pick_only_key_sentence(str1, word): result = re.findall(r'([^.]*'+word+'[^.]*)', str1) return result df['filter_sentence']=df['address'].apply(lambda x : pick_only_key_sentence(x,'Avenue')) print("\nText with the word 'Avenue':") print(df)
81
# Write a Python program to move the specified number of elements to the end of the given list. def move_end(nums, offset): return nums[offset:] + nums[:offset] print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 3)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -3)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 8)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -8)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], 7)) print(move_end([1, 2, 3, 4, 5, 6, 7, 8], -7))
80
# Write a Python program to check if a substring presents in a given list of string values. def find_substring(str1, sub_str): if any(sub_str in s for s in str1): return True return False colors = ["red", "black", "white", "green", "orange"] print("Original list:") print(colors) sub_str = "ack" print("Substring to search:") print(sub_str) print("Check if a substring presents in the said list of string values:") print(find_substring(colors, sub_str)) sub_str = "abc" print("Substring to search:") print(sub_str) print("Check if a substring presents in the said list of string values:") print(find_substring(colors, sub_str))
85
# Minimum of two numbers in Python # Python program to find the # minimum of two numbers       def minimum(a, b):            if a <= b:         return a     else:         return b        # Driver code a = 2 b = 4 print(minimum(a, b))
41
# Write a Python program to Avoid Last occurrence of delimitter # Python3 code to demonstrate working of # Avoid Last occurrence of delimitter # Using map() + join() + str()    # initializing list test_list = [4, 7, 8, 3, 2, 1, 9]    # printing original list print("The original list is : " + str(test_list))    # initializing delim delim = "$"    # appending delim to join # will leave stray "$" at end res = '' for ele in test_list:     res += str(ele) + "$"    # removing last using slicing res = res[:len(res) - 1]    # printing result print("The joined string : " + str(res))
105
# Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array. import numpy as np fvalues = [0, 12, 45.21, 34, 99.91] F = np.array(fvalues) print("Values in Fahrenheit degrees:") print(F) print("Values in Centigrade degrees:") print(5*F/9 - 5*32/9)
49
# Write a Python program to get the n maximum elements from a given list of numbers. def max_n_nums(nums, n = 1): return sorted(nums, reverse = True)[:n] nums = [1, 2, 3] print("Original list elements:") print(nums) print("Maximum values of the said list:", max_n_nums(nums)) nums = [1, 2, 3] print("\nOriginal list elements:") print(nums) print("Two maximum values of the said list:", max_n_nums(nums,2)) nums = [-2, -3, -1, -2, -4, 0, -5] print("\nOriginal list elements:") print(nums) print("Threee maximum values of the said list:", max_n_nums(nums,3)) nums = [2.2, 2, 3.2, 4.5, 4.6, 5.2, 2.9] print("\nOriginal list elements:") print(nums) print("Two maximum values of the said list:", max_n_nums(nums, 2))
103
# Write a Python program to Sort String list by K character frequency # Python3 code to demonstrate working of # Sort String list by K character frequency # Using sorted() + count() + lambda # initializing list test_list = ["geekforgeeks", "is", "best", "for", "geeks"] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 'e' # "-" sign used to reverse sort res = sorted(test_list, key = lambda ele: -ele.count(K)) # printing results print("Sorted String : " + str(res))
87
# Write a Python program to find files and skip directories of a given directory. import os print([f for f in os.listdir('/home/students') if os.path.isfile(os.path.join('/home/students', f))])
25
# Write a Python program to create a backup of a SQLite database. import sqlite3 import io conn = sqlite3.connect('mydatabase.db') with io.open('clientes_dump.sql', 'w') as f: for linha in conn.iterdump(): f.write('%s\n' % linha) print('Backup performed successfully.') print('Saved as mydatabase_dump.sql') conn.close()
39
# Program to check whether a matrix is diagonal or not # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) # check except Diagonal elements are 0 or not point=0 for i in range(len(matrix)): for j in range(len(matrix[0])): # check for diagonals element if i!=j and matrix[i][j]!=0: point=1 break if point==1: print("Given Matrix is not a diagonal Matrix.") else: print("Given Matrix is a diagonal Matrix.")
96
# Write a Python program to find the difference between elements (n+1th - nth) of a given list of numeric values. def elements_difference(nums): result = [j-i for i, j in zip(nums[:-1], nums[1:])] return result nums1 = [1,2,3,4,5,6,7,8,9,10] nums2 = [2,4,6,8] print("Original list:") print(nums1) print("\nDfference between elements (n+1th – nth) of the said list :") print(elements_difference(nums1)) print("\nOriginal list:") print(nums2) print("\nDfference between elements (n+1th – nth) of the said list :") print(elements_difference(nums2))
70
# Python Program to Build Binary Tree if Inorder or Postorder Traversal as Input 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 inorder(self): if self.left is not None: self.left.inorder() print(self.key, end=' ') if self.right is not None: self.right.inorder()   def postorder(self): if self.left is not None: self.left.postorder() if self.right is not None: self.right.postorder() print(self.key, end=' ')     def construct_btree(postord, inord): if postord == [] or inord == []: return None key = postord[-1] node = BinaryTree(key) index = inord.index(key) node.left = construct_btree(postord[:index], inord[:index]) node.right = construct_btree(postord[index:-1], inord[index + 1:]) return node     postord = input('Input post-order traversal: ').split() postord = [int(x) for x in postord] inord = input('Input in-order traversal: ').split() inord = [int(x) for x in inord]   btree = construct_btree(postord, inord) print('Binary tree constructed.') print('Verifying:') print('Post-order traversal: ', end='') btree.postorder() print() print('In-order traversal: ', end='') btree.inorder() print()
148
# Finding the k smallest values of a NumPy array in Python # importing the modules import numpy as np    # creating the array  arr = np.array([23, 12, 1, 3, 4, 5, 6]) print("The Original Array Content") print(arr)    # value of k k = 4    # sorting the array arr1 = np.sort(arr)    # k smallest number of array print(k, "smallest elements of the array") print(arr1[:k])
65
# Write a Python program to print positive numbers in a list # Python program to print positive Numbers in a List    # list of numbers list1 = [11, -21, 0, 45, 66, -93]    # iterating each number in list for num in list1:            # checking condition     if num >= 0:        print(num, end = " ")
56
# Write a Python program to check whether an instance is complex or not. import json def encode_complex(object): # check using isinstance method if isinstance(object, complex): return [object.real, object.imag] # raised error if object is not complex raise TypeError(repr(object) + " is not JSON serialized") complex_obj = json.dumps(2 + 3j, default=encode_complex) print(complex_obj)
52
# Write a Python program to add two given lists of different lengths, start from right. def elementswise_right_join(l1, l2): f_len = len(l1)-(len(l2) - 1) for i in range(len(l1), 0, -1): if i-f_len < 0: break else: l1[i-1] = l1[i-1] + l2[i-f_len] return l1 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 left:") 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 left:") print(elementswise_right_join(nums3, nums4))
94
# Write a Pandas program to create a comparison of the top 10 years in which the UFO was sighted vs the hours of the day. import pandas as pd #Source: https://bit.ly/1l9yjm9 df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') most_sightings_years = df['Date_time'].dt.year.value_counts().head(10) def is_top_years(year): if year in most_sightings_years.index: return year hour_v_year = df.pivot_table(columns=df['Date_time'].dt.hour,index=df['Date_time'].dt.year.apply(is_top_years),aggfunc='count',values='city') hour_v_year.columns = hour_v_year.columns.astype(int) hour_v_year.columns = hour_v_year.columns.astype(str) + ":00" hour_v_year.index = hour_v_year.index.astype(int) print("\nComparison of the top 10 years in which the UFO was sighted vs the hours of the day:") print(hour_v_year.head(10))
82
# Write a NumPy program to create a 4x4 array, now create a new array from the said array swapping first and last, second and third columns. import numpy as np nums = np.arange(16, dtype='int').reshape(-1, 4) print("Original array:") print(nums) print("\nNew array after swapping first and last columns of the said array:") new_nums = nums[:, ::-1] print(new_nums)
56
# Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print ("Original String : ", s) print ("No. of Upper case characters : ", d["UPPER_CASE"]) print ("No. of Lower case Characters : ", d["LOWER_CASE"]) string_test('The quick Brown Fox')
65
# Write a Python program to Check if a given string is binary string or not # Python program to check # if a string is binary or not # function for checking the # string is accepted or not def check(string) :     # set function convert string     # into set of characters .     p = set(string)     # declare set of '0', '1' .     s = {'0', '1'}     # check set p is same as set s     # or set p contains only '0'     # or set p contains only '1'     # or not, if any one condition     # is true then string is accepted     # otherwise not .     if s == p or p == {'0'} or p == {'1'}:         print("Yes")     else :         print("No")           # driver code if __name__ == "__main__" :     string = "101010000111"     # function calling     check(string)
140
# numpy.diff() in Python # Python program explaining # numpy.diff() method     # importing numpy import numpy as geek # input array arr = geek.array([1, 3, 4, 7, 9])    print("Input array  : ", arr) print("First order difference  : ", geek.diff(arr)) print("Second order difference : ", geek.diff(arr, n = 2)) print("Third order difference  : ", geek.diff(arr, n = 3))
57
# Write a Python program to get 90 days of visits broken down by browser for all sites on data.gov. from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://en.wikipedia.org/wiki/Python") bsObj = BeautifulSoup(html) for link in bsObj.findAll("a"): if 'href' in link.attrs: print(link.attrs['href'])
43
# Write a Python code to send a request to a web page, and print the information of headers. Also parse these values and print key-value pairs holding various information. import requests r = requests.get('https://api.github.com/') response = r.headers print("Headers information of the said response:") print(response) print("\nVarious Key-value pairs information of the said resource and request:") print("Date: ",r.headers['date']) print("server: ",r.headers['server']) print("status: ",r.headers['status']) print("cache-control: ",r.headers['cache-control']) print("vary: ",r.headers['vary']) print("x-github-media-type: ",r.headers['x-github-media-type']) print("access-control-expose-headers: ",r.headers['access-control-expose-headers']) print("strict-transport-security: ",r.headers['strict-transport-security']) print("x-content-type-options: ",r.headers['x-content-type-options']) print("x-xss-protection: ",r.headers['x-xss-protection']) print("referrer-policy: ",r.headers['referrer-policy']) print("content-security-policy: ",r.headers['content-security-policy']) print("content-encoding: ",r.headers['content-encoding']) print("X-Ratelimit-Remaining: ",r.headers['X-Ratelimit-Remaining']) print("X-Ratelimit-Reset: ",r.headers['X-Ratelimit-Reset']) print("X-Ratelimit-Used: ",r.headers['X-Ratelimit-Used']) print("Accept-Ranges:",r.headers['Accept-Ranges']) print("X-GitHub-Request-Id:",r.headers['X-GitHub-Request-Id'])
89
# Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. def not_poor(str1): snot = str1.find('not') spoor = str1.find('poor') if spoor > snot and snot>0 and spoor>0: str1 = str1.replace(str1[snot:(spoor+4)], 'good') return str1 else: return str1 print(not_poor('The lyrics is not that poor!')) print(not_poor('The lyrics is poor!'))
71
# Write a Pandas program to create a conversion between strings and datetime. from datetime import datetime from dateutil.parser import parse print("Convert datatime to strings:") stamp=datetime(2019,7,1) print(stamp.strftime('%Y-%m-%d')) print(stamp.strftime('%d/%b/%y')) print("\nConvert strings to datatime:") print(parse('Sept 17th 2019')) print(parse('1/11/2019')) print(parse('1/11/2019', dayfirst=True))
38
# Write a Python program to Ways to remove multiple empty spaces from string List # Python3 code to demonstrate working of  # Remove multiple empty spaces from string List # Using loop + strip()    # initializing list test_list = ['gfg', '   ', ' ', 'is', '            ', 'best']    # printing original list print("The original list is : " + str(test_list))    # Remove multiple empty spaces from string List # Using loop + strip() res = [] for ele in test_list:     if ele.strip():         res.append(ele)        # printing result  print("List after filtering non-empty strings : " + str(res)) 
96
# Write a Python program to sort unsorted numbers using Recursive Quick Sort. def quick_sort(nums: list) -> list: if len(nums) <= 1: return nums else: return ( quick_sort([el for el in nums[1:] if el <= nums[0]]) + [nums[0]] + quick_sort([el for el in nums[1:] if el > nums[0]]) ) nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) print("After applying Recursive Quick Sort the said list becomes:") print(quick_sort(nums)) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) print("After applying Recursive Quick Sort the said list becomes:") print(quick_sort(nums)) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Recursive Quick Sort the said list becomes:") print(quick_sort(nums))
117
# Write a NumPy program to multiply the values of two given vectors. import numpy as np x = np.array([1, 8, 3, 5]) print("Vector-1") print(x) y= np.random.randint(0, 11, 4) print("Vector-2") print(y) result = x * y print("Multiply the values of two said vectors:") print(result)
44
# Remove duplicate elements in an array 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) arr.sort() j=0 #Remove duplicate element for i in range(0, size-1):     if arr[i] != arr[i + 1]:         arr[j]=arr[i]         j+=1 arr[j] = arr[size - 1] j+=1 print("After removing duplicate element array is") for i in range(0, j):     print(arr[i],end=" ")
68
# Convert JSON to dictionary in Python # Python program to demonstrate # Conversion of JSON data to # dictionary       # importing the module import json    # Opening JSON file with open('data.json') as json_file:     data = json.load(json_file)        # Print the type of data variable     print("Type:", type(data))        # Print the data of dictionary     print("\nPeople1:", data['people1'])     print("\nPeople2:", data['people2'])
56
# Write a Python program to calculate magic square. def magic_square_test(my_matrix): iSize = len(my_matrix[0]) sum_list = [] #Horizontal Part: sum_list.extend([sum (lines) for lines in my_matrix]) #Vertical Part: for col in range(iSize): sum_list.append(sum(row[col] for row in my_matrix)) #Diagonals Part result1 = 0 for i in range(0,iSize): result1 +=my_matrix[i][i] sum_list.append(result1) result2 = 0 for i in range(iSize-1,-1,-1): result2 +=my_matrix[i][i] sum_list.append(result2) if len(set(sum_list))>1: return False return True m=[[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]] print(magic_square_test(m)); m=[[2, 7, 6], [9, 5, 1], [4, 3, 8]] print(magic_square_test(m)); m=[[2, 7, 6], [9, 5, 1], [4, 3, 7]] print(magic_square_test(m));
101