code
stringlengths
63
8.54k
code_length
int64
11
747
# Write a Python program to format a specified string limiting the length of a string. str_num = "1234567890" print("Original string:",str_num) print('%.6s' % str_num) print('%.9s' % str_num) print('%.10s' % str_num)
30
# Getting all CSV files from a directory using Python # importing the required modules import glob import pandas as pd    # specifying the path to csv files path = "csvfoldergfg"    # csv files in the path files = glob.glob(path + "/*.csv")    # defining an empty list to store  # content data_frame = pd.DataFrame() content = []    # checking all the csv files in the  # specified path for filename in files:          # reading content of csv file     # content.append(filename)     df = pd.read_csv(filename, index_col=None)     content.append(df)    # converting content to data frame data_frame = pd.concat(content) print(data_frame)
95
# Write a Python Program for ShellSort # Python program for implementation of Shell Sort    def shellSort(arr):        # Start with a big gap, then reduce the gap     n = len(arr)     gap = n/2        # Do a gapped insertion sort for this gap size.     # The first gap elements a[0..gap-1] are already in gapped      # order keep adding one more element until the entire array     # is gap sorted     while gap > 0:            for i in range(gap,n):                # add a[i] to the elements that have been gap sorted             # save a[i] in temp and make a hole at position i             temp = arr[i]                # shift earlier gap-sorted elements up until the correct             # location for a[i] is found             j = i             while  j >= gap and arr[j-gap] >temp:                 arr[j] = arr[j-gap]                 j -= gap                # put temp (the original a[i]) in its correct location             arr[j] = temp         gap /= 2       # Driver code to test above arr = [ 12, 34, 54, 2, 3]    n = len(arr) print ("Array before sorting:") for i in range(n):     print(arr[i]),    shellSort(arr)    print ("\nArray after sorting:") for i in range(n):     print(arr[i]),    # This code is contributed by Mohit Kumra
193
# Write a Python program to generate all sublists of a list. from itertools import combinations def sub_lists(my_list): subs = [] for i in range(0, len(my_list)+1): temp = [list(x) for x in combinations(my_list, i)] if len(temp)>0: subs.extend(temp) return subs l1 = [10, 20, 30, 40] l2 = ['X', 'Y', 'Z'] print("Original list:") print(l1) print("S") print(sub_lists(l1)) print("Sublists of the said list:") print(sub_lists(l1)) print("\nOriginal list:") print(l2) print("Sublists of the said list:") print(sub_lists(l2))
70
# Write a Python program to extract year, month and date value from current datetime using arrow module. import arrow a = arrow.utcnow() print("Year:") print(a.year) print("\nMonth:") print(a.month) print("\nDate:") print(a.day)
29
# Write a Python program to convert all the characters in uppercase and lowercase and eliminate duplicate letters from a given sequence. Use map() function. def change_cases(s): return str(s).upper(), str(s).lower() chrars = {'a', 'b', 'E', 'f', 'a', 'i', 'o', 'U', 'a'} print("Original Characters:\n",chrars) result = map(change_cases, chrars) print("\nAfter converting above characters in upper and lower cases\nand eliminating duplicate letters:") print(set(result))
60
# Write a NumPy program to replace a specific character with another in a given array of string values. import numpy as np str1 = np.array([['Python-NumPy-Exercises'], ['-Python-']]) print("Original array of string values:") print(str1) print("\nReplace '-' with '=' character in the said array of string values:") print(np.char.strip(np.char.replace(str1, '-', '=='))) print("\nReplace '-' with ' ' character in the said array of string values:") print(np.char.strip(np.char.replace(str1, '-', ' ')))
65
# Write a NumPy program to create an array which looks like below array. import numpy as np x = np.triu(np.arange(2, 14).reshape(4, 3), -1) print(x)
25
# Write a Python program to read a square matrix from console and print the sum of matrix primary diagonal. Accept the size of the square matrix and elements for each column separated with a space (for every row) as input from the user. size = int(input("Input the size of the matrix: ")) matrix = [[0] * size for row in range(0, size)] for x in range(0, size): line = list(map(int, input().split())) for y in range(0, size): matrix[x][y] = line[y] matrix_sum_diagonal = sum(matrix[size - i - 1][size - i - 1] for i in range(size)) print("Sum of matrix primary diagonal:") print(matrix_sum_diagonal)
101
# Write a Python program to interleave two given list into another list randomly using map() function. import random def randomly_interleave(nums1, nums2): result = list(map(next, random.sample([iter(nums1)]*len(nums1) + [iter(nums2)]*len(nums2), len(nums1)+len(nums2)))) return result nums1 = [1,2,7,8,3,7] nums2 = [4,3,8,9,4,3,8,9] print("Original lists:") print(nums1) print(nums2) print("\nInterleave two given list into another list randomly:") print(randomly_interleave(nums1, nums2))
51
# Write a Python program to Remove Tuples from the List having every element as None # Python3 code to demonstrate working of  # Remove None Tuples from List # Using all() + list comprehension    # initializing list test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )]    # printing original list print("The original list is : " + str(test_list))    # negating result for discarding all None Tuples res = [sub for sub in test_list if not all(ele == None for ele in sub)]    # printing result  print("Removed None Tuples : " + str(res))
96
# Write a Python program to multiply all the numbers in a given list using lambda. from functools import reduce def mutiple_list(nums): result = reduce(lambda x, y: x*y, nums) return result nums = [4, 3, 2, 2, -1, 18] print ("Original list: ") print(nums) print("Mmultiply all the numbers of the said list:",mutiple_list(nums)) nums = [2, 4, 8, 8, 3, 2, 9] print ("\nOriginal list: ") print(nums) print("Mmultiply all the numbers of the said list:",mutiple_list(nums))
74
# Write a NumPy program to print all the values of an array. import numpy as np np.set_printoptions(threshold=np.nan) x = np.zeros((4, 4)) print(x)
23
# Write a Python program to alter the owner and the group id of a specified file. import os fd = os.open( "/tmp", os.O_RDONLY ) os.fchown( fd, 100, -1) os.fchown( fd, -1, 50) print("Changed ownership successfully..") os.close( fd )
39
# Minimum difference between two elements in an array import sysarr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size):    num = int(input())    arr.append(num)Min_diff=sys.maxsizefor i in range(0,size-1):    for j in range(i+1, size):        if abs(arr[j]-arr[i])<Min_diff:            Min_diff = abs(arr[j] - arr[i])print("Minimum difference between two Element is ",Min_diff)
52
# Write a Python program to Replace NaN values with average of columns # Python code to demonstrate # to replace nan values # with an average of columns    import numpy as np    # Initialising numpy array ini_array = np.array([[1.3, 2.5, 3.6, np.nan],                        [2.6, 3.3, np.nan, 5.5],                       [2.1, 3.2, 5.4, 6.5]])    # printing initial array print ("initial array", ini_array)    # column mean col_mean = np.nanmean(ini_array, axis = 0)    # printing column mean print ("columns mean", str(col_mean))    # find indices where nan value is present inds = np.where(np.isnan(ini_array))    # replace inds with avg of column ini_array[inds] = np.take(col_mean, inds[1])    # printing final array print ("final array", ini_array)
106
# Maximum of two numbers in Python # Python program to find the # maximum of two numbers def maximum(a, b):           if a >= b:         return a     else:         return b       # Driver code a = 2 b = 4 print(maximum(a, b))
41
# Write a Pandas program to convert index of a given dataframe into a column. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 32, 33, 30, 31, 32]}, index = ['t1', 't2', 't3', 't4', 't5', 't6']) print("Original DataFrame:") print(df) print("\nConvert index of the said dataframe into a column:") df.reset_index(level=0, inplace=True) print(df)
74
# Isoformat to datetime – Python # importing datetime module from datetime import datetime    # Getting today's date todays_Date = datetime.now()    # Get date into the isoformat isoformat_date = todays_Date.isoformat()    # print the type of date print(type(isoformat_date))    # convert string date into datetime format result = datetime.fromisoformat(isoformat_date) print(type(result))
48
# Write a NumPy program to create an array of ones and an array of zeros. import numpy as np print("Create an array of zeros") x = np.zeros((1,2)) print("Default type is float") print(x) print("Type changes to int") x = np.zeros((1,2), dtype = np.int) print(x) print("Create an array of ones") y= np.ones((1,2)) print("Default type is float") print(y) print("Type changes to int") y = np.ones((1,2), dtype = np.int) print(y)
67
# Write a Pandas program to create a yearly time period from a specified year and display the properties of this period. import pandas as pd ytp = pd.Period('2020','A-DEC') print("Yearly time perid:",ytp) print("\nAll the properties of the said period:") print(dir(ytp))
40
# Write a Pandas program to remove the duplicates from 'WHO region' column of 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("\nAfter removing the duplicates of WHO region column:") print(w_a_con.drop_duplicates('WHO region'))
46
# Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i n=int(raw_input()) values = [] for i in NumGenerator(n): values.append(str(i)) print ",".join(values)
56
# Write a Python program to Convert JSON to string import json # create a sample json a = {"name" : "GeeksforGeeks", "Topic" : "Json to String", "Method": 1} # Convert JSON to String y = json.dumps(a) print(y) print(type(y))
39
# Write a Python program to use double quotes to display strings. import json print(json.dumps({'Alex': 1, 'Suresh': 2, 'Agnessa': 3}))
20
# Write a NumPy program to sort a given array by row and column in ascending order. import numpy as np nums = np.array([[5.54, 3.38, 7.99], [3.54, 4.38, 6.99], [1.54, 2.39, 9.29]]) print("Original array:") print(nums) print("\nSort the said array by row in ascending order:") print(np.sort(nums)) print("\nSort the said array by column in ascending order:") print(np.sort(nums, axis=0))
56
# Write a Python function to reverses a string if it's length is a multiple of 4. def reverse_string(str1): if len(str1) % 4 == 0: return ''.join(reversed(str1)) return str1 print(reverse_string('abcd')) print(reverse_string('python'))
31
# Write a Python program to Convert Tuple Matrix to Tuple List # Python3 code to demonstrate working of  # Convert Tuple Matrix to Tuple List # Using list comprehension + zip()    # initializing list test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)], [(0, 4), (10, 1)]]    # printing original list print("The original list is : " + str(test_list))    # flattening  temp = [ele for sub in test_list for ele in sub]    # joining to form column pairs res = list(zip(*temp))    # printing result  print("The converted tuple list : " + str(res))
94
# Write a Python program to add leading zeroes to a string. str1='122.22' print("Original String: ",str1) print("\nAdded trailing zeros:") str1 = str1.ljust(8, '0') print(str1) str1 = str1.ljust(10, '0') print(str1) print("\nAdded leading zeros:") str1='122.22' str1 = str1.rjust(8, '0') print(str1) str1 = str1.rjust(10, '0') print(str1)
43
# Write a NumPy program to make all the elements of a given string to a numeric string of 5 digits with zeros on its left. import numpy as np x = np.array(['2', '11', '234', '1234', '12345'], dtype=np.str) print("\nOriginal Array:") print(x) r = np.char.zfill(x, 5) print("\nNumeric string of 5 digits with zeros:") print(r)
53
# Write a Python program which iterates the integers from 1 to a given number and print "Fizz" for multiples of three, print "Buzz" for multiples of five, print "FizzBuzz" for multiples of both three and five using itertools module. #Source:https://bit.ly/30PS62m import itertools as it def fizz_buzz(n): fizzes = it.cycle([""] * 2 + ["Fizz"]) buzzes = it.cycle([""] * 4 + ["Buzz"]) fizzes_buzzes = (fizz + buzz for fizz, buzz in zip(fizzes, buzzes)) result = (word or n for word, n in zip(fizzes_buzzes, it.count(1))) for i in it.islice(result, 100): print(i) n = 50 fizz_buzz(n)
93
# Write a Pandas program to convert year and day of year into a single datetime column of a dataframe. import pandas as pd data = {\ "year": [2002, 2003, 2015, 2018], "day_of_the_year": [250, 365, 1, 140] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) df["combined"] = df["year"]*1000 + df["day_of_the_year"] df["date"] = pd.to_datetime(df["combined"], format = "%Y%j") print("\nNew DataFrame:") print(df)
58
# How to Change a Dictionary Into a Class in Python # Turns a dictionary into a class class Dict2Class(object):            def __init__(self, my_dict):                    for key in my_dict:             setattr(self, key, my_dict[key])    # Driver Code if __name__ == "__main__":            # Creating the dictionary     my_dict = {"Name": "Geeks",                "Rank": "1223",                "Subject": "Python"}            result = Dict2Class(my_dict)            # printing the result     print("After Converting Dictionary to Class : ")     print(result.Name, result.Rank, result.Subject)     print(type(result))
67
# Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib. import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.2) y = np.sin(x) print("Plot the points using matplotlib:") plt.plot(x, y) plt.show()
63
# Write a Python Program to Reverse a linked list # Python program to reverse a linked list # Time Complexity : O(n) # Space Complexity : O(n) as 'next' #variable is getting created in each loop. # Node class class Node:     # Constructor to initialize the node object     def __init__(self, data):         self.data = data         self.next = None class LinkedList:     # Function to initialize head     def __init__(self):         self.head = None     # Function to reverse the linked list     def reverse(self):         prev = None         current = self.head         while(current is not None):             next = current.next             current.next = prev             prev = current             current = next         self.head = prev     # Function to insert a new node at the beginning     def push(self, new_data):         new_node = Node(new_data)         new_node.next = self.head         self.head = new_node     # Utility function to print the linked LinkedList     def printList(self):         temp = self.head         while(temp):             print temp.data,             temp = temp.next # Driver program to test above functions llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(85) print "Given Linked List" llist.printList() llist.reverse() print "\nReversed Linked List" llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
179
# Write a NumPy program to change the data type of an array. import numpy as np x = np.array([[2, 4, 6], [6, 8, 10]], np.int32) print(x) print("Data type of the array x is:",x.dtype) # Change the data type of x y = x.astype(float) print("New Type: ",y.dtype) print(y)
48
# Count distinct substrings of a string using Rabin Karp algorithm in Python # importing libraries import sys import math as mt t = 1 # store prime to reduce overflow mod = 9007199254740881 for ___ in range(t):     # string to check number of distinct substring     s = 'abcd'     # to store substrings     l = []     # to store hash values by Rabin Karp algorithm     d = {}     for i in range(len(s)):         suma = 0         pre = 0         # Number of input alphabets         D = 256         for j in range(i, len(s)):             # calculate new hash value by adding next element             pre = (pre*D+ord(s[j])) % mod             # store string length if non repeat             if d.get(pre, -1) == -1:                 l.append([i, j])             d[pre] = 1     # resulting length     print(len(l))     # resulting distinct substrings     for i in range(len(l)):         print(s[l[i][0]:l[i][1]+1], end=" ")
137
# 7.2 Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. : class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width aRectangle = Rectangle(2,10) print aRectangle.area()
49
# Write a Python program to swap two sublists in a given list. nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print("Original list:") print(nums) nums[6:10], nums[1:3] = nums[1:3], nums[6:10] print("\nSwap two sublists of the said list:") print(nums) nums[1:3], nums[4:6] = nums[4:6], nums[1:3] print("\nSwap two sublists of the said list:") print(nums)
60
# Longest palindromic substring in a string def reverse(s):  str = ""  for i in s:    str = i + str  return strstr=input("Enter Your String:")sub_str=str.split(" ")sub_str1=[]p=0flag=0maxInd=0max=0str_rev=""print("Palindrome Substring are:")for inn in range(len(sub_str)):    str_rev= sub_str[inn]    if reverse(str_rev).__eq__(sub_str[inn]):        sub_str1.append(sub_str[inn])        print(sub_str1[p])        p +=1        flag = 1len2 = pif flag==1:    max = len(sub_str1[0])    for inn in range(0,len2):        len1 = len(sub_str1[inn])        if len1 > max:            max=len1            maxInd=inn    print("Longest palindrome Substring is ",sub_str1[maxInd])else:    print("No palindrome Found")
69
# Write a Python program to find all the h2 tags and list the first four from the webpage python.org. import requests from bs4 import BeautifulSoup url = 'https://www.python.org/' reqs = requests.get(url) soup = BeautifulSoup(reqs.text, 'lxml') print("First four h2 tags from the webpage python.org.:") print(soup.find_all('h2')[0:4])
45
# Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array. import numpy as np arra=np.ones((1,8,8)) print("Original array:") print(arra) result = np.triu(arra, k=1) print("\nResult:") print(result)
37
# How to add time onto a DateTime object in Python # Python3 code to illustrate the addition # of time onto the datetime object    # Importing datetime import datetime    # Initializing a date and time date_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)    print("Original time:") print(date_and_time)    # Calling the timedelta() function  time_change = datetime.timedelta(minutes=75) new_time = date_and_time + time_change    # Printing the new datetime object print("changed time:") print(new_time)
69
# Write a Python program to print the first n Lucky Numbers. n=int(input("Input a Number: ")) List=range(-1,n*n+9,2) i=2 while List[i:]:List=sorted(set(List)-set(List[List[i]::List[i]]));i+=1 print(List[1:n+1])
21
# Write a Python program to sort a list of elements using the insertion sort algorithm. def insertionSort(nlist): for index in range(1,len(nlist)): currentvalue = nlist[index] position = index while position>0 and nlist[position-1]>currentvalue: nlist[position]=nlist[position-1] position = position-1 nlist[position]=currentvalue nlist = [14,46,43,27,57,41,45,21,70] insertionSort(nlist) print(nlist)
42
# rite a Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output (all characters in lower case). lines = [] while True: l = input() if l: lines.append(l.upper()) else: break; for l in lines: print(l)
46
# How to get element-wise true division of an array using Numpy in Python # import library import numpy as np    # create 1d-array x = np.arange(5)    print("Original array:",        x)    # apply true division  # on each array element rslt = np.true_divide(x, 4)    print("After the element-wise division:",        rslt)
48
# Select any row from a Dataframe using iloc[] and iat[] in Pandas in Python import pandas as pd     # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'Cost':[10000, 5000, 15000, 2000]}) # Create an empty list Row_list =[]     # Iterate over each row for i in range((df.shape[0])):         # Using iloc to access the values of      # the current row denoted by "i"     Row_list.append(list(df.iloc[i, :]))     # Print the first 3 elements print(Row_list[:3])
77
# How to create filename containing date or time in Python # import module from datetime import datetime    # get current date and time current_datetime = datetime.now() print("Current date & time : ", current_datetime)    # convert datetime obj to string str_current_datetime = str(current_datetime)    # create a file object along with extension file_name = str_current_datetime+".txt" file = open(file_name, 'w')    print("File created : ", file.name) file.close()
64
# Saving a Networkx graph in GEXF format and visualize using Gephi in Python # importing the required module import networkx as nx # making a simple graph with 1 node. G = nx.path_graph(10) # saving graph created above in gexf format nx.write_gexf(G, "geeksforgeeks.gexf")
44
# Write a Python program to generate a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit. def arithmetic_progression(n, x): return list(range(n, x + 1, n)) print(arithmetic_progression(1, 15)) print(arithmetic_progression(3, 37)) print(arithmetic_progression(5, 25))
42
# Write a Python program to get the current value of the recursion limit. import sys print() print("Current value of the recursion limit:") print(sys.getrecursionlimit()) print()
25
# Python Program to Find the Total Sum of a Nested List Using Recursion def sum1(lst): total = 0 for element in lst: if (type(element) == type([])): total = total + sum1(element) else: total = total + element return total print( "Sum is:",sum1([[1,2],[3,4]]))
43
# Write a Python program to extract every first or specified element from a given two-dimensional list. def specified_element(nums, N): result = [i[N] for i in nums] return result nums = [ [1,2,3,2], [4,5,6,2], [7,1,9,5], ] print("Original list of lists:") print(nums) N = 0 print("\nExtract every first element from the said given two dimensional list:") print(specified_element(nums, N)) N = 2 print("\nExtract every third element from the said given two dimensional list:") print(specified_element(nums, N))
73
# Write a Python program to create multiple lists. obj = {} for i in range(1, 21): obj[str(i)] = [] print(obj)
21
# Write a Python program to combines two or more dictionaries, creating a list of values for each key. from collections import defaultdict def test(*dicts): result = defaultdict(list) for el in dicts: for key in el: result[key].append(el[key]) return dict(result) d1 = {'w': 50, 'x': 100, 'y': 'Green', 'z': 400} d2 = {'x': 300, 'y': 'Red', 'z': 600} print("Original dictionaries:") print(d1) print(d2) print("\nCombined dictionaries, creating a list of values for each key:") print(test(d1, d2))
73
# Program to check whether number is Spy Number or Not num=int(input("Enter a number:")) sum=0 mult=1 while num!=0:     rem = num % 10     sum += rem     mult *= rem     num //= 10 if sum==mult:     print("It is a spy Number.") else:    print("It is not a spy Number.")
46
# How to compute the eigenvalues and right eigenvectors of a given square array using NumPY in Python # importing numpy library import numpy as np    # create numpy 2d-array m = np.array([[1, 2],               [2, 3]])    print("Printing the Original square array:\n",       m)    # finding eigenvalues and eigenvectors w, v = np.linalg.eig(m)    # printing eigen values print("Printing the Eigen values of the given square array:\n",       w)    # printing eigen vectors print("Printing Right eigenvectors of the given square array:\n"       v)
78
# Write a Python program to find the minimum, maximum value for each tuple position in a given list of tuples. def max_min_list_tuples(nums): zip(*nums) result1 = map(max, zip(*nums)) result2 = map(min, zip(*nums)) return list(result1), list(result2) nums = [(2,3),(2,4),(0,6),(7,1)] print("Original list:") print(nums) result = max_min_list_tuples(nums) print("\nMaximum value for each tuple position in the said list of tuples:") print(result[0]) print("\nMinimum value for each tuple position in the said list of tuples:") print(result[1])
70
# Python Program to Reverse a Stack using Recursion 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()   def display(self): for data in reversed(self.items): print(data)   def insert_at_bottom(s, data): if s.is_empty(): s.push(data) else: popped = s.pop() insert_at_bottom(s, data) s.push(popped)     def reverse_stack(s): if not s.is_empty(): popped = s.pop() reverse_stack(s) insert_at_bottom(s, popped)     s = Stack() data_list = input('Please enter the elements to push: ').split() for data in data_list: s.push(int(data))   print('The stack:') s.display() reverse_stack(s) print('After reversing:') s.display()
85
# Write a Pandas program to drop the columns where at least one element is 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':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013], 'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6], 'ord_date': ['2012-10-05','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':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001], 'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]}) print("Original Orders DataFrame:") print(df) print("\nDrop the columns where at least one element is missing:") result = df.dropna(axis='columns') print(result)
60
# Pandas | Basic of Time Series Manipulation in Python import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start ='1/1/2019', end ='1/08/2019',                                                    freq ='Min') print(range_date)
31
# Write a Pandas program to get the items of a given series not present in another given series. import pandas as pd sr1 = pd.Series([1, 2, 3, 4, 5]) sr2 = pd.Series([2, 4, 6, 8, 10]) print("Original Series:") print("sr1:") print(sr1) print("sr2:") print(sr2) print("\nItems of sr1 not present in sr2:") result = sr1[~sr1.isin(sr2)] print(result)
54
# Check if element exists in list in Python # Python code to demonstrate # checking of element existence # using loops and in # Initializing list test_list = [ 1, 6, 3, 5, 3, 4 ] print("Checking if 4 exists in list ( using loop ) : ") # Checking if 4 exists in list # using loop for i in test_list:     if(i == 4) :         print ("Element Exists") print("Checking if 4 exists in list ( using in ) : ") # Checking if 4 exists in list # using in if (4 in test_list):     print ("Element Exists")
99
# Write a Python program to calculate arc length of an angle. def arclength(): pi=22/7 diameter = float(input('Diameter of circle: ')) angle = float(input('angle measure: ')) if angle >= 360: print("Angle is not possible") return arc_length = (pi*diameter) * (angle/360) print("Arc Length is: ", arc_length) arclength()
46
# Write a Python program to construct a Decimal from a float and a Decimal from a string. Also represent the Decimal value as a tuple. Use decimal.Decimal import decimal print("Construct a Decimal from a float:") pi_val = decimal.Decimal(3.14159) print(pi_val) print(pi_val.as_tuple()) print("\nConstruct a Decimal from a string:") num_str = decimal.Decimal("123.25") print(num_str) print(num_str.as_tuple())
52
# Write a NumPy program to test a given array element-wise for finiteness (not infinity or not a Number). import numpy as np a = np.array([1, 0, np.nan, np.inf]) print("Original array") print(a) print("Test a given array element-wise for finiteness :") print(np.isfinite(a))
41
# Write a NumPy program to create a white image of size 512x256. from PIL import Image import numpy as np a = np.full((512, 256, 3), 255, dtype=np.uint8) image = Image.fromarray(a, "RGB") image.save("white.png", "PNG")
34
# Python Program to Compute Prime Factors of an Integer   n=int(input("Enter an integer:")) print("Factors are:") i=1 while(i<=n): k=0 if(n%i==0): j=1 while(j<=i): if(i%j==0): k=k+1 j=j+1 if(k==2): print(i) i=i+1
27
# Write a Python program to Convert numeric words to numbers # Python3 code to demonstrate working of  # Convert numeric words to numbers # Using join() + split()    help_dict = {     'one': '1',     'two': '2',     'three': '3',     'four': '4',     'five': '5',     'six': '6',     'seven': '7',     'eight': '8',     'nine': '9',     'zero' : '0' }    # initializing string test_str = "zero four zero one"    # printing original string print("The original string is : " + test_str)    # Convert numeric words to numbers # Using join() + split() res = ''.join(help_dict[ele] for ele in test_str.split())    # printing result  print("The string after performing replace : " + res) 
105
# Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string. def first_three(str): return str[:3] if len(str) > 3 else str print(first_three('ipy')) print(first_three('python')) print(first_three('py'))
47
# Write a Pandas program to set value in a specific cell in a given dataframe using index. import pandas as pd df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'], 'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'], 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'], 'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'weight': [35, 32, 33, 30, 31, 32]}, index = ['t1', 't2', 't3', 't4', 't5', 't6']) print("Original DataFrame:") print(df) print("\nSet school code 's004' to 's005':") df.at['t6', 'school_code'] = 's005' print(df) print("\nSet date_of_birth of 'Alberto Franco' to '16/05/2002':") df.at['t1', 'date_of_birth'] = '16/05/2002' print(df)
88
# Program to compute the perimeter of Trapezoid print("Enter the value of base:") a=int(input()) b=int(input()) print("Enter the value of side:") c=int(input()) d=int(input()) perimeter=a+b+c+d print("Perimeter of the Trapezoid = ",perimeter)
29
# Maximum difference between two elements in an array import sysarr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size):    num = int(input())    arr.append(num)Max_diff=-sys.maxsize-1for i in range(0,size-1):    for j in range(i+1, size):        if abs(arr[j]-arr[i])>Max_diff:            Max_diff = abs(arr[j] - arr[i])print("Maximum difference between two Element is ",Max_diff)
52
# Create two arrays of six elements. Write a NumPy program to count the number of instances of a value occurring in one array on the condition of another array. import numpy as np x = np.array([10,-10,10,-10,-10,10]) y = np.array([.85,.45,.9,.8,.12,.6]) print("Original arrays:") print(x) print(y) result = np.sum((x == 10) & (y > .5)) print("\nNumber of instances of a value occurring in one array on the condition of another array:") print(result)
70
# Program to Print the Hollow Half Pyramid Star Pattern row_size=int(input("Enter the row size:"))print_control_x=row_size//2+1for out in range(1,row_size+1):    for inn in range(1,row_size+1):        if inn==1 or out==inn or out==row_size:            print("*",end="")        else:            print(" ", end="")    print("\r")
33
# Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns. import pandas as pd df = pd.DataFrame({'year': [2018, 2019, 2020], 'month': [2, 3, 4], 'day': [4, 5, 6], 'hour': [2, 3, 4]}) print("Original dataframe:") print(df) result = pd.to_datetime(df) print("\nSeries of Timestamps from the said dataframe:") print(result) print("\nSeries of Timestamps using specified columns:") print(pd.to_datetime(df[['year', 'month', 'day']]))
73
# Difference between List comprehension and Lambda in Python lst  =  [x ** 2  for x in range (1, 11)   if  x % 2 == 1] print(lst)
27
# 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 = ""                    # initializing ptr to head         ptr = self.head                   # traversing and adding it to res         while ptr:             res += str(ptr.val) + ", "             ptr = ptr.next           # removing trailing commas         res = res.strip(", ")                    # chen checking if          # anything is present in res or not         if len(res):             return "[" + res + "]"         else:             return "[]"       if __name__ == "__main__":          # defining linked list     ll = LinkedList()        # defining nodes     node1 = Node(10)     node2 = Node(15)     node3 = Node(20)        # connecting the nodes     ll.head = node1     node1.next = node2     node2.next = node3            # when print is called, by default      #it calls the __str__ method     print(ll)
143
# numpy string operations | not_equal() function in Python # Python program explaining # numpy.char.not_equal() method     # importing numpy  import numpy as geek    # input arrays   in_arr1 = geek.array('numpy') print ("1st Input array : ", in_arr1)    in_arr2 = geek.array('nump') print ("2nd Input array : ", in_arr2)      # checking if they are not equal out_arr = geek.char.not_equal(in_arr1, in_arr2) print ("Output array: ", out_arr) 
62
# Write a Pandas program to create a time series object that has time indexed data. Also select the dates of same year and select the dates between certain dates. import pandas as pd index = pd.DatetimeIndex(['2011-09-02', '2012-08-04', '2015-09-03', '2010-08-04', '2015-03-03', '2011-08-04', '2015-04-03', '2012-08-04']) s_dates = pd.Series([0, 1, 2, 3, 4, 5, 6, 7], index=index) print("Time series object with indexed data:") print(s_dates) print("\nDates of same year:") print(s_dates['2015']) print("\nDates between 2012-01-01 and 2012-12-31") print(s_dates['2012-01-01':'2012-12-31'])
73
# Write a NumPy program to create two arrays with shape (300,400, 5), fill values using unsigned integer (0 to 255). Insert a new axis that will appear at the beginning in the expanded array shape. Now combine the said two arrays into one. import numpy as np nums1 = np.random.randint(low=0, high=256, size=(200, 300, 3), dtype=np.uint8) nums2 = np.random.randint(low=0, high=256, size=(200, 300, 3), dtype=np.uint8) print("Array1:") print(nums1) print("\nArray2:") print(nums2) nums1 = np.expand_dims(nums1, axis=0) nums2 = np.expand_dims(nums2, axis=0) nums = np.append(nums1, nums2, axis=0) print("\nCombined array:") print(nums)
84
# Write a Python program to convert any base to decimal by using int() method # Python program to convert any base # number to its corresponding decimal # number    # Function to convert any base number # to its corresponding decimal number def any_base_to_decimal(number, base):            # calling the builtin function      # int(number, base) by passing      # two arguments in it number in     # string form and base and store     # the output value in temp     temp = int(number, base)            # printing the corresponding decimal     # number     print(temp)    # Driver's Code if __name__ == '__main__' :     hexadecimal_number = '1A'     base = 16     any_base_to_decimal(hexadecimal_number, base)
104
# Write a Python program to change a given string to a new string where the first and last chars have been exchanged. def change_sring(str1): return str1[-1:] + str1[1:-1] + str1[:1] print(change_sring('abcd')) print(change_sring('12345'))
33
# Write a NumPy program to create to concatenate two given arrays of shape (2, 2) and (2,1). import numpy as np nums1 = np.array([[4.5, 3.5], [5.1, 2.3]]) nums2 = np.array([[1], [2]]) print("Original arrays:") print(nums1) print(nums2) print("\nConcatenating the said two arrays:") print(np.concatenate((nums1, nums2), axis=1))
44
# Write a Python program to create a doubly linked list, append some items and iterate through the list (print forward). class Node(object): # Doubly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linked_list(object): def __init__(self): self.head = None self.tail = None self.count = 0 def append_item(self, data): # Append an item new_item = Node(data, None, None) if self.head is None: self.head = new_item self.tail = self.head else: new_item.prev = self.tail self.tail.next = new_item self.tail = new_item self.count += 1 def print_foward(self): for node in self.iter(): print(node) def iter(self): # Iterate the list current = self.head while current: item_val = current.data current = current.next yield item_val items = doubly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') print("Items in the Doubly linked list: ") items.print_foward()
131
# Write a Pandas program to create a Pivot table and calculate number of women and men were in a particular cabin class. import pandas as pd import numpy as np df = pd.read_csv('titanic.csv') result = df.pivot_table(index=['sex'], columns=['pclass'], aggfunc='count') print(result)
40
# Write a Python program to list the tables of given SQLite database file. import sqlite3 from sqlite3 import Error def sql_connection(): try: conn = sqlite3.connect('mydatabase.db') return conn except Error: print(Error) def sql_table(conn): cursorObj = conn.cursor() # Create two tables cursorObj.execute("CREATE TABLE agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);") cursorObj.execute("CREATE TABLE temp_agent_master(agent_code char(6),agent_name char(40),working_area char(35),commission decimal(10,2),phone_no char(15) NULL);") print("List of tables:") cursorObj.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursorObj.fetchall()) conn.commit() sqllite_conn = sql_connection() sql_table(sqllite_conn) if (sqllite_conn): sqllite_conn.close() print("\nThe SQLite connection is closed.")
81
# Find out all Perfect numbers present within a given range '''Write a Python program to find out all Perfect numbers present within a given range. or Write a program to find out all Perfect numbers present within a given range using Python ''' print("Enter a range:") range1=int(input()) range2=int(input()) print("Perfect numbers between ",range1," and ",range2," are: ") for j in range(range1,range2+1):     sum=0     num=j     for i in range(1,j):         if(j%i==0):             sum=sum+i     if sum==num:       print(j,end=" ") 
73
# Write a Python program to find the first repeated character in a given string. def first_repeated_char(str1): for index,c in enumerate(str1): if str1[:index+1].count(c) > 1: return c return "None" print(first_repeated_char("abcdabcd")) print(first_repeated_char("abcd"))
31
# Write a Python program to concatenate all elements in a list into a string and return it. def concatenate_list_data(list): result= '' for element in list: result += str(element) return result print(concatenate_list_data([1, 5, 12, 2]))
35
# Program to check whether a matrix is symmetric or not # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) if row_size!=col_size: print("Given Matrix is not a Square Matrix.") else: #compute the transpose matrix tran_matrix = [[0 for i in range(col_size)] for i in range(row_size)] for i in range(0, row_size): for j in range(0, col_size): tran_matrix[i][j] = matrix[j][i] # check given matrix elements and transpose # matrix elements are same or not. flag=0 for i in range(0, row_size): for j in range(0, col_size): if matrix[i][j] != tran_matrix[i][j]: flag=1 break if flag==1: print("Given Matrix is not a symmetric Matrix.") else: print("Given Matrix is a symmetric Matrix.")
136
# Write a NumPy program to create a vector of size 10 with values ranging from 0 to 1, both excluded. import numpy as np x = np.linspace(0,1,12,endpoint=True)[1:-1] print(x)
29
# Write a Python program to print a given doubly linked list in reverse order. class Node(object): # Singly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linked_list(object): def __init__(self): self.head = None self.tail = None self.count = 0 def append_item(self, data): # Append an item new_item = Node(data, None, None) if self.head is None: self.head = new_item self.tail = self.head else: new_item.prev = self.tail self.tail.next = new_item self.tail = new_item self.count += 1 def iter(self): # Iterate the list current = self.head while current: item_val = current.data current = current.next yield item_val def print_foward(self): for node in self.iter(): print(node) def reverse(self): """ Reverse linked list. """ current = self.head while current: temp = current.next current.next = current.prev current.prev = temp current = current.prev temp = self.head self.head = self.tail self.tail = temp items = doubly_linked_list() items.append_item('PHP') items.append_item('Python') items.append_item('C#') items.append_item('C++') items.append_item('Java') items.append_item('SQL') print("Reverse list ") items.reverse() items.print_foward()
156
# Write a Python program to split values into two groups, based on the result of the given filtering function. def bifurcate_by(lst, fn): return [ [x for x in lst if fn(x)], [x for x in lst if not fn(x)] ] print(bifurcate_by(['red', 'green', 'black', 'white'], lambda x: x[0] == 'w'))
50
# Write a Pandas program to get the index of an element of a given Series. import pandas as pd ds = pd.Series([1,3,5,7,9,11,13,15], index=[0,1,2,3,4,5,7,8]) print("Original Series:") print(ds) print("\nIndex of 11 in the said series:") x = ds[ds == 11].index[0] print(x)
40
# Write a Python program to Maximum record value key in dictionary # Python3 code to demonstrate working of  # Maximum record value key in dictionary # Using loop    # initializing dictionary test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},              'is' : {'Manjeet' : 8, 'Himani' : 9},              'best' : {'Manjeet' : 10, 'Himani' : 15}}    # printing original dictionary print("The original dictionary is : " + str(test_dict))    # initializing search key key = 'Himani'    # Maximum record value key in dictionary # Using loop res = None res_max = 0 for sub in test_dict:     if test_dict[sub][key] > res_max:         res_max = test_dict[sub][key]         res = sub    # printing result  print("The required key is : " + str(res)) 
118
# Write a Python program to print a long text, convert the string to a list and print all the words and their frequencies. string_words = '''United States Declaration of Independence From Wikipedia, the free encyclopedia The United States Declaration of Independence is the statement adopted by the Second Continental Congress meeting at the Pennsylvania State House (Independence Hall) in Philadelphia on July 4, 1776, which announced that the thirteen American colonies, then at war with the Kingdom of Great Britain, regarded themselves as thirteen independent sovereign states, no longer under British rule. These states would found a new nation – the United States of America. John Adams was a leader in pushing for independence, which was passed on July 2 with no opposing vote cast. A committee of five had already drafted the formal declaration, to be ready when Congress voted on independence. John Adams persuaded the committee to select Thomas Jefferson to compose the original draft of the document, which Congress would edit to produce the final version. The Declaration was ultimately a formal explanation of why Congress had voted on July 2 to declare independence from Great Britain, more than a year after the outbreak of the American Revolutionary War. The next day, Adams wrote to his wife Abigail: "The Second Day of July 1776, will be the most memorable Epocha, in the History of America." But Independence Day is actually celebrated on July 4, the date that the Declaration of Independence was approved. After ratifying the text on July 4, Congress issued the Declaration of Independence in several forms. It was initially published as the printed Dunlap broadside that was widely distributed and read to the public. The source copy used for this printing has been lost, and may have been a copy in Thomas Jefferson's hand.[5] Jefferson's original draft, complete with changes made by John Adams and Benjamin Franklin, and Jefferson's notes of changes made by Congress, are preserved at the Library of Congress. The best-known version of the Declaration is a signed copy that is displayed at the National Archives in Washington, D.C., and which is popularly regarded as the official document. This engrossed copy was ordered by Congress on July 19 and signed primarily on August 2. The sources and interpretation of the Declaration have been the subject of much scholarly inquiry. The Declaration justified the independence of the United States by listing colonial grievances against King George III, and by asserting certain natural and legal rights, including a right of revolution. Having served its original purpose in announcing independence, references to the text of the Declaration were few in the following years. Abraham Lincoln made it the centerpiece of his rhetoric (as in the Gettysburg Address of 1863) and his policies. Since then, it has become a well-known statement on human rights, particularly its second sentence: We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. This has been called "one of the best-known sentences in the English language", containing "the most potent and consequential words in American history". The passage came to represent a moral standard to which the United States should strive. This view was notably promoted by Abraham Lincoln, who considered the Declaration to be the foundation of his political philosophy and argued that it is a statement of principles through which the United States Constitution should be interpreted. The U.S. Declaration of Independence inspired many other similar documents in other countries, the first being the 1789 Declaration of Flanders issued during the Brabant Revolution in the Austrian Netherlands (modern-day Belgium). It also served as the primary model for numerous declarations of independence across Europe and Latin America, as well as Africa (Liberia) and Oceania (New Zealand) during the first half of the 19th century.''' word_list = string_words.split() word_freq = [word_list.count(n) for n in word_list] print("String:\n {} \n".format(string_words)) print("List:\n {} \n".format(str(word_list))) print("Pairs (Words and Frequencies:\n {}".format(str(list(zip(word_list, word_freq)))))
673
# Write a Python program to replace a given tag with whatever's inside a given tag. from bs4 import BeautifulSoup markup = '<a href="https://w3resource.com/">Python exercises.<i>w3resource.com</i></a>' soup = BeautifulSoup(markup, "lxml") a_tag = soup.a print("Original markup:") print(a_tag) a_tag.i.unwrap() print("\nAfter unwrapping:") print(a_tag)
39
# Creating a dataframe from Pandas series in Python import pandas as pd import matplotlib.pyplot as plt    author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']    auth_series = pd.Series(author) print(auth_series)
27

Dataset Card for "python-code-ds-mini"

More Information needed

Downloads last month
184
Edit dataset card

Models trained or fine-tuned on dipesh/python-code-ds-mini