code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python Program for Gnome Sort # Python program to implement Gnome Sort # A function to sort the given list using Gnome sort def gnomeSort( arr, n):     index = 0     while index < n:         if index == 0:             index = index + 1         if arr[index] >= arr[index - 1]:             index = index + 1...
106
# Write a Python program to create a copy of its own source code. def file_copy(src, dest): with open(src) as f, open(dest, 'w') as d: d.write(f.read()) file_copy("untitled0.py", "z.py") with open('z.py', 'r') as filehandle: for line in filehandle: print(line, ...
41
# Find the second most frequent character in a given string str=input("Enter Your String:")arr=[0]*256max=0sec_max=0i=0for i in range(len(str)):    if str[i]!=' ':        num=ord(str[i])        arr[num]+=1for i in range(256):    if arr[i] > arr[max]:        sec_max = max        max = i    elif arr[i]>arr[sec_max] and...
51
# 7.2 Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. : class Shape(object): def __init__(self): pass def area(se...
72
# Write a program that accepts a sentence and calculate the number of letters and digits. s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"]
39
# Write a Python program to Convert Matrix to dictionary # Python3 code to demonstrate working of  # Convert Matrix to dictionary  # Using dictionary comprehension + range()    # initializing list test_list = [[5, 6, 7], [8, 3, 2], [8, 2, 1]]     # printing original list print("The original list is : " + str(test_lis...
81
# Write a Python Program to find minimum number of rotations to obtain actual string def findRotations(str1, str2):            # To count left rotations      # of string     x = 0            # To count right rotations     # of string     y = 0     m = str1            while True:                    # left rotating the...
144
# Program to print the Solid Diamond Star Pattern row_size=int(input("Enter the row size:")) for out in range(row_size,-row_size,-1):     for in1 in range(1,abs(out)+1):         print(" ",end="")     for in2 in range(row_size,abs(out),-1):         print("* ",end="")     print("\r")
30
# Write a Python program to print a specified list after removing the 0th, 4th and 5th elements. color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] color = [x for (i,x) in enumerate(color) if i not in (0,4,5)] print(color)
39
# Calculate inner, outer, and cross products of matrices and vectors using NumPy in Python # Python Program illustrating # numpy.inner() method import numpy as np    # Vectors a = np.array([2, 6]) b = np.array([3, 10]) print("Vectors :") print("a = ", a) print("\nb = ", b)    # Inner Product of Vectors print("\nInner...
103
# Write a Python program to Sort Python Dictionaries by Key or Value # Function calling def dictionairy():  # Declare hash function       key_value ={}    # Initializing value  key_value[2] = 56        key_value[1] = 2  key_value[5] = 12  key_value[4] = 24  key_value[6] = 18       key_value[3] = 323  print ("Task...
85
# Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components. def hex_to_rgb(hex): return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)) print(hex_to_rgb('FFA501')) print(hex_to_rgb('FFFFFF')) print(hex_to_rgb('000000')) print(hex_to_rgb('FF0000')) print(h...
38
# Write a Python Program for Binary Insertion Sort # Python Program implementation   # of binary insertion sort    def binary_search(arr, val, start, end):     # we need to distinugish whether we should insert     # before or after the left boundary.     # imagine [0] is the last step of the binary search     # and w...
177
# Pretty print Linked List in Python class Node:     def __init__(self, val=None):         self.val = val         self.next = None       class LinkedList:     def __init__(self, head=None):         self.head = head        def __str__(self):                  # defining a blank res variable         res = ""            ...
143
# Write a Python program to find the item with maximum frequency in a given list. from collections import defaultdict def max_occurrences(nums): dict = defaultdict(int) for i in nums: dict[i] += 1 result = max(dict.items(), key=lambda x: x[1]) return result nums = [2,3,8,4,7,9,8,2,6,5,1,6,1,...
56
# Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings. def sort_mixed_list(mixed_list): mixed_list.sort(key=lambda e: (isinstance(e, str), e)) return mixed_list mixed_list = [19,'red',12,'green','blue', 10,'white','green',1] print("Ori...
49
# numpy.trim_zeros() in Python import numpy as geek     gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))    # without trim parameter # returns an array without leading and trailing zeros     res = geek.trim_zeros(gfg) print(res)
42
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to make a gradient color on all the values of the said dataframe. import pandas as pd import numpy as np import seaborn as sns np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFram...
63
# Write a Python program to sum of all counts in a collections. import collections num = [2,2,4,6,6,8,6,10,4] print(sum(collections.Counter(num).values()))
19
# Write a Python program to find numbers within a given range where every number is divisible by every digit it contains. def divisible_by_digits(start_num, end_num): return [n for n in range(start_num, end_num+1) \ if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))] print(divisible_...
46
# Create a pandas column using for loop in Python # importing libraries import pandas as pd import numpy as np    raw_Data = {'Voter_name': ['Geek1', 'Geek2', 'Geek3', 'Geek4',                             'Geek5', 'Geek6', 'Geek7', 'Geek8'],              'Voter_age': [15, 23, 25, 9, 67, 54, 42, np.NaN]}    df = pd.Da...
131
# Visualizing Quick Sort using Tkinter in Python # Extension Quick Sort Code # importing time module import time # to implement divide and conquer def partition(data, head, tail, drawData, timeTick):     border = head     pivot = data[tail]     drawData(data, getColorArray(len(data), head,                        ...
254
# Write a Pandas program to generate time series combining day and intraday offsets intervals. import pandas as pd dateset1 = pd.date_range('2029-01-01 00:00:00', periods=20, freq='3h10min') print("Time series with frequency 3h10min:") print(dateset1) dateset2 = pd.date_range('2029-01-01 00:00:00', periods=20, freq=...
49
# How to extract date from Excel file using Pandas in Python # import required module import pandas as pd; import re;    # Read excel file and store in to DataFrame data = pd.read_excel("date_sample_data.xlsx");    print("Original DataFrame") data
37
# Write a Python Program for Anagram Substring Search (Or Search for all permutations) # Python program to search all # anagrams of a pattern in a text    MAX = 256     # This function returns true # if contents of arr1[] and arr2[] # are same, otherwise false. def compare(arr1, arr2):     for i in range(MAX):       ...
221
# Write a Python program to Multiply all numbers in the list (4 different ways) # Python program to multiply all values in the # list using traversal def multiplyList(myList) :           # Multiply elements one by one     result = 1     for x in myList:          result = result * x     return result       # Driver ...
66
# Create a Pandas DataFrame from List of Dicts in Python # Python code demonstrate how to create   # Pandas DataFrame by lists of dicts.  import pandas as pd       # Initialise data to lists.  data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},         {'Geeks':10, 'For': 20, 'geeks': 30}]       # Create...
58
# How to inverse a matrix using NumPy in Python # Python program to inverse # a matrix using numpy    # Import required package import numpy as np    # Taking a 3 * 3 matrix A = np.array([[6, 1, 1],               [4, -2, 5],               [2, 8, 7]])    # Calculating the inverse of the matrix print(np.linalg.inv(A))
54
# Write a Python program to sum all the items in a dictionary. my_dict = {'data1':100,'data2':-54,'data3':247} print(sum(my_dict.values()))
17
# Program to find sum of series 1^1/1!+2^2/2!+3^3/3!...+n^n/n! import math print("Enter the range of number:") n=int(input()) sum=0.0 fact=1 for i in range(1,n+1):     fact*=i     sum += pow(i, i) / fact print("The sum of the series = ",sum)
36
# Check whether number is Trimorphic Number or Not num=int(input("Enter a number:")) flag=0 cube_power=num*num*num while num!=0:     if num%10!=cube_power%10:         flag=1         break     num//=10     cube_power//=10 if flag==0:     print("It is a Trimorphic Number.") else:    print("It is Not a Trimorphic Numbe...
36
# Write a Python program to get date and time properties from datetime function using arrow module. import arrow a = arrow.utcnow() print("Current date:") print(a.date()) print("\nCurrent time:") print(a.time())
28
# Python Program to Reverse a Linked List 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.h...
125
# Find 2nd largest digit in a given number '''Write a Python program to Find the 2nd largest digit in a given number. or Write a program to Find 2nd largest digit in a given number using Python ''' print("Enter the Number :") num=int(input()) Largest=0 Sec_Largest=0 while num > 0:     reminder=num%10     if Larges...
77
# Write a Python program to Convert Lists of List to Dictionary # Python3 code to demonstrate working of  # Convert Lists of List to Dictionary # Using loop    # initializing list test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]    # printing original list print("The original list is : " + str(test_...
88
# Write a Python program to find the maximum, minimum aggregation pair in given list of integers. from itertools import combinations def max_aggregate(l_data): max_pair = max(combinations(l_data, 2), key = lambda pair: pair[0] + pair[1]) min_pair = min(combinations(l_data, 2), key = lambda pair: pair[0] + p...
78
# Write a Pandas program to create a histogram to visualize daily return distribution of Alphabet Inc. stock price between two specific dates. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to...
84
# Write a NumPy program to find the memory size of a NumPy array. import numpy as np n = np.zeros((4,4)) print("%d bytes" % (n.size * n.itemsize))
27
# Write a Pandas program to split the following dataframe into groups based on customer id and create a list of order date for each group. import pandas as pd pd.set_option('display.max_rows', None) #pd.set_option('display.max_columns', None) df = pd.DataFrame({ 'ord_no':[70001,70009,70002,70004,70007,70005,70008,70...
66
# Convert class object to JSON in Python # import required packages import json    # custom class class Student:     def __init__(self, roll_no, name, batch):         self.roll_no = roll_no         self.name = name         self.batch = batch       class Car:     def __init__(self, brand, name, batch):         self.br...
114
# Get unique values from a column in Pandas DataFrame in Python # Import pandas package  import pandas as pd    # create a dictionary with five fields each data = {     'A':['A1', 'A2', 'A3', 'A4', 'A5'],      'B':['B1', 'B2', 'B3', 'B4', 'B4'],      'C':['C1', 'C2', 'C3', 'C3', 'C3'],      'D':['D1', 'D2', 'D2', 'D2...
75
# Write a Pandas program to extract hash attached word from twitter text 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({ 'tweets': ['#Obama says goodbye','Retweets for #cash','A political endorsement in #Indonesia', ...
71
# Write a NumPy program to get the row numbers in given array where at least one item is larger than a specified value. import numpy as np num = np.arange(36) arr1 = np.reshape(num, [4, 9]) print("Original array:") print(arr1) result = np.where(np.any(arr1>10, axis=1)) print("\nRow numbers where at least one item i...
55
# Write a Python program to count the number of students of individual class. from collections import Counter classes = ( ('V', 1), ('VI', 1), ('V', 2), ('VI', 2), ('VI', 3), ('VII', 1), ) students = Counter(class_name for class_name, no_students in classes) print(students)
43
# Write a Python program to retrieve the current working directory and change the dir (moving up one). import os print('Current dir:', os.getcwd()) print('\nChange the dir (moving up one):', os.pardir) os.chdir(os.pardir) print('Current dir:', os.getcwd()) print('\nChange the dir (moving up one):', os.pardir) os.chd...
45
# Compare two Files line by line in Python # Importing difflib import difflib    with open('file1.txt') as file_1:     file_1_text = file_1.readlines()    with open('file2.txt') as file_2:     file_2_text = file_2.readlines()    # Find and print the diff: for line in difflib.unified_diff(         file_1_text, file_2_...
44
# numpy string operations | upper() function in Python # Python Program explaining # numpy.char.upper() function     import numpy as geek        in_arr = geek.array(['p4q r', '4q rp', 'q rp4', 'rp4q']) print ("input array : ", in_arr)    out_arr = geek.char.upper(in_arr) print ("output uppercased array :", out_arr)
44
# Write a NumPy program to test whether specified values are present in an array. import numpy as np x = np.array([[1.12, 2.0, 3.45], [2.33, 5.12, 6.0]], float) print("Original array:") print(x) print(2 in x) print(0 in x) print(6 in x) print(2.3 in x) print(5.12 in x)
46
# Python Program to Count Set Bits in a Number def count_set_bits(n): count = 0 while n: n &= n - 1 count += 1 return count     n = int(input('Enter n: ')) print('Number of set bits:', count_set_bits(n))
37
# Write a Python program to test whether a given path exists or not. If the path exist find the filename and directory portion of the said path. import os print("Test a path exists or not:") path = r'g:\\testpath\\a.txt' print(os.path.exists(path)) path = r'g:\\testpath\\p.txt' print(os.path.exists(path)) print("\nF...
56
# Find indices of elements equal to zero in a NumPy array in Python # importing Numpy package import numpy as np    # creating a 1-D Numpy array n_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,                     6, 7, 5, 0, 8])    print("Original array:") print(n_array)    # finding indices of null elements using np.whe...
72
# Program to Find sum of series 5^2+10^2+15^2+.....N^2 import math print("Enter the range of number(Limit):") n=int(input()) i=5 sum=0 while(i<=n):     sum+=pow(i,2)     i+=5 print("The sum of the series = ",sum)
28
# Write a Python program to count the number of times a specific element presents in a deque object. import collections nums = (2,9,0,8,2,4,0,9,2,4,8,2,0,4,2,3,4,0) nums_dq = collections.deque(nums) print("Number of 2 in the sequence") print(nums_dq.count(2)) print("Number of 4 in the sequence") print(nums_dq.count(...
41
# Write a Python program to Reverse Dictionary Keys Order # Python3 code to demonstrate working of  # Reverse Dictionary Keys Order # Using OrderedDict() + reversed() + items() from collections import OrderedDict    # initializing dictionary test_dict = {'gfg' : 4, 'is' : 2, 'best' : 5}    # printing original diction...
84
# Create a Numpy array filled with all zeros | Python # Python Program to create array with all zeros import numpy as geek     a = geek.zeros(3, dtype = int)  print("Matrix a : \n", a)     b = geek.zeros([3, 3], dtype = int)  print("\nMatrix b : \n", b) 
47
# Write a Python program to check the priority of the four operators (+, -, *, /). from collections import deque import re __operators__ = "+-/*" __parenthesis__ = "()" __priority__ = { '+': 0, '-': 0, '*': 1, '/': 1, } def test_higher_priority(operator1, operator2): return __priority__[operato...
53
# Write a NumPy program to find the most frequent value in an array. import numpy as np x = np.random.randint(0, 10, 40) print("Original array:") print(x) print("Most frequent value in the above array:") print(np.bincount(x).argmax())
34
# How to get weighted random choice in Python import random       sampleList = [100, 200, 300, 400, 500]    randomList = random.choices(   sampleList, weights=(10, 20, 30, 40, 50), k=5)    print(randomList)
29
# Write a NumPy program to find common values between two arrays. import numpy as np array1 = np.array([0, 10, 20, 40, 60]) print("Array1: ",array1) array2 = [10, 30, 40] print("Array2: ",array2) print("Common values between two arrays:") print(np.intersect1d(array1, array2))
39
# Write a Pandas program to keep the rows with at least 2 NaN values 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,np.nan,np.nan,70005,np.nan,70010,70003,70012,np.nan,n...
61
# Write a Pandas program to find out the alcohol consumption details in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' 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 sam...
76
# Write a Python program to interleave multiple lists of the same length. def interleave_multiple_lists(list1,list2,list3): result = [el for pair in zip(list1, list2, list3) for el in pair] return result list1 = [1,2,3,4,5,6,7] list2 = [10,20,30,40,50,60,70] list3 = [100,200,300,400,500,600,700] print(...
48
# Write a Python program to access a specific item in a singly linked list using index value. class Node: # Singly linked node def __init__(self, data=None): self.data = data self.next = None class singly_linked_list: def __init__(self): # Createe an empty list self.tail =...
122
# Write a Python program to Extract values of Particular Key in Nested Values # Python3 code to demonstrate working of  # Extract values of Particular Key in Nested Values # Using list comprehension    # initializing dictionary test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},              'is' : {"a" : 15, "b" : 19...
121
# Assign Function to a Variable in Python def a():   print("GFG")     # assigning function to a variable var=a # calling the variable var()
23
# Write a Python program to find the maximum length of a substring in a given string where all the characters of the substring are same. Use itertools module to solve the problem. import itertools def max_sub_string(str1): return max(len(list(x)) for _, x in itertools.groupby(str1)) str1 = "aaabbccdde...
81
# Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print n1+n2+n3+n4
52
# Write a Python program to Longest Substring Length of K # Python3 code to demonstrate working of  # Longest Substring of K # Using loop    # initializing string test_str = 'abcaaaacbbaa'    # printing original String print("The original string is : " + str(test_str))    # initializing K  K = 'a'    cnt = 0 res = 0 ...
94
# Write a Python program to create Fibonacci series upto n using Lambda. from functools import reduce fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1]) print("Fibonacci series upto 2:") print(fib_series(2)) print("\nFibonacci series upto 5:") print(fi...
48
# Write a NumPy program to compute e import numpy as np x = np.array([1., 2., 3., 4.], np.float32) print("Original array: ") print(x) print("\ne^x, element-wise of the said:") r = np.exp(x) print(r)
32
# How to convert CSV File to PDF File using Python import pandas as pd import pdfkit    # SAVE CSV TO HTML USING PANDAS csv = 'MyCSV.csv' html_file = csv_file[:-3]+'html'    df = pd.read_csv(csv_file, sep=',') df.to_html(html_file)    # INSTALL wkhtmltopdf AND SET PATH IN CONFIGURATION # These two Steps could be elim...
80
# Write a Python program to find the values of length six in a given list using Lambda. weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] days = filter(lambda day: day if len(day)==6 else '', weekdays) for d in days: print(d)
42
# Write a Python program to find the first two elements of a given list whose sum is equal to a given value. Use itertools module to solve the problem. import itertools as it def sum_pairs_list(nums, n): for num2, num1 in list(it.combinations(nums[::-1], 2))[::-1]: if num2 + num1 == n: return...
84
# Write a Python program to Substring presence in Strings List # Python3 code to demonstrate working of  # Substring presence in Strings List # Using loop    # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"]    # printing original lists print("Th...
120
# Write a Python program to pair up the consecutive elements of a given list. def pair_consecutive_elements(lst): result = [[lst[i], lst[i + 1]] for i in range(len(lst) - 1)] return result nums = [1,2,3,4,5,6] print("Original lists:") print(nums) print("Pair up the consecutive elements of the said list:") p...
63
# Find the minimum element in the matrix import sys # 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) ...
89
# Write a Python program to create the largest possible number using the elements of a given list of positive integers. def create_largest_number(lst): if all(val == 0 for val in lst): return '0' result = ''.join(sorted((str(val) for val in lst), reverse=True, key=lambda i: i*( ...
128
# Bubble sort using recursion def BubbleSort(arr,n):    if(n>0):        for i in range(0,n):            if (arr[i]>arr[i+1]):                temp = arr[i]                arr[i] = arr[i + 1]                arr[i + 1] = temp        BubbleSort(arr, n - 1)arr=[]n = int(input("Enter the size of the array: "))print("Enter ...
63
# Write a Python program to find all anagrams of a string in a given list of strings using lambda. from collections import Counter texts = ["bcda", "abce", "cbda", "cbea", "adcb"] str = "abcd" print("Orginal list of strings:") print(texts) result = list(filter(lambda x: (Counter(str) == Counter(x)), texts)) prin...
56
# Write a Pandas program to import excel data (coalpublic2013.xlsx ) into a dataframe and find details where "Mine Name" starts with "P". import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df[df["Mine_Name"].map(lambda x: x.startswith('P'))].head()
37
# Write a Python program to create a datetime from a given timezone-aware datetime using arrow module. import arrow from datetime import datetime from dateutil import tz print("\nCreate a date from a given date and a given time zone:") d1 = arrow.get(datetime(2018, 7, 5), 'US/Pacific') print(d1) print("\nCreate a da...
84
# Write a Python program to Count occurrences of an element in a list # Python code to count the number of occurrences def countX(lst, x):     count = 0     for ele in lst:         if (ele == x):             count = count + 1     return count # Driver Code lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8 print('{} has oc...
68
# Write a NumPy program to test whether any array element along a given axis evaluates to True. import numpy as np print(np.any([[False,False],[False,False]])) print(np.any([[True,True],[True,True]])) print(np.any([10, 20, 0, -50])) print(np.any([10, 20, -50]))
31
# Write a Python program to concatenate element-wise three given lists. def concatenate_lists(l1,l2,l3): return [i + j + k for i, j, k in zip(l1, l2, l3)] l1 = ['0','1','2','3','4'] l2 = ['red','green','black','blue','white'] l3 = ['100','200','300','400','500'] print("Original lists:") print(l1) print(l...
47
# Write a Python program that invoke a given function after specific milliseconds. from time import sleep import math def delay(fn, ms, *args): sleep(ms / 1000) return fn(*args) print("Square root after specific miliseconds:") print(delay(lambda x: math.sqrt(x), 100, 16)) print(delay(lambda x: math.sqrt(x), 100...
48
# Write a Pandas program to get all the sighting years of the unidentified flying object (ufo) and create the year as column. import pandas as pd df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') print("Original Dataframe:") print(df.head()) print("\nSighting years of the uniden...
47
# Write a Python program to Maximum and Minimum K elements in Tuple # Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using sorted() + loop # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initial...
110
# Write a Python program to flatten a shallow list. import itertools original_list = [[2,4,3],[1,5,6], [9], [7,9,0]] new_merged_list = list(itertools.chain(*original_list)) print(new_merged_list)
21
# Change current working directory with Python # Python program to change the # current working directory import os # Function to Get the current # working directory def current_path():     print("Current working directory before")     print(os.getcwd())     print() # Driver's code # Printing CWD before cur...
54
# Write a Pandas program to insert a column in the sixth position of the said excel sheet and fill it with NaN values. import pandas as pd import numpy as np df = pd.read_excel('E:\coalpublic2013.xlsx') df.insert(3, "column1", np.nan) print(df.head)
39
# Write a NumPy program to swap rows and columns of a given array in reverse order. import numpy as np nums = np.array([[[1, 2, 3, 4], [0, 1, 3, 4], [90, 91, 93, 94], [5, 0, 3, 2]]]) print("Original array:") print(nums) print("\nSwap rows and columns of the said array in ...
58
# Program to Calculate the surface area and volume of a Hemisphere import math r=int(input("Enter the radius of the Hemisphere:")) PI=3.14 surface_area=3*PI*math.pow(r,2) volume=(2.0/3.0)*PI*math.pow(r,3) print("Surface Area of the Hemisphere = ",surface_area) print("Volume of the Hemisphere = ",volume)
36
# Write a Python function to check whether a number is perfect or not. def perfect_number(n): sum = 0 for x in range(1, n): if n % x == 0: sum += x return sum == n print(perfect_number(6))
38
# Scrape IMDB movie rating and details using Python from bs4 import BeautifulSoup import requests import re
17
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. value = [] items=[x for x in raw_input().split(',')] for p in items: intp = ...
67
# Write a NumPy program to create a random array with 1000 elements and compute the average, variance, standard deviation of the array elements. import numpy as np x = np.random.randn(1000) print("Average of the array elements:") mean = x.mean() print(mean) print("Standard deviation of the array elements:") std = x....
59
# Write a Python program to Ways to convert array of strings to array of floats # Python code to demonstrate converting # array of strings to array of floats # using astype import numpy as np # initialising array ini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial array print ("initial array",...
74
# Counting the frequencies in a list using dictionary in Python # Python program to count the frequency of # elements in a list using a dictionary def CountFrequency(my_list):     # Creating an empty dictionary     freq = {}     for item in my_list:         if (item in freq):             freq[item] += 1         e...
90
# br/> row_num = int(input("Input number of rows: ")) col_num = int(input("Input number of columns: ")) multi_list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): multi_list[row][col]= row*col print(multi_list)
38
# Write a Python program to Count the Number of matching characters in a pair of string # Python code to count number of matching # characters in a pair of strings    # count function def count(str1, str2):      c, j = 0, 0            # loop executes till length of str1 and      # stores value of str1 character by ch...
177