code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to count the number of each character of a given text of a text file. import collections import pprint file_input = input('File Name: ') with open(file_input, 'r') as info: count = collections.Counter(info.read().upper()) value = pprint.pformat(count) print(value)
41
# Write a Python program to sort a list alphabetically in a dictionary. num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]} sorted_dict = {x: sorted(y) for x, y in num.items()} print(sorted_dict)
37
# Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user. num = int(input("Enter a number: ")) mod = num % 2 if mod > 0: print("This is an odd number.") else: print("This is an even number.")
53
# How to create an empty and a full NumPy array in Python # python program to create # Empty and Full Numpy arrays    import numpy as np       # Create an empty array empa = np.empty((3, 4), dtype=int) print("Empty Array") print(empa)    # Create a full array flla = np.full([3, 3], 55, dtype=int) print("\n Full Array...
56
# Program to print series 0 2 6 12 20 30 42 ...N n=int(input("Enter the range of number(Limit):"))i=1while i<=n:    print((i*i)-i,end=" ")    i+=1
22
# Write a Python code to send cookies to a given server and access cookies from the response of a server. import requests url = 'http://httpbin.org/cookies' # A dictionary (my_cookies) of cookies to send to the specified url. my_cookies = dict(cookies_are='Cookies parameter use to send cookies to the server') r = re...
75
# Using dictionary to remap values in Pandas DataFrame columns in Python # importing pandas as pd import pandas as pd    # Creating the DataFrame df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'C...
44
# Write a Python program to Closest Pair to Kth index element in Tuple # Python3 code to demonstrate working of  # Closest Pair to Kth index element in Tuple # Using enumerate() + loop    # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]    # printing original list print("The original list ...
132
# Write a Pandas program to create an index labels by using 64-bit integers, using floating-point numbers in a given dataframe. import pandas as pd print("Create an Int64Index:") df_i64 = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], ...
133
# Find out all Disarium numbers present within a given range import math print("Enter a range:") range1=int(input()) range2=int(input()) print("Disarium numbers between ",range1," and ",range2," are: ") for i in range(range1,range2+1):     num =i     c = 0     while num != 0:         num //= 10         c += 1     nu...
76
# Write a Python program to find the factorial of a number using itertools module. import itertools as it import operator as op def factorials_nums(n): result = list(it.accumulate(it.chain([1], range(1, 1 + n)), op.mul)) return result; print("Factorials of 5 :", factorials_nums(5)) print("Factorials ...
45
# Write a Python program to get a datetime or timestamp representation from current datetime. import arrow a = arrow.utcnow() print("Datetime representation:") print(a.datetime) b = a.timestamp print("\nTimestamp representation:") print(b)
29
# Write a Python program to create a new Arrow object, representing the "ceiling" of the timespan of the Arrow object in a given timeframe using arrow module. The timeframe can be any datetime property like day, hour, minute. import arrow print(arrow.utcnow()) print("Hour ceiling:") print(arrow.utcnow().ceil('hour')...
51
# Write a Python program to compare two unordered lists (not sets). from collections import Counter def compare_lists(x, y): return Counter(x) == Counter(y) n1 = [20, 10, 30, 10, 20, 30] n2 = [30, 20, 10, 30, 20, 50] print(compare_lists(n1, n2))
41
# Write a Pandas program to get the average mean of the UFO (unidentified flying object) sighting was reported. import pandas as pd #Source: https://bit.ly/32kGinQ df = pd.read_csv(r'ufo.csv') df['date_documented'] = df['date_documented'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) # Add a...
129
# Write a Python program to remove specific words from a given list using lambda. def remove_words(list1, remove_words): result = list(filter(lambda word: word not in remove_words, list1)) return result colors = ['orange', 'red', 'green', 'blue', 'white', 'black'] remove_colors = ['orange','black'] ...
57
# Write a Python program to Multiple indices Replace in String # Python3 code to demonstrate working of  # Multiple indices Replace in String # Using loop + join()    # initializing string test_str = 'geeksforgeeks is best'    # printing original string print("The original string is : " + test_str)    # initializing ...
101
# Write a Python program to insert a specified element in a given list after every nth element. def inset_element_list(lst, x, n): i = n while i < len(lst): lst.insert(i, x) i+= n+1 return lst nums = [1, 3, 5, 7, 9, 11,0, 2, 4, 6, 8, 10,8,9,0,4,3,0] print("Original list:") print(nums) x ...
87
# Print all permutations of a string using recursion import java.util.Scanner;public class AnagramString { static void rotate(char str[],int n) {    int j,size=str.length;    int p=size-n;    char temp=str[p];     for(j=p+1;j<size;j++)        str[j-1]=str[j];     str[j-1]=temp; } static void doAnagram(char str[], int...
92
# Write a Python program to add two given lists and find the difference between lists. Use map() function. def addition_subtrction(x, y): return x + y, x - y nums1 = [6, 5, 3, 9] nums2 = [0, 1, 7, 7] print("Original lists:") print(nums1) print(nums2) result = map(addition_subtrction, nums1, nums2) print("\nRes...
52
# numpy.loadtxt() in Python # Python program explaining  # loadtxt() function import numpy as geek    # StringIO behaves like a file object from io import StringIO       c = StringIO("0 1 2 \n3 4 5") d = geek.loadtxt(c)    print(d)
38
# Write a Python program to compute sum of digits of a given string. def sum_digits_string(str1): sum_digit = 0 for x in str1: if x.isdigit() == True: z = int(x) sum_digit = sum_digit + z return sum_digit print(sum_digits_string("123abcd45")) print(sum_digits_string...
39
# Python Program to Implement Fibonacci Heap import math   class FibonacciTree: def __init__(self, key): self.key = key self.children = [] self.order = 0   def add_at_end(self, t): self.children.append(t) self.order = self.order + 1     class FibonacciHeap: def __in...
250
# Write a Python program to check whether multiple variables have the same value. x = 20 y = 20 z = 20 if x == y == z == 20: print("All variables have same value!")
36
# Write a Python program to convert a given unicode list to a list contains strings. def unicode_to_str(lst): result = [str(x) for x in lst] return result students = [u'S001', u'S002', u'S003', u'S004'] print("Original lists:") print(students) print(" Convert the said unicode list to a list contains strings...
48
# Write a NumPy program to create a 2d array with 1 on the border and 0 inside. import numpy as np x = np.ones((5,5)) print("Original array:") print(x) print("1 on the border and 0 inside in the array") x[1:-1,1:-1] = 0 print(x)
42
# Write a Python Program to print a number diamond of any given size N in Rangoli Style def print_diamond(size):            # print the first triangle     # (the upper half)     for i in range (size):                    # print from first row till         # middle row         rownum = i + 1         num_alphabet = 2 *...
404
# Write a Python program to find the details of a given zip code using Nominatim API and GeoPy package. from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geoapiExercises") zipcode1 = "99501" print("\nZipcode:",zipcode1) location = geolocator.geocode(zipcode1) print("Details of the said pincode...
80
# Write a Python program to move spaces to the front of a given string. def move_Spaces_front(str1): noSpaces_char = [ch for ch in str1 if ch!=' '] spaces_char = len(str1) - len(noSpaces_char) result = ' '*spaces_char result = '"'+result + ''.join(noSpaces_char)+'"' return(result) print(move_Spaces_front(...
49
# rite a Python program that accepts a string and calculate the number of digits and letters. s = input("Input a string") d=l=0 for c in s: if c.isdigit(): d=d+1 elif c.isalpha(): l=l+1 else: pass print("Letters", l) print("Digits", d)
39
# Write a Python program to Swap commas and dots in a String # Python code to replace, with . and vice-versa def Replace(str1):     maketrans = str1.maketrans     final = str1.translate(maketrans(',.', '.,', ' '))     return final.replace(',', ", ") # Driving Code string = "14, 625, 498.002" print(Replace(string)...
46
# Write a Python program to get the cumulative sum of the elements of a given list. from itertools import accumulate def cumsum(lst): return list(accumulate(lst)) nums = [1,2,3,4] print("Original list elements:") print(nums) print("Cumulative sum of the elements of the said list:") print(cumsum(nums)) nums = [-1,...
59
# Write a Pandas program to create a line plot of the historical 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-09-30') ...
74
# Write a Python program to get the Fibonacci series between 0 to 50. x,y=0,1 while y<50: print(y) x,y = y,x+y
21
# Write a Python program to get the top three items in a shop. from heapq import nlargest from operator import itemgetter items = {'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24} for name, value in nlargest(3, items.items(), key=itemgetter(1)): print(name, value)
41
# Write a NumPy program to test element-wise for complex number, real number of a given array. Also test whether a given number is a scalar type or not. import numpy as np a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j]) print("Original array") print(a) print("Checking for complex number:") print(np.iscomplex(a)) print("Ch...
60
# Write a Python program to get the array size of types unsigned integer and float. from array import array a = array("I", (12,25)) print(a.itemsize) a = array("f", (12.236,36.36)) print(a.itemsize)
30
# Write a Python program to count the most common words in a dictionary. words = [ 'red', 'green', 'black', 'pink', 'black', 'white', 'black', 'eyes', 'white', 'black', 'orange', 'pink', 'pink', 'red', 'red', 'white', 'orange', 'white', "black", 'pink', 'green', 'green', 'pink', 'green', 'pink', 'white',...
58
# Write a NumPy program to stack 1-D arrays as row wise. import numpy as np print("\nOriginal arrays:") x = np.array((1,2,3)) y = np.array((2,3,4)) print("Array-1") print(x) print("Array-2") print(y) new_array = np.row_stack((x, y)) print("\nStack 1-D arrays as rows wise:") print(new_array)
39
# Write a Python program to print a dictionary line by line. students = {'Aex':{'class':'V', 'rolld_id':2}, 'Puja':{'class':'V', 'roll_id':3}} for a in students: print(a) for b in students[a]: print (b,':',students[a][b])
29
# Write a NumPy program to convert a given vector of integers to a matrix of binary representation. import numpy as np nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15]) print("Original vector:") print(nums) bin_nums = ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) print("\nBinary representation of the sai...
50
# Write a Python program to Convert Nested Tuple to Custom Key Dictionary # Python3 code to demonstrate working of  # Convert Nested Tuple to Custom Key Dictionary # Using list comprehension + dictionary comprehension    # initializing tuple test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))    # printing o...
97
# Write a Python program to Reverse a numpy array # Python code to demonstrate # how to reverse numpy array # using shortcut method    import numpy as np    # initialising numpy array ini_array = np.array([1, 2, 3, 6, 4, 5])    # printing initial ini_array print("initial array", str(ini_array))    # printing type of ...
72
# Python Program to Find the Smallest Divisor of an Integer   n=int(input("Enter an integer:")) a=[] for i in range(2,n+1): if(n%i==0): a.append(i) a.sort() print("Smallest divisor is:",a[0])
25
# Write a Pandas program to split the following dataframe into groups and count unique values of 'value' column. import pandas as pd df = pd.DataFrame({ 'id': [1, 1, 2, 3, 3, 4, 4, 4], 'value': ['a', 'a', 'b', None, 'a', 'a', None, 'b'] }) print("Original DataFrame:") print(df) print("Count unique values:") ...
53
# Write a NumPy program to split the element of a given array to multiple lines. import numpy as np x = np.array(['Python\Exercises, Practice, Solution'], dtype=np.str) print("Original Array:") print(x) r = np.char.splitlines(x) print(r)
33
# Write a Python program to sort a tuple by its float element. price = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')] print( sorted(price, key=lambda x: float(x[1]), reverse=True))
27
# Different ways to iterate over rows in Pandas Dataframe in Python # import pandas package as pd import pandas as pd    # Define a dictionary containing students data data = {'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka'],                 'Age': [21, 19, 20, 18],                 'Stream': ['Math', 'Commerce', 'A...
96
# Write a Python program to sum a specific column of a list in a given list of lists. def sum_column(nums, C): result = sum(row[C] for row in nums) return result nums = [ [1,2,3,2], [4,5,6,2], [7,8,9,5], ] print("Original list of lists:") print(nums) column = 0 print("\nSum:...
85
# Write a Pandas program to select first 2 rows, 2 columns and specific two columns from World alcohol consumption dataset. import pandas as pd # World alcohol consumption data w_a_con = pd.read_csv('world_alcohol.csv') print("World alcohol consumption sample data:") print(w_a_con.head()) print("\nSelect first 2 row...
56
# Write a Python program to Replace duplicate Occurrence in String # Python3 code to demonstrate working of  # Replace duplicate Occurrence in String # Using split() + enumerate() + loop    # initializing string test_str = 'Gfg is best . Gfg also has Classes now. \                 Classes help understand better . '  ...
130
# Write a Pandas program to import some excel data (coalpublic2013.xlsx ) skipping first twenty rows into a Pandas dataframe. import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx', skiprows = 20) df
35
# Write a Python program to count number of vowels using sets in given string # Python3 code to count vowel in  # a string using set    # Function to count vowel def vowel_count(str):            # Initializing count variable to 0     count = 0            # Creating a set of vowels     vowel = set("aeiouAEIOU")       ...
100
# Write a NumPy program to convert a NumPy array into a csv file. import numpy data = numpy.asarray([ [10,20,30], [40,50,60], [70,80,90] ]) numpy.savetxt("test.csv", data, delimiter=",")
26
# Write a Python program to Merging two Dictionaries # Python code to merge dict using update() method def Merge(dict1, dict2):     return(dict2.update(dict1))       # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # This return None print(Merge(dict1, dict2)) # changes made in dict2 print(dict2)
49
# Write a NumPy program to convert a list and tuple into arrays. import numpy as np my_list = [1, 2, 3, 4, 5, 6, 7, 8] print("List to array: ") print(np.asarray(my_list)) my_tuple = ([8, 4, 6], [1, 2, 3]) print("Tuple to array: ") print(np.asarray(my_tuple))
45
# Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number. def sum_of_cubes(n): n -= 1 total = 0 while n > 0: total += n * n * n n -= 1 return total print("Sum of cubes smaller than the specified number: ",sum_of_c...
60
# Compute the median of the flattened NumPy array in Python # importing numpy as library import numpy as np       # creating 1 D array with odd no of  # elements x_odd = np.array([1, 2, 3, 4, 5, 6, 7]) print("\nPrinting the Original array:") print(x_odd)    # calculating median med_odd = np.median(x_odd) print("\nMed...
63
# Python Program to Calculate the Number of Words and the Number of Characters Present in a String string=raw_input("Enter string:") char=0 word=1 for i in string: char=char+1 if(i==' '): word=word+1 print("Number of words in the string:") print(word) print("Number of characters in the string:...
44
# Write a Python program to print odd numbers in a List # Python program to print odd Numbers in a List    # list of numbers list1 = [10, 21, 4, 45, 66, 93]    # iterating each number in list for num in list1:            # checking condition     if num % 2 != 0:        print(num, end = " ")
58
# How to Add padding to a tkinter widget only on one side in Python # Python program to add padding # to a widget only on left-side    # Import the library tkinter from tkinter import *    # Create a GUI app app = Tk()    # Give title to your GUI app app.title("Vinayak App")    # Maximize the window screen width = a...
99
# Write a Python program to delete all occurrences of a specified character in a given string. def delete_all_occurrences(str1, ch): result = str1.replace(ch, "") return(result) str_text = "Delete all occurrences of a specified character in a given string" print("Original string:") print(str_text) print("...
46
# Write a Python program to reverse a string. def reverse_string(str1): return ''.join(reversed(str1)) print() print(reverse_string("abcdef")) print(reverse_string("Python Exercises.")) print()
18
# Write a Python program to shuffle and print a specified list. from random import shuffle color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] shuffle(color) print(color)
26
# Write a Python program to generate a float between 0 and 1, inclusive and generate a random float within a specific range. Use random.uniform() import random print("Generate a float between 0 and 1, inclusive:") print(random.uniform(0, 1)) print("\nGenerate a random float within a range:") random_float = random.un...
49
# Scrape Table from Website using Write a Python program to Selenium <!DOCTYPE html> <html>    <head>       <title>Selenium Table</title>    </head>    <body>       <table border="1">         <thead>          <tr>             <th>Name</th>             <th>Class</th>          </tr>         </thead>         <tbody>    ...
41
# Write a Python program to sort a list of elements using the merge sort algorithm. def mergeSort(nlist): print("Splitting ",nlist) if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j...
73
# Calculate the QR decomposition of a given matrix using NumPy in Python import numpy as np       # Original matrix matrix1 = np.array([[1, 2, 3], [3, 4, 5]]) print(matrix1)    # Decomposition of the said matrix q, r = np.linalg.qr(matrix1) print('\nQ:\n', q) print('\nR:\n', r)
43
# Write a NumPy program to append values to the end of an array. import numpy as np x = [10, 20, 30] print("Original array:") print(x) x = np.append(x, [[40, 50, 60], [70, 80, 90]]) print("After append values to the end of the array:") print(x)
45
# Write a NumPy program to get the element-wise remainder of an array of division. import numpy as np x = np.arange(7) print("Original array:") print(x) print("Element-wise remainder of division:") print(np.remainder(x, 5))
31
# Write a Python program to extend a list without append. x = [10, 20, 30] y = [40, 50, 60] x[:0] =y print(x)
24
# Apply uppercase to a column in Pandas dataframe in Python # Import pandas package  import pandas as pd       # making data frame  data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")       # calling head() method   # storing in new variable  data_top = data.head(10)       # display  data...
41
# Write a Python Program for Pigeonhole Sort # Python program to implement Pigeonhole Sort */    # source code : "https://en.wikibooks.org/wiki/ #   Algorithm_Implementation/Sorting/Pigeonhole_sort" def pigeonhole_sort(a):     # size of range of values in the list      # (ie, number of pigeonholes we need)     my_min...
143
# Write a Python code to create a program for Bitonic Sort. #License: https://bit.ly/2InTS3W # Python program for Bitonic Sort. Note that this program # works only when size of input is a power of 2. # The parameter dir indicates the sorting direction, ASCENDING # or DESCENDING; if (a[i] > a[j]) agrees with the...
297
# Split a text column into two columns in Pandas DataFrame in Python # import Pandas as pd import pandas as pd     # create a new data frame df = pd.DataFrame({'Name': ['John Larter', 'Robert Junior', 'Jonny Depp'],                    'Age':[32, 34, 36]})     print("Given Dataframe is :\n",df)     # bydefault splitti...
64
# How to Calculate the determinant of a matrix using NumPy in Python # importing Numpy package import numpy as np    # creating a 2X2 Numpy matrix n_array = np.array([[50, 29], [30, 44]])    # Displaying the Matrix print("Numpy Matrix is:") print(n_array)    # calculating the determinant of matrix det = np.linalg.det...
56
# Python Program to Search for an Element in the Linked List without using Recursion class Node: def __init__(self, data): self.data = data self.next = None   class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if sel...
160
# Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character test_string=raw_input("Enter string:") l=test_string.split() d={} for word in l: if(word[0] not in d.keys()): d[word[0]]=[] d[word[0]].append(word) else: if(word not in d...
45
# Write a NumPy program to suppresses the use of scientific notation for small numbers in NumPy array. import numpy as np x=np.array([1.6e-10, 1.6, 1200, .235]) print("Original array elements:") print(x) print("Print array values with precision 3:") np.set_printoptions(suppress=True) print(x)
38
# Write a Python program to Remove empty List from List # Python3 code to demonstrate  # Remove empty List from List # using list comprehension    # Initializing list  test_list = [5, 6, [], 3, [], [], 9]    # printing original list  print("The original list is : " + str(test_list))    # Remove empty List from List #...
84
# Write a Pandas program to generate sequences of fixed-frequency dates and time spans. import pandas as pd dtr = pd.date_range('2018-01-01', periods=12, freq='H') print("Hourly frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='min') print("\nMinutely frequency:") print(dtr) dtr = pd.date_r...
101
# Calculate the sum of all columns in a 2D NumPy array in Python # importing required libraries import numpy # explicit function to compute column wise sum def colsum(arr, n, m):     for i in range(n):         su = 0;         for j in range(m):             su += arr[j][i]         print(su, end = " ")    # creatin...
93
# Write a NumPy program to calculate average values of two given NumPy arrays. import numpy as np array1 = [[0, 1], [2, 3]] array2 = [[4, 5], [0, 3]] print("Original arrays:") print(array1) print(array2) print("Average values of two said numpy arrays:") result = (np.array(array1) + np.array(array2)) / 2 print(result...
49
# Write a Python program to Replace Substrings from String List # Python3 code to demonstrate  # Replace Substrings from String List # using loop + replace() + enumerate()    # Initializing list1 test_list1 = ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] test_list2 = [['Geeks', 'Gks'], ['...
118
# Count number of uppercase letters in a string using Recursion count=0def NumberOfUpperCase(str,i):    global count    if (str[i] >= 'A' and str[i] <= 'Z'):        count+=1    if (i >0):        NumberOfUpperCase(str, i - 1)    return countstr=input("Enter your String:")NoOfUppercase=NumberOfUpperCase(str,len(str)-1)...
53
# Write a Python program to check whether the string is Symmetrical or Palindrome # Python program to demonstrate # symmetry and palindrome of the # string # Function to check whether the # string is palindrome or not def palindrome(a):        # finding the mid, start     # and last index of the string     mid = ...
269
# Getting Unique values from a column in Pandas dataframe in Python # import pandas as pd import pandas as pd    gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url)    record.head()
33
# Write a Python program to convert a list of dictionaries into a list of values corresponding to the specified key. def test(lsts, key): return [x.get(key) for x in lsts] students = [ { 'name': 'Theodore', 'age': 18 }, { 'name': 'Mathew', 'age': 22 }, { 'name': 'Roxanne', 'age': 20 }, { 'name': 'David',...
80
# Write a Pandas program to check whether two given words present in a 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'], 'address': ['9910 Surrey Ave.','92 N. Bis...
75
# Write a Pandas program to create a subtotal of "Labor Hours" against MSHA ID from the given excel data (coalpublic2013.xlsx ). import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df_sub=df[["MSHA ID","Labor_Hours"]].groupby('MSHA ID').sum() df_sub
37
# Write a Python function to create the HTML string with tags around the word(s). def add_tags(tag, word): return "<%s>%s</%s>" % (tag, word, tag) print(add_tags('i', 'Python')) print(add_tags('b', 'Python Tutorial'))
29
# Python Program for Depth First Binary Tree Search without using Recursion class BinaryTree: def __init__(self, key=None): self.key = key self.left = None self.right = None   def set_root(self, key): self.key = key   def insert_left(self, new_node): self.left = new...
244
# Convert binary to string using Python # Python3 code to demonstrate working of  # Converting binary to string # Using BinarytoDecimal(binary)+chr()        # Defining BinarytoDecimal() function def BinaryToDecimal(binary):                binary1 = binary      decimal, i, n = 0, 0, 0     while(binary != 0):          ...
203
# Write a Python program to Cloning or Copying a list # Python program to copy or clone a list # Using the Slice Operator def Cloning(li1):     li_copy = li1[:]     return li_copy    # Driver Code li1 = [4, 8, 2, 10, 15, 18] li2 = Cloning(li1) print("Original List:", li1) print("After Cloning:", li2)
52
# Write a Pandas program to drop the rows where all elements are missing in a given DataFrame. import pandas as pd import numpy as np pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[np.nan,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.na...
55
# Python Program to Determine Whether a Given Number is Even or Odd Recursively def check(n): if (n < 2): return (n % 2 == 0) return (check(n - 2)) n=int(input("Enter number:")) if(check(n)==True): print("Number is even!") else: print("Number is odd!")
40
# Write a Python program to create two strings from a given string. Create the first string using those character which occurs only once and create the second string which consists of multi-time occurring characters in the said string. from collections import Counter def generateStrings(input): str_char_ctr ...
81
# Check whether a given number is a strong number or not '''Write a Python program to check whether a given number is a strong number or not. or  Write a program to check whether a given number is a strong number or not using Python ''' num=int(input("Enter a number:")) num2=num sum=0 while(num!=0):    fact=1    ...
76
# Write a Python program to sort a list of elements using Time sort. # License https://bit.ly/2InTS3W def binary_search(lst, item, start, end): if start == end: if lst[start] > item: return start else: return start + 1 if start > end: return start mid = (s...
215
# Write a Python program to filter the height and width of students, which are stored in a dictionary using lambda. def filter_data(students): result = dict(filter(lambda x: (x[1][0], x[1][1]) > (6.0, 70), students.items())) return result students = {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), '...
62