code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to traverse a given list in reverse order, also print the elements with original index. color = ["red", "green", "white", "black"] print("Original list:") print(color) print("\nTraverse the said list in reverse order:") for i in reversed(color): print(i) print("\nTraverse the said list in reverse order with original index:") for i, el in reversed(list(enumerate(color))): print(i, el)
58
# Program to Convert Binary to Hexadecimal print("Enter a binary number:") binary=input() if(len(binary)%4==1):     binary="000"+binary if(len(binary)%4==2):     binary="00"+binary if(len(binary)%4==3):     binary="0"+binary hex="" len=int(len(binary)/4) print("len:",len) i=0 j=0 k=4 decimal=0 while(i<len):     st=binary[j:k]     bin=int(st)     temp=0     remainder=0     decimal=0     while(bin!=0):         remainder=bin%10         bin=bin//10         decimal=decimal+remainder*pow(2,temp)         temp=temp+1     if decimal==15:         hex=hex+"F"     elif decimal==14:         hex=hex+"E"     elif decimal==13:         hex=hex+"D"     elif decimal==12:         hex = hex + "C"     elif decimal==11:         hex=hex+"B"     elif decimal==10:         hex=hex+"A"     else:         hex=hex+str(decimal)     j=k     k=k+4     i=i+1 print("Binary to HexaDecimal is ",hex)
68
# Write a Python program to insert a given string at the beginning of all items in a list. num = [1,2,3,4] print(['emp{0}'.format(i) for i in num])
27
# Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension. import numpy as np a = np.array([1,2,5]) b = np.array([2,1,0]) print("Original 1-d arrays:") print(a) print(b) print result = np.inner(a, b) print("Inner product of the said vectors:") x = np.arange(9).reshape(3, 3) y = np.arange(3, 12).reshape(3, 3) print("Higher dimension arrays:") print(x) print(y) result = np.inner(x, y) print("Inner product of the said vectors:") print(result)
73
# Write a Python program to break a given list of integers into sets of a given positive number. Return true or false. import collections as clt def check_break_list(nums, n): coll_data = clt.Counter(nums) for x in sorted(coll_data.keys()): for index in range(1, n): coll_data[x+index] = coll_data[x+index] - coll_data[x] if coll_data[x+index] < 0: return False return True nums = [1,2,3,4,5,6,7,8] n = 4 print("Original list:",nums) print("Number to devide the said list:",n) print(check_break_list(nums, n)) nums = [1,2,3,4,5,6,7,8] n = 3 print("\nOriginal list:",nums) print("Number to devide the said list:",n) print(check_break_list(nums, n))
87
# Write a NumPy program to convert the raw data in an array to a binary string and then create an array. import numpy as np x = np.array([10, 20, 30], float) print("Original array:") print(x) s = x.tostring() print("Binary string array:") print(s) print("Array using fromstring():") y = np.fromstring(s) print(y)
49
# How to add a border around a NumPy array in Python # importing Numpy package import numpy as np    # Creating a 2X2 Numpy matrix array = np.ones((2, 2))    print("Original array") print(array)    print("\n0 on the border and 1 inside the array")    # constructing border of 0 around 2D identity matrix # using np.pad() array = np.pad(array, pad_width=1, mode='constant',                constant_values=0)    print(array)
61
# Write a NumPy program to combine last element with first element of two given ndarray with different shapes. import numpy as np array1 = ['PHP','JS','C++'] array2 = ['Python','C#', 'NumPy'] print("Original arrays:") print(array1) print(array2) result = np.r_[array1[:-1], [array1[-1]+array2[0]], array2[1:]] print("\nAfter Combining:") print(result)
42
# Write a Pandas program to split the following given dataframe into groups based on school code and call a specific group with the name of the group. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) student_data = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_Of_Birth ': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], '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(student_data) print('\nSplit the said data on school_code wise:') grouped = student_data.groupby(['school_code']) print("Call school code 's001':") print(grouped.get_group('s001')) print("\nCall school code 's004':") print(grouped.get_group('s004'))
119
# Write a NumPy program to access an array by column. import numpy as np x= np.arange(9).reshape(3,3) print("Original array elements:") print(x) print("Access an array by column:") print("First column:") print(x[:,0]) print("Second column:") print(x[:,1]) print("Third column:") print(x[:,2])
35
# Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org. #https://bit.ly/2lVhlLX # via: https://analytics.usa.gov/ import requests url = 'https://analytics.usa.gov/data/live/realtime.json' j = requests.get(url).json() print("Number of people visiting a U.S. government website-") print("Active Users Right Now:") print(j['data'][0]['active_visitors'])
47
# Python Program to Sort a List According to the Length of the Elements a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=input("Enter element:") a.append(b) a.sort(key=len) print(a)
28
# Write a Python program to read a matrix from console and print the sum for each column. Accept matrix rows, columns and elements for each column separated with a space(for every row) as input from the user. rows = int(input("Input rows: ")) columns = int(input("Input columns: ")) matrix = [[0]*columns for row in range(rows)] print('Input number of elements in a row (1, 2, 3): ') for row in range(rows): lines = list(map(int, input().split())) for column in range(columns): matrix[row][column] = lines[column] sum = [0]*columns print("sum for each column:") for column in range(columns): for row in range(rows): sum[column] += matrix[row][column] print((sum[column]), ' ', end = '')
105
# Write a Python program to create a new list dividing two given lists of numbers. def dividing_two_lists(l1,l2): result = [x/y for x, y in zip(l1,l2)] return result nums1 = [7,2,3,4,9,2,3] nums2 = [9,8,2,3,3,1,2] print("Original list:") print(nums1) print(nums1) print(dividing_two_lists(nums1, nums2))
40
# Write a Python program to find a first even and odd number in a given list of numbers. def first_even_odd(nums): first_even = next((el for el in nums if el%2==0),-1) first_odd = next((el for el in nums if el%2!=0),-1) return first_even,first_odd nums= [1,3,5,7,4,1,6,8] print("Original list:") print(nums) print("\nFirst even and odd number of the said list of numbers:") print(first_even_odd(nums))
58
# Write a Python program to find the maximum and minimum values in a given list of tuples. from operator import itemgetter def max_min_list_tuples(class_students): return_max = max(class_students,key=itemgetter(1))[1] return_min = min(class_students,key=itemgetter(1))[1] return return_max, return_min class_students = [('V', 60), ('VI', 70), ('VII', 75), ('VIII', 72), ('IX', 78), ('X', 70)] print("Original list with tuples:") print(class_students) print("\nMaximum and minimum values of the said list of tuples:") print(max_min_list_tuples(class_students))
63
# Write a Python program to delete the last item from a singly linked list. class Node: # Singly linked node def __init__(self, data=None): self.data = data self.next = None class singly_linked_list: def __init__(self): # Createe an empty list self.tail = None self.head = None self.count = 0 def append_item(self, data): #Append items on the list node = Node(data) if self.head: self.head.next = node self.head = node else: self.tail = node self.head = node self.count += 1 def delete_item(self, data): # Delete an item from the list current = self.tail prev = self.tail while current: if current.data == data: if current == self.tail: self.tail = current.next else: prev.next = current.next self.count -= 1 return prev = current current = current.next def iterate_item(self): # Iterate the list. current_item = self.tail while current_item: val = current_item.data current_item = current_item.next yield val items = singly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') print("Original list:") for val in items.iterate_item(): print(val) print("\nAfter removing the last item from the list:") items.delete_item('Java') for val in items.iterate_item(): print(val)
168
# Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string. def count_chars(str): upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0 for i in range(len(str)): if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1 elif str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1 elif str[i] >= '0' and str[i] <= '9': number_ctr += 1 else: special_ctr += 1 return upper_ctr, lower_ctr, number_ctr, special_ctr str = "@W3Resource.Com" print("Original Substrings:",str) u, l, n, s = count_chars(str) print('\nUpper case characters: ',u) print('Lower case characters: ',l) print('Number case: ',n) print('Special case characters: ',s)
101
# Write a Pandas program to create a Pivot table and separate the gender according to whether they traveled alone or not to get the probability of survival. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table( 'survived' , [ 'sex' , 'alone' ] , 'class' ) print(result)
53
# Write a Python program to shuffle the elements of a given list. Use random.shuffle() import random nums = [1, 2, 3, 4, 5] print("Original list:") print(nums) random.shuffle(nums) print("Shuffle list:") print(nums) words = ['red', 'black', 'green', 'blue'] print("\nOriginal list:") print(words) random.shuffle(words) print("Shuffle list:") print(words)
44
# Write a Pandas program to compute the autocorrelations of a given numeric series. import pandas as pd import numpy as np num_series = pd.Series(np.arange(15) + np.random.normal(1, 10, 15)) print("Original series:") print(num_series) autocorrelations = [num_series.autocorr(i).round(2) for i in range(11)] print("\nAutocorrelations of the said series:") print(autocorrelations[1:])
45
# Write a NumPy program to get the powers of an array values element-wise. import numpy as np x = np.arange(7) print("Original array") print(x) print("First array elements raised to powers from second array, element-wise:") print(np.power(x, 3))
36
# Write a Python dictionary with keys having multiple inputs # Python code to demonstrate a dictionary # with multiple inputs in a key. import random as rn # creating an empty dictionary dict = {} # Insert first triplet in dictionary x, y, z = 10, 20, 30 dict[x, y, z] = x + y - z; # Insert second triplet in dictionary x, y, z = 5, 2, 4 dict[x, y, z] = x + y - z; # print the dictionary print(dict)
85
# Write a Python program to find the most common element of a given list. from collections import Counter language = ['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python','PHP', 'Python'] print("Original list:") print(language) cnt = Counter(language) print("\nMost common element of the said list:") print(cnt.most_common(1)[0][0])
44
# Program to find the normal and trace of a matrix import math # 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 the diagonals element # and Calculate sum of all the element trace=0 sum=0 for i in range(0, row_size): for j in range(0, col_size): if i==j: trace += matrix[i][j] sum+=matrix[i][j] normal=math.sqrt(sum) # Display the normal and trace of the matrix print("Normal Of the Matrix is: ",normal) print("Trace Of the Matrix is: ",trace)
107
# Python Program to Create a Class and Compute the Area and the Perimeter of the Circle import math class circle(): def __init__(self,radius): self.radius=radius def area(self): return math.pi*(self.radius**2) def perimeter(self): return 2*math.pi*self.radius   r=int(input("Enter radius of circle: ")) obj=circle(r) print("Area of circle:",round(obj.area(),2)) print("Perimeter of circle:",round(obj.perimeter(),2))
44
# Write a Python program to find maximum length of consecutive 0's in a given binary string. def max_consecutive_0(input_str): return max(map(len,input_str.split('1'))) str1 = '111000010000110' print("Original string:" + str1) print("Maximum length of consecutive 0’s:") print(max_consecutive_0(str1)) str1 = '111000111' print("Original string:" + str1) print("Maximum length of consecutive 0’s:") print(max_consecutive_0(str1))
47
# Write a Pandas program to create a Pivot table and find the maximum sale value of the items. import pandas as pd import numpy as np df = pd.read_excel('E:\SaleData.xlsx') table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=np.max) print(table)
37
# Write a Pandas program to compute the Euclidean distance between two given series. import pandas as pd import numpy as np x = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = pd.Series([11, 8, 7, 5, 6, 5, 3, 4, 7, 1]) print("Original series:") print(x) print(y) print("\nEuclidean distance between two said series:") print(np.linalg.norm(x-y))
57
# Write a NumPy program to remove the trailing whitespaces of all the elements of a given array. import numpy as np x = np.array([' python exercises ', ' PHP ', ' java ', ' C++'], dtype=np.str) print("Original Array:") print(x) rstripped_char = np.char.rstrip(x) print("\nRemove the trailing whitespaces : ", rstripped_char)
50
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and draw a bar plot comparing year, MSHA ID, Production and Labor_hours of first ten records. import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_excel('E:\coalpublic2013.xlsx') df.head(10).plot(kind='bar', figsize=(20,8)) plt.show()
48
# Write a Python program to find the k class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def kth_smallest(root, k): stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if k == 0: break root = root.right return root.val root = TreeNode(8) root.left = TreeNode(5) root.right = TreeNode(14) root.left.left = TreeNode(4) root.left.right = TreeNode(6) root.left.right.left = TreeNode(8) root.left.right.right = TreeNode(7) root.right.right = TreeNode(24) root.right.right.left = TreeNode(22) print(kth_smallest(root, 2)) print(kth_smallest(root, 3))
86
# Write a Pandas program to add some data to an existing Series. import pandas as pd s = pd.Series(['100', '200', 'python', '300.12', '400']) print("Original Data Series:") print(s) print("\nData Series after adding some data:") new_s = s.append(pd.Series(['500', 'php'])) print(new_s)
39
# Write a Python program to round the numbers of a given list, print the minimum and maximum numbers and multiply the numbers by 5. Print the unique numbers in ascending order separated by space. nums = [22.4, 4.0, 16.22, 9.10, 11.00, 12.22, 14.20, 5.20, 17.50] print("Original list:", nums) numbers=list(map(round,nums)) print("Minimum value: ",min(numbers)) print("Maximum value: ",max(numbers)) numbers=list(set(numbers)) numbers=(sorted(map(lambda n:n*5,numbers))) print("Result:") for numb in numbers: print(numb,end=' ')
66
# Write a Python program to remove a key from a dictionary. myDict = {'a':1,'b':2,'c':3,'d':4} print(myDict) if 'a' in myDict: del myDict['a'] print(myDict)
23
# Automate Youtube with Python from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import speech_recognition as sr import pyttsx3 import time       def automateYoutube(searchtext):          # giving the path of chromedriver to selenium websriver     path = "C:\\Users\\hp\\Downloads\\chromedriver"        url = "https://www.youtube.com/"            # opening the youtube in chromedriver     driver = webdriver.Chrome(path)     driver.get(url)        # find the search bar using selenium find_element function     driver.find_element_by_name("search_query").send_keys(searchtext)        # clicking on the search button     driver.find_element_by_css_selector(         "#search-icon-legacy.ytd-searchbox").click()        # For findding the right match search     WebDriverWait(driver, 0).until(expected_conditions.title_contains(MyText))        # clicking on the match search having same as in searched query     WebDriverWait(driver, 30).until(         expected_conditions.element_to_be_clickable((By.ID, "img"))).click()        # while(True):     #     pass       speak = sr.Recognizer() try:     with sr.Microphone() as speaky:                  # adjust the energy threshold based on         # the surrounding noise level         speak.adjust_for_ambient_noise(speaky, duration=0.2)         print("listening...")                    # listens for the user's input         searchquery = speak.listen(speaky)                    # Using ggogle to recognize audio         MyText = speak.recognize_google(searchquery)         MyText = MyText.lower()    except sr.RequestError as e:     print("Could not request results; {0}".format(e))    except sr.UnknownValueError:     print("unknown error occured")    # Calling thr function automateYoutube(MyText)
170
# Write a Python program to iterate over two lists simultaneously. num = [1, 2, 3] color = ['red', 'white', 'black'] for (a,b) in zip(num, color): print(a, b)
28
# Write a Python program to Queue using Doubly Linked List # A complete working Python program to demonstrate all  # Queue operations using doubly linked list      # Node class  class Node:     # Function to initialise the node object     def __init__(self, data):         self.data = data # Assign data         self.next = None # Initialize next as null         self.prev = None # Initialize prev as null                         # Queue class contains a Node object class Queue:         # Function to initialize head      def __init__(self):         self.head = None         self.last=None                 # Function to add an element data in the Queue     def enqueue(self, data):         if self.last is None:             self.head =Node(data)             self.last =self.head         else:             self.last.next = Node(data)             self.last.next.prev=self.last             self.last = self.last.next                                                 # Function to remove first element and return the element from the queue      def dequeue(self):             if self.head is None:             return None         else:             temp= self.head.data             self.head = self.head.next             self.head.prev=None             return temp         # Function to return top element in the queue      def first(self):             return self.head.data         # Function to return the size of the queue     def size(self):             temp=self.head         count=0         while temp is not None:             count=count+1             temp=temp.next         return count                 # Function to check if the queue is empty or not           def isEmpty(self):             if self.head is None:             return True         else:             return False                     # Function to print the stack      def printqueue(self):                     print("queue elements are:")         temp=self.head         while temp is not None:             print(temp.data,end="->")             temp=temp.next                     # Code execution starts here           if __name__=='__main__':      # Start with the empty queue   queue = Queue()       print("Queue operations using doubly linked list")     # Insert 4 at the end. So queue becomes 4->None     queue.enqueue(4)     # Insert 5 at the end. So queue becomes 4->5None     queue.enqueue(5)     # Insert 6 at the end. So queue becomes 4->5->6->None     queue.enqueue(6)     # Insert 7 at the end. So queue becomes 4->5->6->7->None     queue.enqueue(7)     # Print the queue    queue.printqueue()     # Print the first element    print("\nfirst element is ",queue.first())     # Print the queue size    print("Size of the queue is ",queue.size())     # remove the first element    queue.dequeue()     # remove the first element    queue.dequeue()     # first two elements are removed # Print the queue    print("After applying dequeue() two times")   queue.printqueue()     # Print True if queue is empty else False    print("\nqueue is empty:",queue.isEmpty())
350
# Write a NumPy program to create a new array which is the average of every consecutive triplet of elements of a given array. import numpy as np arr1 = np.array([1,2,3, 2,4,6, 1,2,12, 0,-12,6]) print("Original array:") print(arr1) result = np.mean(arr1.reshape(-1, 3), axis=1) print("Average of every consecutive triplet of elements of the said array:") print(result)
54
# Creating a Pandas Series from Lists in Python # import pandas as pd import pandas as pd    # create Pandas Series with default index values # default index ranges is from 0 to len(list) - 1 x = pd.Series(['Geeks', 'for', 'Geeks'])    # print the Series print(x)
47
# numpy.poly1d() in Python # Python code explaining # numpy.poly1d()    # importing libraries import numpy as np    # Constructing polynomial p1 = np.poly1d([1, 2]) p2 = np.poly1d([4, 9, 5, 4])    print ("P1 : ", p1) print ("\n p2 : \n", p2)    # Solve for x = 2 print ("\n\np1 at x = 2 : ", p1(2)) print ("p2 at x = 2 : ", p2(2))    # Finding Roots print ("\n\nRoots of P1 : ", p1.r) print ("Roots of P2 : ", p2.r)    # Finding Coefficients print ("\n\nCoefficients of P1 : ", p1.c) print ("Coefficients of P2 : ", p2.coeffs)    # Finding Order print ("\n\nOrder / Degree of P1 : ", p1.o) print ("Order / Degree of P2 : ", p2.order)
120
# Write a Python program to get the maximum and minimum value in a dictionary. my_dict = {'x':500, 'y':5874, 'z': 560} key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Maximum Value: ',my_dict[key_max]) print('Minimum Value: ',my_dict[key_min])
39
# Python Program to Sum All the Items in a Dictionary d={'A':100,'B':540,'C':239} print("Total sum of values in the dictionary:") print(sum(d.values()))
20
# Write a NumPy program to find elements within range from a given array of numbers. import numpy as np a = np.array([1, 3, 7, 9, 10, 13, 14, 17, 29]) print("Original array:") print(a) result = np.where(np.logical_and(a>=7, a<=20)) print("\nElements within range: index position") print(result)
44
# Write a Pandas program to create a plot of distribution of UFO (unidentified flying object) observation time. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r'ufo.csv') df['duration_sec'] = (df['length_of_encounter_seconds'].astype(float))/60 s = df["duration_sec"].quantile(0.95) temp = df['duration_sec'] temp = temp.sort_values() temp = temp[temp < s] plt.figure(figsize=(10, 8)) sns.distplot(temp) plt.xlabel('Duration(min)', fontsize=20) plt.ylabel("Frequency", fontsize=15) plt.xticks(fontsize=12) plt.title("-Distribution of UFO obervation time-", fontsize=20) plt.show()
65
# Write a Python Program to print digit pattern # function to print the pattern def pattern(n):        # traverse through the elements     # in n assuming it as a string     for i in n:            # print | for every line         print("|", end = "")            # print i number of * s in          # each line         print("*" * int(i))    # get the input as string         n = "41325" pattern(n)
68
# Write a Python program to extract h1 tag from example.com. from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://en.wikipedia.org/wiki/Main_Page') bs = BeautifulSoup(html, "html.parser") titles = bs.find_all(['h1', 'h2','h3','h4','h5','h6']) print('List all the header tags :', *titles, sep='\n\n')
38
# Write a Pandas program to convert given series into a dataframe with its index as another column on the dataframe. import numpy as np import pandas as pd char_list = list('ABCDEFGHIJKLMNOP') num_arra = np.arange(8) num_dict = dict(zip(char_list, num_arra)) num_ser = pd.Series(num_dict) df = num_ser.to_frame().reset_index() print(df.head())
46
# Sum a list of numbers. Write a Python program to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on. #Source: shorturl.at/csxLM def test(list1): result = [(x + y) / 2.0 for (x, y) in zip(list1[:-1], list1[1:])] return list(result) nums = [1,2,3,4,5,6,7] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums)) nums = [0,1,-3,3,7,-5,6,7,11] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums))
82
# rite a NumPy program to create a null vector of size 10 and update sixth value to 11. import numpy as np x = np.zeros(10) print(x) print("Update sixth value to 11") x[6] = 11 print(x)
36
# Write a Python program to create a two-dimensional list from given list of lists. def two_dimensional_list(nums): return list(zip(*nums)) print(two_dimensional_list([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])) print(two_dimensional_list([[1, 2], [4, 5]]))
35
# Write a Python function that takes a list and returns a new list with unique elements of the first list. def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x print(unique_list([1,2,3,3,3,3,4,5]))
39
# Write a Python program to sort Counter by value. from collections import Counter x = Counter({'Math':81, 'Physics':83, 'Chemistry':87}) print(x.most_common())
20
# Write a Python program to count the number occurrence of a specific character in a string. s = "The quick brown fox jumps over the lazy dog." print("Original string:") print(s) print("Number of occurrence of 'o' in the said string:") print(s.count("o"))
41
# Clean the string data in the given Pandas Dataframe in Python # importing pandas as pd import pandas as pd    # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                    'Product':[' UMbreLla', '  maTress', 'BaDmintoN ', 'Shuttle'],                    'Updated_Price':[1250, 1450, 1550, 400],                    'Discount':[10, 8, 15, 10]})    # Print the dataframe print(df)
51
# Write a Python Program for Odd-Even Sort / Brick Sort # Python Program to implement  # Odd-Even / Brick Sort    def oddEvenSort(arr, n):     # Initially array is unsorted     isSorted = 0     while isSorted == 0:         isSorted = 1         temp = 0         for i in range(1, n-1, 2):             if arr[i] > arr[i+1]:                 arr[i], arr[i+1] = arr[i+1], arr[i]                 isSorted = 0                            for i in range(0, n-1, 2):             if arr[i] > arr[i+1]:                 arr[i], arr[i+1] = arr[i+1], arr[i]                 isSorted = 0            return       arr = [34, 2, 10, -9] n = len(arr)    oddEvenSort(arr, n); for i in range(0, n):     print(arr[i], end =" ")        # Code Contribute by Mohit Gupta_OMG <(0_o)>
106
# Write a Python program to All substrings Frequency in String # Python3 code to demonstrate working of  # All substrings Frequency in String # Using loop + list comprehension    # initializing string test_str = "abababa"    # printing original string print("The original string is : " + str(test_str))    # list comprehension to extract substrings temp = [test_str[idx: j] for idx in range(len(test_str))        for j in range(idx + 1, len(test_str) + 1)]    # loop to extract final result of frequencies res = {} for idx in temp:      if idx not in res.keys():              res[idx] = 1      else:              res[idx] += 1                 # printing result  print("Extracted frequency dictionary : " + str(res)) 
108
# Count the number of vowels, consonants, numbers, and special characters present in a string str=input("Enter the String:") v_count = 0 s_count = 0 n_count = 0 for i in range(len(str)):     if str[i] == 'a' or str[i] == 'A' or str[i] == 'e' or str[i] == 'E' or str[i] == 'i' or str[i] == 'I' or str[i] == 'o' or str[i] == 'O' or str[i] == 'u' or str[i] == 'U':         v_count+=1     elif str[i] >= '0' and str[i] <= '9':         n_count+=1     elif str[i] >=chr(0) and str[i] <= chr(47) or str[i] >= chr(58) and str[i] <=chr(64) or str[i] >=chr(91) and str[i] <= chr(96) or str[i] >= chr(123) and str[i] <= chr(127):         s_count+=1 print("Number of digits: ",n_count) print("Number of vowels: ", v_count) print("Number of special character: ",s_count) print("Number of consonants: ",len(str) - n_count - v_count - s_count)
135
# Write a Python program to calculate the product of the unique numbers of a given list. def unique_product(list_data): temp = list(set(list_data)) p = 1 for i in temp: p *= i return p nums = [10, 20, 30, 40, 20, 50, 60, 40] print("Original List : ",nums) print("Product of the unique numbers of the said list: ",unique_product(nums))
58
# Write a Python program to compute the sum of digits of each number of a given list. def sum_of_digits(nums): return sum(int(el) for n in nums for el in str(n) if el.isdigit()) nums = [10,2,56] print("Original tuple: ") print(nums) print("Sum of digits of each number of the said list of integers:") print(sum_of_digits(nums)) nums = [10,20,4,5,'b',70,'a'] print("\nOriginal tuple: ") print(nums) print("Sum of digits of each number of the said list of integers:") print(sum_of_digits(nums)) nums = [10,20,-4,5,-70] print("\nOriginal tuple: ") print(nums) print("Sum of digits of each number of the said list of integers:") print(sum_of_digits(nums))
92
# Write a Python program to display some information about the OS where the script is running. import platform as pl os_profile = [ 'architecture', 'linux_distribution', 'mac_ver', 'machine', 'node', 'platform', 'processor', 'python_build', 'python_compiler', 'python_version', 'release', 'system', 'uname', 'version', ] for key in os_profile: if hasattr(pl, key): print(key + ": " + str(getattr(pl, key)()))
53
# Write a Python program to get the minimum value of a list, after mapping each element to a value using a given function. def min_by(lst, fn): return min(map(fn, lst)) print(min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
50
# Write a NumPy program to find the indices of the maximum and minimum values along the given axis of an array. import numpy as np x = np.array([1, 2, 3, 4, 5, 6]) print("Original array: ",x) print("Maximum Values: ",np.argmax(x)) print("Minimum Values: ",np.argmin(x))
43
# Write a Python program to check if first digit/character of each element in a given list is same or not. def test(lst): result = all(str(x)[0] == str(lst[0])[0] for x in lst) return result nums = [1234, 122, 1984, 19372, 100] print("\nOriginal list:") print(nums) print("Check if first digit in each element of the said given list is same or not!") print(test(nums)) nums = [1234, 922, 1984, 19372, 100] print("\nOriginal list:") print(nums) print("Check if first digit in each element of the said given list is same or not!") print(test(nums)) nums = ['aabc', 'abc', 'ab', 'a'] print("\nOriginal list:") print(nums) print("Check if first character in each element of the said given list is same or not!") print(test(nums)) nums = ['aabc', 'abc', 'ab', 'ha'] print("\nOriginal list:") print(nums) print("Check if first character in each element of the said given list is same or not!") print(test(nums))
140
# Write a Python program to sort unsorted numbers using Random Pivot Quick Sort. Picks the random index as the pivot. #Ref.https://bit.ly/3pl5kyn import random def partition(A, left_index, right_index): pivot = A[left_index] i = left_index + 1 for j in range(left_index + 1, right_index): if A[j] < pivot: A[j], A[i] = A[i], A[j] i += 1 A[left_index], A[i - 1] = A[i - 1], A[left_index] return i - 1 def quick_sort_random(A, left, right): if left < right: pivot = random.randint(left, right - 1) A[pivot], A[left] = ( A[left], A[pivot], ) # switches the pivot with the left most bound pivot_index = partition(A, left, right) quick_sort_random( A, left, pivot_index ) # recursive quicksort to the left of the pivot point quick_sort_random( A, pivot_index + 1, right ) # recursive quicksort to the right of the pivot point nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 0, len(nums)) print(nums) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 0, len(nums)) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 0, len(nums)) print(nums) nums = [1.1, 1, 0, -1, -1.1, .1] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 1, len(nums)) print(nums) nums = ['z','a','y','b','x','c'] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 0, len(nums)) print(nums) nums = ['z','a','y','b','x','c'] print("\nOriginal list:") print(nums) print("After applying Random Pivot Quick Sort the said list becomes:") quick_sort_random(nums, 2, len(nums)) print(nums)
280
# Write a Python program to that retrieves an arbitary Wikipedia page of "Python" and creates a list of links on that page. from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup def getTitle(url): try: html = urlopen(url) except HTTPError as e: return None try: bsObj = BeautifulSoup(html.read(), "lxml") title = bsObj.body.h1 except AttributeError as e: return None return title title = getTitle(url) if title == None: return "Title could not be found" else: return title print(getTitle("https://www.w3resource.com/")) print(getTitle("http://www.example.com/"))
81
# How to read multiple text files from folder in Python # Import Module import os    # Folder Path path = "Enter Folder Path"    # Change the directory os.chdir(path)    # Read text File       def read_text_file(file_path):     with open(file_path, 'r') as f:         print(f.read())       # iterate through all file for file in os.listdir():     # Check whether file is in text format or not     if file.endswith(".txt"):         file_path = f"{path}\{file}"            # call read text file function         read_text_file(file_path)
72
# Write a NumPy program to stack arrays in sequence vertically. import numpy as np print("\nOriginal arrays:") x = np.arange(9).reshape(3,3) y = x*3 print("Array-1") print(x) print("Array-2") print(y) new_array = np.vstack((x,y)) print("\nStack arrays in sequence vertically:") print(new_array)
36
# Write a Python program to check if all the elements of a list are included in another given list. def test_includes_all(nums, lsts): for x in lsts: if x not in nums: return False return True print(test_includes_all([10, 20, 30, 40, 50, 60], [20, 40])) print(test_includes_all([10, 20, 30, 40, 50, 60], [20, 80]))
52
# Count of groups having largest size while grouping according to sum of its digits in Python // C++ implementation to Count the // number of groups having the largest // size where groups are according // to the sum of its digits #include <bits/stdc++.h> using namespace std; // function to return sum of digits of i int sumDigits(int n){     int sum = 0;     while(n)     {         sum += n%10;         n /= 10;     }     return sum; } // Create the dictionary of unique sum map<int,int> constDict(int n){           // dictionary that contain     // unique sum count     map<int,int> d;     for(int i = 1; i < n + 1; ++i){         // calculate the sum of its digits         int sum1 = sumDigits(i);         if(d.find(sum1) == d.end())             d[sum1] = 1;         else             d[sum1] += 1;            }     return d; } // function to find the // largest size of group int countLargest(int n){           map<int,int> d = constDict(n);           int size = 0;     // count of largest size group     int count = 0;     for(auto it = d.begin(); it != d.end(); ++it){         int k = it->first;         int val = it->second;         if(val > size){                        size = val;             count = 1;         }         else if(val == size)                        count += 1;     }     return count; }       // Driver code int main() {     int    n = 13;     int group = countLargest(n);     cout << group << endl;     return 0; }
221
# Building an undirected graph and finding shortest path using Dictionaries in Python # Python3 implementation to build a # graph using Dictonaries from collections import defaultdict # Function to build the graph def build_graph():     edges = [         ["A", "B"], ["A", "E"],         ["A", "C"], ["B", "D"],         ["B", "E"], ["C", "F"],         ["C", "G"], ["D", "E"]     ]     graph = defaultdict(list)           # Loop to iterate over every     # edge of the graph     for edge in edges:         a, b = edge[0], edge[1]                   # Creating the graph         # as adjacency list         graph[a].append(b)         graph[b].append(a)     return graph if __name__ == "__main__":     graph = build_graph()           print(graph)
98
# Write a Python program to check if a function is a user-defined function or not. Use types.FunctionType, types.LambdaType() import types def func(): return 1 print(isinstance(func, types.FunctionType)) print(isinstance(func, types.LambdaType)) print(isinstance(lambda x: x, types.FunctionType)) print(isinstance(lambda x: x, types.LambdaType)) print(isinstance(max, types.FunctionType)) print(isinstance(max, types.LambdaType)) print(isinstance(abs, types.FunctionType)) print(isinstance(abs, types.LambdaType))
45
# Write a Python program to Dictionary with maximum count of pairs # Python3 code to demonstrate working of  # Dictionary with maximum keys # Using loop + len()    # initializing list test_list = [{"gfg": 2, "best" : 4},               {"gfg": 2, "is" : 3, "best" : 4},               {"gfg": 2}]    # printing original list print("The original list is : " + str(test_list))    res = {}  max_len = 0 for ele in test_list:            # checking for lengths     if len(ele) > max_len:          res = ele         max_len = len(ele)            # printing results print("Maximum keys Dictionary : " + str(res))
95
# Python Program to Print Numbers in a Range (1,upper) Without Using any Loops def printno(upper): if(upper>0): printno(upper-1) print(upper) upper=int(input("Enter upper limit: ")) printno(upper)
24
# Check whether two strings are equal or not str=input("Enter the 1st String:") str1=input("Enter the 2nd String:") if(len(str)==len(str1)):     print("Two strings are equal.") else:     print("Two strings are not equal.")
28
# Write a Python program to print the following floating numbers upto 2 decimal places with a sign. x = 3.1415926 y = -12.9999 print("\nOriginal Number: ", x) print("Formatted Number with sign: "+"{:+.2f}".format(x)); print("Original Number: ", y) print("Formatted Number with sign: "+"{:+.2f}".format(y)); print()
43
# numpy matrix operations | rand() function in Python # Python program explaining # numpy.matlib.rand() function    # importing matrix library from numpy import numpy as geek import numpy.matlib    # desired 3 x 4 random output matrix  out_mat = geek.matlib.rand((3, 4))  print ("Output matrix : ", out_mat) 
46
# Write a Python program to extract values from a given dictionaries and create a list of lists from those values. def test(dictt,keys): return [list(d[k] for k in keys) for d in dictt] students = [ {'student_id': 1, 'name': 'Jean Castro', 'class': 'V'}, {'student_id': 2, 'name': 'Lula Powell', 'class': 'V'}, {'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'}, {'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'}, {'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'} ] print("\nOriginal Dictionary:") print(students) print("\nExtract values from the said dictionarie and create a list of lists using those values:") print("\n",test(students,('student_id', 'name', 'class'))) print("\n",test(students,('student_id', 'name'))) print("\n",test(students,('name', 'class')))
97
# Write a NumPy program to create a two-dimensional array of specified format. import numpy as np print("Create an array of shape (15,10):") print("Command-1") print(np.arange(1, 151).reshape(15, 10)) print("\nCommand-2") print(np.arange(1, 151).reshape(-1, 10)) print("\nCommand-3") print(np.arange(1, 151).reshape(15, -1))
35
# Write a Pandas program to convert integer or float epoch times to Timestamp and DatetimeIndex. import pandas as pd dates1 = pd.to_datetime([1329806505, 129806505, 1249892905, 1249979305, 1250065705], unit='s') print("Convert integer or float epoch times to Timestamp and DatetimeIndex upto second:") print(dates1) print("\nConvert integer or float epoch times to Timestamp and DatetimeIndex upto milisecond:") dates2 = pd.to_datetime([1249720105100, 1249720105200, 1249720105300, 1249720105400, 1249720105500], unit='ms') print(dates2)
62
# Write a NumPy program to change the sign of a given array to that of a given array, element-wise. import numpy as np x1 = np.array([-1, 0, 1, 2]) print("Original array: ") print(x1) x2 = -2.1 print("\nSign of x1 to that of x2, element-wise:") print(np.copysign(x1, x2))
47
# Write a NumPy program to check whether two arrays are equal (element wise) or not. import numpy as np nums1 = np.array([0.5, 1.5, 0.2]) nums2 = np.array([0.4999999999, 1.500000000, 0.2]) np.set_printoptions(precision=15) print("Original arrays:") print(nums1) print(nums2) print("\nTest said two arrays are equal (element wise) or not:?") print(nums1 == nums2) nums1 = np.array([0.5, 1.5, 0.23]) nums2 = np.array([0.4999999999, 1.5000000001, 0.23]) print("\nOriginal arrays:") np.set_printoptions(precision=15) print(nums1) print(nums2) print("\nTest said two arrays are equal (element wise) or not:?") print(np.equal(nums1, nums2))
75
# Write a Python program to find the specified number of largest products from two given list, multiplying an element from each list. def top_product(nums1, nums2, N): result = sorted([x*y for x in nums1 for y in nums2], reverse=True)[:N] return result nums1 = [1, 2, 3, 4, 5, 6] nums2 = [3, 6, 8, 9, 10, 6] print("Original lists:") print(nums1) print(nums2,"\n") N = 3 print(N,"Number of largest products from the said two lists:") print(top_product(nums1, nums2, N)) N = 4 print(N,"Number of largest products from the said two lists:") print(top_product(nums1, nums2, N))
91
# Write a NumPy program (using NumPy) to sum of all the multiples of 3 or 5 below 100. import numpy as np x = np.arange(1, 100) # find multiple of 3 or 5 n= x[(x % 3 == 0) | (x % 5 == 0)] print(n[:1000]) # print sum the numbers print(n.sum())
53
# Write a Python program to computing square roots using the Babylonian method. def BabylonianAlgorithm(number): if(number == 0): return 0; g = number/2.0; g2 = g + 1; while(g != g2): n = number/ g; g2 = g; g = (g + n)/2; return g; print('The Square root of 0.3 =', BabylonianAlgorithm(0.3));
52
# Handling missing keys in Python dictionaries # Python code to demonstrate Dictionary and # missing value error # initializing Dictionary d = { 'a' : 1 , 'b' : 2 } # trying to output value of absent key print ("The value associated with 'c' is : ") print (d['c'])
51
# Write a Python program to check if a given function is a generator or not. Use types.GeneratorType() import types def a(x): yield x def b(x): return x def add(x, y): return x + y print(isinstance(a(456), types.GeneratorType)) print(isinstance(b(823), types.GeneratorType)) print(isinstance(add(8,2), types.GeneratorType))
41
# Write a Python program to remove the first occurrence of a specified element from an array. from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) print("Original array: "+str(array_num)) print("Remove the first occurrence of 3 from the said array:") array_num.remove(3) print("New array: "+str(array_num))
49
# How to count the frequency of unique values in NumPy array in Python # import library import numpy as np    ini_array = np.array([10, 20, 5,                       10, 8, 20,                       8, 9])    # Get a tuple of unique values  # and their frequency in # numpy array unique, frequency = np.unique(ini_array,                                return_counts = True) # print unique values array print("Unique Values:",        unique)    # print frequency array print("Frequency Values:",       frequency)
68
# Write a Pandas program to check whether alphabetic values present in a given column of a DataFrame. import pandas as pd df = pd.DataFrame({ 'company_code': ['Company','Company a001','Company 123', 'abcd', 'Company 12'], '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("\nWhether Alphabetic values present in company_code column?") df['company_code_is_alpha'] = list(map(lambda x: x.isalpha(), df['company_code'])) print(df)
58
# Write a Python program to change the position of every n-th value with the (n+1)th in a list. from itertools import zip_longest, chain, tee def replace2copy(lst): lst1, lst2 = tee(iter(lst), 2) return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2]))) n = [0,1,2,3,4,5] print(replace2copy(n))
39
# Write a Python program to Numpy dstack() method # import numpy import numpy as np    gfg1 = np.array([1, 2, 3]) gfg2 = np.array([4, 5, 6])    # using numpy.dstack() method print(np.dstack((gfg1, gfg2)))
32
# Check whether an alphabet is vowel or consonant alphabet=input("Enter an alphabet:") if(alphabet=='a' or alphabet=='A' or alphabet=='e' or alphabet=='E' or alphabet=='i' or alphabet=='I' or alphabet=='o' or alphabet=='O' or alphabet=='u' or alphabet=='U'):  print("It is Vowel") else:  print("It is Consonant")
38
# Check whether number is Sunny Number or Not. import math num=int(input("Enter a number:")) root=math.sqrt(num+1) if int(root)==root:     print("It is a Sunny Number.") else:    print("It is Not a Sunny Number.")
29
# Getting the time since OS startup using Python # for using os.popen() import os # sending the uptime command as an argument to popen() # and saving the returned result (after truncating the trailing \n) t = os.popen('uptime -p').read()[:-1] print(t)
41
# Write a Python program to create a ctime formatted representation of the date and time using arrow module. import arrow print("Ctime formatted representation of the date and time:") a = arrow.utcnow().ctime() print(a)
33
# Write a Python program to convert an integer to binary keep leading zeros. x = 12 print(format(x, '08b')) print(format(x, '010b'))
21
# Program to Find nth Neon Number rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:         sqr = num * num         # Sum of digit         sum = 0         while sqr != 0:             rem = sqr % 10             sum += rem             sqr //= 10         if sum == num:             c+=1             letest = num         num = num + 1 print(rangenumber,"th Magic number is ",latest)
69
# Write a Python program to chunk a given list into smaller lists of a specified size. from math import ceil def chunk_list(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(ceil(len(lst) / size))))) print(chunk_list([1, 2, 3, 4, 5, 6, 7, 8], 3))
47
# Write a Python program to convert a pair of values into a sorted unique array. L = [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1, 2), (3, 4), (3, 4), (7, 8), (9, 10)] print("Original List: ", L) print("Sorted Unique Data:",sorted(set().union(*L)))
45