code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python program to find all lower and upper mixed case combinations of a given string.
import itertools
def combination(str1):
result = map(''.join, itertools.product(*((c.lower(), c.upper()) for c in str1)))
return list(result)
st ="abc"
print("Original string:")
print(st)
print("All lower and upper mixed case combinations of the said string:")
print(combination(st))
st ="w3r"
print("\nOriginal string:")
print(st)
print("All lower and upper mixed case combinations of the said string:")
print(combination(st))
st ="Python"
print("\nOriginal string:")
print(st)
print("All lower and upper mixed case combinations of the said string:")
print(combination(st))
| 84 |
# Write a Python program to create a new Arrow object, cloned from the current one.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
cloned = a.clone()
print("\nCloned datetime:")
print(cloned)
| 30 |
# Write a Python program to Maximum occurring Substring from list
# Python3 code to demonstrate working of
# Maximum occurring Substring from list
# Using regex() + groupby() + max() + lambda
import re
import itertools
# initializing string
test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb"
test_list = ['gfg', 'is', 'best']
# printing original string and list
print("The original string is : " + test_str)
print("The original list is : " + str(test_list))
# Maximum occurring Substring from list
# Using regex() + groupby() + max() + lambda
seqs = re.findall(str.join('|', test_list), test_str)
grps = [(key, len(list(j))) for key, j in itertools.groupby(seqs)]
res = max(grps, key = lambda ele : ele[1])
# printing result
print("Maximum frequency substring : " + str(res[0])) | 118 |
# Write a Pandas program to get the items which are not common of two given series.
import pandas as pd
import numpy as np
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 a given series not present in another given series:")
sr11 = pd.Series(np.union1d(sr1, sr2))
sr22 = pd.Series(np.intersect1d(sr1, sr2))
result = sr11[~sr11.isin(sr22)]
print(result)
| 68 |
# Write a Python program to AND operation between Tuples
# Python3 code to demonstrate working of
# Cross Tuple AND operation
# using map() + lambda
# initialize tuples
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Cross Tuple AND operation
# using map() + lambda
res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2))
# printing result
print("Resultant tuple after AND operation : " + str(res)) | 92 |
# Write a Pandas program to create a Pivot table and find the region wise total sale.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\SaleData.xlsx')
table = pd.pivot_table(df,index="Region",values="Sale_amt", aggfunc = np.sum)
print(table)
| 35 |
# Write a NumPy program to repeat elements of an array.
import numpy as np
x = np.repeat(3, 4)
print(x)
x = np.array([[1,2],[3,4]])
print(np.repeat(x, 2))
| 25 |
# Python Program to Read a File and Capitalize the First Letter of Every Word in the File
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
l=line.title()
print(l) | 35 |
# Make a Pandas DataFrame with two-dimensional list | Python
# import pandas as pd
import pandas as pd
# List1
lst = [['Geek', 25], ['is', 30],
['for', 26], ['Geeksforgeeks', 22]]
# creating df object with columns specified
df = pd.DataFrame(lst, columns =['Tag', 'number'])
print(df ) | 46 |
# Print array elements in reverse order
arr=[]
cout=0
sum=0
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("After reversing array is :");
for i in range(size-1,-1,-1):
print(arr[i],end=" ") | 44 |
# Write a Python program to check whether lowercase letters exist in a string.
str1 = 'A8238i823acdeOUEI'
print(any(c.islower() for c in str1))
| 22 |
# Write a Python program to Numpy matrix.take()
# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1, 12, 3, 4, 6, 7]')
# applying matrix.take() method
geek = gfg.take(2)
print(geek) | 41 |
# Write a Python program to convert a given decimal number to binary list.
def decimal_to_binary_list(n):
result = [int(x) for x in list('{0:0b}'.format(n))]
return result
n = 8
print("Original Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))
n = 45
print("\nOriginal Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))
n = 100
print("\nOriginal Number:",n)
print("Decimal number (",n,") to binary list:")
print(decimal_to_binary_list(n))
| 61 |
# Write a Python dictionary, set and counter to check if frequencies can become same
# Function to Check if frequency of all characters
# can become same by one removal
from collections import Counter
def allSame(input):
# calculate frequency of each character
# and convert string into dictionary
dict=Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same)>2:
print('No')
elif len (same)==2 and same[1]-same[0]>1:
print('No')
else:
print('Yes')
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == "__main__":
input = 'xxxyyzzt'
allSame(input) | 100 |
# Write a Pandas program to insert a column at a specific index in a given DataFrame.
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'],
'weight': [35, 32, 33, 30, 31, 32]},
index = [1, 2, 3, 4, 5, 6])
print("Original DataFrame with single index:")
print(df)
date_of_birth = ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997']
idx = 3
print("\nInsert 'date_of_birth' column in 3rd position of the said DataFrame:")
df.insert(loc=idx, column='date_of_birth', value=date_of_birth)
print(df)
| 85 |
# Write a Python program to find all the values in a list are greater than a specified number.
list1 = [220, 330, 500]
list2 = [12, 17, 21]
print(all(x >= 200 for x in list1))
print(all(x >= 25 for x in list2))
| 43 |
# Write a Python program to create a deep copy of a given dictionary. Use copy.copy
import copy
nums_x = {"a":1, "b":2, 'cc':{"c":3}}
print("Original dictionary: ", nums_x)
nums_y = copy.deepcopy(nums_x)
print("\nDeep copy of the said list:")
print(nums_y)
print("\nChange the value of an element of the original dictionary:")
nums_x["cc"]["c"] = 10
print(nums_x)
print("\nSecond dictionary (Deep copy):")
print(nums_y)
nums = {"x":1, "y":2, 'zz':{"z":3}}
nums_copy = copy.deepcopy(nums)
print("\nOriginal dictionary :")
print(nums)
print("\nDeep copy of the said list:")
print(nums_copy)
print("\nChange the value of an element of the original dictionary:")
nums["zz"]["z"] = 10
print("\nFirst dictionary:")
print(nums)
print("\nSecond dictionary (Deep copy):")
print(nums_copy)
| 96 |
# How to get the Daily News using Python
import requests
from bs4 import BeautifulSoup | 15 |
# Write a Python program to get the sum of a non-negative integer.
def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))
print(sumDigits(345))
print(sumDigits(45))
| 32 |
# Write a NumPy program to check whether the NumPy array is empty or not.
import numpy as np
x = np.array([2, 3])
y = np.array([])
# size 2, array is not empty
print(x.size)
# size 0, array is empty
print(y.size)
| 41 |
# Write a Python Program to print hollow half diamond hash pattern
# python program to print
# hollow half diamond star
# function to print hollow
# half diamond star
def hollow_half_diamond(N):
# this for loop is for
# printing upper half
for i in range( 1, N + 1):
for j in range(1, i + 1):
# this is the condition to
# print "#" only on the
# boundaries
if i == j or j == 1:
print("#", end =" ")
# print " "(space) on the rest
# of the area
else:
print(" ", end =" ")
print()
# this for loop is to print lower half
for i in range(N - 1, 0, -1):
for j in range(1, i + 1):
if j == 1 or i == j:
print("#", end =" ")
else:
print(" ", end =" ")
print()
# Driver Code
if __name__ == "__main__":
N = 7
hollow_half_diamond( N )
| 158 |
# Write a Python program to create a list of empty dictionaries.
n = 5
l = [{} for _ in range(n)]
print(l)
| 23 |
# Convert the column type from string to datetime format in Pandas dataframe in Python
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({'Date':['11/8/2011', '04/23/2008', '10/2/2019'],
'Event':['Music', 'Poetry', 'Theatre'],
'Cost':[10000, 5000, 15000]})
# Print the dataframe
print(df)
# Now we will check the data type
# of the 'Date' column
df.info() | 58 |
# Write a Python program to scramble the letters of string in a given list.
from random import shuffle
def shuffle_word(text_list):
text_list = list(text_list)
shuffle(text_list)
return ''.join(text_list)
text_list = ['Python', 'list', 'exercises', 'practice', 'solution']
print("Original list:")
print(text_list)
print("\nAfter scrambling the letters of the strings of the said list:")
result = [shuffle_word(word) for word in text_list]
print(result)
| 56 |
# Write a Python program to print the following 'here document'.
print("""
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
""")
| 30 |
# Write a Python program to find the nested lists elements which are present in another list.
def intersection_nested_lists(l1, l2):
result = [[n for n in lst if n in l1] for lst in l2]
return result
nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums2 = [[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]]
print("\nOriginal lists:")
print(nums1)
print(nums2)
print("\nIntersection of said nested lists:")
print(intersection_nested_lists(nums1, nums2))
| 82 |
# Write a NumPy program to find the k smallest values of a given NumPy array.
import numpy as np
array1 = np.array([1, 7, 8, 2, 0.1, 3, 15, 2.5])
print("Original arrays:")
print(array1)
k = 4
result = np.argpartition(array1, k)
print("\nk smallest values:")
print(array1[result[:k]])
| 44 |
# Creating a Pandas Series from Dictionary in Python
# import the pandas lib as pd
import pandas as pd
# create a dictionary
dictionary = {'A' : 10, 'B' : 20, 'C' : 30}
# create a series
series = pd.Series(dictionary)
print(series) | 43 |
# Write a Python program to sort a list of elements using the quick sort algorithm.
def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
def quickSortHlp(data_list,first,last):
if first < last:
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = data_list[leftmark]
data_list[leftmark] = data_list[rightmark]
data_list[rightmark] = temp
temp = data_list[first]
data_list[first] = data_list[rightmark]
data_list[rightmark] = temp
return rightmark
data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)
print(data_list)
| 105 |
# Write a Python program to Program to print duplicates from a list of integers
# Python program to print
# duplicates from a list
# of integers
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size):
k = i + 1
for j in range(k, _size):
if x[i] == x[j] and x[i] not in repeated:
repeated.append(x[i])
return repeated
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
50, -20, 60, 60, -20, -20]
print (Repeat(list1))
# This code is contributed
# by Sandeep_anand | 90 |
# Write a Python program to sort a list of elements using Selection sort.
def selection_sort(nums):
for i, n in enumerate(nums):
mn = min(range(i,len(nums)), key=nums.__getitem__)
nums[i], nums[mn] = nums[mn], n
return nums
user_input = input("Input numbers separated by a comma:\n").strip()
nums = [int(item) for item in user_input.split(',')]
print(selection_sort(nums))
| 48 |
# Write a NumPy program to create an array with values ranging from 12 to 38.
import numpy as np
x = np.arange(12, 38)
print(x)
| 25 |
# Write a NumPy program to create an array of 4,5 shape and to reverse the rows of the said array. After reversing 1st row will be 4th and 4th will be 1st, 2nd row will be 3rd row and 3rd row will be 2nd row.
import numpy as np
array_nums = np.arange(20).reshape(4,5)
print("Original array:")
print(array_nums)
print("\nAfter reversing:")
array_nums[:] = array_nums[3::-1]
print(array_nums)
| 62 |
# Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).
print(abs.__doc__) | 17 |
# Write a Python program to Reverse All Strings in String List
# Python3 code to demonstrate
# Reverse All Strings in String List
# using list comprehension
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# Reverse All Strings in String List
res = [i[::-1] for i in test_list]
# printing result
print ("The reversed string list is : " + str(res)) | 82 |
# Program to find the nth Hashed number
print("Enter the Nth value:")
rangenumber=int(input())
num = 1
c = 0
letest = 0
while (c != rangenumber):
num2=num
num1=num
sum=0
while(num1!=0):
rem=num1%10
num1=num1//10
sum=sum+rem
if(num2%sum==0):
c+=1
letest=num
num = num + 1
print(rangenumber,"th Harshad number is ", letest);
| 47 |
# Write a NumPy program to find rows of a given array of shape (8,3) that contain elements of each row of another given array of shape (2,2).
import numpy as np
nums1 = np.random.randint(0,6,(6,4))
nums2 = np.random.randint(0,6,(2,3))
print("Original arrays:")
print(nums1)
print("\n",nums2)
temp = (nums1[..., np.newaxis, np.newaxis] == nums2)
rows = (temp.sum(axis=(1,2,3)) >= nums2.shape[1]).nonzero()[0]
print("\nRows of a given array that contain elements of each row of another given array:")
print(rows)
| 70 |
# Write a Python program to get the frequency of the elements in a given list of lists.
def count_elements_lists(nums):
nums = [item for sublist in nums for item in sublist]
dic_data = {}
for num in nums:
if num in dic_data.keys():
dic_data[num] += 1
else:
key = num
value = 1
dic_data[key] = value
return dic_data
nums = [
[1,2,3,2],
[4,5,6,2],
[7,8,9,5],
]
print("Original list of lists:")
print(nums)
print("\nFrequency of the elements in the said list of lists:")
print(count_elements_lists(nums))
| 80 |
# Write a Pandas program to create a plot of adjusted closing prices, 30 days simple moving average and exponential moving average of Alphabet Inc. between two specific dates.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
close_px = stock_data['Adj Close']
stock_data['SMA_30_days'] = stock_data.iloc[:,4].rolling(window=30).mean()
stock_data['EMA_20_days'] = stock_data.iloc[:,4].ewm(span=20,adjust=False).mean()
plt.figure(figsize=[15,10])
plt.grid(True)
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]\n',fontsize=18, color='black')
plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price', color='black')
plt.plot(stock_data['SMA_30_days'],label='30 days Simple moving average', color='red')
plt.plot(stock_data['EMA_20_days'],label='20 days Exponential moving average', color='green')
plt.legend(loc=2)
plt.show()
| 103 |
# Write a NumPy program to create a three-dimension array with shape (3,5,4) and set to a variable.
import numpy as np
nums = np.array([[[1, 5, 2, 1],
[4, 3, 5, 6],
[6, 3, 0, 6],
[7, 3, 5, 0],
[2, 3, 3, 5]],
[[2, 2, 3, 1],
[4, 0, 0, 5],
[6, 3, 2, 1],
[5, 1, 0, 0],
[0, 1, 9, 1]],
[[3, 1, 4, 2],
[4, 1, 6, 0],
[1, 2, 0, 6],
[8, 3, 4, 0],
[2, 0, 2, 8]]])
print("Array:")
print(nums)
| 86 |
# Write a Pandas program to filter those records where WHO region contains "Ea" substring from world alcohol consumption dataset.
import pandas as pd
# World alcohol consumption data
w_a_con = pd.read_csv('world_alcohol.csv')
print("World alcohol consumption sample data:")
print(w_a_con.head())
# Remove NA / NaN values
new_w_a_con = w_a_con.dropna()
print("\nMatch if a given column has a particular sub string:")
print(new_w_a_con[new_w_a_con["WHO region"].str.contains("Ea")])
| 59 |
# Convert decimal to binary using recursion
def DecimalToBinary(n): if n==0: return 0 else: return (n% 2 + 10 * DecimalToBinary(n // 2))n=int(input("Enter the Decimal Value:"))print("Binary Value of Decimal number is:",DecimalToBinary(n)) | 31 |
# Find the roots of the polynomials using NumPy in Python
# import numpy library
import numpy as np
# Enter the coefficients of the poly in the array
coeff = [1, 2, 1]
print(np.roots(coeff)) | 35 |
# Program to find the transpose of a 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()])
# Compute transpose of two matrices
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]
# display transpose of the matrix
print("Transpose of the Given Matrix is:")
for m in tran_matrix:
print(m) | 89 |
# Write a Python program to sort unsorted numbers using Stooge sort.
#Ref.https://bit.ly/3pk7iPH
def stooge_sort(arr):
stooge(arr, 0, len(arr) - 1)
return arr
def stooge(arr, i, h):
if i >= h:
return
# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
arr[i], arr[h] = arr[h], arr[i]
# If there are more than 2 elements in the array
if h - i + 1 > 2:
t = (int)((h - i + 1) / 3)
# Recursively sort first 2/3 elements
stooge(arr, i, (h - t))
# Recursively sort last 2/3 elements
stooge(arr, i + t, (h))
# Recursively sort first 2/3 elements
stooge(arr, i, (h - t))
lst = [4, 3, 5, 1, 2]
print("\nOriginal list:")
print(lst)
print("After applying Stooge sort the said list becomes:")
print(stooge_sort(lst))
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
print("\nOriginal list:")
print(lst)
print("After applying Stooge sort the said list becomes:")
print(stooge_sort(lst))
lst = [1.1, 1, 0, -1, -1.1, .1]
print("\nOriginal list:")
print(lst)
print("After applying Stooge sort the said list becomes:")
print(stooge_sort(lst))
| 178 |
# Write a Python program to Split String of list on K character
# Python3 code to demonstrate
# Split String of list on K character
# using loop + split()
# Initializing list
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
# printing original list
print("The original list is : " + str(test_list))
K = ' '
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
sub = ele.split(K)
res.extend(sub)
# printing result
print ("The extended list after split strings : " + str(res)) | 96 |
# Write a Python program to remove a specified item using the index from an array.
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
print("Remove the third item form the array:")
array_num.pop(2)
print("New array: "+str(array_num))
| 42 |
# Write a Python program to Multiply Adjacent elements
# Python3 code to demonstrate working of
# Adjacent element multiplication
# using zip() + generator expression + tuple
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Adjacent element multiplication
# using zip() + generator expression + tuple
res = tuple(i * j for i, j in zip(test_tup, test_tup[1:]))
# printing result
print("Resultant tuple after multiplication : " + str(res)) | 83 |
# Search a specified integer in an array
arr=[]
temp=0
pos=0
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("Enter the search element:")
ele=int(input())
print("Array elements are:")
for i in range(0,size):
print(arr[i],end=" ")
for i in range(0,size):
if arr[i] == ele:
temp = 1
if temp==1:
print("\nElement found....")
else:
print("\nElement not found....") | 67 |
# Write a NumPy program to join a sequence of arrays along a new axis.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([2, 3, 4])
print("Original arrays:")
print(x)
print(y)
print("Sequence of arrays along a new axis:")
print(np.vstack((x, y)))
x = np.array([[1], [2], [3]])
y = np.array([[2], [3], [4]])
print("\nOriginal arrays:")
print(x)
print()
print(y)
print("Sequence of arrays along a new axis:")
print(np.vstack((x, y)))
| 66 |
# 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 with 2:")
print(a.replace(day=2))
print("\nReplace year with 2021:")
print(a.replace(year=2021))
print("\nReplace month with 11:")
print(a.replace(month=11))
print("\nReplace timezone with 'US/Pacific:")
print(a.replace(tzinfo='US/Pacific'))
| 62 |
# Write a NumPy program to compute the reciprocal for all elements in a given array.
import numpy as np
x = np.array([1., 2., .2, .3])
print("Original array: ")
print(x)
r1 = np.reciprocal(x)
r2 = 1/x
assert np.array_equal(r1, r2)
print("Reciprocal for all elements of the said array:")
print(r1)
| 48 |
# Write a Pandas program to convert a series of date strings to a timeseries.
import pandas as pd
date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20'])
print("Original Series:")
print(date_series)
print("\nSeries of date strings to a timeseries:")
print(pd.to_datetime(date_series))
| 40 |
# Multithreaded Priority Queue in Python
import queue
import threading
import time
thread_exit_Flag = 0
class sample_Thread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("initializing " + self.name)
process_data(self.name, self.q)
print ("Exiting " + self.name)
# helper function to process data
def process_data(threadName, q):
while not thread_exit_Flag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("% s processing % s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
thread_list = ["Thread-1", "Thread-2", "Thread-3"]
name_list = ["A", "B", "C", "D", "E"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for thread_name in thread_list:
thread = sample_Thread(threadID, thread_name, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for items in name_list:
workQueue.put(items)
queueLock.release()
# Wait for the queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
thread_exit_Flag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exit Main Thread") | 169 |
# Write a Pandas program to create a stacked histograms plot of opening, closing, high, low stock prices of Alphabet Inc. between two specific dates.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(25,25))
df2.plot.hist(stacked=True, bins=20)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='blue')
plt.show()
| 74 |
# Write a Python program to get the size, permissions, owner, device, created, last modified and last accessed date time of a specified path.
import os
import sys
import time
path = 'g:\\testpath\\'
print('Path Name ({}):'.format(path))
print('Size:', stat_info.st_size)
print('Permissions:', oct(stat_info.st_mode))
print('Owner:', stat_info.st_uid)
print('Device:', stat_info.st_dev)
print('Created :', time.ctime(stat_info.st_ctime))
print('Last modified:', time.ctime(stat_info.st_mtime))
print('Last accessed:', time.ctime(stat_info.st_atime))
| 53 |
# Write a NumPy program to multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product.
import numpy as np
x = np.random.random((5,3))
print("First array:")
print(x)
y = np.random.random((3,2))
print("Second array:")
print(y)
z = np.dot(x, y)
print("Dot product of two arrays:")
print(z)
| 46 |
# Write a Pandas program to import excel data (employee.xlsx ) into a Pandas dataframe and find a list of employees where hire_date> 01-01-07.
import pandas as pd
import numpy as np
df = pd.read_excel('E:\employee.xlsx')
df[df['hire_date'] >='20070101']
| 37 |
# Write a Python program to remove all elements from a given list present in another list.
def index_on_inner_list(list1, list2):
result = [x for x in list1 if x not in list2]
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))
| 56 |
# Write a Python program to Reverse Sort a String
# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = ''.join(sorted(test_string, reverse = True))
# print result
print("String after reverse sorting : " + str(res)) | 72 |
# Write a Python program to Remove suffix from string list
# Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = 'x'
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
if word.endswith(suff):
test_list.remove(word)
# printing result
print("List after removal of suffix elements : " + str(test_list)) | 92 |
# Python Program to Remove Duplicates from a Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def get_prev_node(self, ref_node):
current = self.head
while (current and current.next != ref_node):
current = current.next
return current
def remove(self, node):
prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
def remove_duplicates(llist):
current1 = llist.head
while current1:
data = current1.data
current2 = current1.next
while current2:
if current2.data == data:
llist.remove(current2)
current2 = current2.next
current1 = current1.next
a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))
remove_duplicates(a_llist)
print('The list with duplicates removed: ')
a_llist.display() | 153 |
# Add between 2 numbers without using arithmetic operators
'''Write a Python
program to add between 2 numbers without using arithmetic operators.
or Write a program to add between 2 numbers without using
arithmetic operators using Python '''
print("Enter first number:")
num1=int(input())
print("Enter second number:")
num2=int(input())
while num2 != 0:
carry= num1 & num2
num1= num1 ^ num2
num2=carry << 1
print("Addition of two number is ",num1)
| 67 |
# How to get selected value from listbox in tkinter in Python
# Python3 program to get selected
# value(s) from tkinter listbox
# Import tkinter
from tkinter import *
# Create the root window
root = Tk()
root.geometry('180x200')
# Create a listbox
listbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE)
# Inserting the listbox items
listbox.insert(1, "Data Structure")
listbox.insert(2, "Algorithm")
listbox.insert(3, "Data Science")
listbox.insert(4, "Machine Learning")
listbox.insert(5, "Blockchain")
# Function for printing the
# selected listbox value(s)
def selected_item():
# Traverse the tuple returned by
# curselection method and print
# corresponding value(s) in the listbox
for i in listbox.curselection():
print(listbox.get(i))
# Create a button widget and
# map the command parameter to
# selected_item function
btn = Button(root, text='Print Selected', command=selected_item)
# Placing the button and listbox
btn.pack(side='bottom')
listbox.pack()
root.mainloop() | 130 |
# Write a NumPy program to create a new shape to an array without changing its data.
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6])
y = np.reshape(x,(3,2))
print("Reshape 3x2:")
print(y)
z = np.reshape(x,(2,3))
print("Reshape 2x3:")
print(z)
| 41 |
# Write a Pandas program to split a given dataset, group by two columns and convert other columns of the dataframe into a dictionary with column header as key.
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
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'],
'age': [12, 12, 13, 13, 14, 12],
'height': [173, 192, 186, 167, 151, 159],
'weight': [35, 32, 33, 30, 31, 32],
'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(df)
dict_data_list = list()
for gg, dd in df.groupby(['school_code','class']):
group = dict(zip(['school_code','class'], gg))
ocolumns_list = list()
for _, data in dd.iterrows():
data = data.drop(labels=['school_code','class'])
ocolumns_list.append(data.to_dict())
group['other_columns'] = ocolumns_list
dict_data_list.append(group)
print(dict_data_list)
| 129 |
# Python Program to Count Number of Leaf Node in a Tree
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add(self, node):
self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def count_leaf_nodes(self):
leaf_nodes = []
self.count_leaf_nodes_helper(leaf_nodes)
return len(leaf_nodes)
def count_leaf_nodes_helper(self, leaf_nodes):
if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_nodes_helper(leaf_nodes)
tree = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('count')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)
elif operation == 'count':
if tree is None:
print('Tree is empty.')
else:
count = tree.count_leaf_nodes()
print('Number of leaf nodes: {}'.format(count))
elif operation == 'quit':
break | 188 |
# Write a Pandas program to convert the first column of a DataFrame as a Series.
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
s1 = df.ix[:,0]
print("\n1st column as a Series:")
print(s1)
print(type(s1))
| 58 |
# Write a Python program to square and cube every number in a given list of integers using Lambda.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original list of integers:")
print(nums)
print("\nSquare every number of the said list:")
square_nums = list(map(lambda x: x ** 2, nums))
print(square_nums)
print("\nCube every number of the said list:")
cube_nums = list(map(lambda x: x ** 3, nums))
print(cube_nums)
| 68 |
# Write a Python program to search a date from a given string using arrow module.
import arrow
print("\nSearch a date from a string:")
d1 = arrow.get('David was born in 11 June 2003', 'DD MMMM YYYY')
print(d1)
| 37 |
# Ways to convert string to dictionary in Python
# Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
# At first the string will be splitted
# at the occurence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split("=") for subString in str.split(";"))
# printing the generated dictionary
print(dictionary) | 88 |
# Student management system in Python
# This is simplest Student data management program in python
# Create class "Student"
class Student:
# Constructor
def __init__(self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
# Function to create and append new student
def accept(self, Name, Rollno, marks1, marks2 ):
# use ' int(input()) ' method to take input from user
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
# Function to display student details
def display(self, ob):
print("Name : ", ob.name)
print("RollNo : ", ob.rollno)
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")
# Search Function
def search(self, rn):
for i in range(ls.__len__()):
if(ls[i].rollno == rn):
return i
# Delete Function
def delete(self, rn):
i = obj.search(rn)
del ls[i]
# Update Function
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
# Create a list to add Students
ls =[]
# an object of Student class
obj = Student('', 0, 0, 0)
print("\nOperations used, ")
print("\n1.Accept Student details\n2.Display Student Details\n" /
/ "3.Search Details of a Student\n4.Delete Details of Student" /
/ "\n5.Update Student Details\n6.Exit")
# ch = int(input("Enter choice:"))
# if(ch == 1):
obj.accept("A", 1, 100, 100)
obj.accept("B", 2, 90, 90)
obj.accept("C", 3, 80, 80)
# elif(ch == 2):
print("\n")
print("\nList of Students\n")
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 3):
print("\n Student Found, ")
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
print(ls.__len__())
print("List after deletion")
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
print(ls.__len__())
print("List after updation")
for i in range(ls.__len__()):
obj.display(ls[i])
# else:
print("Thank You !")
| 268 |
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the maximum value in each column.
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
def highlight_max(s):
'''
highlight the maximum in a Series green.
'''
is_max = s == s.max()
return ['background-color: green' if v else '' for v in is_max]
print("\nHighlight the maximum value in each column:")
df.style.apply(highlight_max,subset=pd.IndexSlice[:, ['B', 'C', 'D', 'E']])
| 104 |
# rite a Python program to find the first repeated word in a given string.
def first_repeated_word(str1):
temp = set()
for word in str1.split():
if word in temp:
return word;
else:
temp.add(word)
return 'None'
print(first_repeated_word("ab ca bc ab"))
print(first_repeated_word("ab ca bc ab ca ab bc"))
print(first_repeated_word("ab ca bc ca ab bc"))
print(first_repeated_word("ab ca bc"))
| 54 |
# Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
| 46 |
# Ways to sort list of dictionaries by values in Write a Python program to Using lambda function
# Python code demonstrate the working of
# sorted() with lambda
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
# using sorted and lambda to print list sorted
# by age
print "The list printed sorting by age: "
print sorted(lis, key = lambda i: i['age'])
print ("\r")
# using sorted and lambda to print list sorted
# by both age and name. Notice that "Manjeet"
# now comes before "Nandini"
print "The list printed sorting by age and name: "
print sorted(lis, key = lambda i: (i['age'], i['name']))
print ("\r")
# using sorted and lambda to print list sorted
# by age in descending order
print "The list printed sorting by age in descending order: "
print sorted(lis, key = lambda i: i['age'],reverse=True) | 165 |
# Write a Python program to map the values of a given list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.
def test(itr, fn):
return dict(zip(itr, map(fn, itr)))
print(test([1, 2, 3, 4], lambda x: x * x))
| 56 |
# Write a Python program to Elements frequency in Tuple
# Python3 code to demonstrate working of
# Elements frequency in Tuple
# Using defaultdict()
from collections import defaultdict
# initializing tuple
test_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
res = defaultdict(int)
for ele in test_tup:
# incrementing frequency
res[ele] += 1
# printing result
print("Tuple elements frequency is : " + str(dict(res))) | 79 |
# Write a Pandas program to create a combination from two dataframes where a column id combination appears more than once in both dataframes.
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']})
data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'R': ['R0', 'R1', 'R2', 'R3'],
'S': ['S0', 'S1', 'S2', 'S3']})
print("Original DataFrames:")
print(data1)
print("--------------------")
print(data2)
print("\nMerged Data (many-to-many join case):")
result = pd.merge(data1, data2, on='key1')
print(result)
| 88 |
# Program to print the Inverted Half Pyramid Number Pattern
row_size=int(input("Enter the row size:"))
for out in range(row_size,0,-1):
for in1 in range(row_size,out,-1):
print(" ",end="")
for in2 in range(1, out+1):
print(in2,end="")
print("\r")
| 31 |
# Write a Python program to Check order of character in string using OrderedDict( )
# Function to check if string follows order of
# characters defined by a pattern
from collections import OrderedDict
def checkOrder(input, pattern):
# create empty OrderedDict
# output will be like {'a': None,'b': None, 'c': None}
dict = OrderedDict.fromkeys(input)
# traverse generated OrderedDict parallel with
# pattern string to check if order of characters
# are same or not
ptrlen = 0
for key,value in dict.items():
if (key == pattern[ptrlen]):
ptrlen = ptrlen + 1
# check if we have traverse complete
# pattern string
if (ptrlen == (len(pattern))):
return 'true'
# if we come out from for loop that means
# order was mismatched
return 'false'
# Driver program
if __name__ == "__main__":
input = 'engineers rock'
pattern = 'egr'
print (checkOrder(input,pattern)) | 138 |
# Write a Python program to find the majority element from a given array of size n using Collections module.
import collections
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:return type: int
"""
count_ele=collections.Counter(nums)
return count_ele.most_common()[0][0]
result = Solution().majorityElement([10,10,20,30,40,10,20,10])
print(result)
| 42 |
# Write a Python program to find tag(s) beneath other tag(s) in a given html document.
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismod egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor volutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget. Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris dignissim
elementum nunc, non elementum felis condimentum eu. In in turpis quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi at sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a href="https://www.w3resource.com/css/CSS-tutorials.php">Learn CSS from
w3resource.com</a></p>
</body>
</html>
"""
soup = BeautifulSoup(html_doc,"lxml")
print("\na tag(s) Beneath body tag:")
print(soup.select("body a"))
print("\nBeneath html head:")
print(soup.select("html head title"))
| 172 |
# Write a Python program to Flatten tuple of List to tuple
# Python3 code to demonstrate working of
# Flatten tuple of List to tuple
# Using sum() + tuple()
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Flatten tuple of List to tuple
# Using sum() + tuple()
res = tuple(sum(test_tuple, []))
# printing result
print("The flattened tuple : " + str(res)) | 80 |
# Write a Python program to get all combinations of key-value pairs in a given dictionary.
import itertools
def test(dictt):
result = list(map(dict, itertools.combinations(dictt.items(), 2)))
return result
students = {'V' : [1, 4, 6, 10], 'VI' : [1, 4, 12], 'VII' : [1, 3, 8]}
print("\nOriginal Dictionary:")
print(students)
print("\nCombinations of key-value pairs of the said dictionary:")
print(test(students))
students = {'V' : [1, 3, 5], 'VI' : [1, 5]}
print("\nOriginal Dictionary:")
print(students)
print("\nCombinations of key-value pairs of the said dictionary:")
print(test(students))
| 80 |
# Write a NumPy program to count the frequency of unique values in NumPy array.
import numpy as np
a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )
print("Original array:")
print(a)
unique_elements, counts_elements = np.unique(a, return_counts=True)
print("Frequency of unique values of the said array:")
print(np.asarray((unique_elements, counts_elements)))
| 43 |
# Write a Python program to check if a given function returns True for at least one element in the list.
def some(lst, fn = lambda x: x):
return any(map(fn, lst))
print(some([0, 1, 2, 0], lambda x: x >= 2 ))
print(some([5, 10, 20, 10], lambda x: x < 2 ))
| 51 |
# Capitalize first letter of a column in Pandas dataframe in Python
# Create a simple dataframe
# importing pandas as pd
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'],
'B': ['masters', 'graduate', 'graduate',
'Masters', 'Graduate'],
'C': [27, 23, 21, 23, 24]})
df | 51 |
# Write a Python program to create a list taking alternate elements from a given list.
def alternate_elements(list_data):
result=[]
for item in list_data[::2]:
result.append(item)
return result
colors = ["red", "black", "white", "green", "orange"]
print("Original list:")
print(colors)
print("List with alternate elements from the said list:")
print(alternate_elements(colors))
nums = [2,0,3,4,0,2,8,3,4,2]
print("\nOriginal list:")
print(nums)
print("List with alternate elements from the said list:")
print(alternate_elements(nums))
| 60 |
# Overuse of lambda expressions in Python
# Python program showing a use
# lambda function
# performing a addition of three number
x1 = (lambda x, y, z: (x + y) * z)(1, 2, 3)
print(x1)
# function using a lambda function
x2 = (lambda x, y, z: (x + y) if (z == 0) else (x * y))(1, 2, 3)
print(x2) | 63 |
# Write a Python program that reads each row of a given csv file and skip the header of the file. Also print the number of rows and the field names.
import csv
fields = []
rows = []
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar=',')
# Following command skips the first row of the CSV file.
fields = next(data)
for row in data:
print(', '.join(row))
print("\nTotal no. of rows: %d"%(data.line_num))
print('Field names are:')
print(', '.join(field for field in fields))
| 84 |
# Write a NumPy program to rearrange the dimensions of a given array.
import numpy as np
x = np.arange(24).reshape((6,4))
print("Original arrays:")
print(x)
new_array = np.transpose(x)
print("After reverse the dimensions:")
print(new_array)
| 31 |
# Set update() in Python to do union of n arrays
# Function to combine n arrays
def combineAll(input):
# cast first array as set and assign it
# to variable named as result
result = set(input[0])
# now traverse remaining list of arrays
# and take it's update with result variable
for array in input[1:]:
result.update(array)
return list(result)
# Driver program
if __name__ == "__main__":
input = [[1, 2, 2, 4, 3, 6],
[5, 1, 3, 4],
[9, 5, 7, 1],
[2, 4, 1, 3]]
print (combineAll(input)) | 88 |
# Write a Python program to calculate the discriminant value.
def discriminant():
x_value = float(input('The x value: '))
y_value = float(input('The y value: '))
z_value = float(input('The z value: '))
discriminant = (y_value**2) - (4*x_value*z_value)
if discriminant > 0:
print('Two Solutions. Discriminant value is:', discriminant)
elif discriminant == 0:
print('One Solution. Discriminant value is:', discriminant)
elif discriminant < 0:
print('No Real Solutions. Discriminant value is:', discriminant)
discriminant()
| 67 |
# Write a Pandas program to split the following datasets into groups on customer_id to summarize purch_amt and calculate percentage of purch_amt in each group.
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,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': ['05-10-2012','09-10-2012','05-10-2012','08-17-2012','10-09-2012','07-27-2012','10-09-2012','10-10-2012','10-10-2012','06-17-2012','07-08-2012','04-25-2012'],
'customer_id':[3001,3001,3005,3001,3005,3001,3005,3001,3005,3001,3005,3005],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]})
print("Original Orders DataFrame:")
print(df)
gr_data = df.groupby(['customer_id','salesman_id']).agg({'purch_amt': 'sum'})
gr_data["% (Purch Amt.)"] = gr_data.apply(lambda x: 100*x / x.sum())
print("\nPercentage of purch_amt in each group of customer_id:")
print(gr_data)
| 70 |
# Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
def sum(x, y):
sum = x + y
if sum in range(15, 20):
return 20
else:
return sum
print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))
| 48 |
# Write a Python function that checks whether a passed string is palindrome or not.
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))
| 45 |
# Write a Python program to create the next bigger number by rearranging the digits of a given number.
def rearrange_bigger(n):
#Break the number into digits and store in a list
nums = list(str(n))
for i in range(len(nums)-2,-1,-1):
if nums[i] < nums[i+1]:
z = nums[i:]
y = min(filter(lambda x: x > z[0], z))
z.remove(y)
z.sort()
nums[i:] = [y] + z
return int("".join(nums))
return False
n = 12
print("Original number:",n)
print("Next bigger number:",rearrange_bigger(n))
n = 10
print("\nOriginal number:",n)
print("Next bigger number:",rearrange_bigger(n))
n = 201
print("\nOriginal number:",n)
print("Next bigger number:",rearrange_bigger(n))
n = 102
print("\nOriginal number:",n)
print("Next bigger number:",rearrange_bigger(n))
n = 445
print("\nOriginal number:",n)
print("Next bigger number:",rearrange_bigger(n))
| 104 |
# Write a NumPy program to check whether each element of a given array is composed of digits only, lower case letters only and upper case letters only.
import numpy as np
x = np.array(['Python', 'PHP', 'JS', 'Examples', 'html5', '5'], dtype=np.str)
print("\nOriginal Array:")
print(x)
r1 = np.char.isdigit(x)
r2 = np.char.islower(x)
r3 = np.char.isupper(x)
print("Digits only =", r1)
print("Lower cases only =", r2)
print("Upper cases only =", r3)
| 67 |
# Print the most occurring elements in an array
import sys
arr=[]
freq=[]
max=-sys.maxsize-1
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)
for i in range(0, size):
if arr[i]>=max:
max=arr[i]
for i in range(0,max+1):
freq.append(0)
for i in range(0, size):
freq[arr[i]]+=1
most_oc=0
most_v=0
for i in range(0, size):
if freq[arr[i]] > most_oc:
most_oc = freq[arr[i]]
most_v = arr[i]
print("The Most occurring Number ",most_v," occurs ",most_oc," times.") | 81 |
Subsets and Splits