code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a NumPy program to compute the eigenvalues and right eigenvectors of a given square array. import numpy as np m = np.mat("3 -2;1 0") print("Original matrix:") print("a\n", m) w, v = np.linalg.eig(m) print( "Eigenvalues of the said matrix",w) print( "Eigenvectors of the said matrix",v)
46
# Write a NumPy program to create a NumPy array of 10 integers from a generator. import numpy as np iterable = (x for x in range(10)) print(np.fromiter(iterable, np.int))
29
# Write a Pandas program to extract year between 1800 to 2200 from the specified column of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'], 'year': ['year 1800','year 1700','year 2300', 'year 1900', 'year 2200'] }) print("Original DataFrame:") print(df) def find_year(text): #line=re.findall(r"\b(18[0][0]|2[0-2][00])\b",text) result = re.findall(r"\b(18[0-9]{2}|19[0-8][0-9]|199[0-9]|2[01][0-9]{2}|2200)\b",text) return result df['year_range']=df['year'].apply(lambda x: find_year(x)) print("\Extracting year between 1800 to 2200:") print(df)
68
# Program to print window pattern in Python // C++ program to print the pattern  // hollow square with plus inside it // window pattern #include <bits/stdc++.h> using namespace std;    // Function to print pattern n means  // number of rows which we want void window_pattern (int n) {     int c, d;            // If n is odd then we will have     // only one middle element     if (n % 2 != 0)     {         c = (n / 2) + 1;         d = 0;     }        // If n is even then we will have two     // values     else     {         c = (n / 2) + 1;         d = n / 2 ;     }        for(int i = 1; i <= n; i++)     {         for(int j = 1; j <= n; j++)         {                         // If i,j equals to corner row or             // column then "*"             if (i == 1 || j == 1 ||                 i == n || j == n)                 cout << "* ";                else             {                                 // If i,j equals to the middle                  // row or column then  "*"                 if (i == c || j == c)                     cout << "* ";                    else if (i == d || j == d)                     cout << "* ";                    else                     cout << "  ";             }         }         cout << '\n';     } }    // Driver Code int main() {     int n = 7;         window_pattern(n);     return 0;    }    // This code is contributed by himanshu77
235
# Print the frequency of all numbers in an array import sys arr=[] freq=[] max=-sys.maxsize-1 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) for i in range(0, size):     if(arr[i]>=max):         max=arr[i] for i in range(0,max+1):     freq.append(0) for i in range(0, size):     freq[arr[i]]+=1 for i in range(0, max+1):     if(freq[i]!=0):         print("occurs ",i," ",freq[i]," times")
66
# Write a Python program to count the even, odd numbers in a given array of integers using Lambda. array_nums = [1, 2, 3, 5, 7, 8, 9, 10] print("Original arrays:") print(array_nums) odd_ctr = len(list(filter(lambda x: (x%2 != 0) , array_nums))) even_ctr = len(list(filter(lambda x: (x%2 == 0) , array_nums))) print("\nNumber of even numbers in the above array: ", even_ctr) print("\nNumber of odd numbers in the above array: ", odd_ctr)
70
# Write a Python program to pack consecutive duplicates of a given list elements into sublists. from itertools import groupby def pack_consecutive_duplicates(l_nums): return [list(group) for key, group in groupby(l_nums)] n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ] print("Original list:") print(n_list) print("\nAfter packing consecutive duplicates of the said list elements into sublists:") print(pack_consecutive_duplicates(n_list))
63
# Python Program to Print all Numbers in a Range Divisible by a Given Number   lower=int(input("Enter lower range limit:")) upper=int(input("Enter upper range limit:")) n=int(input("Enter the number to be divided by:")) for i in range(lower,upper+1): if(i%n==0): print(i)
36
# Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix. import numpy as np nums = np.random.randint(0,4,(6,3)) print("Original vector:") print(nums) new_nums = np.logical_and.reduce(nums[:,1:] == nums[:,:-1], axis=1) result = nums[~new_nums] print("\nRows with unequal values:") print(result)
40
# Write a Pandas program to find which years have all non-zero values and which years have any non-zero values from world alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nFind which years have all non-zero values:") print(w_a_con.loc[:,w_a_con.all()]) print("\nFind which years have any non-zero values:") print(w_a_con.loc[:,w_a_con.any()])
59
# Write a NumPy program to collapse a 3-D array into one dimension array. import numpy as np x = np.eye(3) print("3-D array:") print(x) f = np.ravel(x, order='F') print("One dimension array:") print(f)
32
# Write a Python program to Remove Dictionary Key Words # Python3 code to demonstrate working of  # Remove Dictionary Key Words # Using split() + loop + replace()    # initializing string test_str = 'gfg is best for geeks'    # printing original string print("The original string is : " + str(test_str))    # initializing Dictionary test_dict = {'geeks' : 1, 'best': 6}    # Remove Dictionary Key Words # Using split() + loop + replace() for key in test_dict:     if key in test_str.split(' '):         test_str = test_str.replace(key, "")    # printing result  print("The string after replace : " + str(test_str)) 
97
# Write a Python program to create a new deque with three items and iterate over the deque's elements. from collections import deque dq = deque('aeiou') for element in dq: print(element)
31
# numpy.squeeze() in Python # Python program explaining # numpy.squeeze function    import numpy as geek    in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])     print ("Input array : ", in_arr)  print("Shape of input array : ", in_arr.shape)      out_arr = geek.squeeze(in_arr)     print ("output squeezed array : ", out_arr) print("Shape of output array : ", out_arr.shape) 
53
# Write a Python program to Find missing and additional values in two lists # Python program to find the missing  # and additional elements     # examples of lists list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8]    # prints the missing and additional elements in list2  print("Missing values in second list:", (set(list1).difference(list2))) print("Additional values in second list:", (set(list2).difference(list1)))    # prints the missing and additional elements in list1 print("Missing values in first list:", (set(list2).difference(list1))) print("Additional values in first list:", (set(list1).difference(list2)))
86
# Write a Numpy program to test whether numpy array is faster than Python list or not. import time import numpy as np SIZE = 200000 list1 = range(SIZE) list2 = range(SIZE) arra1 = np.arange(SIZE) arra2 = np.arange(SIZE) start_list = time.time() result=[(x,y) for x,y in zip(list1,list2)] print("Time to aggregates elements from each of the iterables:") print("List:") print((time.time()-start_list)*1000) start_array = time.time() result = arra1 + arra2 print("NumPy array:") print((time.time()-start_array)*1000)
68
# Change data type of given numpy array in Python # importing the numpy library as np import numpy as np    # Create a numpy array arr = np.array([10, 20, 30, 40, 50])    # Print the array print(arr)
38
# Program to Find the reverse of a given number num=int(input("Enter a number:")) num2=0 while(num!=0):    rem=num%10    num=int(num/10)    num2=num2*10+rem print("The reverse of the number is",num2)
24
# Write a Pandas program to extract email from a specified column of string type of a given DataFrame. import pandas as pd import re as re pd.set_option('display.max_columns', 10) df = pd.DataFrame({ 'name_email': ['Alberto Franco [email protected]','Gino Mcneill [email protected]','Ryan Parkes [email protected]', 'Eesha Hinton', 'Gino Mcneill [email protected]'] }) print("Original DataFrame:") print(df) def find_email(text): email = re.findall(r'[\w\.-][email protected][\w\.-]+',str(text)) return ",".join(email) df['email']=df['name_email'].apply(lambda x: find_email(x)) print("\Extracting email from dataframe columns:") print(df)
70
# Program to check whether a matrix is symmetric 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()]) if row_size!=col_size: print("Given Matrix is not a Square Matrix.") else: #compute the transpose matrix tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)] for i in range(0, row_size): for j in range(0, col_size): tran_matrix[i][j] = matrix[j][i] # check given matrix elements and transpose # matrix elements are same or not. flag=0 for i in range(0, row_size): for j in range(0, col_size): if matrix[i][j] != tran_matrix[i][j]: flag=1 break if flag==1: print("Given Matrix is not a symmetric Matrix.") else: print("Given Matrix is a symmetric Matrix.")
136
# Define a class named American and its subclass NewYorker. : class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker() print anAmerican print aNewYorker
27
# Write a Pandas program to calculate the number of characters in each word in a given series. import pandas as pd series1 = pd.Series(['Php', 'Python', 'Java', 'C#']) print("Original Series:") print(series1) result = series1.map(lambda x: len(x)) print("\nNumber of characters in each word in the said series:") print(result)
47
# Create a list from rows in 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/11'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'Cost':[10000, 5000, 15000, 2000]})    # Print the dataframe print(df)
43
# Write a Python program to Row-wise element Addition in Tuple Matrix # Python3 code to demonstrate working of  # Row-wise element Addition in Tuple Matrix # Using enumerate() + list comprehension    # initializing list test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]    # printing original list print("The original list is : " + str(test_list))    # initializing Custom eles cus_eles = [6, 7, 8]    # Row-wise element Addition in Tuple Matrix # Using enumerate() + list comprehension res = [[sub + (cus_eles[idx], ) for sub in val] for idx, val in enumerate(test_list)]    # printing result  print("The matrix after row elements addition : " + str(res)) 
109
# Write a NumPy program to round elements of the array to the nearest integer. import numpy as np x = np.array([-.7, -1.5, -1.7, 0.3, 1.5, 1.8, 2.0]) print("Original array:") print(x) x = np.rint(x) print("Round elements of the array to the nearest integer:") print(x)
44
# Python Program to Find the Number of Nodes in a Binary Tree 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 insert_left(self, new_node): self.left = new_node   def insert_right(self, new_node): self.right = new_node   def search(self, key): if self.key == key: return self if self.left is not None: temp = self.left.search(key) if temp is not None: return temp if self.right is not None: temp = self.right.search(key) return temp return None     def count_nodes(node): if node is None: return 0 return 1 + count_nodes(node.left) + count_nodes(node.right)     btree = None   print('Menu (this assumes no duplicate keys)') print('insert <data> at root') print('insert <data> left of <data>') print('insert <data> right of <data>') print('count') print('quit')   while True: print('inorder traversal of binary tree: ', end='') if btree is not None: btree.inorder() print()   do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'insert': data = int(do[1]) new_node = BinaryTree(data) suboperation = do[2].strip().lower() if suboperation == 'at': btree = new_node else: position = do[4].strip().lower() key = int(position) ref_node = None if btree is not None: ref_node = btree.search(key) if ref_node is None: print('No such key.') continue if suboperation == 'left': ref_node.insert_left(new_node) elif suboperation == 'right': ref_node.insert_right(new_node)   elif operation == 'count': print('Number of nodes in tree: {}'.format(count_nodes(btree)))   elif operation == 'quit': break
236
# Write a Python program to get string representing the date, controlled by an explicit format string. import arrow a = arrow.utcnow() print("Current datetime:") print(a) print("\nString representing the date, controlled by an explicit format string:") print(arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%m-%d %H:%M:%S')) print(arrow.utcnow().strftime('%Y-%d-%m %H:%M:%S'))
41
# Write a Pandas program to create a bar plot of the trading volume 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-4-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') plt.figure(figsize=(6,6)) plt.suptitle('Trading Volume of Alphabet Inc. stock,\n01-04-2020 to 30-04-2020', fontsize=16, color='black') plt.xlabel("Date",fontsize=12, color='black') plt.ylabel("Trading Volume", fontsize=12, color='black') df2['Volume'].plot(kind='bar'); plt.show()
74
# Given variables x=30 and y=20, write a Python program to print "30+20=50". x = 30 y = 20 print("\n%d+%d=%d" % (x, y, x+y)) print()
25
# Python Program to Count Number of Non Leaf Nodes of a given Tree class Tree: def __init__(self, data=None): self.key = data self.children = []   def set_root(self, data): self.key = data   def add(self, node): self.children.append(node)   def search(self, key): if self.key == key: return self for child in self.children: temp = child.search(key) if temp is not None: return temp return None   def count_nonleaf_nodes(self): nonleaf_count = 0 if self.children != []: nonleaf_count = 1 for child in self.children: nonleaf_count = nonleaf_count + child.count_nonleaf_nodes() return nonleaf_count     tree = None   print('Menu (this assumes no duplicate keys)') print('add <data> at root') print('add <data> below <data>') print('count') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'add': data = int(do[1]) new_node = Tree(data) suboperation = do[2].strip().lower() if suboperation == 'at': tree = new_node elif suboperation == 'below': position = do[3].strip().lower() key = int(position) ref_node = None if tree is not None: ref_node = tree.search(key) if ref_node is None: print('No such key.') continue ref_node.add(new_node)   elif operation == 'count': if tree is None: print('Tree is empty.') else: count = tree.count_nonleaf_nodes() print('Number of nonleaf nodes: {}'.format(count))   elif operation == 'quit': break
191
# Write a Python program to remove spaces from dictionary keys. student_list = {'S 001': ['Math', 'Science'], 'S 002': ['Math', 'English']} print("Original dictionary: ",student_list) student_dict = {x.translate({32: None}): y for x, y in student_list.items()} print("New dictionary: ",student_dict)
37
# Write a Python Program for Comb Sort # Python program for implementation of CombSort    # To find next gap from current def getNextGap(gap):        # Shrink gap by Shrink factor     gap = (gap * 10)/13     if gap < 1:         return 1     return gap    # Function to sort arr[] using Comb Sort def combSort(arr):     n = len(arr)        # Initialize gap     gap = n        # Initialize swapped as true to make sure that     # loop runs     swapped = True        # Keep running while gap is more than 1 and last     # iteration caused a swap     while gap !=1 or swapped == 1:            # Find next gap         gap = getNextGap(gap)            # Initialize swapped as false so that we can         # check if swap happened or not         swapped = False            # Compare all elements with current gap         for i in range(0, n-gap):             if arr[i] > arr[i + gap]:                 arr[i], arr[i + gap]=arr[i + gap], arr[i]                 swapped = True       # Driver code to test above arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0] combSort(arr)    print ("Sorted array:") for i in range(len(arr)):     print (arr[i]),       # This code is contributed by Mohit Kumra
190
# Write a Python program to insert an item in front of a given doubly linked list. class Node(object): # Singly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linked_list(object): def __init__(self): self.head = None self.tail = None self.count = 0 def append_item(self, data): # Append an item new_item = Node(data, None, None) if self.head is None: self.head = new_item self.tail = self.head else: new_item.prev = self.tail self.tail.next = new_item self.tail = new_item self.count += 1 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 insert_start(self, data): if self.head is not None: new_node = Node(data, None, None) new_node.next = self.head self.head.prev = new_node self.head = new_node self.count += 1 items = doubly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') items.append_item('SQL') print("Original list:") items.print_foward() print("\nAppend item in front of the list:") items.insert_start("Perl") items.print_foward()
157
# Program to Print series 1,2,8,16,32...n n=int(input("Enter the range of number(Limit):"))i=1while i<=n:    print(i,end=" ")    i*=2
15
# Check whether number is Evil Number or Not num=int(input("Enter a number:")) one_c=0 while num!=0:     if num%2==1:         one_c+=1     num//=2 if one_c%2==0:     print("It is an Evil Number.") else:    print("It is Not an Evil Number.")
33
# Write a Pandas program to create a dataframe and set a title or name of the index column. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_Of_Birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 32, 33, 30, 31, 32], 'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']}, index = ['t1', 't2', 't3', 't4', 't5', 't6']) print("Original DataFrame:") print(df) df.index.name = 'Index_name' print("\nSaid DataFrame with a title or name of the index column:") print(df)
88
# Write a Python program to find the index position of the largest value smaller than a given number in a sorted list using Binary Search (bisect). from bisect import bisect_left def Binary_Search(l, x): i = bisect_left(l, x) if i: return (i-1) else: return -1 nums = [1, 2, 3, 4, 8, 8, 10, 12] x = 5 num_position = Binary_Search(nums, x) if num_position == -1: print("Not found..!") else: print("Largest value smaller than ", x, " is at index ", num_position )
82
# Linear Search Program in C | C++ | Java | Python 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) search_elm=int(input("Enter the search element: ")) found=0 for i in range(size):     if arr[i]==search_elm:             found=1 if found==1:         print("Search element is found.") else:         print("Search element is not found.")
61
# Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length. def check_string(s): messg = [] if not any(x.isupper() for x in s): messg.append('String must have 1 upper case character.') if not any(x.islower() for x in s): messg.append('String must have 1 lower case character.') if not any(x.isdigit() for x in s): messg.append('String must have 1 number.') if len(s) < 8: messg.append('String length should be atleast 8.') if not messg: messg.append('Valid string.') return messg s = input("Input the string: ") print(check_string(s))
94
# Write a Python program to count the frequency of the elements of a given unordered list. from itertools import groupby uno_list = [2,1,3,8,5,1,4,2,3,4,0,8,2,0,8,4,2,3,4,2] print("Original list:") print(uno_list) uno_list.sort() print(uno_list) print("\nSort the said unordered list:") print(uno_list) print("\nFrequency of the elements of the said unordered list:") result = [len(list(group)) for key, group in groupby(uno_list)] print(result)
53
# Write a Python program to remove an element from a given list. student = ['Ricky Rivera', 98, 'Math', 90, 'Science'] print("Original list:") print(student) print("\nAfter deleting an element:, using index of the element:") del(student[0]) print(student)
35
# Implementation of XOR Linked List in Python # import required module import ctypes          # create node class class Node:     def __init__(self, value):         self.value = value         self.npx = 0                  # create linked list class class XorLinkedList:        # constructor     def __init__(self):         self.head = None         self.tail = None         self.__nodes = []        # method to insert node at beginning     def InsertAtStart(self, value):         node = Node(value)         if self.head is None:  # If list is empty             self.head = node             self.tail = node         else:             self.head.npx = id(node) ^ self.head.npx             node.npx = id(self.head)             self.head = node         self.__nodes.append(node)        # method to insert node at end     def InsertAtEnd(self, value):         node = Node(value)         if self.head is None:  # If list is empty             self.head = node             self.tail = node         else:             self.tail.npx = id(node) ^ self.tail.npx             node.npx = id(self.tail)             self.tail = node         self.__nodes.append(node)        # method to remove node at beginning     def DeleteAtStart(self):         if self.isEmpty():  # If list is empty             return "List is empty !"         elif self.head == self.tail:  # If list has 1 node             self.head = self.tail = None         elif (0 ^ self.head.npx) == id(self.tail):  # If list has 2 nodes             self.head = self.tail             self.head.npx = self.tail.npx = 0         else:  # If list has more than 2 nodes             res = self.head.value             x = self.__type_cast(0 ^ self.head.npx)  # Address of next node             y = (id(self.head) ^ x.npx)  # Address of next of next node             self.head = x             self.head.npx = 0 ^ y             return res        # method to remove node at end     def DeleteAtEnd(self):         if self.isEmpty():  # If list is empty             return "List is empty !"         elif self.head == self.tail:  # If list has 1 node             self.head = self.tail = None         elif self.__type_cast(0 ^ self.head.npx) == (self.tail):  # If list has 2 nodes             self.tail = self.head             self.head.npx = self.tail.npx = 0         else:  # If list has more than 2 nodes             prev_id = 0             node = self.head             next_id = 1             while next_id:                 next_id = prev_id ^ node.npx                 if next_id:                     prev_id = id(node)                     node = self.__type_cast(next_id)             res = node.value             x = self.__type_cast(prev_id).npx ^ id(node)             y = self.__type_cast(prev_id)             y.npx = x ^ 0             self.tail = y             return res        # method to traverse linked list     def Print(self):         """We are printing values rather than returning it bacause         for returning we have to append all values in a list         and it takes extra memory to save all values in a list."""            if self.head != None:             prev_id = 0             node = self.head             next_id = 1             print(node.value, end=' ')             while next_id:                 next_id = prev_id ^ node.npx                 if next_id:                     prev_id = id(node)                     node = self.__type_cast(next_id)                     print(node.value, end=' ')                 else:                     return         else:             print("List is empty !")        # method to traverse linked list in reverse order     def ReversePrint(self):            # Print Values is reverse order.         """We are printing values rather than returning it bacause         for returning we have to append all values in a list         and it takes extra memory to save all values in a list."""            if self.head != None:             prev_id = 0             node = self.tail             next_id = 1             print(node.value, end=' ')             while next_id:                 next_id = prev_id ^ node.npx                 if next_id:                     prev_id = id(node)                     node = self.__type_cast(next_id)                     print(node.value, end=' ')                 else:                     return         else:             print("List is empty !")        # method to get length of linked list     def Length(self):         if not self.isEmpty():             prev_id = 0             node = self.head             next_id = 1             count = 1             while next_id:                 next_id = prev_id ^ node.npx                 if next_id:                     prev_id = id(node)                     node = self.__type_cast(next_id)                     count += 1                 else:                     return count         else:             return 0        # method to get node data value by index     def PrintByIndex(self, index):         prev_id = 0         node = self.head         for i in range(index):             next_id = prev_id ^ node.npx                if next_id:                 prev_id = id(node)                 node = self.__type_cast(next_id)             else:                 return "Value dosn't found index out of range."         return node.value        # method to check if the liked list is empty or not     def isEmpty(self):         if self.head is None:             return True         return False        # method to return a new instance of type     def __type_cast(self, id):         return ctypes.cast(id, ctypes.py_object).value                # Driver Code    # create object obj = XorLinkedList()    # insert nodes obj.InsertAtEnd(2) obj.InsertAtEnd(3) obj.InsertAtEnd(4) obj.InsertAtStart(0) obj.InsertAtStart(6) obj.InsertAtEnd(55)    # display length print("\nLength:", obj.Length())    # traverse print("\nTraverse linked list:") obj.Print()    print("\nTraverse in reverse order:") obj.ReversePrint()    # display data values by index print('\nNodes:') for i in range(obj.Length()):     print("Data value at index", i, 'is', obj.PrintByIndex(i))    # removing nodes print("\nDelete Last Node: ", obj.DeleteAtEnd()) print("\nDelete First Node: ", obj.DeleteAtStart())    # new length print("\nUpdated length:", obj.Length())    # display data values by index print('\nNodes:') for i in range(obj.Length()):     print("Data value at index", i, 'is', obj.PrintByIndex(i))    # traverse print("\nTraverse linked list:") obj.Print()    print("\nTraverse in reverse order:") obj.ReversePrint()
744
# Write a Python program to count positive and negative numbers in a list # Python program to count positive and negative numbers in a List    # list of numbers list1 = [10, -21, 4, -45, 66, -93, 1]    pos_count, neg_count = 0, 0    # iterating each number in list for num in list1:            # checking condition     if num >= 0:         pos_count += 1        else:         neg_count += 1            print("Positive numbers in the list: ", pos_count) print("Negative numbers in the list: ", neg_count)
82
# Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters. def to_uppercase(str1): num_upper = 0 for letter in str1[:4]: if letter.upper() == letter: num_upper += 1 if num_upper >= 2: return str1.upper() return str1 print(to_uppercase('Python')) print(to_uppercase('PyThon'))
52
# Write a Python program to find the list with maximum and minimum length. def max_length_list(input_list): max_length = max(len(x) for x in input_list ) max_list = max(input_list, key = len) return(max_length, max_list) def min_length_list(input_list): min_length = min(len(x) for x in input_list ) min_list = min(input_list, key = len) return(min_length, min_list) list1 = [[0], [1, 3], [5, 7], [9, 11], [13, 15, 17]] print("Original list:") print(list1) print("\nList with maximum length of lists:") print(max_length_list(list1)) print("\nList with minimum length of lists:") print(min_length_list(list1)) list1 = [[0], [1, 3], [5, 7], [9, 11], [3, 5, 7]] print("Original list:") print(list1) print("\nList with maximum length of lists:") print(max_length_list(list1)) print("\nList with minimum length of lists:") print(min_length_list(list1)) list1 = [[12], [1, 3], [1, 34, 5, 7], [9, 11], [3, 5, 7]] print("Original list:") print(list1) print("\nList with maximum length of lists:") print(max_length_list(list1)) print("\nList with minimum length of lists:") print(min_length_list(list1))
139
# Write a Python program to read a given string character by character and compress repeated character by storing the length of those character(s). from itertools import groupby def encode_str(input_str): return [(len(list(n)), m) for m,n in groupby(input_str)] str1 = "AAASSSSKKIOOOORRRREEETTTTAAAABBBBBBDDDDD" print("Original string:") print(str1) print("Result:") print(encode_str(str1)) str1 = "jjjjiiiiooooosssnssiiiiwwwweeeaaaabbbddddkkkklll" print("\nOriginal string:") print(str1) print("Result:") print(encode_str(str1))
53
# Program to convert binary to octal using while loop print("Enter a binary number: ") binary=int(input()); octal = 0 decimal = 0 i = 0 while (binary != 0):       decimal = decimal + (binary % 10) * pow (2, i)       i+=1       binary = binary // 10 i = 1 while (decimal != 0):       octal = octal + (decimal % 8) * i       decimal = decimal // 8       i = i * 10 print("octal value: ",octal)
75
# Write a Python program to perform an action if a condition is true. n=1 if n == 1: print("\nFirst day of a Month!") print()
25
# Write a Pandas program to join the two dataframes with matching records from both sides where available. 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]}) print("Original DataFrames:") print(student_data1) print(student_data2) merged_data = pd.merge(student_data1, student_data2, on='student_id', how='outer') print("Merged data (outer join):") print(merged_data)
89
# Write a Python program to Combinations of sum with tuples in tuple list # Python3 code to demonstrate working of # Summation combination in tuple lists # Using list comprehension + combinations from itertools import combinations    # initialize list  test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]    # printing original list  print("The original list : " + str(test_list))    # Summation combination in tuple lists # Using list comprehension + combinations res = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)]     # printing result print("The Summation combinations are : " + str(res))
100
# Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x2 matrix representing cartesian coordinates. import numpy as np z= np.random.random((10,2)) x,y = z[:,0], z[:,1] r = np.sqrt(x**2+y**2) t = np.arctan2(y,x) print(r) print(t)
38
# Write a Python program to Find Mean of a List of Numpy Array # Python code to find mean of every numpy array in list    # Importing module import numpy as np    # List Initialization Input = [np.array([1, 2, 3]),          np.array([4, 5, 6]),          np.array([7, 8, 9])]    # Output list initialization Output = []    # using np.mean() for i in range(len(Input)):    Output.append(np.mean(Input[i]))    # Printing output print(Output)
66
# Write a Python program to test whether a number is within 100 of 1000 or 2000. def near_thousand(n): return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) print(near_thousand(1000)) print(near_thousand(900)) print(near_thousand(800)) print(near_thousand(2200))
35
# Convert alternate characters to capital letters str=input("Enter the String:") j=0 newStr="" for i in range(len(str)):     if j%2==1:         if str[i]>='A' and str[i]<='Z' :             ch=chr(ord(str[i])+32)             newStr=newStr+ch         else:             newStr=newStr+str[i]     else:         if str[i] >= 'a' and str[i] <= 'z':             ch=chr(ord(str[i])-32)             newStr=newStr+ch         else:             newStr=newStr+str[i]     if str[i]==' ':         continue     j=j+1 print("After converting Your String is :", newStr)
52
# Write a Python program to split a list based on first character of word. from itertools import groupby from operator import itemgetter word_list = ['be','have','do','say','get','make','go','know','take','see','come','think', 'look','want','give','use','find','tell','ask','work','seem','feel','leave','call'] for letter, words in groupby(sorted(word_list), key=itemgetter(0)): print(letter) for word in words: print(word)
39
# Write a NumPy program to count the lowest index of "P" in a given array, element-wise. import numpy as np x1 = np.array(['Python', 'PHP', 'JS', 'EXAMPLES', 'HTML'], dtype=np.str) print("\nOriginal Array:") print(x1) print("count the lowest index of ‘P’:") r = np.char.find(x1, "P") print(r)
43
# Write a Python program to list home directory without absolute path. import os.path print(os.path.expanduser('~'))
15
# Write a NumPy program to convert a Python dictionary to a NumPy ndarray. import numpy as np from ast import literal_eval udict = """{"column0":{"a":1,"b":0.0,"c":0.0,"d":2.0}, "column1":{"a":3.0,"b":1,"c":0.0,"d":-1.0}, "column2":{"a":4,"b":1,"c":5.0,"d":-1.0}, "column3":{"a":3.0,"b":-1.0,"c":-1.0,"d":-1.0} }""" t = literal_eval(udict) print("\nOriginal dictionary:") print(t) print("Type: ",type(t)) result_nparra = np.array([[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()]) print("\nndarray:") print(result_nparra) print("Type: ",type(result_nparra))
56
# Write a NumPy program to create a 3x3 identity matrix. import numpy as np array_2D=np.identity(3) print('3x3 matrix:') print(array_2D)
19
# Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it. import numpy as np import os x = np.arange(10) y = np.arange(11, 20) print("Original arrays:") print(x) print(y) np.savez('temp_arra.npz', x=x, y=y) print("Load arrays from the 'temp_arra.npz' file:") with np.load('temp_arra.npz') as data: x2 = data['x'] y2 = data['y'] print(x2) print(y2)
60
# Write a Python program to format a number with a percentage. x = 0.25 y = -0.25 print("\nOriginal Number: ", x) print("Formatted Number with percentage: "+"{:.2%}".format(x)); print("Original Number: ", y) print("Formatted Number with percentage: "+"{:.2%}".format(y)); print()
37
# Write a Python program to compute the sum of non-zero groups (separated by zeros) of a given list of numbers. def test(lst): result = [] ele_val = 0 for digit in lst: if digit == 0: if ele_val != 0: result.append(ele_val) ele_val = 0 else: ele_val += digit if ele_val>0: result.append(ele_val) return result nums = [3,4,6,2,0,0,0,0,0,0,6,7,6,9,10,0,0,0,0,0,7,4,4,0,0,0,0,0,0,5,3,2,9,7,1,0,0,0] print("\nOriginal list:") print(nums) print("\nCompute the sum of non-zero groups (separated by zeros) of the said list of numbers:") print(test(nums))
76
# Write a Python program to Multiply 2d numpy array corresponding to 1d array # Python code to demonstrate # multiplication of 2d array # with 1d array    import numpy as np    ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) ini_array2 = np.array([0, 2, 3])    # printing initial arrays print("initial array", str(ini_array1))    # Multiplying arrays result = ini_array1 * ini_array2[:, np.newaxis]    # printing result print("New resulting array: ", result)
72
# Execute a String of Code in Python # Python program to illustrate use of exec to # execute a given code as string. # function illustrating how exec() functions. def exec_code():     LOC = """ def factorial(num):     fact=1     for i in range(1,num+1):         fact = fact*i     return fact print(factorial(5)) """     exec(LOC)       # Driver Code exec_code()
54
# Python Program to Form a Dictionary from an Object of a Class class A(object): def __init__(self): self.A=1 self.B=2 obj=A() print(obj.__dict__)
21
# Write a Pandas program to create a Pivot table and find the probability of survival by class, gender, solo boarding and port of embarkation. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table('survived', ['sex' , 'alone' ], [ 'embark_town', 'class' ]) print(result)
48
# Python Program to Generate all the Divisors of an Integer   n=int(input("Enter an integer:")) print("The divisors of the number are:") for i in range(1,n+1): if(n%i==0): print(i)
26
# Program to convert Decimal to Hexadecimal i=0 dec=int(input("Enter Decimal number: ")) Hex=['0']*50 while dec!=0:     rem=dec%16;     #Convert Integer to char     if rem<10:         Hex[i]=chr(rem+48)#48 Ascii=0         i+=1     else:         Hex[i]=chr(rem+55) #55 Ascii=7         i+=1     dec//=16 print("Hexadecimal number is:") for j in range(i-1,-1,-1):     print(Hex[j],end="")
39
# How to access different rows of a multidimensional NumPy array in Python # Importing Numpy module import numpy as np    # Creating a 3X3 2-D Numpy array arr = np.array([[10, 20, 30],                  [40, 5, 66],                  [70, 88, 94]])    print("Given Array :") print(arr)    # Access the First and Last rows of array res_arr = arr[[0,2]] print("\nAccessed Rows :") print(res_arr)
59
# Write a Python program to count number of items in a dictionary value that is a list. dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} ctr = sum(map(len, dict.values())) print(ctr)
32
# Write a Python program to extract the nth element from a given list of tuples. def extract_nth_element(test_list, n): result = [x[n] for x in test_list] return result students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] print ("Original list:") print(students) n = 0 print("\nExtract nth element ( n =",n,") from the said list of tuples:") print(extract_nth_element(students, n)) n = 2 print("\nExtract nth element ( n =",n,") from the said list of tuples:") print(extract_nth_element(students, n))
84
# Write a Pandas program to add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit. import pandas as pd nums = {'amount': ['10', '250', '3000', '40000', '500000']} print("Original dataframe:") df = pd.DataFrame(nums) print(df) print("\nAdd leading zeros:") df['amount'] = list(map(lambda x: x.zfill(10), df['amount'])) print(df)
55
# Write a Python program to Add Space between Potential Words # Python3 code to demonstrate working of # Add Space between Potential Words # Using loop + join() # initializing list test_list = ["gfgBest", "forGeeks", "andComputerScience"] # printing original list print("The original list : " + str(test_list)) res = [] # loop to iterate all strings for ele in test_list:     temp = [[]]     for char in ele:                   # checking for upper case character         if char.isupper():             temp.append([])                       # appending character at latest list         temp[-1].append(char)           # joining lists after adding space     res.append(' '.join(''.join(ele) for ele in temp)) # printing result print("The space added list of strings : " + str(res))
109
# Program to display a lower triangular matrix # 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()]) #Display Lower triangular matrix print("Lower Triangular Matrix is:\n") for i in range(len(matrix)): for j in range(len(matrix[0])): if i<j: print("0 ",end="") else: print(matrix[i][j],end=" ") print()
71
# Write a Pandas program to check whether only space is present in a given column of a DataFrame. import pandas as pd df = pd.DataFrame({ 'company_code': ['Abcd','EFGF ', ' ', 'abcd', ' '], 'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'], 'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]}) print("Original DataFrame:") print(df) print("\nIs space is present?") df['company_code_is_title'] = list(map(lambda x: x.isspace(), df['company_code'])) print(df)
57
# Write a Python program to chose specified number of colours from three different colours and generate all the combinations with repetitions. from itertools import combinations_with_replacement def combinations_colors(l, n): return combinations_with_replacement(l,n) l = ["Red","Green","Blue"] print("Original List: ",l) n=1 print("\nn = 1") print(list(combinations_colors(l, n))) n=2 print("\nn = 2") print(list(combinations_colors(l, n))) n=3 print("\nn = 3") print(list(combinations_colors(l, n)))
55
# Write a Python program to Sort dictionaries list by Key’s Value list index # Python3 code to demonstrate working of  # Sort dictionaries list by Key's Value list index # Using sorted() + lambda    # initializing lists test_list = [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10},               {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19},              {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}]    # printing original list print("The original list : " + str(test_list))    # initializing K  K = "Gfg"    # initializing idx  idx = 2    # using sorted() to perform sort in basis of 1 parameter key and  # index res = sorted(test_list, key = lambda ele: ele[K][idx])        # printing result  print("The required sort order : " + str(res))
130
# Write a Python program to convert a string to a list. import ast color ="['Red', 'Green', 'White']" print(ast.literal_eval(color))
19
# Write a Python program to remove a specified column from a given nested list. def remove_column(nums, n): for i in nums: del i[n] return nums list1 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]] n = 0 print("Original Nested list:") print(list1) print("After removing 1st column:") print(remove_column(list1, n)) list2 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]] n = 2 print("\nOriginal Nested list:") print(list2) print("After removing 3rd column:") print(remove_column(list2, n))
74
# Write a NumPy program to count a given word in each row of a given array of string values. import numpy as np str1 = np.array([['Python','NumPy','Exercises'], ['Python','Pandas','Exercises'], ['Python','Machine learning','Python']]) print("Original array of string values:") print(str1) print("\nCount 'Python' row wise in the above array of string values:") print(np.char.count(str1, 'Python'))
49
# Write a Python program that reads a given expression and evaluates it. #https://bit.ly/2lxQysi import re print("Input number of data sets:") class c(int): def __add__(self,n): return c(int(self)+int(n)) def __sub__(self,n): return c(int(self)-int(n)) def __mul__(self,n): return c(int(self)*int(n)) def __truediv__(self,n): return c(int(int(self)/int(n))) for _ in range(int(input())): print("Input an expression:") print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))
47
# Write a Python function that takes a list of words and return the longest word and the length of the longest one. def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][0], word_len[-1][1] result = find_longest_word(["PHP", "Exercises", "Backend"]) print("\nLongest word: ",result[1]) print("Length of the longest word: ",result[0])
52
# Write a Pandas program to find out the alcohol consumption of a given year from the 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("\nThe world alcohol consumption details in the year 1985:") print(w_a_con[w_a_con['Year']==1985].head(10)) print("\nThe world alcohol consumption details in the year 1989:") print(w_a_con[w_a_con['Year']==1989].head(10))
59
# Write a Python program to find missing and additional values in two lists. list1 = ['a','b','c','d','e','f'] list2 = ['d','e','f','g','h'] print('Missing values in second list: ', ','.join(set(list1).difference(list2))) print('Additional values in second list: ', ','.join(set(list2).difference(list1)))
34
# Write a Python program to insert an element at a specified position into a given list. def insert_spec_position(x, n_list, pos): return n_list[:pos-1]+[x]+n_list[pos-1:] n_list = [1,1,2,3,4,4,5,1] print("Original list:") print(n_list) kth_position = 3 x = 12 result = insert_spec_position(x, n_list, kth_position) print("\nAfter inserting an element at kth position in the said list:") print(result)
52
# Write a Pandas program to calculate the frequency counts of each unique value of a given series. import pandas as pd import numpy as np num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40))) print("Original Series:") print(num_series) print("Frequency of each unique value of the said series.") result = num_series.value_counts() print(result)
47
# Write a Python program to find smallest window that contains all characters of a given string. from collections import defaultdict def find_sub_string(str): str_len = len(str) # Count all distinct characters. dist_count_char = len(set([x for x in str])) ctr, start_pos, start_pos_index, min_len = 0, 0, -1, 9999999999 curr_count = defaultdict(lambda: 0) for i in range(str_len): curr_count[str[i]] += 1 if curr_count[str[i]] == 1: ctr += 1 if ctr == dist_count_char: while curr_count[str[start_pos]] > 1: if curr_count[str[start_pos]] > 1: curr_count[str[start_pos]] -= 1 start_pos += 1 len_window = i - start_pos + 1 if min_len > len_window: min_len = len_window start_pos_index = start_pos return str[start_pos_index: start_pos_index + min_len] str1 = "asdaewsqgtwwsa" print("Original Strings:\n",str1) print("\nSmallest window that contains all characters of the said string:") print(find_sub_string(str1))
121
# Write a NumPy program to get the block-sum (block size is 5x5) from a given array of shape 25x25. import numpy as np arra1 = np.ones((25,25)) k = 5 print("Original arrays:") print(arra1) result = np.add.reduceat(np.add.reduceat(arra1, np.arange(0, arra1.shape[0], k), axis=0), np.arange(0, arra1.shape[1], k), axis=1) print("\nBlock-sum (5x5) of the said array:") print(result)
51
# How to Build Web scraping bot in Python # These are the imports to be made import time from selenium import webdriver from datetime import datetime
27
# Python Program to Find the Second Largest Number in a List Using Bubble Sort a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=int(input("Enter element:")) a.append(b) for i in range(0,len(a)): for j in range(0,len(a)-i-1): if(a[j]>a[j+1]): temp=a[j] a[j]=a[j+1] a[j+1]=temp print('Second largest number is:',a[n-2])
43
# Write a NumPy program to compute the line graph of a set of data. import numpy as np import matplotlib.pyplot as plt arr = np.random.randint(1, 50, 10) y, x = np.histogram(arr, bins=np.arange(51)) fig, ax = plt.subplots() ax.plot(x[:-1], y) fig.show()
40
# Write a Pandas program to create a histograms plot of opening, closing, high, low stock prices of Alphabet Inc. 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[['Open','Close','High','Low']] #df3 = df2.set_index('Date') plt.figure(figsize=(25,25)) df2.plot.hist(alpha=0.5) plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='blue') plt.show()
75
# Create Pandas Series using NumPy functions in Python # import pandas and numpy import pandas as pd import numpy as np    # series with numpy linspace()  ser1 = pd.Series(np.linspace(3, 33, 3)) print(ser1)    # series with numpy linspace() ser2 = pd.Series(np.linspace(1, 100, 10)) print("\n", ser2)   
45
# Write a Python program to find the index of the first element in the given list that satisfies the provided testing function. def find_index(nums, fn): return next(i for i, x in enumerate(nums) if fn(x)) print(find_index([1, 2, 3, 4], lambda n: n % 2 == 1))
46
# Write a Python program to remove a tag from a given tree of html document and destroy it and its contents. from bs4 import BeautifulSoup html_content = '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>' soup = BeautifulSoup(html_content, "lxml") print("Original Markup:") a_tag = soup.a print(a_tag) new_tag = soup.a.decompose() print("After decomposing:") print(new_tag)
47
# Write a Python program to append the same value /a list multiple times to a list/list-of-lists. print("Add a value(7), 5 times, to a list:") nums = [] nums += 5 * ['7'] print(nums) nums1 = [1,2,3,4] print("\nAdd 5, 6 times, to a list:") nums1 += 6 * [5] print(nums1) print("\nAdd a list, 4 times, to a list of lists:") nums1 = [] nums1 += 4 * [[1,2,5]] print(nums1) print("\nAdd a list, 4 times, to a list of lists:") nums1 = [[5,6,7]] nums1 += 4 * [[1,2,5]] print(nums1)
88
# Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple def last(n): return n[-1]   def sort(tuples): return sorted(tuples, key=last)   a=input("Enter a list of tuples:") print("Sorted:") print(sort(a))
35
# Write a Python program to create a shallow copy of a given dictionary. Use copy.copy import copy nums_x = {"a":1, "b":2, 'cc':{"c":3}} print("Original dictionary: ", nums_x) nums_y = copy.copy(nums_x) print("\nCopy of the said list:") print(nums_y) print("\nChange the value of an element of the original dictionary:") nums_x["cc"]["c"] = 10 print(nums_x) print("\nSecond dictionary:") print(nums_y) nums = {"x":1, "y":2, 'zz':{"z":3}} nums_copy = copy.copy(nums) print("\nOriginal dictionary :") print(nums) print("\nCopy of the said list:") print(nums_copy) print("\nChange the value of an element of the original dictionary:") nums["zz"]["z"] = 10 print("\nFirst dictionary:") print(nums) print("\nSecond dictionary (copy):") print(nums_copy)
91
# Write a Python program to sort each sublist of strings in a given list of lists. def sort_sublists(input_list): result = list(map(sorted, input_list)) return result color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]] print("\nOriginal list:") print(color1) print("\nAfter sorting each sublist of the said list of lists:") print(sort_sublists(color1))
48
# Write a Pandas program to create a horizontal stacked bar plot of opening, closing stock prices of Alphabet Inc. 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-4-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[['Date', 'Open', 'Close']] df3 = df2.set_index('Date') plt.figure(figsize=(20,20)) df3.plot.barh(stacked=True) plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020 to 30-04-2020', fontsize=12, color='black') plt.show()
74