code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python program to extract numbers from a given string.
def test(str1):
result = [int(str1) for str1 in str1.split() if str1.isdigit()]
return result
str1 = "red 12 black 45 green"
print("Original string:", str1)
print("Extract numbers from the said string:")
print(test(str1))
| 42 |
# Write a Pandas program to filter rows based on row numbers ended with 0, like 0, 10, 20, 30 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())
print("\nFilter rows based on row numbers ended with 0, like 0, 10, 20, 30:")
print(w_a_con.filter(regex='0$', axis=0))
| 59 |
# Write a Python program to extract characters from various text files and puts them into a list.
import glob
char_list = []
files_list = glob.glob("*.txt")
for file_elem in files_list:
with open(file_elem, "r") as f:
char_list.append(f.read())
print(char_list)
| 37 |
# Write a NumPy program to extract second and fourth elements of the second and fourth rows 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: Second and fourth elements of the second and fourth rows ")
print(arra_data[1::2, 1::2])
| 48 |
# Write a Pandas program to split a given dataset, group by one column and remove those groups if all the values of a specific columns are not available.
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],
'weight': [173, 192, 186, 167, 151, 159],
'height': [35, None, 33, 30, None, 32]},
index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
print("Original DataFrame:")
print(df)
print("\nGroup by one column and remove those groups if all the values of a specific columns are not available:")
result = df[(~df['height'].isna()).groupby(df['school_code']).transform('any')]
print(result)
| 116 |
# Write a Python Code for time Complexity plot of Heap Sort
# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
# find left child of node i
def left(i):
聽聽聽聽return 2 * i + 1
# find right child of node i
def right(i):
聽聽聽聽return 2 * i + 2
# calculate and return array size
def heapSize(A):
聽聽聽聽return len(A)-1
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
聽聽聽聽# print("in heapy", i)
聽聽聽聽l = left(i)
聽聽聽聽r = right(i)
聽聽聽聽聽
聽聽聽聽# heapSize = len(A)
聽聽聽聽# print("left", l, "Rightt", r, "Size", heapSize)
聽聽聽聽if l<= heapSize(A) and A[l] > A[i] :
聽聽聽聽聽聽聽聽largest = l
聽聽聽聽else:
聽聽聽聽聽聽聽聽largest = i
聽聽聽聽if r<= heapSize(A) and A[r] > A[largest]:
聽聽聽聽聽聽聽聽largest = r
聽聽聽聽if largest != i:
聽聽聽聽聽聽聽# print("Largest", largest)
聽聽聽聽聽聽聽聽A[i], A[largest]= A[largest], A[i]
聽聽聽聽聽聽聽# print("List", A)
聽聽聽聽聽聽聽聽MaxHeapify(A, largest)
聽聽聽聽聽
# this function makes a heapified array
def BuildMaxHeap(A):
聽聽聽聽for i in range(int(heapSize(A)/2)-1, -1, -1):
聽聽聽聽聽聽聽聽MaxHeapify(A, i)
聽聽聽聽聽聽聽聽聽
# Sorting is done using heap of array
def HeapSort(A):
聽聽聽聽BuildMaxHeap(A)
聽聽聽聽B = list()
聽聽聽聽heapSize1 = heapSize(A)
聽聽聽聽for i in range(heapSize(A), 0, -1):
聽聽聽聽聽聽聽聽A[0], A[i]= A[i], A[0]
聽聽聽聽聽聽聽聽B.append(A[heapSize1])
聽聽聽聽聽聽聽聽A = A[:-1]
聽聽聽聽聽聽聽聽heapSize1 = heapSize1-1
聽聽聽聽聽聽聽聽MaxHeapify(A, 0)
聽聽聽聽聽聽聽聽聽
# randomly generates list of different
# sizes and call HeapSort function
elements = list()
times = list()
for i in range(1, 10):
聽聽聽聽# generate some integers
聽聽聽聽a = randint(0, 1000 * i, 1000 * i)
聽聽聽聽# print(i)
聽聽聽聽start = time.clock()
聽聽聽聽HeapSort(a)
聽聽聽聽end = time.clock()
聽聽聽聽# print("Sorted list is ", a)
聽聽聽聽print(len(a), "Elements Sorted by HeapSort in ", end-start)
聽聽聽聽elements.append(len(a))
聽聽聽聽times.append(end-start)
plt.xlabel('List Length')
plt.ylabel('Time Complexity')
plt.plot(elements, times, label ='Heap Sort')
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal | 332 |
# Write a Python Program to Replace Text in a File
# Python program to replace text in a file
s = input("Enter text to replace the existing contents:")
f = open("file.txt", "r+")
# file.txt is an example here,
# it should be replaced with the file name
# r+ mode opens the file in read and write mode
f.truncate(0)
f.write(s)
f.close()
print("Text successfully replaced") | 65 |
# Write a Pandas program to count the number of missing values of a specified column in a given DataFrame.
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,np.nan,65.26,110.5,948.5,np.nan,5760,1983.43,np.nan,250.45, 75.29,3045.6],
'sale_amt':[10.5,20.65,np.nan,11.5,98.5,np.nan,57,19.43,np.nan,25.45, 75.29,35.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("\nMissing values in purch_amt column:")
result = df['purch_amt'].value_counts(dropna=False).loc[np.nan]
print(result)
| 57 |
# Write a Python program to add two given lists of different lengths, start from left , using itertools module.
from itertools import zip_longest
def elementswise_left_join(l1, l2):
result = [a + b for a,b in zip_longest(l1, l2, fillvalue=0)][::1]
return result
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print("\nOriginal lists:")
print(nums1)
print(nums2)
print("\nAdd said two lists from left:")
print(elementswise_left_join(nums1, nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print("\nOriginal lists:")
print(nums3)
print(nums4)
print("\nAdd said two lists from left:")
print(elementswise_left_join(nums3, nums4))
| 91 |
# Python Program to Determine all Pythagorean Triplets in the Range
limit=int(input("Enter upper limit:"))
c=0
m=2
while(c<limit):
for n in range(1,m+1):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1 | 34 |
# Write a Python program to make a chain of function decorators (bold, italic, underline etc.) in Python.
def make_bold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def make_italic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
def make_underline(fn):
def wrapped():
return "<u>" + fn() + "</u>"
return wrapped
@make_bold
@make_italic
@make_underline
def hello():
return "hello world"
print(hello()) ## returns "<b><i><u>hello world</u></i></b>"
| 67 |
# You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
:
Solutions:
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))
| 124 |
# Find sum and average of List in Python
# Python program to find the sum
# and average of the list
聽聽
L = [4, 5, 1, 2, 9, 7, 10, 8]
聽聽
聽聽
# variable to store the sum of聽
# the list
count = 0
聽聽
# Finding the sum
for i in L:
聽聽聽聽count += i
聽聽聽聽聽聽
# divide the total elements by
# number of elements
avg = count/len(L)
聽聽
print("sum = ", count)
print("average = ", avg) | 77 |
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the entire row in Yellow where a specific column value is greater than 0.5.
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)
print("Original array:")
print(df)
print("\nDataframe - table style:")
def highlight_greaterthan(x):
if x.C > .5:
return ['background-color: yellow']*5
else:
return ['background-color: white']*5
df.style.apply(highlight_greaterthan, axis=1)
| 76 |
# Program to Find the nth Palindrome Number
rangenumber=int(input("Enter a Nth Number:"))
c = 0
letest = 0
num = 1
while c != rangenumber:
聽 聽 num2=0
聽 聽 num1 = num
聽 聽 while num1 != 0:
聽 聽 聽 聽 rem = num1 % 10
聽 聽 聽 聽 num1 //= 10
聽 聽 聽 聽 num2 = num2 * 10 + rem
聽 聽 if num==num2:
聽 聽 聽 聽 c+=1
聽 聽 聽 聽 letest = num
聽 聽 num = num + 1
print(rangenumber,"th Palindrome Number is ",letest) | 64 |
# Write a Python program to get the difference between two given lists, after applying the provided function to each list element of both.
def difference_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) not in _b]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor))
print(difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']))
| 68 |
# numpy.sqrt() in Python
# Python program explaining
# numpy.sqrt() method聽
聽聽
# importing numpy
import numpy as geek聽
聽聽
# applying sqrt() method on integer numbers聽
arr1 = geek.sqrt([1, 4, 9, 16])
arr2 = geek.sqrt([6, 10, 18])
聽聽
print("square-root of an array1聽 : ", arr1)
print("square-root of an array2聽 : ", arr2) | 50 |
# Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.
import numpy as np
array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("Original array:")
print(array_nums)
print("\nNumber of items of the said array:")
print(array_nums.size)
print("\nArray dimensions:")
print(array_nums.shape)
print("\nNumber of array dimensions:")
print(array_nums.ndim)
print("\nMemory size of each element of the said array")
print(array_nums.itemsize)
| 75 |
# Write a Python program to convert an array to an array of machine values and return the bytes representation.
from array import *
print("Bytes to String: ")
x = array('b', [119, 51, 114, 101, 115, 111, 117, 114, 99, 101])
s = x.tobytes()
print(s)
| 45 |
# Write a Python program to add two given lists of different lengths, start from left.
def elementswise_left_join(l1, l2):
f_len = len(l1)-(len(l2) - 1)
for i in range(0, len(l2), 1):
if f_len - i >= len(l1):
break
else:
l1[i] = l1[i] + l2[i]
return l1
nums1 = [2, 4, 7, 0, 5, 8]
nums2 = [3, 3, -1, 7]
print("\nOriginal lists:")
print(nums1)
print(nums2)
print("\nAdd said two lists from left:")
print(elementswise_left_join(nums1,nums2))
nums3 = [1, 2, 3, 4, 5, 6]
nums4 = [2, 4, -3]
print("\nOriginal lists:")
print(nums3)
print(nums4)
print("\nAdd said two lists from left:")
print(elementswise_left_join(nums3,nums4))
| 94 |
# Write a Python program to remove duplicates from a list.
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
| 32 |