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 = pre...
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)) # initializin...
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 get...
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...
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 tot...
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...
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, ...
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...
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 o...
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': 'Pre...
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 t...
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 ...
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.app...
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</h...
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...
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 ...
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.geoc...
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):         ...
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_num...
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 th...
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:")...
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',...
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...
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(Tup...
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 : ...
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: ...
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) p...
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(dat...
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:")...
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, l...
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 d...
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...
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("Inpu...
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]...
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)...
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') ...
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 T...
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"]...
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) ...
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 = Coun...
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 = ...
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):...
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('S...
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 i...
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(...
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 out...
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/2...
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...
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("...
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))    # init...
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...
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...
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...
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')...
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([...
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("\nD...
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...
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...
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 J...
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 =...
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_co...
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 a...
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:...
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 ...
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)) prin...
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: ...
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(respons...
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 > sno...
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:") prin...
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...
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[...
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...
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)) ...
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 ...
101