code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python program to square the elements of a list using map() function.
def square_num(n):
return n * n
nums = [4, 5, 2, 9]
print("Original List: ",nums)
result = map(square_num, nums)
print("Square the elements of the said list using map():")
print(list(result))
| 44 |
# Validate an IP address using Python without using RegEx
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# check number of periods
if s.count('.') != 3:
return 'Invalid Ip address'
l = list(map(str, s.split('.')))
# check range of each number between periods
for ele in l:
if int(ele) < 0 or int(ele) > 255:
return 'Invalid Ip address'
return 'Valid Ip address'
# Driver Code
print(isValidIP('666.1.2.2')) | 76 |
# Write a Pandas program to create a Pivot table and find the minimum sale value of the items.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df, index='Item', values='Sale_amt', aggfunc=np.min)
print(table)
| 37 |
# Write a Python program to add a prefix text to all of the lines in a string.
import textwrap
sample_text ='''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
text_without_Indentation = textwrap.dedent(sample_text)
wrapped = textwrap.fill(text_without_Indentation, width=50)
#wrapped += '\n\nSecond paragraph after a blank line.'
final_result = textwrap.indent(wrapped, '> ')
print()
print(final_result)
print()
| 85 |
# Replace NumPy array elements that doesn’t satisfy the given condition in Python
# Importing Numpy module
import numpy as np
# Creating a 1-D Numpy array
n_arr = np.array([75.42436315, 42.48558583, 60.32924763])
print("Given array:")
print(n_arr)
print("\nReplace all elements of array which are greater than 50. to 15.50")
n_arr[n_arr > 50.] = 15.50
print("New array :\n")
print(n_arr) | 56 |
# Write a Python program to Filter the List of String whose index in second List contaons the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using zip() + loop + in
# operator
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and",
"not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok",
"ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
res = []
# using zip() to map by index
for ele1, ele2 in zip(test_list1, test_list2):
# checking for substring
if sub_str in ele2:
res.append(ele1)
# printing result
print("The extracted list : " + str(res)) | 135 |
# Write a Python program to convert a given list of integers and a tuple of integers in a list of strings.
nums_list = [1,2,3,4]
nums_tuple = (0, 1, 2, 3)
print("Original list and tuple:")
print(nums_list)
print(nums_tuple)
result_list = list(map(str,nums_list))
result_tuple = tuple(map(str,nums_tuple))
print("\nList of strings:")
print(result_list)
print("\nTuple of strings:")
print(result_tuple)
| 51 |
# Check if two arrays are the disjoint or not
arr=[]
arr2=[]
size = int(input("Enter the size of the 1st array: "))
size2 = int(input("Enter the size of the 2nd array: "))
print("Enter the Element of the 1st array:")
for i in range(0,size):
num = int(input())
arr.append(num)
print("Enter the Element of the 2nd array:")
for i in range(0,size2):
num2 = int(input())
arr2.append(num2)
count=0
for i in range(0, size):
for j in range(0, size2):
if arr[i] == arr2[j]:
count+=1
if count>=1:
print("Arrays are not disjoint.")
else:
print("Arrays are disjoint.") | 88 |
# Write a NumPy program to compute the inner product of two given vectors.
import numpy as np
x = np.array([4, 5])
y = np.array([7, 10])
print("Original vectors:")
print(x)
print(y)
print("Inner product of said vectors:")
print(np.dot(x, y))
| 37 |
# Define a class, which have a class parameter and have a same instance parameter.
:
class Person:
# Define the class parameter "name"
name = "Person"
def __init__(self, name = None):
# self.name is the instance parameter
self.name = name
jeffrey = Person("Jeffrey")
print "%s name is %s" % (Person.name, jeffrey.name)
nico = Person()
nico.name = "Nico"
print "%s name is %s" % (Person.name, nico.name)
| 66 |
# Program to print the Half Pyramid Number Pattern
row_size=int(input("Enter the row size:"))
for out in range(row_size+1):
for i in range(1,out+1):
print(i,end="")
print("\r")
| 23 |
# Write a Pandas program to calculate all Thursdays between two given days.
import pandas as pd
thursdays = pd.date_range('2020-01-01',
'2020-12-31', freq="W-THU")
print("All Thursdays between 2020-01-01 and 2020-12-31:\n")
print(thursdays.values)
| 29 |
# Write a Python program to remove a tag or string from a given tree of html document and replace it with the given tag or string.
from bs4 import BeautifulSoup
html_markup= '<a href="https://w3resource.com/">Python exercises<i>w3resource</i></a>'
soup = BeautifulSoup(html_markup, "lxml")
print("Original markup:")
a_tag = soup.a
print(a_tag)
new_tag = soup.new_tag("b")
new_tag.string = "PHP"
b_tag = a_tag.i.replace_with(new_tag)
print("New Markup:")
print(a_tag)
| 57 |
# Write a NumPy program to extract all the elements of the second and third columns from a given (4x4) array.
import numpy as np
arra_data = np.arange(0,16).reshape((4, 4))
print("Original array:")
print(arra_data)
print("\nExtracted data: All the elements of the second and third columns")
print(arra_data[:,[1,2]])
| 44 |
# Write a Python program to Sort Nested keys by Value
# Python3 code to demonstrate working of
# Sort Nested keys by Value
# Using sorted() + generator expression + lamda
# initializing dictionary
test_dict = {'Nikhil' : {'English' : 5, 'Maths' : 2, 'Science' : 14},
'Akash' : {'English' : 15, 'Maths' : 7, 'Science' : 2},
'Akshat' : {'English' : 5, 'Maths' : 50, 'Science' : 20}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Sort Nested keys by Value
# Using sorted() + generator expression + lamda
res = {key : dict(sorted(val.items(), key = lambda ele: ele[1]))
for key, val in test_dict.items()}
# printing result
print("The sorted dictionary : " + str(res)) | 120 |
# How to get list of parameters name from a function in Python
# import required modules
import inspect
import collections
# use signature()
print(inspect.signature(collections.Counter)) | 25 |
# Write a NumPy program to create a one dimensional array of forty pseudo-randomly generated values. Select random numbers from a uniform distribution between 0 and 1.
import numpy as np
np.random.seed(10)
print(np.random.rand(40))
| 33 |
# Program to print the Solid Inverted Half 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 p in range(row_size,abs(out),-1):
print("*",end="")
print("\r") | 31 |
# Write a Python program to match key values in two dictionaries.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
| 45 |
# Write a Python program to create a list containing the power of said number in bases raised to the corresponding number in the index using Python map.
bases_num = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Base numbers abd index: ")
print(bases_num)
print(index)
result = list(map(pow, bases_num, index))
print("\nPower of said number in bases raised to the corresponding number in the index:")
print(result)
| 79 |
# Write a program to Find the nth Perfect Number
'''Write a Python
program to find the nth perfect number. or Write a
program to find the nth perfect number using Python '''
print("Enter a Nth Number:")
rangenumber=int(input())
c = 0
letest = 0
num = 1
while (c != rangenumber):
sum = 0
for i in range(num):
if (num % i == 0):
sum = sum + i
if (sum == num):
c+=1
letest = num
num = num + 1
print(rangenumber,"th perfect number is ",letest)
| 87 |
# Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors.
def smallest_multiple(n):
if (n<=2):
return n
i = n * 2
factors = [number for number in range(n, 1, -1) if number * 2 > n]
print(factors)
while True:
for a in factors:
if i % a != 0:
i += n
break
if (a == factors[-1] and i % a == 0):
return i
print(smallest_multiple(13))
print(smallest_multiple(11))
print(smallest_multiple(2))
print(smallest_multiple(1))
| 78 |
# Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included).
def printValues():
l = list()
for i in range(1,31):
l.append(i**2)
print(l[5:])
printValues()
| 42 |
# Working with large CSV files in Python
# import required modules
import pandas as pd
import numpy as np
import time
# time taken to read data
s_time = time.time()
df = pd.read_csv("gender_voice_dataset.csv")
e_time = time.time()
print("Read without chunks: ", (e_time-s_time), "seconds")
# data
df.sample(10) | 46 |
# Intersection of two arrays in Python ( Lambda expression and filter function )
# Function to find intersection of two arrays
def interSection(arr1,arr2):
# filter(lambda x: x in arr1, arr2) -->
# filter element x from list arr2 where x
# also lies in arr1
result = list(filter(lambda x: x in arr1, arr2))
print ("Intersection : ",result)
# Driver program
if __name__ == "__main__":
arr1 = [1, 3, 4, 5, 7]
arr2 = [2, 3, 5, 6]
interSection(arr1,arr2) | 79 |
# Write a Python program to find the difference between consecutive numbers in a given list.
def diff_consecutive_nums(nums):
result = [b-a for a, b in zip(nums[:-1], nums[1:])]
return result
nums1 = [1, 1, 3, 4, 4, 5, 6, 7]
print("Original list:")
print(nums1)
print("Difference between consecutive numbers of the said list:")
print(diff_consecutive_nums(nums1))
nums2 = [4, 5, 8, 9, 6, 10]
print("\nOriginal list:")
print(nums2)
print("Difference between consecutive numbers of the said list:")
print(diff_consecutive_nums(nums2))
| 71 |
# Write a Python program to iterate over dictionaries using for loops.
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
print(color_key, 'corresponds to ', d[color_key])
| 30 |
# Write a Python program that sum the length of the names of a given list of names after removing the names that starts with an lowercase letter. Use lambda function.
sample_names = ['sally', 'Dylan', 'rebecca', 'Diana', 'Joanne', 'keith']
sample_names=list(filter(lambda el:el[0].isupper() and el[1:].islower(),sample_names))
print("Result:")
print(len(''.join(sample_names)))
| 45 |
# Write a NumPy program to compute the factor of a given array by Singular Value Decomposition.
import numpy as np
a = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float32)
print("Original array:")
print(a)
U, s, V = np.linalg.svd(a, full_matrices=False)
q, r = np.linalg.qr(a)
print("Factor of a given array by Singular Value Decomposition:")
print("U=\n", U, "\ns=\n", s, "\nV=\n", V)
| 72 |
# Find the Smallest digit in a number
'''Write a Python
program to add find the Smallest digit in a number. or Write a
program to add find the Smallest digit in a number using Python '''
print("Enter the Number :")
num=int(input())
smallest=num%10
while num > 0:
reminder = num % 10
if smallest > reminder:
smallest = reminder
num =int(num / 10)
print("The Smallest Digit is ", smallest)
| 69 |
# Write a Python program to sort a given list of tuples on specified element.
def sort_on_specific_item(lst, n):
result = sorted((lst), key=lambda x: x[n])
return result
items = [('item2', 10, 10.12), ('item3', 15, 25.10), ('item1', 11, 24.50),('item4', 12, 22.50)]
print("Original list of tuples:")
print(items)
print("\nSort on 1st element of the tuple of the said list:")
n = 0
print(sort_on_specific_item(items, n))
print("\nSort on 2nd element of the tuple of the said list:")
n = 1
print(sort_on_specific_item(items, n))
print("\nSort on 3rd element of the tuple of the said list:")
n = 2
print(sort_on_specific_item(items, n))
| 92 |
# Program to Find the sum of a lower 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(j) for j in input().split()])
#Calculate sum of lower triangular matrix element
sum=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i<j:
sum += matrix[i][j]
# display the sum of a lower triangular matrix element
print("Sum of Lower Triangular Matrix Elements is: ",sum) | 89 |
# Write a Python program to Intersection of two lists
# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2)) | 68 |
# Write a Python program to find files having a particular extension using RegEx
# import library
import re
# list of different types of file
filenames = ["gfg.html", "geeks.xml",
"computer.txt", "geeksforgeeks.jpg"]
for file in filenames:
# search given pattern in the line
match = re.search("\.xml$", file)
# if match is found
if match:
print("The file ending with .xml is:",
file) | 61 |
# Python Program to Implement Binary Tree using Linked List
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def search(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
btree = None
print('Menu (this assumes no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('quit')
while True:
print('inorder traversal of binary tree: ', end='')
if btree is not None:
btree.inorder()
print()
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)
elif operation == 'quit':
break | 208 |
# Write a NumPy program to encode all the elements of a given array in cp500 and decode it again.
import numpy as np
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
print("Original Array:")
print(x)
encoded_char = np.char.encode(x, 'cp500')
decoded_char = np.char.decode(encoded_char,'cp500')
print("\nencoded =", encoded_char)
print("decoded =", decoded_char)
| 48 |
# Write a NumPy program to compute cross-correlation of two given arrays.
import numpy as np
x = np.array([0, 1, 3])
y = np.array([2, 4, 5])
print("\nOriginal array1:")
print(x)
print("\nOriginal array1:")
print(y)
print("\nCross-correlation of the said arrays:\n",np.cov(x, y))
| 38 |
# Write a Python program to configure the rounding to round to the floor, ceiling. Use decimal.ROUND_FLOOR, decimal.ROUND_CEILING
import decimal
print("Configure the rounding to round to the floor:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_FLOOR
print(decimal.Decimal(20) / decimal.Decimal(6))
print("\nConfigure the rounding to round to the ceiling:")
decimal.getcontext().prec = 4
decimal.getcontext().rounding = decimal.ROUND_CEILING
print(decimal.Decimal(20) / decimal.Decimal(6))
| 54 |
# Write a NumPy program to extract all numbers from a given array which are less and greater than a specified number.
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)
n = 5
print("\nElements of the said array greater than",n)
print(nums[nums > n])
n = 6
print("\nElements of the said array less than",n)
print(nums[nums < n])
| 66 |
# Write a Python program to sort a list of nested dictionaries.
my_list = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
print("Original List: ")
print(my_list)
my_list.sort(key=lambda e: e['key']['subkey'], reverse=True)
print("Sorted List: ")
print(my_list)
| 35 |
# Find 2nd smallest digit in a given number
'''Write a Python
program to Find 2nd smallest digit in a given number. or Write a
program to Find 2nd smallest digit in a given number using Python '''
import sys
print("Enter the Number :")
num=int(input())
smallest=sys.maxsize
sec_smallest=sys.maxsize
while num > 0:
reminder = num % 10
if smallest >= reminder:
sec_smallest=smallest
smallest = reminder
elif reminder <= sec_smallest:
sec_smallest=reminder
num =num // 10
print("The Second Smallest Digit is ", sec_smallest)
| 80 |
# Write a Python program to split a list every Nth element.
C = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
def list_slice(S, step):
return [S[i::step] for i in range(step)]
print(list_slice(C,3))
| 38 |
# Write a NumPy program to save a given array to a binary file .
import numpy as np
import os
a = np.arange(20)
np.save('temp_arra.npy', a)
print("Check if 'temp_arra.npy' exists or not?")
if os.path.exists('temp_arra.npy'):
x2 = np.load('temp_arra.npy')
print(np.array_equal(a, x2))
| 39 |
# Write a Python program to calculate the maximum and minimum sum of a sublist in a given list of lists.
def max_min_sublist(lst):
max_result = (max(lst, key=sum))
min_result = (min(lst, key=sum))
return max_result,min_result
nums = [[1,2,3,5], [2,3,5,4], [0,5,4,1], [3,7,2,1], [1,2,1,2]]
print("Original list:")
print(nums)
result = max_min_sublist(nums)
print("\nMaximum sum of sub list of the said list of lists:")
print(result[0])
print("\nMinimum sum of sub list of the said list of lists:")
print(result[1])
| 70 |
# Write a Python program to insert an element before each element of a list.
color = ['Red', 'Green', 'Black']
print("Original List: ",color)
color = [v for elt in color for v in ('c', elt)]
print("Original List: ",color)
| 38 |
# Write a Python program to Read CSV Columns Into List
# importing module
from pandas import *
# reading CSV file
data = read_csv("company_sales_data.csv")
# converting column data to list
month = data['month_number'].tolist()
fc = data['facecream'].tolist()
fw = data['facewash'].tolist()
tp = data['toothpaste'].tolist()
sh = data['shampoo'].tolist()
# printing list data
print('Facecream:', fc)
print('Facewash:', fw)
print('Toothpaste:', tp)
print('Shampoo:', sh) | 58 |
# Write a Pandas program to check whether only proper case or title case is present in a given column of a DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'Hhhh', 'abcd', 'EAWQaaa'],
'date_of_sale ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]})
print("Original DataFrame:")
print(df)
print("\nIs proper case or title case?")
df['company_code_is_title'] = list(map(lambda x: x.istitle(), df['company_code']))
print(df)
| 60 |
# Write a NumPy program to remove a specific column from a given array.
import numpy as np
nums = np.random.random((7, 5))
print("Original array:")
print(nums)
print("\nDelete the first column of the said array:")
print(np.delete(nums, [0], axis=1))
print("\nDelete the last column of the said array:")
print(np.delete(nums, [4], axis=1))
| 47 |
# Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
:
Solution
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print evenNumbers
| 33 |
# Write a Python program to create a datetime object, converted to the specified timezone using arrow module.
import arrow
utc = arrow.utcnow()
pacific=arrow.now('US/Pacific')
nyc=arrow.now('America/Chicago').tzinfo
print(pacific.astimezone(nyc))
| 26 |
# Write a Python program to calculate the product of a given list of numbers using lambda.
import functools
def remove_duplicates(nums):
result = functools.reduce(lambda x, y: x * y, nums, 1)
return result
nums1 = [1,2,3,4,5,6,7,8,9,10]
nums2 = [2.2,4.12,6.6,8.1,8.3]
print("list1:", nums1)
print("Product of the said list numbers:")
print(remove_duplicates(nums1))
print("\nlist2:", nums2)
print("Product of the said list numbers:")
print(remove_duplicates(nums2))
| 57 |
# With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
n=int(raw_input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print d
| 47 |
# Write a Python program to find the longest common sub-string from two given strings.
from difflib import SequenceMatcher
def longest_Substring(s1,s2):
seq_match = SequenceMatcher(None,s1,s2)
match = seq_match.find_longest_match(0, len(s1), 0, len(s2))
# return the longest substring
if (match.size!=0):
return (s1[match.a: match.a + match.size])
else:
return ('Longest common sub-string not present')
s1 = 'abcdefgh'
s2 = 'xswerabcdwd'
print("Original Substrings:\n",s1+"\n",s2)
print("\nCommon longest sub_string:")
print(longest_Substring(s1,s2))
| 61 |
# Write a Python program to check if a given list is strictly increasing or not. Moreover, If removing only one element from the list results in a strictly increasing list, we still consider the list true.
# Source: https://bit.ly/3qZqcwm
def almost_increasing_sequence(sequence):
if len(sequence) < 3:
return True
a, b, *sequence = sequence
skipped = 0
for c in sequence:
if a < b < c: # XXX
a, b = b, c
continue
elif b < c: # !XX
a, b = b, c
elif a < c: # X!X
a, b = a, c
skipped += 1
if skipped == 2:
return False
return a < b
print(almost_increasing_sequence([]))
print(almost_increasing_sequence([1]))
print(almost_increasing_sequence([1, 2]))
print(almost_increasing_sequence([1, 2, 3]))
print(almost_increasing_sequence([3, 1, 2]))
print(almost_increasing_sequence([1, 2, 3, 0, 4, 5, 6]))
print(almost_increasing_sequence([1, 2, 3, 0]))
print(almost_increasing_sequence([1, 2, 0, 3]))
print(almost_increasing_sequence([10, 1, 2, 3, 4, 5]))
print(almost_increasing_sequence([1, 2, 10, 3, 4]))
print(almost_increasing_sequence([1, 2, 3, 12, 4, 5]))
print(almost_increasing_sequence([3, 2, 1]))
print(almost_increasing_sequence([1, 2, 0, -1]))
print(almost_increasing_sequence([5, 6, 1, 2]))
print(almost_increasing_sequence([1, 2, 3, 0, -1]))
print(almost_increasing_sequence([10, 11, 12, 2, 3, 4, 5]))
| 174 |
# Write a Python program to find common element(s) in a given nested lists.
def common_in_nested_lists(nested_list):
result = list(set.intersection(*map(set, nested_list)))
return result
nested_list = [[12, 18, 23, 25, 45], [7, 12, 18, 24, 28], [1, 5, 8, 12, 15, 16, 18]]
print("\nOriginal lists:")
print(nested_list)
print("\nCommon element(s) in nested lists:")
print(common_in_nested_lists(nested_list))
| 50 |
# Program to print the Solid Half Diamond Number Pattern
row_size=int(input("Enter the row size:"))for out in range(row_size,-(row_size+1),-1): for inn in range(row_size,abs(out)-1,-1): print(inn,end="") print("\r") | 23 |
# Write a Python program to remove all elements from a given list present in another list using lambda.
def index_on_inner_list(list1, list2):
result = list(filter(lambda x: x not in list2, list1))
return result
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [2,4,6,8]
print("Original lists:")
print("list1:", list1)
print("list2:", list2)
print("\nRemove all elements from 'list1' present in 'list2:")
print(index_on_inner_list(list1, list2))
| 55 |
# Write a Python program to read the current line from a given CSV file. Use csv.reader
import csv
f = open("employees.csv", newline='')
csv_reader = csv.reader(f)
print(next(csv_reader))
print(next(csv_reader))
print(next(csv_reader))
| 29 |
# Formatting float column of Dataframe in Pandas in Python
# import pandas lib as pd
import pandas as pd
# create the data dictionary
data = {'Month' : ['January', 'February', 'March', 'April'],
'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}
# create the dataframe
dataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])
print("Given Dataframe :\n", dataframe)
# round to two decimal places in python pandas
pd.options.display.float_format = '{:.2f}'.format
print('\nResult :\n', dataframe) | 69 |
# Write a Python program to find the items starts with specific character from a given list.
def test(lst, char):
result = [i for i in lst if i.startswith(char)]
return result
text = ["abcd", "abc", "bcd", "bkie", "cder", "cdsw", "sdfsd", "dagfa", "acjd"]
print("\nOriginal list:")
print(text)
char = "a"
print("\nItems start with",char,"from the said list:")
print(test(text, char))
char = "d"
print("\nItems start with",char,"from the said list:")
print(test(text, char))
char = "w"
print("\nItems start with",char,"from the said list:")
print(test(text, char))
| 78 |
# Write a NumPy program to compute the natural logarithm of one plus each element of a given array in floating-point accuracy.
import numpy as np
x = np.array([1e-99, 1e-100])
print("Original array: ")
print(x)
print("\nNatural logarithm of one plus each element:")
print(np.log1p(x))
| 42 |
# Write a NumPy program to find the number of elements of an array, length of one array element in bytes and total bytes consumed by the elements.
import numpy as np
x = np.array([1,2,3], dtype=np.float64)
print("Size of the array: ", x.size)
print("Length of one array element in bytes: ", x.itemsize)
print("Total bytes consumed by the elements of the array: ", x.nbytes)
| 62 |
# Convert a column to row name/index in Pandas in Python
# importing pandas as pd
import pandas as pd
# Creating a dict of lists
data = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"],
'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],
'Score':["80","90","60", "30", "50"],
'Result': ["Pass","Pass","Pass","Fail","Fail"]}
# creating a dataframe
df = pd.DataFrame(data)
df | 50 |
# Write a NumPy program to compute the weighted of a given array.
import numpy as np
x = np.arange(5)
print("\nOriginal array:")
print(x)
weights = np.arange(1, 6)
r1 = np.average(x, weights=weights)
r2 = (x*(weights/weights.sum())).sum()
assert np.allclose(r1, r2)
print("\nWeighted average of the said array:")
print(r1)
| 44 |
# Creating Pandas dataframe using list of lists in Python
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['Geeks', 10], ['for', 15], ['geeks', 20]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
print(df ) | 48 |
# 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_list))
# Convert Lists of List to Dictionary
# Using loop
res = dict()
for sub in test_list:
res[tuple(sub[:2])] = tuple(sub[2:])
# printing result
print("The mapped Dictionary : " + str(res)) | 88 |
# Write a Python program to check whether a string contains all letters of the alphabet.
import string
alphabet = set(string.ascii_lowercase)
input_string = 'The quick brown fox jumps over the lazy dog'
print(set(input_string.lower()) >= alphabet)
input_string = 'The quick brown fox jumps over the lazy cat'
print(set(input_string.lower()) >= alphabet)
| 49 |
# Write a Python Program for Rabin-Karp Algorithm for Pattern Searching
# Following program is the python implementation of
# Rabin Karp Algorithm given in CLRS book
# d is the number of characters in the input alphabet
d = 256
# pat -> pattern
# txt -> text
# q -> A prime number
def search(pat, txt, q):
M = len(pat)
N = len(txt)
i = 0
j = 0
p = 0 # hash value for pattern
t = 0 # hash value for txt
h = 1
# The value of h would be "pow(d, M-1)% q"
for i in xrange(M-1):
h = (h * d)% q
# Calculate the hash value of pattern and first window
# of text
for i in xrange(M):
p = (d * p + ord(pat[i]))% q
t = (d * t + ord(txt[i]))% q
# Slide the pattern over text one by one
for i in xrange(N-M + 1):
# Check the hash values of current window of text and
# pattern if the hash values match then only check
# for characters on by one
if p == t:
# Check for characters one by one
for j in xrange(M):
if txt[i + j] != pat[j]:
break
j+= 1
# if p == t and pat[0...M-1] = txt[i, i + 1, ...i + M-1]
if j == M:
print "Pattern found at index " + str(i)
# Calculate hash value for next window of text: Remove
# leading digit, add trailing digit
if i < N-M:
t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q
# We might get negative values of t, converting it to
# positive
if t < 0:
t = t + q
# Driver program to test the above function
txt = "GEEKS FOR GEEKS"
pat = "GEEK"
q = 101 # A prime number
search(pat, txt, q)
# This code is contributed by Bhavya Jain | 320 |
# Python Program to Find the Binary Equivalent of a Number without Using Recursion
n=int(input("Enter a number: "))
a=[]
while(n>0):
dig=n%2
a.append(dig)
n=n//2
a.reverse()
print("Binary Equivalent is: ")
for i in a:
print(i,end=" ") | 34 |
# Program to print the diamond shape in Python
// C++ program to print diamond shape
// with 2n rows
#include <bits/stdc++.h>
using namespace std;
// Prints diamond pattern with 2n rows
void printDiamond(int n)
{
int space = n - 1;
// run loop (parent loop)
// till number of rows
for (int i = 0; i < n; i++)
{
// loop for initially space,
// before star printing
for (int j = 0;j < space; j++)
cout << " ";
// Print i+1 stars
for (int j = 0; j <= i; j++)
cout << "* ";
cout << endl;
space--;
}
// Repeat again in reverse order
space = 0;
// run loop (parent loop)
// till number of rows
for (int i = n; i > 0; i--)
{
// loop for initially space,
// before star printing
for (int j = 0; j < space; j++)
cout << " ";
// Print i stars
for (int j = 0;j < i;j++)
cout << "* ";
cout << endl;
space++;
}
}
// Driver code
int main()
{
printDiamond(5);
return 0;
}
// This is code is contributed
// by rathbhupendra | 196 |
# Write a Python program to Read CSV Column into List without header
import csv
# reading data from a csv file 'Data.csv'
with open('Data.csv', newline='') as file:
reader = csv.reader(file, delimiter = ' ')
# store the headers in a separate variable,
# move the reader object to point on the next row
headings = next(reader)
# output list to store all rows
Output = []
for row in reader:
Output.append(row[:])
for row_num, rows in enumerate(Output):
print('data in row number {} is {}'.format(row_num+1, rows))
print('headers were: ', headings) | 89 |
# Write a Python Counter to find the size of largest subset of anagram words
# Function to find the size of largest subset
# of anagram words
from collections import Counter
def maxAnagramSize(input):
# split input string separated by space
input = input.split(" ")
# sort each string in given list of strings
for i in range(0,len(input)):
input[i]=''.join(sorted(input[i]))
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
freqDict = Counter(input)
# get maximum value of frequency
print (max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = 'ant magenta magnate tan gnamate'
maxAnagramSize(input) | 105 |
# Write a Python function that takes a number as a parameter and check the number is prime or not.
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))
| 43 |
# Write a python program to find the longest words.
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('test.txt'))
| 35 |
# Python Program to Remove All Tuples in a List of Tuples with the USN Outside the Given Range
y=[('a','12CS039'),('b','12CS320'),('c','12CS055'),('d','12CS100')]
low=int(input("Enter lower roll number (starting with 12CS):"))
up=int(input("Enter upper roll number (starting with 12CS):"))
l='12CS0'+str(low)
u='12CS'+str(up)
p=[x for x in y if x[1]>l and x[1]<u]
print(p) | 46 |
# Write a NumPy program to convert a PIL Image into a NumPy array.
import numpy as np
import PIL
img_data = PIL.Image.open('w3resource-logo.png' )
img_arr = np.array(img_data)
print(img_arr)
| 28 |
# Write a Python program for counting sort.
def counting_sort(array1, max_val):
m = max_val + 1
count = [0] * m
for a in array1:
# count occurences
count[a] += 1
i = 0
for a in range(m):
for c in range(count[a]):
array1[i] = a
i += 1
return array1
print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))
| 64 |
# How to open two files together in Python
# opening both the files in reading modes
with open("file1.txt") as f1, open("file2.txt") as f2:
# reading f1 contents
line1 = f1.readline()
# reading f2 contents
line2 = f2.readline()
# printing contents of f1 followed by f2
print(line1, line2) | 48 |
# Write a Python program to Replace negative value with zero in numpy array
# Python code to demonstrate
# to replace negative value with 0
import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print("initial array", ini_array1)
# code to replace all negative value with 0
ini_array1[ini_array1<0] = 0
# printing result
print("New resulting array: ", ini_array1) | 65 |
# Write a NumPy program to test whether a given 2D array has null columns or not.
import numpy as np
print("Original array:")
nums = np.random.randint(0,3,(4,10))
print(nums)
print("\nTest whether the said array has null columns or not:")
print((~nums.any(axis=0)).any())
| 38 |
# Write a Python program to get the key, value and item in a dictionary.
dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
print("key value count")
for count, (key, value) in enumerate(dict_num.items(), 1):
print(key,' ',value,' ', count)
| 43 |
# Write a Python program to find the power of a number using recursion
def power(N, P):
# if power is 0 then return 1
if P == 0:
return 1
# if power is 1 then number is
# returned
elif P == 1:
return N
else:
return (N*power(N, P-1))
# Driver program
N = 5
P = 2
print(power(N, P)) | 62 |
# Write a Python program to reverse a given list of lists.
def reverse_list_of_lists(list1):
return list1[::-1]
colors = [['orange', 'red'], ['green', 'blue'], ['white', 'black', 'pink']]
print("Original list:")
print(colors)
print("\nReverse said list of lists:")
print(reverse_list_of_lists(colors))
nums = [[1,2,3,4], [0,2,4,5], [2,3,4,2,4]]
print("\nOriginal list:")
print(nums)
print("\nReverse said list of lists:")
print(reverse_list_of_lists(nums))
| 48 |
# Write a Python program to iterate over all pairs of consecutive items in a given list.
def pairwise(l1):
temp = []
for i in range(len(l1) - 1):
current_element, next_element = l1[i], l1[i + 1]
x = (current_element, next_element)
temp.append(x)
return temp
l1 = [1,1,2,3,3,4,4,5]
print("Original lists:")
print(l1)
print("\nIterate over all pairs of consecutive items of the said list:")
print(pairwise(l1))
| 60 |
# How to get file creation and modification date or time in Python
import os
import time
# Path to the file/directory
path = r"C:\Program Files (x86)\Google\pivpT.png"
# Both the variables would contain time
# elapsed since EPOCH in float
ti_c = os.path.getctime(path)
ti_m = os.path.getmtime(path)
# Converting the time in seconds to a timestamp
c_ti = time.ctime(ti_c)
m_ti = time.ctime(ti_m)
print(
f"The file located at the path {path}
was created at {c_ti} and was last modified at {m_ti}") | 79 |
# Write a NumPy program to create a 1-D array going from 0 to 50 and an array from 10 to 50.
import numpy as np
x = np.arange(50)
print("Array from 0 to 50:")
print(x)
x = np.arange(10, 50)
print("Array from 10 to 50:")
print(x)
| 45 |
# Write a Python program to check whether a string starts with specified characters.
string = "w3resource.com"
print(string.startswith("w3r"))
| 18 |
# Write a Python program to create a dictionary from a string.
from collections import defaultdict, Counter
str1 = 'w3resource'
my_dict = {}
for letter in str1:
my_dict[letter] = my_dict.get(letter, 0) + 1
print(my_dict)
| 34 |
# Write a Python program to print four values decimal, octal, hexadecimal (capitalized), binary in a single line of a given integer.
i = int(input("Input an integer: "))
o = str(oct(i))[2:]
h = str(hex(i))[2:]
h = h.upper()
b = str(bin(i))[2:]
d = str(i)
print("Decimal Octal Hexadecimal (capitalized), Binary")
print(d,' ',o,' ',h,' ',b)
| 52 |
# Check whether a given number is prime or not
'''Write
a Python program to check whether a given number is a prime or not. or
Write a program to check whether
a given number is a prime or not using
Python '''
import math
num=int(input("Enter a number:"))
count=0
for i in range(2,int(math.sqrt(num))+1):
if num%i==0:
count+=1
if count==0:
print("It is Prime")
else:
print("It is not Prime")
| 66 |
# Write a Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res)) | 112 |
# How to choose elements from the list with different probability using NumPy in Python
# import numpy library
import numpy as np
# create a list
num_list = [10, 20, 30, 40, 50]
# uniformly select any element
# from the list
number = np.random.choice(num_list)
print(number) | 47 |
# Write a Python Program to Generate Random binary string
# Python program for random
# binary string generation
import random
# Function to create the
# random binary string
def rand_key(p):
# Variable to store the
# string
key1 = ""
# Loop to find the string
# of desired length
for i in range(p):
# randint function to generate
# 0, 1 randomly and converting
# the result into str
temp = str(random.randint(0, 1))
# Concatenatin the random 0, 1
# to the final result
key1 += temp
return(key1)
# Driver Code
n = 7
str1 = rand_key(n)
print("Desired length random binary string is: ", str1) | 108 |
# Write a Python program to get a list of locally installed Python modules.
import pkg_resources
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
for i in installed_packages])
for m in installed_packages_list:
print(m)
| 34 |
# Write a NumPy program to create a 12x12x4 array with random values and extract any array of shape(6,6,3) from the said array.
import numpy as np
nums = np.random.random((8,8,3))
print("Original array:")
print(nums)
print("\nExtract array of shape (6,6,3) from the said array:")
new_nums = nums[:6, :6, :]
print(new_nums)
| 48 |
# Convert multiple JSON files to CSV Python
# importing packages
import pandas as pd
# load json file using pandas
df1 = pd.read_json('file1.json')
# view data
print(df1)
# load json file using pandas
df2 = pd.read_json('file2.json')
# view data
print(df2)
# use pandas.concat method
df = pd.concat([df1,df2])
# view the concatenated dataframe
print(df)
# convert dataframe to csv file
df.to_csv("CSV.csv",index=False)
# load the resultant csv file
result = pd.read_csv("CSV.csv")
# and view the data
print(result) | 76 |
# Write a Python program to Convert List of Dictionaries to List of Lists
# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
{'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
{'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
# printing original list
print("The original list is : " + str(test_list))
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
res = []
for idx, sub in enumerate(test_list, start = 0):
if idx == 0:
res.append(list(sub.keys()))
res.append(list(sub.values()))
else:
res.append(list(sub.values()))
# printing result
print("The converted list : " + str(res)) | 122 |
# Write a NumPy program to generate inner, outer, and cross products of matrices and vectors.
import numpy as np
x = np.array([1, 4, 0], float)
y = np.array([2, 2, 1], float)
print("Matrices and vectors.")
print("x:")
print(x)
print("y:")
print(y)
print("Inner product of x and y:")
print(np.inner(x, y))
print("Outer product of x and y:")
print(np.outer(x, y))
print("Cross product of x and y:")
print(np.cross(x, y))
| 63 |
# Print the Inverted Pant's Shape Star Pattern
row_size=int(input("Enter the row size:"))for out in range(1,row_size+1): for inn in range(1,row_size*2): if inn<=out or inn>=row_size*2-out: print("*",end="") else: print(" ", end="") print("\r") | 29 |
# Python Program to Solve Fractional Knapsack Problem using Greedy Algorithm
def fractional_knapsack(value, weight, capacity):
"""Return maximum value of items and their fractional amounts.
(max_value, fractions) is returned where max_value is the maximum value of
items with total weight not more than capacity.
fractions is a list where fractions[i] is the fraction that should be taken
of item i, where 0 <= i < total number of items.
value[i] is the value of item i and weight[i] is the weight of item i
for 0 <= i < n where n is the number of items.
capacity is the maximum weight.
"""
# index = [0, 1, 2, ..., n - 1] for n items
index = list(range(len(value)))
# contains ratios of values to weight
ratio = [v/w for v, w in zip(value, weight)]
# index is sorted according to value-to-weight ratio in decreasing order
index.sort(key=lambda i: ratio[i], reverse=True)
max_value = 0
fractions = [0]*len(value)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += value[i]
capacity -= weight[i]
else:
fractions[i] = capacity/weight[i]
max_value += value[i]*capacity/weight[i]
break
return max_value, fractions
n = int(input('Enter number of items: '))
value = input('Enter the values of the {} item(s) in order: '
.format(n)).split()
value = [int(v) for v in value]
weight = input('Enter the positive weights of the {} item(s) in order: '
.format(n)).split()
weight = [int(w) for w in weight]
capacity = int(input('Enter maximum weight: '))
max_value, fractions = fractional_knapsack(value, weight, capacity)
print('The maximum value of items that can be carried:', max_value)
print('The fractions in which the items should be taken:', fractions) | 263 |
Subsets and Splits