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") print(flla)
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 = requests.get(url, cookies = my_cookies) print(r.text) # Accessing cookies with Requests # url = 'http://WebsiteName/cookie/setting/url' # res = requests.get(url) # Value of cookies # print(res.cookies['cookie_name'])
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'],                     'Cost':[10000, 5000, 15000, 2000]})    # Print the dataframe print(df)
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 is : " + str(test_list))    # initializing tuple tup = (17, 23)    # initializing K  K = 1    # Closest Pair to Kth index element in Tuple # Using enumerate() + loop min_dif, res = 999999999, None for idx, val in enumerate(test_list):     dif = abs(tup[K - 1] - val[K - 1])     if dif < min_dif:         min_dif, res = dif, idx    # printing result  print("The nearest tuple to Kth index element is : " + str(test_list[res])) 
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'], '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=[1, 2, 3, 4, 5, 6]) print(df_i64) print("\nView the Index:") print(df_i64.index) print("\nFloating-point labels using Float64Index:") df_f64 = 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=[.1, .2, .3, .4, .5, .6]) print(df_f64) print("\nView the Index:") print(df_f64.index)
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     num = i     sum = 0     while num != 0:         rem = num % 10         sum += math.pow(rem, c)         num //= 10         c -= 1     if sum == i:         print(i,end=" ")
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 of 9 :", factorials_nums(9))
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')) print("\nMinute ceiling:") print(arrow.utcnow().ceil('minute')) print("\nSecond ceiling:") print(arrow.utcnow().ceil('second'))
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 new column instance, this adds a value to each instance of ufo sighting df['instance'] = 1 # set index to time, this makes df a time series df and then you can apply pandas time series functions. df.set_index(df['date_documented'], drop=True, inplace=True) # create another df by resampling the original df and counting the instance column by Month ('M' is resample by month) ufo2 = pd.DataFrame(df['instance'].resample('M').count()) # just to find month of resampled observation ufo2['date_documented'] = pd.to_datetime(ufo2.index.values) ufo2['month'] = ufo2['date_documented'].apply(lambda x: x.month) print("Average mean of the UFO (unidentified flying object) sighting was reported:") print(ufo2.groupby(by='month').mean())
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'] print("Original list:") print(colors) print("\nRemove words:") print(remove_colors) print("\nAfter removing the specified words from the said list:") print(remove_words(colors, remove_colors))
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 list  test_list = [2, 4, 7, 10]    # initializing repl char repl_char = '*'    # Multiple indices Replace in String # Using loop + join() temp = list(test_str) for idx in test_list:     temp[idx] = repl_char res = ''.join(temp)    # printing result  print("The String after performing replace : " + str(res)) 
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 = 20 n = 4 print("\nInsert",x,"in said list after every",n,"th element:") print(inset_element_list(nums, x, n)) chars = ['s','d','f','j','s','a','j','d','f','d'] print("\nOriginal list:") print(chars) x = 'Z' n = 3 print("\nInsert",x,"in said list after every",n,"th element:") print(inset_element_list(chars, x, n))
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 n) {     if(n==1)         return;     for(int j=0;j<n;j++)      {         doAnagram(str,n-1);         if(n==2)          {             display(str);          }         rotate(str,n);      } } static void display(char str[]) {  int size=str.length,j;     for(j=0; j<size; j++)     System.out.print(str[j]);     System.out.print(" "); } public static void main(String[] args) {           Scanner cs=new Scanner(System.in);           String str1;           System.out.print("Enter your String:");           str1=cs.nextLine();           char str[]=str1.toCharArray();           System.out.print("All permutations of a Given string are:");           doAnagram(str,str.length);         cs.close(); } }
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("\nResult:") print(list(result))
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("abcd1234"))
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 __init__(self): self.trees = [] self.least = None self.count = 0   def insert(self, key): new_tree = FibonacciTree(key) self.trees.append(new_tree) if (self.least is None or key < self.least.key): self.least = new_tree self.count = self.count + 1   def get_min(self): if self.least is None: return None return self.least.key   def extract_min(self): smallest = self.least if smallest is not None: for child in smallest.children: self.trees.append(child) self.trees.remove(smallest) if self.trees == []: self.least = None else: self.least = self.trees[0] self.consolidate() self.count = self.count - 1 return smallest.key   def consolidate(self): aux = (floor_log2(self.count) + 1)*[None]   while self.trees != []: x = self.trees[0] order = x.order self.trees.remove(x) while aux[order] is not None: y = aux[order] if x.key > y.key: x, y = y, x x.add_at_end(y) aux[order] = None order = order + 1 aux[order] = x   self.least = None for k in aux: if k is not None: self.trees.append(k) if (self.least is None or k.key < self.least.key): self.least = k     def floor_log2(x): return math.frexp(x)[1] - 1     fheap = FibonacciHeap()   print('Menu') print('insert <data>') print('min get') print('min extract') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0].strip().lower() if operation == 'insert': data = int(do[1]) fheap.insert(data) elif operation == 'min': suboperation = do[1].strip().lower() if suboperation == 'get': print('Minimum value: {}'.format(fheap.get_min())) elif suboperation == 'extract': print('Minimum value removed: {}'.format(fheap.extract_min()))   elif operation == 'quit': break
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:") print(unicode_to_str(students))
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 * rownum - 1         space_in_between_alphabets = num_alphabet - 1                    total_spots = (2 * size - 1) * 2 - 1         total_space = total_spots - num_alphabet                    space_leading_trailing = total_space - space_in_between_alphabets         lead_space = int(space_leading_trailing / 2)         trail_space = int(space_leading_trailing / 2)                    # print the leading spaces         for j in range(lead_space):             print('-', end ='')                    # determine the middle character         mid_char = (1 + size - 1) - int(num_alphabet / 2)                    # start with the last character          k = 1 + size - 1         is_alphabet_printed = False         mid_char_reached = False                    # print the numbers alternated by '-'         for j in range(num_alphabet + space_in_between_alphabets):                            if not is_alphabet_printed:                 print(str(k), end ='')                 is_alphabet_printed = True                                    if k == mid_char:                     mid_char_reached = True                                    if mid_char_reached == True:                     k += 1                                    else:                     k -= 1                            else:                 print('-', end ='')                 is_alphabet_printed = False                    # print the trailing spaces         for j in range(trail_space):             print('-', end ='')                    # go to the next line         print('')            # print the rows after middle row      # till last row (the second triangle      # which is inverted, i.e., the lower half)     for i in range(size + 1, 2 * size):                    rownum = i         num_alphabet = 2 * (2 * size - rownum) - 1         space_in_between_alphabets = num_alphabet - 1                    total_spots = (2 * size - 1) * 2 - 1         total_space = total_spots - num_alphabet                    space_leading_trailing = total_space - space_in_between_alphabets         lead_space = int(space_leading_trailing / 2)         trail_space = int(space_leading_trailing / 2)                    # print the leading spaces         for j in range(lead_space):             print('-', end ='')                    mid_char = (1 + size - 1) - int(num_alphabet / 2)                    # start with the last char         k = 1 + size - 1         is_alphabet_printed = False         mid_char_reached = False                    # print the numbers alternated by '-'         for j in range(num_alphabet + space_in_between_alphabets):                            if not is_alphabet_printed:                 print(str(k), end ='')                 is_alphabet_printed = True                                    if k == mid_char:                     mid_char_reached = True                                    if mid_char_reached == True:                     k += 1                                    else:                     k -= 1                            else:                 print('-', end ='')                 is_alphabet_printed = False                    # print the trailing spaces         for j in range(trail_space):             print('-', end ='')                    # go to the next line         print('')    # Driver Code if __name__ == '__main__':            n = 5     print_diamond(n)
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:") print(location.address) zipcode2 = "CA9 3HX" print("\nZipcode:",zipcode2) location = geolocator.geocode(zipcode2) print("Details of the said pincode:") print(location.address) zipcode3 = "61000" print("\nZipcode:",zipcode3) location = geolocator.geocode(zipcode3) print("Details of the said pincode:") print(location.address) zipcode4 = "713101" print("\nZipcode:",zipcode4) location = geolocator.geocode(zipcode4) print("Details of the said pincode:") print(location.address)
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("w3resource . com ")) print(move_Spaces_front(" w3resource.com "))
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,-2,-3,4] print("\nOriginal list elements:") print(nums) print("Cumulative sum of the elements of the said list:") print(cumsum(nums))
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') 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=(5,5)) plt.suptitle('Stock prices of Alphabet Inc.,\n01-04-2020 to 30-09-2020', \ fontsize=18, color='black') plt.xlabel("Date",fontsize=16, color='black') plt.ylabel("$ price", fontsize=16, color='black') df2['Close'].plot(color='green'); plt.show()
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("Checking for real number:") print(np.isreal(a)) print("Checking for scalar type:") print(np.isscalar(3.1)) print(np.isscalar([3.1]))
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', 'orange', "orange", 'red' ] from collections import Counter word_counts = Counter(words) top_four = word_counts.most_common(4) print(top_four)
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 said vector:") print(bin_nums[:,::-1])
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 original tuple print("The original tuple : " + str(test_tuple))    # Convert Nested Tuple to Custom Key Dictionary # Using list comprehension + dictionary comprehension res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}                                 for sub in test_tuple]    # printing result  print("The converted dictionary : " + str(res))
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 ini_array print("type of ini_array", type(ini_array))    # using shortcut method to reverse res = ini_array[::-1]    # printing result print("final array", str(res))
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:") print (df.groupby('value')['id'].nunique())
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', 'Arts', 'Biology'],                 'Percentage': [88, 92, 95, 70]}    # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Percentage'])    print("Given Dataframe :\n", df)    print("\nIterating over rows using index attribute :\n")    # iterate through each row and select  # 'Name' and 'Stream' column respectively. for ind in df.index:      print(df['Name'][ind], df['Stream'][ind])
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: 1st column of the said list of lists:") print(sum_column(nums, column)) column = 1 print("\nSum: 2nd column of the said list of lists:") print(sum_column(nums, column)) column = 3 print("\nSum: 4th column of the said list of lists:") print(sum_column(nums, column))
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 rows:") print(w_a_con.iloc[:2]) print("\nSelect first 2 columns:") print(w_a_con.iloc[:,:2].head()) print("\nSelect 2 specific columns:") print(w_a_con[['Display Value', 'Year']])
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 . '    # printing original string print("The original string is : " + str(test_str))    # initializing replace mapping  repl_dict = {'Gfg' :  'It', 'Classes' : 'They' }    # Replace duplicate Occurrence in String # Using split() + enumerate() + loop test_list = test_str.split(' ') res = set() for idx, ele in enumerate(test_list):     if ele in repl_dict:         if ele in res:             test_list[idx] = repl_dict[ele]         else:             res.add(ele) res = ' '.join(test_list)    # printing result  print("The string after replacing : " + str(res)) 
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")            # Loop to traverse the alphabet     # in the given string     for alphabet in str:                # If alphabet is present         # in set vowel         if alphabet in vowel:             count = count + 1            print("No. of vowels :", count)        # Driver code  str = "GeeksforGeeks"    # Function Call vowel_count(str)
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_cubes(3))
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("\nMedian of the array that contains \ odd no of elements:") print(med_odd)
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:") print(char)
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 = app.winfo_screenwidth() height = app.winfo_screenheight() app.geometry("%dx%d" % (width, height))    # Construct the label in your app l1 = Label(app, text='Geeks For Geeks')    # Give the leftmost padding l1.grid(padx=(200, 0), pady=(0, 0))    # Make the loop for displaying app app.mainloop()
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("\nModified string:") ch='a' print(delete_all_occurrences(str_text, ch))
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.uniform(1.0, 3.0) print(random_float)
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>          <tr>             <td>Vinayak</td>             <td>12</td>          </tr>          <tr>             <td>Ishita</td>             <td>10</td>          </tr>         </tbody>       </table>    </body> </html>
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=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): nlist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): nlist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",nlist) nlist = [14,46,43,27,57,41,45,21,70] mergeSort(nlist) print(nlist)
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_top
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 = min(a)     my_max = max(a)     size = my_max - my_min + 1        # our list of pigeonholes     holes = [0] * size        # Populate the pigeonholes.     for x in a:         assert type(x) is int, "integers only please"         holes[x - my_min] += 1        # Put the elements back into the array in order.     i = 0     for count in range(size):         while holes[count] > 0:             holes[count] -= 1             a[i] = count + my_min             i += 1                   a = [8, 3, 2, 7, 4, 6, 8] print("Sorted order is : ", end =" ")    pigeonhole_sort(a)            for i in range(0, len(a)):     print(a[i], end =" ")      
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 direction, # then a[i] and a[j] are interchanged.*/ def compAndSwap(a, i, j, dire): if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]): a[i], a[j] = a[j], a[i] # It recursively sorts a bitonic sequence in ascending order, # if dir = 1, and in descending order otherwise (means dir=0). # The sequence to be sorted starts at index position low, # the parameter cnt is the number of elements to be sorted. def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) for i in range(low, low + k): compAndSwap(a, i, i + k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low + k, k, dire) # This funcion first produces a bitonic sequence by recursively # sorting its two halves in opposite sorting orders, and then # calls bitonicMerge to make them in the same order def bitonicSort(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) bitonicSort(a, low, k, 1) bitonicSort(a, low + k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N # in ASCENDING order def sort(a, N, up): bitonicSort(a, 0, N, up) # Driver code to test above a = [] print("How many numbers u want to enter?"); n = int(input()) print("Input the numbers:"); for i in range(n): a.append(int(input())) up = 1 sort(a, n, up) print("\n\nSorted array is:") for i in range(n): print("%d" % a[i])
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 splitting is done on the basis of single space. print("\nSplitting 'Name' column into two different columns :\n",                                   df.Name.str.split(expand=True))
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(n_array)    print("\nDeterminant of given 2X2 matrix:") print(int(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 self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next   def display(self): current = self.head while current is not None: print(current.data, end = ' ') current = current.next   def find_index(self, key): current = self.head   index = 0 while current: if current.data == key: return index current = current.next index = index + 1   return -1   a_llist = LinkedList() for data in [4, -3, 1, 0, 9, 11]: a_llist.append(data) print('The linked list: ', end = '') a_llist.display() print()   key = int(input('What data item would you like to search for? ')) index = a_llist.find_index(key) if index == -1: print(str(key) + ' was not found.') else: print(str(key) + ' is at index ' + str(index) + '.')
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[word[0]]): d[word[0]].append(word) for k,v in d.items(): print(k,":",v)
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 # using list comprehension res = [ele for ele in test_list if ele != []]    # printing result  print ("List after empty list removal : " + str(res))
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_range('2018-01-01', periods=12, freq='S') print("\nSecondly frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='2H') print("nMultiple Hourly frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='5min') print("\nMultiple Minutely frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='BQ') print("\nMultiple Secondly frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='w') print("\nWeekly frequency:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='2h20min') print("\nCombine together day and intraday offsets-1:") print(dtr) dtr = pd.date_range('2018-01-01', periods=12, freq='1D10U') print("\nCombine together day and intraday offsets-2:") print(dtr)
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 = " ")    # creating the 2D Array TwoDList = [[1, 2, 3], [4, 5, 6],             [7, 8, 9], [10, 11, 12]] TwoDArray = numpy.array(TwoDList) # displaying the 2D Array print("2D Array:") print(TwoDArray) # printing the sum of each column print("\nColumn-wise Sum:") colsum(TwoDArray, len(TwoDArray[0]), len(TwoDArray))
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'], ['And', '&'], ['Computer', 'Comp']]    # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2))    # Replace Substrings from String List # using loop + replace() + enumerate() sub = dict(test_list2) for key, val in sub.items():     for idx, ele in enumerate(test_list1):         if key in ele:             test_list1[idx] = ele.replace(key, val)    # printing result  print ("The list after replacement : " + str(test_list1))
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)if(NoOfUppercase==0):    print("No UpperCase Letter present in a given string.")else:    print("Number Of UpperCase Letter Present in a given String is:",NoOfUppercase)
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 = (len(a)-1)//2     #you can remove the -1 or you add <= sign in line 21      start = 0                #so that you can compare the middle elements also.     last = len(a)-1     flag = 0     # A loop till the mid of the     # string     while(start <= mid):            # comparing letters from right         # from the letters from left         if (a[start]== a[last]):                           start += 1             last -= 1                       else:             flag = 1             break;                   # Checking the flag variable to     # check if the string is palindrome     # or not     if flag == 0:         print("The entered string is palindrome")     else:         print("The entered string is not palindrome")           # Function to check whether the # string is symmetrical or not        def symmetry(a):           n = len(a)     flag = 0           # Check if the string's length     # is odd or even     if n%2:         mid = n//2 +1     else:         mid = n//2               start1 = 0     start2 = mid           while(start1 < mid and start2 < n):                   if (a[start1]== a[start2]):             start1 = start1 + 1             start2 = start2 + 1         else:             flag = 1             break            # Checking the flag variable to     # check if the string is symmetrical     # or not     if flag == 0:         print("The entered string is symmetrical")     else:         print("The entered string is not symmetrical")           # Driver code string = 'amaama' palindrome(string) symmetry(string)
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', 'age': 18 } ] print("Original list of dictionaries:") print(students) print("\nConvert a list of dictionaries into a list of values corresponding to the specified key:") print(test(students, 'age'))
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. Bishop Ave.','9910 Golden Star Ave.', '102 Dunbar St.', '17 West Livingston Court'] }) print("Original DataFrame:") print(df) def test_and_cond(text): result = re.findall(r'(?=.*Ave.)(?=.*9910).*', text) return " ".join(result) df['check_two_words']=df['address'].apply(lambda x : test_and_cond(x)) print("\nPresent two words!") print(df)
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_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 preorder_depth_first(self): s = Stack() s.push(self) while (not s.is_empty()): node = s.pop() print(node.key, end=' ') if node.right is not None: s.push(node.right) if node.left is not None: s.push(node.left)     class Stack: def __init__(self): self.items = []   def is_empty(self): return self.items == []   def push(self, data): self.items.append(data)   def pop(self): return self.items.pop()     btree = BinaryTree()   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('dfs') print('quit')   while True: 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 == 'dfs': print('pre-order dfs traversal: ', end='') if btree is not None: btree.preorder_depth_first() print()   elif operation == 'quit': break
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):          dec = binary % 10         decimal = decimal + dec * pow(2, i)          binary = binary//10         i += 1     return (decimal)        # Driver's code  # initializing binary data bin_data ='10001111100101110010111010111110011'     # print binary data print("The binary value is:", bin_data)     # initializing a empty string for  # storing the string data str_data =' '     # slicing the input and converting it  # in decimal and then converting it in string for i in range(0, len(bin_data), 7):            # slicing the bin_data from index range [0, 6]     # and storing it as integer in temp_data     temp_data = int(bin_data[i:i + 7])             # passing temp_data in BinarytoDecimal() function     # to get decimal value of corresponding temp_data     decimal_data = BinaryToDecimal(temp_data)             # Deccoding the decimal value returned by      # BinarytoDecimal() function, using chr()      # function which return the string corresponding      # character for given ASCII value, and store it      # in str_data     str_data = str_data + chr(decimal_data)      # printing the result print("The Binary value after string conversion is:",         str_data)
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.nan,70013], 'purch_amt':[np.nan,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6], 'ord_date': [np.nan,'2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'], 'customer_id':[np.nan,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001]}) print("Original Orders DataFrame:") print(df) print("\nDrop the rows where all elements are missing:") result = df.dropna(how='all') print(result)
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 = Counter(input) part1 = [ key for (key,count) in str_char_ctr.items() if count==1] part2 = [ key for (key,count) in str_char_ctr.items() if count>1] part1.sort() part2.sort() return part1,part2 input = "aabbcceffgh" s1, s2 = generateStrings(input) print(''.join(s1)) print(''.join(s2))
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    rem=num%10    num=int(num/10)    for i in range(1,rem+1):       fact=fact*i    sum=sum+fact if sum==num2:    print("It is a Strong Number") else:    print("It is not a Strong Number")
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 = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index+1:] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def time_sort(lst): runs, sorted_runs = [], [] length = len(lst) new_run = [lst[0]] sorted_array = [] for i in range(1, length): if i == length - 1: new_run.append(lst[i]) runs.append(new_run) break if lst[i] < lst[i - 1]: if not new_run: runs.append([lst[i - 1]]) new_run.append(lst[i]) else: runs.append(new_run) new_run = [] else: new_run.append(lst[i]) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array user_input = input("Input numbers separated by a comma:\n").strip() nums = [int(item) for item in user_input.split(',')] print(time_sort(nums))
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), 'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)} print("Original Dictionary:") print(students) print("\nHeight> 6ft and Weight> 70kg:") print(filter_data(students))
62