code stringlengths 63 8.54k | code_length int64 11 747 |
|---|---|
# Write a Python program to Extract elements with Frequency greater than K
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using count() + loop
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_li... | 110 |
# Python Program to Create a Linked List & Display the Elements in the 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_no... | 107 |
# Write a NumPy program to select indices satisfying multiple conditions in a NumPy array.
import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print("Original arrays")
print(a)
print(b)
print("Elements from the second array corresponding to elements in the first array that... | 61 |
# Write a Python program to Generate k random dates between two other dates
# Python3 code to demonstrate working of
# Random K dates in Range
# Using choices() + timedelta() + loop
from datetime import date, timedelta
from random import choices
# initializing dates ranges
test_date1, test_date2 = date(2015, 6, 3... | 118 |
# Python Program to Detect if Two Strings are Anagrams
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.") | 26 |
# Write a Pandas program to extract date (format: mm-dd-yyyy) from a given column of a given DataFrame.
import pandas as pd
import re as re
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'date_of_sale': ['12/05/2002','16/02/1999','05/09/1998','12/02/2022','15/09/1997'],... | 64 |
# Write a Python program to find second largest number in a list
# Python program to find second largest
# number in a list
# list of numbers - length of
# list should be at least 2
list1 = [10, 20, 4, 45, 99]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)
for i in range(2,n):
if lis... | 73 |
# How to convert a Python datetime.datetime to excel serial date number
# Python3 code to illustrate the conversion of
# datetime.datetime to excel serial date number
# Importing datetime module
import datetime
# Calling the now() function to return
# current date and time
current_datetime = datetime.datetime.now... | 67 |
# Write a Pandas program to manipulate and convert date times with timezone information.
import pandas as pd
dtt = pd.date_range('2018-01-01', periods=3, freq='H')
dtt = dtt.tz_localize('UTC')
print(dtt)
print("\nFrom UTC to America/Los_Angeles:")
dtt = dtt.tz_convert('America/Los_Angeles')
print(dtt)
| 35 |
# Write a Python program to Get file id of windows file
# importing popen from the os library
from os import popen
# Path to the file whose id we would
# be obtaining (relative / absolute)
file = r"C:\Users\Grandmaster\Desktop\testing.py"
# Running the command for obtaining the fileid,
# and saving the output of ... | 72 |
# Write a Python program to Convert Nested dictionary to Mapped Tuple
# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
... | 110 |
# Write a Python program to Convert Tuple to Tuple Pair
# Python3 code to demonstrate working of
# Convert Tuple to Tuple Pair
# Using product() + next()
from itertools import product
# initializing tuple
test_tuple = ('G', 'F', 'G')
# printing original tuple
print("The original tuple : " + str(test_tuple))
... | 80 |
# Write a NumPy program to create a 90x30 array filled with random point numbers, increase the number of items (10 edge elements) shown by the print statement.
import numpy as np
nums = np.random.randint(10, size=(90, 30))
print("Original array:")
print(nums)
print("\nIncrease the number of items (10 edge elements)... | 55 |
# Mapping external values to dataframe values in Pandas in Python
# Creating new dataframe
import pandas as pd
initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'],
'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'],
'Age': [42, 52, 36, 21, 23],
'City': ['Mum... | 81 |
# Check whether a year is leap year or not
year=int(input("Enter a Year:"))
if ((year % 100 == 0 and year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)):
print("It is a Leap Year")
else:
print("It is not a Leap Year") | 49 |
# Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
values=raw_input()
l=values.split(",")
t=tuple(l)
print l
print t
| 31 |
#
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
import re
emailAddress = raw_input()
pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAdd... | 49 |
# Find the maximum 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 Pandas program to count year-country wise frequency of reporting dates of unidentified flying object(UFO).
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())
df['Year'] = df['Date_time'].apply(lambda x: "... | 50 |
# Write a NumPy program to get a copy of a matrix with the elements below the k-th diagonal zeroed.
import numpy as np
result = np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
print("\nCopy of a matrix with the elements below the k-th diagonal zeroed:")
print(result)
| 41 |
# Write a Python program to Test if tuple is distinct
# Python3 code to demonstrate working of
# Test if tuple is distinct
# Using loop
# initialize tuple
test_tup = (1, 4, 5, 6, 1, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Test if tuple is distinct
# Using loop
res =... | 89 |
# Access the elements of a Series in Pandas in Python
# importing pandas module
import pandas as pd
# making data frame
df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
ser = pd.Series(df['Name'])
ser.head(10)
# or simply df['Name'].head(10) | 34 |
# Program to remove all numbers from a String
str=input("Enter the String:")
str2 = []
i = 0
while i < len(str):
ch = str[i]
if not(ch >= '0' and ch <= '9'):
str2.append(ch)
i += 1
Final_String = ''.join(str2)
print("After removing numbers string is:",Final_String) | 45 |
# Write a Python program generate permutations of specified elements, drawn from specified values.
from itertools import product
def permutations_colors(inp, n):
for x in product(inp, repeat=n):
c = ''.join(x)
print(c,end=', ')
str1 = "Red"
print("Original String: ",str1)
print("Permutations o... | 89 |
# Write a Python program to count the number of sublists contain a particular element.
def count_element_in_list(input_list, x):
ctr = 0
for i in range(len(input_list)):
if x in input_list[i]:
ctr+= 1
return ctr
list1 = [[1, 3], [5, 7], [1, 11], [1, 15, 7]]
prin... | 94 |
# Bisect Algorithm Functions in Python
# Python code to demonstrate the working of
# bisect(), bisect_left() and bisect_right()
# importing "bisect" for bisection operations
import bisect
# initializing list
li = [1, 3, 4, 4, 4, 6, 7]
# using bisect() to find index to insert new element
# returns 5 ( right m... | 149 |
#
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.
:
def removeDuplicate( li ):
newli=[]
seen = set()
for item in li:
if item not in seen:
seen.add( item )
newli.ap... | 49 |
# Write a Python program to move the specified number of elements to the start of the given list.
def move_start(nums, offset):
return nums[-offset:] + nums[:-offset]
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 3))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], -3))
print(move_start([1, 2, 3, 4, 5, 6, 7, 8], 8))
print... | 80 |
# Write a Python program to append a list to the second list.
list1 = [1, 2, 3, 0]
list2 = ['Red', 'Green', 'Black']
final_list = list1 + list2
print(final_list)
| 30 |
# How to count number of instances of a class in Python
# code
class geeks:
# this is used to print the number
# of instances of a class
counter = 0
# constructor of geeks class
def __init__(self):
# increment
geeks.counter += 1
# object or instance of geeks ... | 62 |
# Write a Pandas program to create a Pivot table and find the total sale amount region wise, manager wise.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
print(pd.pivot_table(df,index = ["Region","Manager"], values = ["Sale_amt"],aggfunc=np.sum))
| 37 |
# How to Convert an image to NumPy array and saveit to CSV file using Python
# import required libraries
from PIL import Image
import numpy as gfg
# read an image
img = Image.open('geeksforgeeks.jpg')
# convert image object into array
imageToMatrice = gfg.asarray(img)
# printing shape of image
print(imageToMatr... | 50 |
# Write a Python program to sort each sublist of strings in a given list of lists using lambda.
def sort_sublists(input_list):
result = [sorted(x, key = lambda x:x[0]) for x in input_list]
return result
color1 = [["green", "orange"], ["black", "white"], ["white", "black", "orange"]]
print("\nOriginal list:"... | 57 |
# Write a Pandas program to split the following dataset using group by on first column and aggregate over multiple lists on second column.
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({
'student_id': ['S001','S001','S0... | 58 |
# Write a Python program to sort a list of elements using shell sort algorithm.
def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for start_position in range(sublistcount):
gap_InsertionSort(alist, start_position, sublistcount)
print("After increments of size",su... | 69 |
# Write a Pandas program to count of occurrence of a specified substring in a DataFrame column.
import pandas as pd
df = pd.DataFrame({
'name_code': ['c001','c002','c022', 'c2002', 'c2222'],
'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22... | 55 |
# Write a NumPy program to find point by point distances of a random vector with shape (10,2) representing coordinates.
import numpy as np
a= np.random.random((10,2))
x,y = np.atleast_2d(a[:,0], a[:,1])
d = np.sqrt( (x-x.T)**2 + (y-y.T)**2)
print(d)
| 37 |
# Write a Python program to insert an element in a given list after every nth position.
def insert_elemnt_nth(lst, ele, n):
result = []
for st_idx in range(0, len(lst), n):
result.extend(lst[st_idx:st_idx+n])
result.append(ele)
result.pop()
return result
nums = [1,2,3,4,5,6,7,8,9... | 71 |
# Write a NumPy program to calculate the absolute value element-wise.
import numpy as np
x = np.array([-10.2, 122.2, .20])
print("Original array:")
print(x)
print("Element-wise absolute value:")
print(np.absolute(x))
| 27 |
# Write a Python program to sort unsorted strings using natural sort.
#Ref.https://bit.ly/3a657IZ
from __future__ import annotations
import re
def natural_sort(input_list: list[str]) -> list[str]:
def alphanum_key(key):
return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)]
... | 136 |
# Subtract Two Numbers Operator without using Minus(-) operator
num1=int(input("Enter first number:"))
num2=int(input("Enter second number:"))
sub=num1+(~num2+1)#number + 2's complement of number
print("Subtraction of two number is ",sub)
| 27 |
# Write a Python program to Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
# using list comprehension + all()
from itertools import groupby
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# initializing char list
char_list... | 116 |
# Write a Python program to sort unsorted numbers using Merge-insertion sort.
#Ref.https://bit.ly/3r32ezJ
from __future__ import annotations
def merge_insertion_sort(collection: list[int]) -> list[int]:
"""Pure implementation of merge-insertion sort algorithm in Python
:param collection: some mutable order... | 613 |
# Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.
import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)
| 36 |
# Python Program to Implement Binomial Heap
class BinomialTree:
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 BinomialHeap:
def __init__(self):
... | 251 |
# Find the number of occurrences of a sequence in a NumPy array in Python
# importing package
import numpy
# create numpy array
arr = numpy.array([[2, 8, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
# Counting sequence
output = repr(arr).count("9, 4... | 53 |
# Write a Python program to split a given multiline string into a list of lines.
def split_lines(s):
return s.split('\n')
print("Original string:")
print("This\nis a\nmultiline\nstring.\n")
print("Split the said multiline string into a list of lines:")
print(split_lines('This\nis a\nmultiline\nstring.\n'))
| 36 |
# Write a Pandas program to compare the elements of the two Pandas Series.
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Grea... | 57 |
# Write a Python program to convert string values of a given dictionary, into integer/float datatypes.
def convert_to_int(lst):
result = [dict([a, int(x)] for a, x in b.items()) for b in lst]
return result
def convert_to_float(lst):
result = [dict([a, float(x)] for a, x in b.items()) for b in lst]
r... | 97 |
# Write a Python program to check if a nested list is a subset of another nested list.
def checkSubset(input_list1, input_list2):
return all(map(input_list1.__contains__, input_list2))
list1 = [[1, 3], [5, 7], [9, 11], [13, 15, 17]]
list2 = [[1, 3],[13,15,17]]
print("Original list:")
print(list1)
p... | 131 |
# Write a Pandas program to extract only non alphanumeric characters from the specified column of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'company_code': ['c0001#','[email protected]^2','$c0003', 'c0003', '&c0004'],
'year': ['year 18... | 69 |
# Write a Python program to remove a specified dictionary from a given list.
def remove_dictionary(colors, r_id):
colors[:] = [d for d in colors if d.get('id') != r_id]
return colors
colors = [{"id" : "#FF0000", "color" : "Red"},
{"id" : "#800000", "color" : "Maroon"},
{"id" : "#FFFF00... | 73 |
# How to iterate over files in directory using Python
# import required module
import os
# assign directory
directory = 'files'
# iterate over files in
# that directory
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
# checking if it is a file
if os.path.isfile(f):
p... | 48 |
# Write a Python program to remove duplicates from Dictionary.
student_data = {'id1':
{'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id2':
{'name': ['David'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id3':
... | 69 |
# Write a Python program to Check if two strings are Rotationally Equivalent
# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
# initializing strings
test_str1 = 'geeks'
test_str2 = 'eksge'
# printing original strings
print("The original s... | 111 |
# Write a NumPy program to add an extra column to a NumPy array.
import numpy as np
x = np.array([[10,20,30], [40,50,60]])
y = np.array([[100], [200]])
print(np.append(x, y, axis=1))
| 29 |
#
Write a function to compute 5/0 and use try/except to catch the exceptions.
:
def throws():
return 5/0
try:
throws()
except ZeroDivisionError:
print "division by zero!"
except Exception, err:
print 'Caught an exception'
finally:
print 'In finally block for cleanup'
| 41 |
# Write a Python Program for Cocktail Sort
# Python program for implementation of Cocktail Sort
def cocktailSort(a):
n = len(a)
swapped = True
start = 0
end = n-1
while (swapped==True):
# reset the swapped flag on entering the loop,
# because it might be true from a previous
... | 219 |
# Write a Python program to get information about the file pertaining to the file mode. Print the information - ID of device containing file, inode number, protection, number of hard links, user ID of owner, group ID of owner, total size (in bytes), time of last access, time of last modification and time of last status... | 131 |
# Write a Python program to Consecutive Kth column Difference in Tuple List
# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using loop
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
# printing original list
print("The original list is :... | 96 |
# Find the size of a Set in Python
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), ( 2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1: " + str(sys.getsizeof(Set1)) + "bytes")
print("Size ... | 70 |
# Evaluate Einstein’s summation convention of two multidimensional NumPy arrays in Python
# Importing library
import numpy as np
# Creating two 2X2 matrix
matrix1 = np.array([[1, 2], [0, 2]])
matrix2 = np.array([[0, 1], [3, 4]])
print("Original matrix:")
print(matrix1)
print(matrix2)
# Output
result = np.ein... | 55 |
# Python Program to Count the Number of Digits in a Number
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count) | 26 |
# Write a Python program to create datetime from integers, floats and strings timestamps using arrow module.
import arrow
i = arrow.get(1857900545)
print("Date from integers: ")
print(i)
f = arrow.get(1857900545.234323)
print("\nDate from floats: ")
print(f)
s = arrow.get('1857900545')
print("\nDate from Strings: ")... | 43 |
# Python Program to Add a Key-Value Pair to the Dictionary
key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d) | 33 |
# Write a Python program to print even length words in a string
# Python3 program to print
# even length words in a string
def printWords(s):
# split the string
s = s.split(' ')
# iterate in words of string
for word in s:
# if length is even
if len(w... | 62 |
# Program to Find the sum of series 3+33+333.....+N
n=int(input("Enter the range of number:"))sum=0p=3for i in range(1,n+1): sum += p p=(p*10)+3print("The sum of the series = ",sum) | 27 |
# Write a Python program to replace hour, minute, day, month, year and timezone with specified value of current datetime using arrow.
import arrow
a = arrow.utcnow()
print("Current date and time:")
print(a)
print("\nReplace hour and minute with 5 and 35:")
print(a.replace(hour=5, minute=35))
print("\nReplace day wit... | 62 |
# Write a Python program to get the number of datasets currently listed on data.gov.
from lxml import html
import requests
response = requests.get('http://www.data.gov/')
doc_gov = html.fromstring(response.text)
link_gov = doc_gov.cssselect('small a')[0]
print("Number of datasets currently listed on data.gov:")... | 39 |
# Write a Python program to compare two given lists and find the indices of the values present in both lists.
def matched_index(l1, l2):
l2 = set(l2)
return [i for i, el in enumerate(l1) if el in l2]
nums1 = [1, 2, 3, 4, 5 ,6]
nums2 = [7, 8, 5, 2, 10, 12]
print("Original lists:")
print(nums1)
print(nums2)
p... | 149 |
# Get all rows in a Pandas DataFrame containing given substring in Python
# importing pandas
import pandas as pd
# Creating the dataframe with dict of lists
df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'],
'Team': ['Boston', 'Boston', 'Boston', 'Chele', 'Barse'],
... | 102 |
# Write a Python program to Count tuples occurrence in list of tuples
# Python code to count unique
# tuples in list of list
import collections
Output = collections.defaultdict(int)
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
[('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
... | 59 |
# Separate even and odd numbers in an array
arr=[]
size = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,size):
num = int(input())
arr.append(num)
print("\nOdd numbers are:")
for i in range(0,size):
if (arr[i] % 2 != 0):
print(arr[i],end=" ")... | 63 |
# Program to check the given number is a palindrome or not
'''Write
a Python program to check the given number is a palindrome or not. or
Write a program to check the
given number is a palindrome or not
using Python '''
num=int(input("Enter a number:"))
num1=num
num2=0
while(num!=0):
rem=num%10
num=int... | 61 |
# Write a NumPy program to sort the specified number of elements from beginning of a given array.
import numpy as np
nums = np.random.rand(10)
print("Original array:")
print(nums)
print("\nSorted first 5 elements:")
print(nums[np.argpartition(nums,range(5))])
| 33 |
# Write a Python program to replace dictionary values with their average.
def sum_math_v_vi_average(list_of_dicts):
for d in list_of_dicts:
n1 = d.pop('V')
n2 = d.pop('VI')
d['V+VI'] = (n1 + n2)/2
return list_of_dicts
student_details= [
{'id' : 1, 'subject' : 'math', 'V' : 70, 'VI'... | 71 |
# Write a Python program to get variable unique identification number or string.
x = 100
print(format(id(x), 'x'))
s = 'w3resource'
print(format(id(s), 'x'))
| 23 |
# Write a Python program to set a new value of an 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.ta... | 161 |
# Create Address Book in Write a Python program to Using Tkinter
# Import Module
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x500')
# Add Buttons, Label, ListBox
Name = StringVar()
Number = StringVar()
frame = Frame()
frame.pack(pady=10)
frame1 = Frame()
frame1.pa... | 124 |
# Write a Pandas program to import given excel data (employee.xlsx ) into a Pandas dataframe and sort based on multiple given columns.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\employee.xlsx')
result = df.sort_values(by=['first_name','last_name'],ascending=[0,1])
result
| 38 |
# Write a Python program to remove words from a given list of strings containing a character or string.
def remove_words(in_list, char_list):
new_list = []
for line in in_list:
new_words = ' '.join([word for word in line.split() if not any([phrase in word for phrase in char_list])])
new_list.... | 73 |
# Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0.
import numpy as np
x = np.eye(3)
print(x)
| 28 |
# Write a Python program to Replace words from Dictionary
# Python3 code to demonstrate working of
# Replace words from Dictionary
# Using split() + join() + get()
# initializing string
test_str = 'geekforgeeks best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# l... | 97 |
# Program to check whether a matrix is sparse 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([in... | 96 |
# Write a NumPy program to remove all rows in a NumPy array that contain non-numeric values.
import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print("Original array:")
print(x)
print("Remove all non-numeric elements of the said array")
print(x[~np.isnan(x).any(axis=1)])
| 41 |
# Program to find the sum of an upper triangular matrix
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([int... | 89 |
# Write a Python program to create the smallest 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=False,
key=lambda i: i*... | 128 |
# Write a Python program to sort a list of dictionaries using Lambda.
models = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'Mi Max', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}]
print("Original list of dictionaries :")
print(models)
sorted_models = sorted(models, key = l... | 47 |
# Write a Pandas program to find out the 'WHO region, 'Country', 'Beverage Types' 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 co... | 83 |
# Write a Python program to lowercase first n characters in a string.
str1 = 'W3RESOURCE.COM'
print(str1[:4].lower() + str1[4:])
| 19 |
# Write a Python program to set a random seed and get a random number between 0 and 1. Use random.random.
import random
print("Set a random seed and get a random number between 0 and 1:")
random.seed(0)
new_random_value = random.random()
print(new_random_value)
random.seed(1)
new_random_value = random.random()
prin... | 51 |
# Write a Pandas program to convert given datetime to timestamp.
import pandas as pd
import datetime as dt
import numpy as np
df = pd.DataFrame(index=pd.DatetimeIndex(start=dt.datetime(2019,1,1,0,0,1),
end=dt.datetime(2019,1,1,10,0,1), freq='H'))\
.reset_index().rename(columns={'index':'datetime'})
print("Samp... | 46 |
# Python Program to Remove the Given Key from a Dictionary
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d) | 36 |
# Write a NumPy program to get the qr factorization of a given array.
import numpy as np
a = np.array([[4, 12, -14], [12, 37, -53], [-14, -53, 98]], dtype=np.int32)
print("Original array:")
print(a)
q, r = np.linalg.qr(a)
print("qr factorization of the said array:")
print( "q=\n", q, "\nr=\n", r)
| 48 |
# Write a NumPy program to broadcast on different shapes of arrays where a(,3) + b(3).
import numpy as np
p = np.array([[0], [10], [20]])
q= np.array([10, 11, 12])
print("Original arrays:")
print("Array-1")
print(p)
print("Array-2")
print(q)
print("\nNew Array:")
new_array1 = p + q
print(new_array1)
| 43 |
# How to insert a space between characters of all the elements of a given NumPy array in Python
# importing numpy as np
import numpy as np
# creating array of string
x = np.array(["geeks", "for", "geeks"],
dtype=np.str)
print("Printing the Original Array:")
print(x)
# inserting space using np.ch... | 64 |
# Write a NumPy program to convert a given array into bytes, and load it as array.
import numpy as np
import os
a = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(a)
a_bytes = a.tostring()
a2 = np.fromstring(a_bytes, dtype=a.dtype)
print("After loading, content of the text file:")
print(a2)
print(np.arr... | 51 |
# Print mirrored right triangle Alphabet pattern
print("Enter the row and column size:");
row_size=input()
for out in range(ord('A'),ord(row_size)+1):
for i in range(ord('A'),out+1):
print(chr(i),end=" ")
print("\r")
| 25 |
# Write a NumPy program to create an array of equal shape and data type of a given array.
import numpy as np
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 8.32, 6.99],
[1.54, 2.39, 9.29]])
print("Original array:")
print(nums)
print("\nNew array of equal shape and data type of the said arr... | 53 |
# Write a Pandas program to join two dataframes using keys from right dataframe only.
import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3... | 94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.