code
stringlengths 63
8.54k
| code_length
int64 11
747
|
---|---|
# Write a Python program to read a file line by line store it into an array.
def file_read(fname):
content_array = []
with open(fname) as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
print(content_array)
file_read('test.txt')
| 42 |
# Convert Set to String in Python
# create a set
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s) | 58 |
# Write a Python program to calculate the sum of the positive and negative numbers of a given list of numbers using lambda function.
nums = [2, 4, -6, -9, 11, -12, 14, -5, 17]
print("Original list:",nums)
total_negative_nums = list(filter(lambda nums:nums<0,nums))
total_positive_nums = list(filter(lambda nums:nums>0,nums))
print("Sum of the positive numbers: ",sum(total_negative_nums))
print("Sum of the negative numbers: ",sum(total_positive_nums))
| 57 |
# Program to check whether a matrix is sparse or not
# Get size of matrix
row_size=int(input("Enter the row Size Of the Matrix:"))
col_size=int(input("Enter the columns Size Of the Matrix:"))
matrix=[]
# Taking input of the 1st matrix
print("Enter the Matrix Element:")
for i in range(row_size):
matrix.append([int(j) for j in input().split()])
count_zero=0
#Count number of zeros present in the given Matrix
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]==0:
count_zero+=1
#check if zeros present in the given Matrix>(row*column)/2
if count_zero>(row_size*col_size)//2:
print("Given Matrix is a sparse Matrix.")
else:
print("Given Matrix is not a sparse Matrix.") | 96 |
# Write a Python program to Cross Pairing in Tuple List
# Python3 code to demonstrate working of
# Cross Pairing in Tuple List
# Using list comprehension
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# corresponding loop in list comprehension
res = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]]
# printing result
print("The mapped tuples : " + str(res)) | 103 |
# Write a Python program to convert an address (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).
import requests
geo_url = 'http://maps.googleapis.com/maps/api/geocode/json'
my_address = {'address': '21 Ramkrishana Road, Burdwan, East Burdwan, West Bengal, India',
'language': 'en'}
response = requests.get(geo_url, params = my_address)
results = response.json()['results']
my_geo = results[0]['geometry']['location']
print("Longitude:",my_geo['lng'],"\n","Latitude:",my_geo['lat'])
| 57 |
# Write a Python program to find the second lowest grade of any student(s) from the given names and grades of each student using lists and lambda. Input number of students, names and grades of each student.
students = []
sec_name = []
second_low = 0
n = int(input("Input number of students: "))
for _ in range(n):
s_name = input("Name: ")
score = float(input("Grade: "))
students.append([s_name,score])
print("\nNames and Grades of all students:")
print(students)
order =sorted(students, key = lambda x: int(x[1]))
for i in range(n):
if order[i][1] != order[0][1]:
second_low = order[i][1]
break
print("\nSecond lowest grade: ",second_low)
sec_student_name = [x[0] for x in order if x[1] == second_low]
sec_student_name.sort()
print("\nNames:")
for s_name in sec_student_name:
print(s_name)
| 114 |
# Write a Python program to Convert list of nested dictionary into Pandas dataframe
# importing pandas
import pandas as pd
# List of nested dictionary initialization
list = [
{
"Student": [{"Exam": 90, "Grade": "a"},
{"Exam": 99, "Grade": "b"},
{"Exam": 97, "Grade": "c"},
],
"Name": "Paras Jain"
},
{
"Student": [{"Exam": 89, "Grade": "a"},
{"Exam": 80, "Grade": "b"}
],
"Name": "Chunky Pandey"
}
]
#print(list) | 66 |
# Write a Pandas program to create the todays date.
import pandas as pd
from datetime import date
now = pd.to_datetime(str(date.today()), format='%Y-%m-%d')
print("Today's date:")
print(now)
| 25 |
# Write a Python program to find the dimension of a given matrix.
def matrix_dimensions(test_list):
row = len(test_list)
column = len(test_list[0])
return row,column
lst = [[1,2],[2,4]]
print("\nOriginal list:")
print(lst)
print("Dimension of the said matrix:")
print(matrix_dimensions(lst))
lst = [[0,1,2],[2,4,5]]
print("\nOriginal list:")
print(lst)
print("Dimension of the said matrix:")
print(matrix_dimensions(lst))
lst = [[0,1,2],[2,4,5],[2,3,4]]
print("\nOriginal list:")
print(lst)
print("Dimension of the said matrix:")
print(matrix_dimensions(lst))
| 59 |
# Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary.
import itertools
d ={'1':['a','b'], '2':['c','d']}
for combo in itertools.product(*[d[k] for k in sorted(d.keys())]):
print(''.join(combo))
| 37 |
# Program to find sum of series 1+4-9+16-25+.....+N
import math
print("Enter the range of number(Limit):")
n=int(input())
i=2
sum=1
while(i<=n):
if(i%2==0):
sum+=pow(i,2)
else:
sum-=pow(i,2)
i+=1
print("The sum of the series = ",sum) | 31 |
# Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes.
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
age = pd.cut(df['age'], [0, 20, 55])
result = df.pivot_table('survived', index=['sex', age], columns='class')
print(result)
| 48 |
# Write a Python program to insert a new text within a url in a specified position.
from bs4 import BeautifulSoup
html_doc = '<a href="http://example.com/">HTML<i>w3resource.com</i></a>'
soup = BeautifulSoup(html_doc, "lxml")
tag = soup.a
print("Original Markup:")
print(tag.contents)
tag.insert(2, "CSS") #2-> Position of the text (1, 2, 3…)
print("\nNew url after inserting the text:")
print(tag.contents)
| 52 |
# Write a Python program to find the first repeated character of a given string where the index of first occurrence is smallest.
def first_repeated_char_smallest_distance(str1):
temp = {}
for ch in str1:
if ch in temp:
return ch, str1.index(ch);
else:
temp[ch] = 0
return 'None'
print(first_repeated_char_smallest_distance("abcabc"))
print(first_repeated_char_smallest_distance("abcb"))
print(first_repeated_char_smallest_distance("abcc"))
print(first_repeated_char_smallest_distance("abcxxy"))
print(first_repeated_char_smallest_distance("abc"))))
| 50 |
# latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map.
from lxml import html
import requests
response = requests.get('http://catalog.data.gov/dataset?q=&sort=metadata_created+desc')
doc = html.fromstring(response.text)
title = doc.cssselect('h3.dataset-heading')[0].text_content()
print("The name of the most recently added dataset on data.gov:")
print(title.strip())
| 46 |
# Write a Python program to initialize a list containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.
from math import floor, log
def geometric_progression(end, start=1, step=2):
return [start * step ** i for i in range(floor(log(end / start)
/ log(step)) + 1)]
print(geometric_progression(256))
print(geometric_progression(256, 3))
print(geometric_progression(256, 1, 4))
| 68 |
# Write a Python program to sort a list of elements using Cycle sort.
# License: https://bit.ly/2V5W81t
def cycleSort(vector):
"Sort a vector in place and return the number of writes."
writes = 0
# Loop through the vector to find cycles to rotate.
for cycleStart, item in enumerate(vector):
# Find where to put the item.
pos = cycleStart
for item2 in vector[cycleStart + 1:]:
if item2 < item:
pos += 1
# If the item is already there, this is not a cycle.
if pos == cycleStart:
continue
# Otherwise, put the item there or right after any duplicates.
while item == vector[pos]:
pos += 1
vector[pos], item = item, vector[pos]
writes += 1
# Rotate the rest of the cycle.
while pos != cycleStart:
# Find where to put the item.
pos = cycleStart
for item2 in vector[cycleStart + 1:]:
if item2 < item:
pos += 1
# Put the item there or right after any duplicates.
while item == vector[pos]:
pos += 1
vector[pos], item = item, vector[pos]
writes += 1
return writes
if __name__ == '__main__':
x = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
xcopy = x[::]
writes = cycleSort(xcopy)
if xcopy != sorted(x):
print('Wrong order!')
else:
print('%r\nIs correctly sorted using cycleSort to'
'\n%r\nUsing %i writes.' % (x, xcopy, writes))
| 222 |
# 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 |
# Write a Python program to find intersection of two given arrays using Lambda.
array_nums1 = [1, 2, 3, 5, 7, 8, 9, 10]
array_nums2 = [1, 2, 4, 8, 9]
print("Original arrays:")
print(array_nums1)
print(array_nums2)
result = list(filter(lambda x: x in array_nums1, array_nums2))
print ("\nIntersection of the said arrays: ",result)
| 50 |
# Write a Python program to find the maximum value in a given heterogeneous list using lambda.
def max_val(list_val):
max_val = max(list_val, key = lambda i: (isinstance(i, int), i))
return(max_val)
list_val = ['Python', 3, 2, 4, 5, 'version']
print("Original list:")
print(list_val)
print("\nMaximum values in the said list using lambda:")
print(max_val(list_val))
| 50 |
# Convert “unknown format” strings to datetime objects in Python
# Python3 code to illustrate the conversion of
# "unknown format" strings to DateTime objects
# Importing parser from the dateutil.parser
import dateutil.parser as parser
# Initializing an unknown format date string
date_string = "19750503T080120"
# Calling the parser to parse the above
# specified unformatted date string
# into a datetime objects
date_time = parser.parse(date_string)
# Printing the converted datetime object
print(date_time) | 73 |
# Write a Python program to find the length of a given dictionary values.
def test(dictt):
result = {}
for val in dictt.values():
result[val] = len(val)
return result
color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Length of dictionary values:")
print(test(color_dict))
color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Length of dictionary values:")
print(test(color_dict))
| 79 |
# Write a NumPy program to split the element of a given array with spaces.
import numpy as np
x = np.array(['Python PHP Java C++'], dtype=np.str)
print("Original Array:")
print(x)
r = np.char.split(x)
print("\nSplit the element of the said array with spaces: ")
print(r)
| 43 |
# numpy.searchsorted() in Python
# Python program explaining
# searchsorted() function
import numpy as geek
# input array
in_arr = [2, 3, 4, 5, 6]
print ("Input array : ", in_arr)
# the number which we want to insert
num = 4
print("The number which we want to insert : ", num)
out_ind = geek.searchsorted(in_arr, num)
print ("Output indices to maintain sorted array : ", out_ind) | 66 |
# Write a Python program to Remove all duplicates words from a given sentence
from collections import Counter
def remov_duplicates(input):
# split input string separated by space
input = input.split(" ")
# joins two adjacent elements in iterable way
for i in range(0, len(input)):
input[i] = "".join(input[i])
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
UniqW = Counter(input)
# joins two adjacent elements in iterable way
s = " ".join(UniqW.keys())
print (s)
# Driver program
if __name__ == "__main__":
input = 'Python is great and Java is also great'
remov_duplicates(input) | 102 |
# Write a Pandas program to extract year, month, day, hour, minute, second and weekday from unidentified flying object (UFO) reporting date.
import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
print("\nYear:")
print(df.Date_time.dt.year.head())
print("\nMonth:")
print(df.Date_time.dt.month.head())
print("\nDay:")
print(df.Date_time.dt.day.head())
print("\nHour:")
print(df.Date_time.dt.hour.head())
print("\nMinute:")
print(df.Date_time.dt.minute.head())
print("\nSecond:")
print(df.Date_time.dt.second.head())
print("\nWeekday:")
print(df.Date_time.dt.weekday_name.head())
| 49 |
# Write a Python program to convert a given Bytearray to Hexadecimal string.
def bytearray_to_hexadecimal(list_val):
result = ''.join('{:02x}'.format(x) for x in list_val)
return(result)
list_val = [111, 12, 45, 67, 109]
print("Original Bytearray :")
print(list_val)
print("\nHexadecimal string:")
print(bytearray_to_hexadecimal(list_val))
| 37 |
# How to compare two NumPy arrays in Python
import numpy as np
an_array = np.array([[1, 2], [3, 4]])
another_array = np.array([[1, 2], [3, 4]])
comparison = an_array == another_array
equal_arrays = comparison.all()
print(equal_arrays) | 34 |
# Binary Search Program in C | C++ | Java | Python
arr=[]
size = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,size):
num = int(input())
arr.append(num)
search_elm=int(input("Enter the search element: "))
found=0
lowerBound = 0
upperBound = size-1
while lowerBound<=upperBound and not found:
mid = (lowerBound + upperBound ) // 2
if arr[mid]==search_elm:
found=1
else:
if arr[mid] < search_elm:
lowerBound = mid + 1
else:
upperBound = mid - 1
if found==1:
print("Search element is found.")
else:
print("Search element is not found.")
| 92 |
# Adding and Subtracting Matrices in Python
# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B)) | 58 |
# Write a Python program to create a 3X3 grid with numbers.
nums = []
for i in range(3):
nums.append([])
for j in range(1, 4):
nums[i].append(j)
print("3X3 grid with numbers:")
print(nums)
| 31 |
# Write a Python function to insert a string in the middle of a string.
def insert_sting_middle(str, word):
return str[:2] + word + str[2:]
print(insert_sting_middle('[[]]', 'Python'))
print(insert_sting_middle('{{}}', 'PHP'))
print(insert_sting_middle('<<>>', 'HTML'))
| 30 |
# Write a Pandas program to convert a specified character column in title case in a given DataFrame.
import pandas as pd
df = pd.DataFrame({
'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],
'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("\nTitle cases:")
df['company_code_title_cases'] = list(map(lambda x: x.title(), df['company_code']))
print(df)
| 51 |
# Count number of zeros in a number using recursion
count=0def count_digit(num): global count if (num >0): if(num%10==0): count +=1 count_digit(num // 10) return countn=int(input("Enter a number:"))print("The number of Zeros in the Given number is:",count_digit(n)) | 35 |
# Write a Python program to create the combinations of 3 digit combo.
numbers = []
for num in range(1000):
num=str(num).zfill(3)
print(num)
numbers.append(num)
| 23 |
# Write a NumPy program to create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.
import numpy as np
x = np.zeros((4, 4))
x[::2, 1::2] = 1
x[1::2, ::2] = 1
print(x)
| 40 |
# GUI to generate and store passwords in SQLite using Python
import random
import webbrowser
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import back
import csv
from ttkbootstrap import *
class window:
# these are lists of initialized characters
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
sym = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|',
'~', '>', '*', '<']
def __init__(self, root, geo, title) -> None:
self.root = root
self.root.title(title)
self.root.geometry(geo)
self.root.resizable(width=False, height=False)
Label(self.root, text='Your Password').grid(
row=0, column=0, padx=10, pady=10)
Label(self.root, text='Corresponding User_id').grid(
row=1, column=0, padx=10, pady=10)
Label(self.root, text='Of').grid(row=2, column=0, padx=10, pady=10)
self.pa = StringVar()
self.user_id = StringVar()
self.site = StringVar()
ttk.Entry(self.root, width=30, textvariable=self.pa
).grid(row=0, column=1, padx=10, pady=10)
ttk.Entry(self.root, width=30, textvariable=self.user_id
).grid(row=1, column=1, padx=10, pady=10)
ttk.Entry(self.root, width=30, textvariable=self.site
).grid(row=2, column=1, padx=10, pady=10)
self.length = StringVar()
e = ttk.Combobox(self.root, values=['4', '8', '12', '16', '20', '24'],
textvariable=self.length)
e.grid(row=0, column=2)
e['state'] = 'readonly'
self.length.set('Set password length')
ttk.Button(self.root, text='Generate', padding=5,
style='success.Outline.TButton', width=20,
command=self.generate).grid(row=1, column=2)
ttk.Button(self.root, text='Save to Database', style='success.TButton',
width=20, padding=5, command=self.save).grid(row=3, column=2)
ttk.Button(self.root, text='Delete', width=20, style='danger.TButton',
padding=5, command=self.erase).grid(row=2, column=2)
ttk.Button(self.root, text='Show All', width=20, padding=5,
command=self.view).grid(row=3, column=0)
ttk.Button(self.root, text='Update', width=20, padding=5,
command=self.update).grid(row=3, column=1)
# ========self.tree view=============
self.tree = ttk.Treeview(self.root, height=5)
self.tree['columns'] = ('site', 'user', 'pas')
self.tree.column('#0', width=0, stretch=NO)
self.tree.column('site', width=160, anchor=W)
self.tree.column('user', width=140, anchor=W)
self.tree.column('pas', width=180, anchor=W)
self.tree.heading('#0', text='')
self.tree.heading('site', text='Site name')
self.tree.heading('user', text='User Id')
self.tree.heading('pas', text='Password')
self.tree.grid(row=4, column=0, columnspan=3, pady=10)
self.tree.bind("<ButtonRelease-1>", self.catch)
# this command will call the catch function
# this is right click pop-up menu
self.menu = Menu(self.root, tearoff=False)
self.menu.add_command(label='Refresh', command=self.refresh)
self.menu.add_command(label='Insert', command=self.save)
self.menu.add_command(label='Update', command=self.update)
self.menu.add_separator()
self.menu.add_command(label='Show All', command=self.view)
self.menu.add_command(label='Clear Fields', command=self.clear)
self.menu.add_command(label='Clear Table', command=self.table)
self.menu.add_command(label='Export', command=self.export)
self.menu.add_separator()
self.menu.add_command(label='Delete', command=self.erase)
self.menu.add_command(label='Help', command=self.help)
self.menu.add_separator()
self.menu.add_command(label='Exit', command=self.root.quit)
# this binds the button 3 of the mouse with
self.root.bind("<Button-3>", self.poppin)
# poppin function
def help(self):
# this function will open the help.txt in
# notepad when called
webbrowser.open('help.txt')
def refresh(self):
# this function basically refreshes the table
# or tree view
self.table()
self.view()
def table(self):
# this function will clear all the values
# displayed in the table
for r in self.tree.get_children():
self.tree.delete(r)
def clear(self):
# this function will clear all the entry
# fields
self.pa.set('')
self.user_id.set('')
self.site.set('')
def poppin(self, e):
# it triggers the right click pop-up menu
self.menu.tk_popup(e.x_root, e.y_root)
def catch(self, event):
# this function will take all the selected data
# from the table/ tree view and will fill up the
# respective entry fields
self.pa.set('')
self.user_id.set('')
self.site.set('')
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
self.site.set(value[0])
self.user_id.set(value[1])
self.pa.set(value[2])
def update(self):
# this function will update database with new
# values given by the user
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
back.edit(self.site.get(), self.user_id.get(), self.pa.get())
self.refresh()
def view(self):
# this will show all the data from the database
# this is similar to "SELECT * FROM TABLE" sql
# command
if back.check() is False:
messagebox.showerror('Attention Amigo!', 'Database is EMPTY!')
else:
for row in back.show():
self.tree.insert(parent='', text='', index='end',
values=(row[0], row[1], row[2]))
def erase(self):
# this will delete or remove the selected tuple or
# row from the database
selected = self.tree.focus()
value = self.tree.item(selected, 'value')
back.Del(value[2])
self.refresh()
def save(self):
# this function will insert all the data into the
# database
back.enter(self.site.get(), self.user_id.get(), self.pa.get())
self.tree.insert(parent='', index='end', text='',
values=(self.site.get(), self.user_id.get(), self.pa.get()))
def generate(self):
# this function will produce a random string which
# will be used as password
if self.length.get() == 'Set password length':
messagebox.showerror('Attention!', "You forgot to SELECT")
else:
a = ''
for x in range(int(int(self.length.get())/4)):
a0 = random.choice(self.uc)
a1 = random.choice(self.lc)
a2 = random.choice(self.sym)
a3 = random.choice(self.digits)
a = a0+a1+a2+a3+a
self.pa.set(a)
def export(self):
# this function will save all the data from the
# database in a csv format which can be opened
# in excel
pop = Toplevel(self.root)
pop.geometry('300x100')
self.v = StringVar()
Label(pop, text='Save File Name as').pack()
ttk.Entry(pop, textvariable=self.v).pack()
ttk.Button(pop, text='Save', width=18,
command=lambda: exp(self.v.get())).pack(pady=5)
def exp(x):
with open(x + '.csv', 'w', newline='') as f:
chompa = csv.writer(f, dialect='excel')
for r in back.show():
chompa.writerow(r)
messagebox.showinfo("File Saved", "Saved as " + x + ".csv")
if __name__ == '__main__':
win = Style(theme='darkly').master
name = 'Password Generator'
dimension = '565x320'
app = window(win, dimension, name)
win.mainloop() | 728 |
# Extract time from datetime in Python
# import important module
import datetime
from datetime import datetime
# Create datetime string
datetime_str = "24AUG2001101010"
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str,
"%d%b%Y%H%M%S")
# It will print the datetime object
print(datetime_obj)
# extract the time from datetime_obj
time = datetime_obj.time()
# it will print time that
# we have extracted from datetime obj
print(time) | 69 |
# Write a Python program to check if the elements of the first list are contained in the second one regardless of order.
def is_contained_in(l1, l2):
for x in set(l1):
if l1.count(x) > l2.count(x):
return False
return True
print(is_contained_in([1, 2], [2, 4, 1]))
print(is_contained_in([1], [2, 4, 1]))
print(is_contained_in([1, 1], [4, 2, 1]))
print(is_contained_in([1, 1], [3, 2, 4, 1, 5, 1]))
| 60 |
# Write a Python program to Divide date range to N equal duration
# Python3 code to demonstrate working of
# Convert date range to N equal durations
# Using loop
import datetime
# initializing dates
test_date1 = datetime.datetime(1997, 1, 4)
test_date2 = datetime.datetime(1997, 1, 30)
# printing original dates
print("The original date 1 is : " + str(test_date1))
print("The original date 2 is : " + str(test_date2))
# initializing N
N = 7
temp = []
# getting diff.
diff = ( test_date2 - test_date1) // N
for idx in range(0, N):
# computing new dates
temp.append((test_date1 + idx * diff))
# using strftime to convert to userfriendly
# format
res = []
for sub in temp:
res.append(sub.strftime("%Y/%m/%d %H:%M:%S"))
# printing result
print("N equal duration dates : " + str(res)) | 131 |
# How to save a NumPy array to a text file in Python
# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
file = open("file1.txt", "w+")
# Saving the array in a text file
content = str(Array)
file.write(content)
file.close()
# Displaying the contents of the text file
file = open("file1.txt", "r")
content = file.read()
print("\nContent in file1.txt:\n", content)
file.close() | 87 |
# Write a Python program to create a 3-tuple ISO year, ISO week number, ISO weekday and an ISO 8601 formatted representation of the date and time.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\n3-tuple - ISO year, ISO week number, ISO weekday:")
print(arrow.utcnow().isocalendar())
print("\nISO 8601 formatted representation of the date and time:")
print(arrow.utcnow().isoformat())
| 55 |
# Find a pair with given sum in the array
arr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size): num = int(input()) arr.append(num)sum=int(input("Enter the Sum Value:"))flag=0for i in range(0,size-1): for j in range(i+1, size): if arr[i]+arr[j]==sum: flag=1 print("Given sum pairs of elements are ", arr[i]," and ", arr[j],".\n")if flag==0: print("Given sum Pair is not Present.") | 63 |
# Write a Python program to solve (x + y) * (x + y).
x, y = 4, 3
result = x * x + 2 * x * y + y * y
print("({} + {}) ^ 2) = {}".format(x, y, result))
| 43 |
# How to multiply a polynomial to another using NumPy in Python
# importing package
import numpy
# define the polynomials
# p(x) = 5(x**2) + (-2)x +5
px = (5, -2, 5)
# q(x) = 2(x**2) + (-5)x +2
qx = (2, -5, 2)
# mul the polynomials
rx = numpy.polynomial.polynomial.polymul(px, qx)
# print the resultant polynomial
print(rx) | 59 |
# Convert JSON data Into a Custom Python Object
# importing the module
import json
from collections import namedtuple
# creating the data
data = '{"name" : "Geek", "id" : 1, "location" : "Mumbai"}'
# making the object
x = json.loads(data, object_hook =
lambda d : namedtuple('X', d.keys())
(*d.values()))
# accessing the JSON data as an object
print(x.name, x.id, x.location) | 60 |
# Write a Python program to Numpy matrix.sum()
# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1; 12, 3]')
# applying matrix.sum() method
geek = gfg.sum()
print(geek) | 38 |
# Write a NumPy program to compute an element-wise indication of the sign for all elements in a given array.
import numpy as np
x = np.array([1, 3, 5, 0, -1, -7, 0, 5])
print("Original array;")
print(x)
r1 = np.sign(x)
r2 = np.copy(x)
r2[r2 > 0] = 1
r2[r2 < 0] = -1
assert np.array_equal(r1, r2)
print("Element-wise indication of the sign for all elements of the said array:")
print(r1)
| 69 |
# Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.
:
Solution
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print li[:5]
printList()
| 48 |
# Write a Python program to count the number 4 in a given list.
def list_count_4(nums):
count = 0
for num in nums:
if num == 4:
count = count + 1
return count
print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4])) | 45 |
# Write a Python program to display a number in left, right and center aligned of width 10.
x = 22
print("\nOriginal Number: ", x)
print("Left aligned (width 10) :"+"{:< 10d}".format(x));
print("Right aligned (width 10) :"+"{:10d}".format(x));
print("Center aligned (width 10) :"+"{:^10d}".format(x));
print()
| 42 |
# Write a NumPy program to create a new array of 3*5, filled with 2.
import numpy as np
#using no.full
x = np.full((3, 5), 2, dtype=np.uint)
print(x)
#using no.ones
y = np.ones([3, 5], dtype=np.uint) *2
print(y)
| 37 |
# Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display the dataframe in table style.
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)
print("\nDataframe - table style:")
# Set CSS properties for th elements in dataframe
th_props = [
('font-size', '12px'),
('text-align', 'center'),
('font-weight', 'bold'),
('color', '#6d6d6d'),
('background-color', '#f7ffff')
]
# Set CSS properties for td elements in dataframe
td_props = [
('font-size', '12px')
]
# Set table styles
styles = [
dict(selector="th", props=th_props),
dict(selector="td", props=td_props)
]
(df.style
.set_table_styles(styles))
| 120 |
# Define a function which can compute the sum of two numbers.
:
Solution
def SumFunction(number1, number2):
return number1+number2
print SumFunction(1,2)
| 21 |
# Check whether a given number is positive or negative
num=int(input("Enter a number:"))
if(num<0):
print("The number is negative")
elif(num>0):
print("The number is positive")
else:
print("The number is neither negative nor positive") | 31 |
# Write a Python program to start a new process replacing the current process.
import os
import sys
program = "python"
arguments = ["hello.py"]
print(os.execvp(program, (program,) + tuple(arguments)))
print("Goodbye")
| 29 |
# How to read numbers in CSV files in Python
import csv
# creating a nested list of roll numbers,
# subjects and marks scored by each roll number
marks = [
["RollNo", "Maths", "Python"],
[1000, 80, 85],
[2000, 85, 89],
[3000, 82, 90],
[4000, 83, 98],
[5000, 82, 90]
]
# using the open method with 'w' mode
# for creating a new csv file 'my_csv' with .csv extension
with open('my_csv.csv', 'w', newline = '') as file:
writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC,
delimiter = ' ')
writer.writerows(marks)
# opening the 'my_csv' file to read its contents
with open('my_csv.csv', newline = '') as file:
reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC,
delimiter = ' ')
# storing all the rows in an output list
output = []
for row in reader:
output.append(row[:])
for rows in output:
print(rows) | 137 |
# Write a Python program to Remove K length Duplicates from String
# Python3 code to demonstrate working of
# Remove K length Duplicates from String
# Using loop + slicing
# initializing strings
test_str = 'geeksforfreeksfo'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 3
memo = set()
res = []
for idx in range(0, len(test_str) - K):
# slicing K length substrings
sub = test_str[idx : idx + K]
# checking for presence
if sub not in memo:
memo.add(sub)
res.append(sub)
res = ''.join(res[ele] for ele in range(0, len(res), K))
# printing result
print("The modified string : " + str(res)) | 110 |
# Adding and Subtracting Matrices in Python
# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B)) | 58 |
# Write a Python program to find the list in a list of lists whose sum of elements is the highest.
num = [[1,2,3], [4,5,6], [10,11,12], [7,8,9]]
print(max(num, key=sum))
| 29 |
# Write a Python program to remove all the values except integer values from a given array of mixed values.
def test(lst):
return [lst for lst in lst if isinstance(lst, int)]
mixed_list = [34.67, 12, -94.89, "Python", 0, "C#"]
print("Original list:", mixed_list)
print("After removing all the values except integer values from the said array of mixed values:")
print(test(mixed_list))
| 58 |
# Write a Python program to generate groups of five consecutive numbers in a list.
l = [[5*i + j for j in range(1,6)] for i in range(5)]
print(l)
| 29 |
# Check if a string contains a given substring
str=input("Enter Your String:")str1=input("Enter your Searching word:")out = 0i=0j=0while out< len(str1): for i in range(len(str)): for j in range(len(str1)): if (str[i] == str1[j]): j+=1 else: j=0 out+=1if(j==out): print("Searching word is Found.")else: print("Searching Word is not Found.") | 44 |
# Write a Python program find the sorted sequence from a set of permutations of a given input.
from itertools import permutations
from more_itertools import windowed
def is_seq_sorted(lst):
print(lst)
return all(
x <= y
for x, y in windowed(lst, 2)
)
def permutation_sort(lst):
return next(
permutation_seq
for permutation_seq in permutations(lst)
if is_seq_sorted(permutation_seq)
)
print("All the sequences:")
print("\nSorted sequence: ",permutation_sort([12, 10, 9]))
print("\n\nAll the sequences:")
print("\nSorted sequence: ",permutation_sort([2, 3, 1, 0]))
| 70 |
# Write a Python program to Numpy matrix.sort()
# import the important module in python
import numpy as np
# make matrix with numpy
gfg = np.matrix('[4, 1; 12, 3]')
# applying matrix.sort() method
gfg.sort()
print(gfg) | 36 |
# Write a Python function to check whether a string is a pangram or not.
import string, sys
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
print ( ispangram('The quick brown fox jumps over the lazy dog'))
| 39 |
# Write a Python program to check if all items of a given list of strings is equal to a given string.
color1 = ["green", "orange", "black", "white"]
color2 = ["green", "green", "green", "green"]
print(all(c == 'blue' for c in color1))
print(all(c == 'green' for c in color2))
| 48 |
# Download Google Image Using Python and Selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# What you enter here will be searched for in
# Google Images
query = "dogs"
# Creating a webdriver instance
driver = webdriver.Chrome('Enter-Location-Of-Your-Webdriver')
# Maximize the screen
driver.maximize_window()
# Open Google Images in the browser
driver.get('https://images.google.com/')
# Finding the search box
box = driver.find_element_by_xpath('//*[@id="sbtc"]/div/div[2]/input')
# Type the search query in the search box
box.send_keys(query)
# Pressing enter
box.send_keys(Keys.ENTER)
# Fumction for scrolling to the bottom of Google
# Images results
def scroll_to_bottom():
last_height = driver.execute_script('\
return document.body.scrollHeight')
while True:
driver.execute_script('\
window.scrollTo(0,document.body.scrollHeight)')
# waiting for the results to load
# Increase the sleep time if your internet is slow
time.sleep(3)
new_height = driver.execute_script('\
return document.body.scrollHeight')
# click on "Show more results" (if exists)
try:
driver.find_element_by_css_selector(".YstHxe input").click()
# waiting for the results to load
# Increase the sleep time if your internet is slow
time.sleep(3)
except:
pass
# checking if we have reached the bottom of the page
if new_height == last_height:
break
last_height = new_height
# Calling the function
# NOTE: If you only want to capture a few images,
# there is no need to use the scroll_to_bottom() function.
scroll_to_bottom()
# Loop to capture and save each image
for i in range(1, 50):
# range(1, 50) will capture images 1 to 49 of the search results
# You can change the range as per your need.
try:
# XPath of each image
img = driver.find_element_by_xpath(
'//*[@id="islrg"]/div[1]/div[' +
str(i) + ']/a[1]/div[1]/img')
# Enter the location of folder in which
# the images will be saved
img.screenshot('Download-Location' +
query + ' (' + str(i) + ').png')
# Each new screenshot will automatically
# have its name updated
# Just to avoid unwanted errors
time.sleep(0.2)
except:
# if we can't find the XPath of an image,
# we skip to the next image
continue
# Finally, we close the driver
driver.close() | 317 |
# Write a Python program to merge some list items in given list using index value.
def merge_some_chars(lst,merge_from,merge_to):
result = lst
result[merge_from:merge_to] = [''.join(result[merge_from:merge_to])]
return result
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print("Original lists:")
print(chars)
merge_from = 2
merge_to = 4
print("\nMerge items from",merge_from,"to",merge_to,"in the said List:")
print(merge_some_chars(chars,merge_from,merge_to))
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
merge_from = 3
merge_to = 7
print("\nMerge items from",merge_from,"to",merge_to,"in the said List:")
print(merge_some_chars(chars,merge_from,merge_to))
| 73 |
# Write a Python program to merge more than one dictionary in a single expression.
import collections as ct
def merge_dictionaries(color1,color2):
merged_dict = dict(ct.ChainMap({}, color1, color2))
return merged_dict
color1 = { "R": "Red", "B": "Black", "P": "Pink" }
color2 = { "G": "Green", "W": "White" }
print("Original dictionaries:")
print(color1,' ',color2)
print("\nMerged dictionary:")
print(merge_dictionaries(color1, color2))
def merge_dictionaries(color1,color2, color3):
merged_dict = dict(ct.ChainMap({}, color1, color2, color3))
return merged_dict
color1 = { "R": "Red", "B": "Black", "P": "Pink" }
color2 = { "G": "Green", "W": "White" }
color3 = { "O": "Orange", "W": "White", "B": "Black" }
print("\nOriginal dictionaries:")
print(color1,' ',color2, color3)
print("\nMerged dictionary:")
# Duplicate colours have automatically removed.
print(merge_dictionaries(color1, color2, color3))
| 109 |
# Write a Python program to find maximum difference pair in a given list.
from itertools import combinations
from heapq import nlargest
def test(lst):
result = nlargest(1, combinations(lst, 2),
key=lambda sub: abs(sub[0] - sub[1]))
return result
marks = [32,14,90,10,22,42,31]
print("\nOriginal list:")
print(marks)
print("\nFind maximum difference pair of the said list:")
print(test(marks))
| 51 |
# Write a Python program to Maximum and Minimum in a Set
# Python code to get the maximum element from a set
def MAX(sets):
return (max(sets))
# Driver Code
sets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])
print(MAX(sets)) | 42 |
# Write a Python Library for Linked List
# importing module
import collections
# initialising a deque() of arbitary length
linked_lst = collections.deque()
# filling deque() with elements
linked_lst.append('first')
linked_lst.append('second')
linked_lst.append('third')
print("elements in the linked_list:")
print(linked_lst)
# adding element at an arbitary position
linked_lst.insert(1, 'fourth')
print("elements in the linked_list:")
print(linked_lst)
# deleting the last element
linked_lst.pop()
print("elements in the linked_list:")
print(linked_lst)
# removing a specific element
linked_lst.remove('fourth')
print("elements in the linked_list:")
print(linked_lst) | 72 |
# Write a Python program to group a sequence of key-value pairs into a dictionary of lists.
from collections import defaultdict
class_roll = [('v', 1), ('vi', 2), ('v', 3), ('vi', 4), ('vii', 1)]
d = defaultdict(list)
for k, v in class_roll:
d[k].append(v)
print(sorted(d.items()))
| 43 |
# Write a Python program to remove consecutive duplicates of a given list.
from itertools import groupby
def compress(l_nums):
return [key for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print("Original list:")
print(n_list)
print("\nAfter removing consecutive duplicates:")
print(compress(n_list))
| 53 |
# Write a Python program to print all odd numbers in a range
# Python program to print odd Numbers in given range
start, end = 4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 != 0:
print(num, end = " ") | 55 |
# Write a Pandas program to extract numbers greater than 940 from the specified column of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
'address': ['7277 Surrey Ave.1111','920 N. Bishop Ave.','9910 Golden Star St.', '1025 Dunbar St.', '1700 West Livingston Court']
})
print("Original DataFrame:")
print(df)
def test_num_great(text):
result = re.findall(r'95[5-9]|9[6-9]\d|[1-9]\d{3,}',text)
return " ".join(result)
df['num_great']=df['address'].apply(lambda x : test_num_great(x))
print("\nNumber greater than 940:")
print(df)
| 74 |
# Write a Pandas program to extract elements in the given positional indices along an axis of a dataframe.
import pandas as pd
import numpy as np
sales_arrays = [['sale1', 'sale1', 'sale3', 'sale3', 'sale2', 'sale2', 'sale4', 'sale4'],
['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']]
sales_tuples = list(zip(*sales_arrays))
sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city'])
print("\nConstruct a Dataframe using the said MultiIndex levels:")
df = pd.DataFrame(np.random.randn(8, 5), index=sales_index)
print(df)
print("\nSelect 1st, 2nd and 3rd row of the said DataFrame:")
positions = [1, 2, 5]
print(df.take([1, 2, 5]))
print("\nTake elements at indices 1 and 2 along the axis 1 (column selection):")
print(df.take([1, 2], axis=1))
print("\nTake elements at indices 4 and 3 using negative integers along the axis 1 (column selection):")
print(df.take([-1, -2], axis=1))
| 120 |
# Write a Python program to right rotate n-numbers by 1
def print_pattern(n):
for i in range(1, n+1, 1):
for j in range(1, n+1, 1):
# check that if index i is
# equal to j
if i == j:
print(j, end=" ")
# if index i is less than j
if i <= j:
for k in range(j+1, n+1, 1):
print(k, end=" ")
for p in range(1, j, 1):
print(p, end=" ")
# print new line
print()
# Driver's code
print_pattern(3) | 82 |
# Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.
import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print("Original String:")
print(j_str)
print("\nJSON data:")
print(json.dumps(j_str, sort_keys=True, indent=4))
| 44 |
# Find the sum of n natural numbers using recursion
def SumOfNaturalNumber(n): if n>0: return n+SumOfNaturalNumber(n-1) else: return nn=int(input("Enter the N Number:"))print("Sum of N Natural Number Using Recursion is:",SumOfNaturalNumber(n)) | 29 |
# Visualize data from CSV file in Python
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('biostats.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter = ',')
for row in plots:
x.append(row[0])
y.append(int(row[2]))
plt.bar(x, y, color = 'g', width = 0.72, label = "Age")
plt.xlabel('Names')
plt.ylabel('Ages')
plt.title('Ages of different persons')
plt.legend()
plt.show() | 55 |
# Python Program to Print Largest Even and Largest Odd Number in a List
n=int(input("Enter the number of elements to be in the list:"))
b=[]
for i in range(0,n):
a=int(input("Element: "))
b.append(a)
c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1+1
for j in d:
count2=count2+1
print("Largest even number:",c[count1-1])
print("Largest odd number",d[count2-1]) | 62 |
# Write a Python program to parse a string representing a time according to a format.
import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\ntime.struct_time, in the current timezone:")
print(arrow.utcnow().timetuple())
| 30 |
# Python Program to Solve Rod Cutting Problem using Dynamic Programming with Memoization
def cut_rod(p, n):
"""Take a list p of prices and the rod length n and return lists r and s.
r[i] is the maximum revenue that you can get and s[i] is the length of the
first piece to cut from a rod of length i."""
# r[i] is the maximum revenue for rod length i
# r[i] = -1 means that r[i] has not been calculated yet
r = [-1]*(n + 1)
# s[i] is the length of the initial cut needed for rod length i
# s[0] is not needed
s = [-1]*(n + 1)
cut_rod_helper(p, n, r, s)
return r, s
def cut_rod_helper(p, n, r, s):
"""Take a list p of prices, the rod length n, a list r of maximum revenues
and a list s of initial cuts and return the maximum revenue that you can get
from a rod of length n.
Also, populate r and s based on which subproblems need to be solved.
"""
if r[n] >= 0:
return r[n]
if n == 0:
q = 0
else:
q = -1
for i in range(1, n + 1):
temp = p[i] + cut_rod_helper(p, n - i, r, s)
if q < temp:
q = temp
s[n] = i
r[n] = q
return q
n = int(input('Enter the length of the rod in inches: '))
# p[i] is the price of a rod of length i
# p[0] is not needed, so it is set to None
p = [None]
for i in range(1, n + 1):
price = input('Enter the price of a rod of length {} in: '.format(i))
p.append(int(price))
r, s = cut_rod(p, n)
print('The maximum revenue that can be obtained:', r[n])
print('The rod needs to be cut into length(s) of ', end='')
while n > 0:
print(s[n], end=' ')
n -= s[n] | 314 |
# Write a Python program to get the symmetric difference between two iterables, without filtering out duplicate values.
def symmetric_difference(x, y):
(_x, _y) = (set(x), set(y))
return [item for item in x if item not in _y] + [item for item in y
if item not in _x]
print(symmetric_difference([10, 20, 30], [10, 20, 40]))
| 54 |
# Write a Python program to remove a newline in Python.
str1='Python Exercises\n'
print(str1)
print(str1.rstrip())
| 15 |
# Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.
area = 1256.66
volume = 1254.725
decimals = 2
print("The area of the rectangle is {0:.{1}f}cm\u00b2".format(area, decimals))
decimals = 3
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
| 51 |
# Write a Python program to find the index of a given string at which a given substring starts. If the substring is not found in the given string return 'Not found'.
def find_Index(str1, pos):
if len(pos) > len(str1):
return 'Not found'
for i in range(len(str1)):
for j in range(len(pos)):
if str1[i + j] == pos[j] and j == len(pos) - 1:
return i
elif str1[i + j] != pos[j]:
break
return 'Not found'
print(find_Index("Python Exercises", "Ex"))
print(find_Index("Python Exercises", "yt"))
print(find_Index("Python Exercises", "PY"))
| 83 |
# Write a Python program to split a string on the last occurrence of the delimiter.
str1 = "w,3,r,e,s,o,u,r,c,e"
print(str1.rsplit(',', 1))
print(str1.rsplit(',', 2))
print(str1.rsplit(',', 5))
| 25 |
# Write a NumPy program to find the position of the index of a specified value greater than existing value in NumPy array.
import numpy as np
n= 4
nums = np.arange(-6, 6)
print("\nOriginal array:")
print(nums)
print("\nPosition of the index:")
print(np.argmax(nums>n/2))
| 41 |
# Write a NumPy program to create a new array of given shape (5,6) and type, filled with zeros.
import numpy as np
nums = np.zeros(shape=(5, 6), dtype='int')
print("Original array:")
print(nums)
nums[::2, ::2] = 3
nums[1::2, ::2] = 7
print("\nNew array:")
print(nums)
| 42 |
# Write a program to calculate compound interest
principle=float(input("Enter principle:"))
rate=float(input("Enter rate(%):"))
n=float(input("Enter n:"))
time=float(input("Enter time:"))
amount=principle*pow(1+(rate/100.0)/n,n*time)
print("The compound interest is",amount) | 21 |
# Write a Python program to count the number of items of a given doubly linked list.
class Node(object):
# Singly linked node
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class doubly_linked_list(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def append_item(self, data):
# Append an item
new_item = Node(data, None, None)
if self.head is None:
self.head = new_item
self.tail = self.head
else:
new_item.prev = self.tail
self.tail.next = new_item
self.tail = new_item
self.count += 1
items = doubly_linked_list()
items.append_item('PHP')
items.append_item('Python')
items.append_item('C#')
items.append_item('C++')
items.append_item('Java')
items.append_item('SQL')
print("Number of items of the Doubly linked list:",items.count)
| 102 |
# Write a Python program to define a string containing special characters in various forms.
print()
print("\#{'}${\"}@/")
print("\#{'}${"'"'"}@/")
print(r"""\#{'}${"}@/""")
print('\#{\'}${"}@/')
print('\#{'"'"'}${"}@/')
print(r'''\#{'}${"}@/''')
print()
| 23 |
# Write a Pandas program to join (left join) the two dataframes using keys from left dataframe only.
import pandas as pd
data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'P': ['P0', 'P1', 'P2', 'P3'],
'Q': ['Q0', 'Q1', 'Q2', 'Q3']})
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 (keys from data1):")
merged_data = pd.merge(data1, data2, how='left', on=['key1', 'key2'])
print(merged_data)
print("\nMerged Data (keys from data2):")
merged_data = pd.merge(data2, data1, how='left', on=['key1', 'key2'])
print(merged_data)
| 97 |
# Dumping queue into list or array in Python
# Python program to
# demonstrate queue implementation
# using collections.dequeue
from collections import deque
# Initializing a queue
q = deque()
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
# display the queue
print("Initial queue")
print(q,"\n")
# display the type
print(type(q)) | 52 |
# Print with your own font using Python !!
# Python3 code to print input in your own font
name = "GEEK"
# To take input from User
# name = input("Enter your name: \n\n")
length = len(name)
l = ""
for x in range(0, length):
c = name[x]
c = c.upper()
if (c == "A"):
print("..######..\n..#....#..\n..######..", end = " ")
print("\n..#....#..\n..#....#..\n\n")
elif (c == "B"):
print("..######..\n..#....#..\n..#####...", end = " ")
print("\n..#....#..\n..######..\n\n")
elif (c == "C"):
print("..######..\n..#.......\n..#.......", end = " ")
print("\n..#.......\n..######..\n\n")
elif (c == "D"):
print("..#####...\n..#....#..\n..#....#..", end = " ")
print("\n..#....#..\n..#####...\n\n")
elif (c == "E"):
print("..######..\n..#.......\n..#####...", end = " ")
print("\n..#.......\n..######..\n\n")
elif (c == "F"):
print("..######..\n..#.......\n..#####...", end = " ")
print("\n..#.......\n..#.......\n\n")
elif (c == "G"):
print("..######..\n..#.......\n..#.####..", end = " ")
print("\n..#....#..\n..#####...\n\n")
elif (c == "H"):
print("..#....#..\n..#....#..\n..######..", end = " ")
print("\n..#....#..\n..#....#..\n\n")
elif (c == "I"):
print("..######..\n....##....\n....##....", end = " ")
print("\n....##....\n..######..\n\n")
elif (c == "J"):
print("..######..\n....##....\n....##....", end = " ")
print("\n..#.##....\n..####....\n\n")
elif (c == "K"):
print("..#...#...\n..#..#....\n..##......", end = " ")
print("\n..#..#....\n..#...#...\n\n")
elif (c == "L"):
print("..#.......\n..#.......\n..#.......", end = " ")
print("\n..#.......\n..######..\n\n")
elif (c == "M"):
print("..#....#..\n..##..##..\n..#.##.#..", end = " ")
print("\n..#....#..\n..#....#..\n\n")
elif (c == "N"):
print("..#....#..\n..##...#..\n..#.#..#..", end = " ")
print("\n..#..#.#..\n..#...##..\n\n")
elif (c == "O"):
print("..######..\n..#....#..\n..#....#..", end = " ")
print("\n..#....#..\n..######..\n\n")
elif (c == "P"):
print("..######..\n..#....#..\n..######..", end = " ")
print("\n..#.......\n..#.......\n\n")
elif (c == "Q"):
print("..######..\n..#....#..\n..#.#..#..", end = " ")
print("\n..#..#.#..\n..######..\n\n")
elif (c == "R"):
print("..######..\n..#....#..\n..#.##...", end = " ")
print("\n..#...#...\n..#....#..\n\n")
elif (c == "S"):
print("..######..\n..#.......\n..######..", end = " ")
print("\n.......#..\n..######..\n\n")
elif (c == "T"):
print("..######..\n....##....\n....##....", end = " ")
print("\n....##....\n....##....\n\n")
elif (c == "U"):
print("..#....#..\n..#....#..\n..#....#..", end = " ")
print("\n..#....#..\n..######..\n\n")
elif (c == "V"):
print("..#....#..\n..#....#..\n..#....#..", end = " ")
print("\n...#..#...\n....##....\n\n")
elif (c == "W"):
print("..#....#..\n..#....#..\n..#.##.#..", end = " ")
print("\n..##..##..\n..#....#..\n\n")
elif (c == "X"):
print("..#....#..\n...#..#...\n....##....", end = " ")
print("\n...#..#...\n..#....#..\n\n")
elif (c == "Y"):
print("..#....#..\n...#..#...\n....##....", end = " ")
print("\n....##....\n....##....\n\n")
elif (c == "Z"):
print("..######..\n......#...\n.....#....", end = " ")
print("\n....#.....\n..######..\n\n")
elif (c == " "):
print("..........\n..........\n..........", end = " ")
print("\n..........\n\n")
elif (c == "."):
print("----..----\n\n") | 328 |
# Write a Python program to Count the frequency of matrix row length
# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
[10, 12, 7], [4, 11]]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
for sub in test_list:
# initializing incase of new length
if len(sub) not in res:
res[len(sub)] = 1
# increment in case of length present
else:
res[len(sub)] += 1
# printing result
print("Row length frequencies : " + str(res)) | 99 |