Write a program to Add Two Numbers.
Solution:
a = 1
b = 2
c= a+b
print(c)
a = int(input("enter a number: "))
b = int(input("enter a number: "))
c= a+b
print(c)
Write a program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
Solution:
a = int(input("enter a number: "))
if a % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
Write a program to check whether a number entered by the user is positive, negative or zero.
Solution:
a = int(input("Enter a number: "))
if a > 0:
print("Positive number")
elif a == 0:
print("Zero")
else:
print("Negative number")
Write a program to display the calendar of a given date.
Solution:
import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))
Write a program to ask the user to enter the string and print that string as output of the program.
Solution:
string = input("Enter string: ")
print("You entered:",string)
Write a program to Concatenate Two Strings.
Solution:
string1 = input("Enter first string to concatenate: ")
string2 = input("Enter second string to concatenate: ")
string3 = string1 + string2
print("String after concatenation = ",string3)
Write a program to Check if an item exists in the list.
Solution:
list_of_items = ["ball", "book", "pencil"]
item = input("Type item to check: ")
if item in list_of_items:
print("Item exists in the list.")
else:
print("Item does not exist in the list.")
Write a program to Join two or more lists.
Solution:
list1 = ["This" , "is", "a", "sample", "program"]
list2 = [10, 2, 45, 3, 5, 7, 8, 10]
finalList = list1 + list2
print(finalList)
Write a program to Calculate Cube of a Number.
Solution:
import math
a = int(input("Enter a number: "))
b=math.pow(a,3)
print (b)
Write a program to Calculate Square root of a Number.
Solution:
import math
a = int(input("Enter a number: "))
b=math.sqrt(a)
print (b)
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.
Solution:
a = [5, 10, 15, 20, 25]
print([a[0], a[4]])
Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.
Solution:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
if i < 5:
print(i)
Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list 'a' and makes a new list that has only the even elements of this list in it.
Solution:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = [number for number in a if number % 2 == 0]
print(b)
Ask the user for a string and print out whether this string is a palindrome or not (A palindrome is a string that reads the same forwards and backwards).
Solution:
a=input("Please enter a word: ")
c = a.casefold()
b = reversed(c)
if list(c) == list(b):
print("It is palindrome")
else:
print("It is not palindrome")
Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
Solution:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
result = [i for i in set(a) if i in b]
print(result)
Write a program to add a string to text file.
Solution:
file = open("testfile.txt","w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Write a program to read a file and display its contents on console.
Solution:
with open('testfile.txt') as f:
line = f.readline()
while line:
print(line)
line = f.readline()
Take two sets, say for example these two: a = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89} b = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} and write a program that returns a set that contains only the elements that are common between the sets.
Solution:
a = {1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89}
b = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
c = set(a) & set(b)
print(c)
Write a program to split the characters of the given string into a list.
Solution:
s = "mystring"
l = list(s)
print (l)
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
Solution:
n=int(input("Enter an integer: "))
print("The divisors of the number are: ")
for i in range(1,n+1):
if(n%i==0):
print(i)
Write a program to Find the largest of three numbers.
Solution:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
print("The largest number is", largest)
Write a Program to Find Absolute value of a Number.
Solution:
num = int(input("Enter a number: "))
if num >= 0:
print(num)
else:
print(-num)
Write a program to Find the length of a String.
Solution:
print("Enter 'y' for exit.")
string = input("Enter a string: ")
if string == 'y':
exit()
else:
print("Length of the string =", len(string))
Write a program to Print Natural Numbers from 1 to N.
Solution:
N = int(input("Please Enter any Number: "))
for i in range(1, N+1):
print (i)
Write a program to calculate the sum and average of Natural Numbers from 1 to N.
Solution:
N = int(input("Please Enter any Number: "))
sum = 0
for i in range(1,N+1):
sum = sum + i
print(sum)
average = sum / N
print(average)
Write a program to Print a Statement Any Number of Times.
Solution:
n = int(input("Please Enter any Number: "))
for i in range(n):
print("hello world")
Write a program To Multiply Two Numbers Using Function.
Solution:
def my_function():
a = int(input("enter a number: "))
b=int(input("enter a number: "))
c= a*b
return c
d = my_function()
print (d)
Write a program To add an item to the end of the list.
Solution:
list1 = ["pen", "book", "ball"]
list1.append("bat")
print(list1)
Write a program To remove an item from the list.
Solution:
list1 = ["pen", "book", "ball"]
list1.remove("ball")
print(list1)
Write a program To print the number of elements in an array.
Solution:
list1 = ["pen", "book", "ball"]
a = len(list1)
print(a)
Write a program To calculate the variance and standard deviation of the elements of the list.
Solution:
import numpy as np
a= [2,6,8,12,18,24,28,32]
variance= np.var(a)
std = np.std(a)
print(variance)
print(std)
Write a program to get the difference between the two lists.
Solution:
list1 = [4, 5, 6, 7]
list2 = [4, 5]
print(list(set(list1) - set(list2)))
Write a program to select an item randomly from a list.
Solution:
import random
list = ['Paper', 'Pencil', 'Book', 'Bag', 'Pen']
print(random.choice(list))
Write a program that prints all the numbers from 0 to 6 except 2 and 6.
Solution:
for x in range(6):
if (x == 2 or x==6):
continue
print(x)
Write a program that takes input from the user and displays that input back in upper and lower cases.
Solution:
a = input("What's your name? ")
print(a.upper())
print(a.lower())
Write a program to check whether a string starts with specified characters.
Solution:
string = "myw3schools.com"
print(string.startswith("w3s"))
Write a program to create the multiplication table (from 1 to 10) of a number.
Solution:
n = int(input("Enter a number: "))
for i in range(1,11):
print(n,'x',i,'=',n*i)
Write a program to check a triangle is equilateral, isosceles or scalene.
Solution:
print("Enter lengths of the triangle sides: ")
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a == b == c:
print("Equilateral triangle")
elif a==b or b==c or c==a:
print("isosceles triangle")
else:
print("Scalene triangle")
Write a program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
Solution:
a = int(input("enter a number: "))
b = int(input("enter a number: "))
c= a+b
if c in range(15, 20):
print (20)
else:
print(c)
Write a program to convert degree to radian.
Solution:
pi=22/7
degree = int(input("Input degrees: "))
radian = degree*(pi/180)
print(radian)
Write a program to Generate a Random Number.
Solution:
import random
print(random.randint(0,9))
Write a Program to find the semi-perimeter of triangle.
Solution:
a = int(input('Enter first side: '))
b = int(input('Enter second side: '))
c = int(input('Enter third side: '))
s = (a + b + c) / 2
print(s)
Given a list of numbers, Iterate it and print only those numbers which are divisible of 2.
Solution:
List = [10, 20, 33, 46, 55]
for i in List:
if (i % 2 == 0):
print(i)
Write a program to Multiply all numbers in the list.
Solution:
import numpy
list = [1, 2, 3]
result = numpy.prod(list)
print(result)
Write a program to print ASCII Value of a character.
Solution:
a = 'j'
print("The ASCII value of '" + a + "' is", ord(a))
Write a program to list files in a directory.
Solution:
# Import os module to read directory
import os
# Set the directory path
path = 'C:/Users/Manju/.spyder-py3/'
# Read the content of the file
files = os.listdir(path)
# Print the content of the directory
for file in files:
print(file)
Write a program to Read and Write File.
Solution:
#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")
# Add some text
fileHandler.write("Bash\n")
fileHandler.write("Python\n")
fileHandler.write("PHP\n")
# Close the file
fileHandler.close()
# Open file for reading
fileHandler = open(filename, "r")
# Read a file line by line
for line in fileHandler:
print(line)
# Close the file
fileHandler.close()
Write a program to add and search data in the dictionary.
Solution:
# Define a dictionary
customers = {'1':'Mehzabin Afroze','2':'Md. Ali',
'3':'Mosarof Ahmed','4':'Mila Hasan', '5':'Yaqub Ali'}
# Append a new data
customers['6'] = 'Mehboba Ferdous'
print("The customer names are:")
# Print the values of the dictionary
for customer in customers:
print(customers[customer])
# Take customer ID as input to search
name = input("Enter customer ID:")
# Search the ID in the dictionary
for customer in customers:
if customer == name:
print(customers[customer])
break
Write a program to add and search data in the set.
Solution:
# Define the number set
numbers = {23, 90, 56, 78, 12, 34, 67}
# Add a new data
numbers.add(50)
# Print the set values
print(numbers)
message = "Number is not found"
# Take a number value for search
search_number = int(input("Enter a number:"))
# Search the number in the set
for val in numbers:
if val == search_number:
message = "Number is found"
break
print(message)
Write a program to demonstrate throw and catch exception.
Solution:
# Try block
try:
# Take a number
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Number is even")
else:
print("Number is odd")
# Exception block
except (ValueError):
# Print error message
print("Enter a numeric value")
Write a program to illustrate password authentication.
Solution:
# import getpass module
import getpass
# Take password from the user
passwd = getpass.getpass('Password:')
# Check the password
if passwd == "python":
print("You are authenticated")
else:
print("You are not authenticated")
Write a program to calculate the average of numbers in a given list.
Solution:
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Write a program to exchange the values of two numbers without using a temporary variable.
Solution:
a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
a=a+b
b=a-b
a=a-b
print("a is:",a," b is:",b)
Write a program to reverse a given number.
Solution:
n=int(input("Enter number: "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Write a program to take in the marks of 5 subjects and display the grade.
Solution:
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Write a program to print all numbers in a range divisible by a given number.
Solution:
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)
Write a program to read two numbers and print their quotient and remainder.
Solution:
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Write a program to accept three distinct digits and print all possible combinations from the digits.
Solution:
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
d=[]
d.append(a)
d.append(b)
d.append(c)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(d[i],d[j],d[k])
Write a program to print odd numbers within a given range.
Solution:
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)
Write a program to find the smallest divisor of an integer.
Solution:
n=int(input("Enter an integer:"))
a=[]
for i in range(2,n+1):
if(n%i==0):
a.append(i)
a.sort()
print("Smallest divisor is:",a[0])
Write a program to count the number of digits in a number.
Solution:
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
Write a program to read a number n and print and compute the series "1+2+…+n=".
Solution:
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
Write a program to read a number n and print the natural numbers summation pattern.
Solution:
n=int(input("Enter a number: "))
for j in range(1,n+1):
a=[]
for i in range(1,j+1):
print(i,sep=" ",end=" ")
if(i<j):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
Write a program to read a number n and print an identity matrix of the desired size.
Solution:
n=int(input("Enter a number: "))
for i in range(0,n):
for j in range(0,n):
if(i==j):
print("1",sep=" ",end=" ")
else:
print("0",sep=" ",end=" ")
print()
Write a program to read a number n and print an inverted star pattern of the desired size.
Solution:
n=int(input("Enter number of rows: "))
for i in range (n,0,-1):
print((n-i) * ' ' + i * '*')
Write a program to print prime numbers in a range using Sieve of Eratosthenes.
Solution:
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))
print()
Write a program to find the largest number in a list.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Write a program to find the second largest number in a list.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Second largest element is:",a[n-2])
Write a program to put the even and odd elements in a list into two different lists.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
Write a program to sort the list according to the second element in the sublist.
Solution:
a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j][1]>a[j+1][1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print(a)
Write a program to find the second largest number in a list using bubble sort.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print('Second largest number is:',a[n-2])
Write a program to sort a list according to the length of the elements.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=input("Enter element:")
a.append(b)
a.sort(key=len)
print(a)
Write a program to create a list of tuples with the first element as the number and the second element as the square of the number.
Solution:
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
Write a program to create a list of all numbers in a range which are perfect squares and the sum of the digits of the number is less than 10.
Solution:
l=int(input("Enter lower range: "))
u=int(input("Enter upper range: "))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10]
print(a)
Write a program to find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list.
Solution:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
Write a program to generate random numbers from 1 to 20 and append them to the list.
Solution:
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
Write a program to sort a list of tuples in increasing order by the last element in each tuple.
Solution:
def last(n):
return n[-1]
def sort(tuples):
return sorted(tuples, key=last)
a=input("Enter a list of tuples:")
print("Sorted:")
print(sort(a))
Write a program to swap the first and last value of a list.
Solution:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print("New list is:")
print(a)
Write a program to remove the duplicate items from a list.
Solution:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Write a program to read a list of words and return the length of the longest one.
Solution:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
max1=len(a[0])
temp=a[0]
for i in a:
if(len(i)>max1):
max1=len(i)
temp=i
print("The word with the longest length is:")
print(temp)
Write a program to remove the ith occurrence of the given word in list where words can repeat.
Solution:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
print(a)
c=[]
count=0
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
if(i==b):
count=count+1
if(count!=n):
c.append(i)
else:
c.append(i)
if(count==0):
print("Item not found ")
else:
print("The number of repetitions is: ",count)
print("Updated list is: ",c)
print("The distinct elements are: ",set(a))
Write a program to solve the maximum subarray problem using divide and conquer technique.
Solution:
def find_max_subarray(alist, start, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end."""
# base case
if start == end - 1:
return start, end, alist[start]
else:
mid = (start + end)//2
left_start, left_end, left_max = find_max_subarray(alist, start, mid)
right_start, right_end, right_max = find_max_subarray(alist, mid, end)
cross_start, cross_end, cross_max = find_max_crossing_subarray(alist, start, mid, end)
if (left_max > right_max and left_max > cross_max):
return left_start, left_end, left_max
elif (right_max > left_max and right_max > cross_max):
return right_start, right_end, right_max
else:
return cross_start, cross_end, cross_max
def find_max_crossing_subarray(alist, start, mid, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray within
alist with start <= l < mid <= r < end with sum m. The arguments start, mid,
end must satisfy start <= mid <= end."""
sum_left = float('-inf')
sum_temp = 0
cross_start = mid
for i in range(mid - 1, start - 1, -1):
sum_temp = sum_temp + alist[i]
if sum_temp > sum_left:
sum_left = sum_temp
cross_start = i
sum_right = float('-inf')
sum_temp = 0
cross_end = mid + 1
for i in range(mid, end):
sum_temp = sum_temp + alist[i]
if sum_temp > sum_right:
sum_right = sum_temp
cross_end = i + 1
return cross_start, cross_end, sum_left + sum_right
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))
Write a program to solve the maximum subarray problem using Kadane's algorithm.
Solution:
def find_max_subarray(alist, start, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end."""
max_ending_at_i = max_seen_so_far = alist[start]
max_left_at_i = max_left_so_far = start
# max_right_at_i is always i + 1
max_right_so_far = start + 1
for i in range(start + 1, end):
if max_ending_at_i > 0:
max_ending_at_i += alist[i]
else:
max_ending_at_i = alist[i]
max_left_at_i = i
if max_ending_at_i > max_seen_so_far:
max_seen_so_far = max_ending_at_i
max_left_so_far = max_left_at_i
max_right_so_far = i + 1
return max_left_so_far, max_right_so_far, max_seen_so_far
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))
Write a program to find the element that occurs odd number of times in a list.
Solution:
def find_odd_occurring(alist):
"""Return the element that occurs odd number of times in alist.
alist is a list in which all elements except one element occurs an even
number of times.
"""
ans = 0
for element in alist:
ans ^= element
return ans
alist = input('Enter the list: ').split()
alist = [int(i) for i in alist]
ans = find_odd_occurring(alist)
print('The element that occurs odd number of times:', ans)
Write a program to check if a date is valid and print the incremented date if it is.
Solution:
date=input("Enter the date: ")
dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
max1=29
else:
max1=28
if(mm<1 or mm>12):
print("Date is invalid.")
elif(dd<1 or dd>max1):
print("Date is invalid.")
elif(dd==max1 and mm!=12):
dd=1
mm=mm+1
print("The incremented date is: ",dd,mm,yy)
elif(dd==31 and mm==12):
dd=1
mm=1
yy=yy+1
print("The incremented date is: ",dd,mm,yy)
else:
dd=dd+1
print("The incremented date is: ",dd,mm,yy)
Write a program to compute simple interest given all the required values.
Solution:
principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is:",simple_interest)
Write a program to check whether a given year is a leap year or not.
Solution:
year=int(input("Enter year to be checked:"))
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
else:
print("The year isn't a leap year!")
Write a program to compute prime factors of an integer.
Solution:
n=int(input("Enter an integer:"))
print("Factors are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i=i+1
Write a program to generate all the divisors of an integer.
Solution:
n=int(input("Enter an integer:"))
print("The divisors of the number are:")
for i in range(1,n+1):
if(n%i==0):
print(i)
Write a program to print the table of a given number.
Solution:
n=int(input("Enter the number to print the tables for:"))
for i in range(1,11):
print(n,"x",i,"=",n*i)
Write a program to check if a number is an Armstrong number.
Solution:
n=int(input("Enter any number: "))
a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
print("The number is an armstrong number. ")
else:
print("The number isn't an arsmtrong number. ")
Write a program to print the Pascal's triangle for n number of rows given by the user.
Solution:
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])
if(n!=0):
a[i].append(1)
for i in range(n):
print(" "*(n-i),end=" ",sep=" ")
for j in range(0,i+1):
print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
print()
Write a program to check if a number is a Perfect number.
Solution:
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
Write a program to find the LCM of two numbers.
Solution:
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if(a>b):
min1=a
else:
min1=b
while(1):
if(min1%a==0 and min1%b==0):
print("LCM is:",min1)
break
min1=min1+1
Write a program to find the GCD of two numbers.
Solution:
import math
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
print("The GCD of the two numbers is",math.gcd(a,b))
Write a program to compute a polynomial equation given that the coefficients of the polynomial are stored in the list.
Solution:
import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
a=int(input("Enter coefficient:"))
lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
while(j>0):
sum1=sum1+(lst[i]*math.pow(x,j))
break
j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)
Write a program to check if two numbers are amicable numbers.
Solution:
x=int(input('Enter number 1: '))
y=int(input('Enter number 2: '))
sum1=0
sum2=0
for i in range(1,x):
if x%i==0:
sum1+=i
for j in range(1,y):
if y%j==0:
sum2+=j
if(sum1==y and sum2==x):
print('Amicable!')
else:
print('Not Amicable!')
Write a program to find the area of a triangle given all three sides.
Solution:
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
Write a program to find the gravitational force acting between two objects.
Solution:
m1=float(input("Enter the first mass: "))
m2=float(input("Enter the second mass: "))
r=float(input("Enter the distance between the centres of the masses: "))
G=6.673*(10**-11)
f=(G*m1*m2)/(r**2)
print("Hence, the gravitational force is: ",round(f,2),"N")
Write a program to find the sum of sine series.
Solution:
import math
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sin(x,n),2))
Write a program to find the sum of cosine series.
Solution:
import math
def cosine(x,n):
cosx = 1
sign = -1
for i in range(2, n, 2):
pi=22/7
y=x*(pi/180)
cosx = cosx + (sign*(y**i))/math.factorial(i)
sign = -sign
return cosx
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(cosine(x,n),2))
Write a program to find the sum of first N Natural Numbers.
Solution:
n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print("The sum of first n natural numbers is",sum1)
Write a program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.
Solution:
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
Write a program to determine all Pythagorean triplets till the upper limit.
Solution:
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
Write a program to search the number of times a particular number occurs in a list.
Solution:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
k=0
num=int(input("Enter the number to be counted:"))
for j in a:
if(j==num):
k=k+1
print("Number of times",num,"appears is",k)
Write a program to test Collatz conjecture for a given number.
Solution:
def collatz(n):
while n > 1:
print(n, end=' ')
if (n % 2):
# n is odd
n = 3*n + 1
else:
# n is even
n = n//2
print(1, end='')
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)
Write a program to count set bits in a number.
Solution:
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
n = int(input('Enter n: '))
print('Number of set bits:', count_set_bits(n))
Write a program to find whether a number is a power of two.
Solution:
def is_power_of_two(n):
"""Return True if n is a power of two."""
if n <= 0:
return False
else:
return n & (n - 1) == 0
n = int(input('Enter a number: '))
if is_power_of_two(n):
print('{} is a power of two.'.format(n))
else:
print('{} is not a power of two.'.format(n))
Write a program to clear the rightmost set bit of a number.
Solution:
def clear_rightmost_set_bit(n):
"""Clear rightmost set bit of n and return it."""
return n & (n - 1)
n = int(input('Enter a number: '))
ans = clear_rightmost_set_bit(n)
print('n with its rightmost set bit cleared equals:', ans)
Write a program to generate all gray codes using recursion.
Solution:
def get_gray_codes(n):
"""Return n-bit Gray code in a list."""
if n == 0:
return ['']
first_half = get_gray_codes(n - 1)
second_half = first_half.copy()
first_half = ['0' + code for code in first_half]
second_half = ['1' + code for code in reversed(second_half)]
return first_half + second_half
n = int(input('Enter the number of bits: '))
codes = get_gray_codes(n)
print('All {}-bit Gray Codes:'.format(n))
print(codes)
Write a program to convert Gray code to binary.
Solution:
def gray_to_binary(n):
"""Convert Gray codeword to binary and return it."""
n = int(n, 2) # convert to int
mask = n
while mask != 0:
mask >>= 1
n ^= mask
# bin(n) returns n's binary representation with a '0b' prefixed
# the slice operation is to remove the prefix
return bin(n)[2:]
g = input('Enter Gray codeword: ')
b = gray_to_binary(g)
print('In binary:', b)
Write a program to convert binary to Gray code.
Solution:
def binary_to_gray(n):
"""Convert Binary to Gray codeword and return it."""
n = int(n, 2) # convert to int
n ^= (n >> 1)
# bin(n) returns n's binary representation with a '0b' prefixed
# the slice operation is to remove the prefix
return bin(n)[2:]
g = input('Enter binary number: ')
b = binary_to_gray(g)
print('Gray codeword:', b)
Write a program to replace all occurrences of 'a' with '$' in a string.
Solution:
string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)
Write a program to remove the nth index character from a non-empty string.
Solution:
def remove(string, n):
first = string[:n]
last = string[n+1:]
return first + last
string=input("Enter the string:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))
Write a program to detect if two strings are anagrams.
Solution:
s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
Write a program to form a string where the first character and the last character have been exchanged.
Solution:
def change(string):
return string[-1:] + string[1:-1] + string[:1]
string=input("Enter string:")
print("Modified string:")
print(change(string))
Write a program to count the number of vowels in a string.
Solution:
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Write a program to take a string and replace every blank space with a hyphen.
Solution:
string=input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)
Write a program to calculate the length of a string without using library functions.
Solution:
string=input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
Write a program to remove the characters of odd index values in a string.
Solution:
def modify(string):
final = ""
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string=input("Enter string:")
print("Modified string is:")
print(modify(string))
Write a program to calculate the number of words and characters present in a string.
Solution:
string=input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
Write a program to take in two strings and display the larger string without using built-in functions.
Solution:
string1=input("Enter first string:")
string2=input("Enter second string:")
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
print("Larger string is:")
print(string2)
elif(count1==count2):
print("Both strings are equal.")
else:
print("Larger string is:")
print(string1)
Write a program to count number of lowercase characters in a string.
Solution:
string=input("Enter string:")
count=0
for i in string:
if(i.islower()):
count=count+1
print("The number of lowercase characters is:")
print(count)
Write a program to count the number of lowercase letters and uppercase letters in a string.
Solution:
string=input("Enter string:")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
Write a program to calculate the number of digits and letters in a string.
Solution:
string=input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
Write a program to form a new string made of the first 2 characters and last 2 characters from a given string.
Solution:
string=input("Enter string:")
count=0
for i in string:
count=count+1
new=string[0:2]+string[count-2:count]
print("Newly formed string is:")
print(new)
Write a program to count the occurrences of each word in a given string sentence.
Solution:
string=input("Enter string:")
word=input("Enter word:")
a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print("Count of the word is:")
print(count)
Write a program to check if a substring is present in a given string.
Solution:
string=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==-1):
print("Substring not found in string!")
else:
print("Substring in string!")
Write a program to print all permutations of a string in lexicographic order without using recursion.
Solution:
from math import factorial
def print_permutations_lexicographic_order(s):
"""Print all permutations of string s in lexicographic order."""
seq = list(s)
# there are going to be n! permutations where n = len(seq)
for _ in range(factorial(len(seq))):
# print permutation
print(''.join(seq))
# find p such that seq[p:] is the largest sequence with elements in
# descending lexicographic order
p = len(seq) - 1
while p > 0 and seq[p - 1] > seq[p]:
p -= 1
# reverse seq[p:]
seq[p:] = reversed(seq[p:])
if p > 0:
# find q such that seq[q] is the smallest element in seq[p:] such that
# seq[q] > seq[p - 1]
q = p
while seq[p - 1] > seq[q]:
q += 1
# swap seq[p - 1] and seq[q]
seq[p - 1], seq[q] = seq[q], seq[p - 1]
s = input('Enter the string: ')
print_permutations_lexicographic_order(s)
Write a program to print all permutations of a string in lexicographic order using recursion.
Solution:
from math import factorial
def print_permutations_lexicographic_order(s):
"""Print all permutations of string s in lexicographic order."""
seq = list(s)
for _ in range(factorial(len(seq))):
print(''.join(seq))
nxt = get_next_permutation(seq)
# if seq is the highest permutation
if nxt is None:
# then reverse it
seq.reverse()
else:
seq = nxt
def get_next_permutation(seq):
"""Return next greater lexicographic permutation. Return None if cannot.
This will return the next greater permutation of seq in lexicographic
order. If seq is the highest permutation then this will return None.
seq is a list.
"""
if len(seq) == 0:
return None
nxt = get_next_permutation(seq[1:])
# if seq[1:] is the highest permutation
if nxt is None:
# reverse seq[1:], so that seq[1:] now is in ascending order
seq[1:] = reversed(seq[1:])
# find q such that seq[q] is the smallest element in seq[1:] such that
# seq[q] > seq[0]
q = 1
while q < len(seq) and seq[0] > seq[q]:
q += 1
# if cannot find q, then seq is the highest permutation
if q == len(seq):
return None
# swap seq[0] and seq[q]
seq[0], seq[q] = seq[q], seq[0]
return seq
else:
return [seq[0]] + nxt
s = input('Enter the string: ')
print_permutations_lexicographic_order(s)
Write a program to add a key-value pair to a dictionary.
Solution:
key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Write a program to concatenate two dictionaries into one dictionary.
Solution:
d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
Write a program to check if a given key exists in a dictionary or not.
Solution:
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else:
print("Key isn't present!")
Write a program to find the sum all the items in a dictionary.
Solution:
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))
Write a program to multiply all the items in a dictionary.
Solution:
d={'A':10,'B':10,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Write a program to remove the given key from a dictionary.
Solution:
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Write a program to form a dictionary from an object of a class.
Solution:
class A(object):
def __init__(self):
self.A=1
self.B=2
obj=A()
print(obj.__dict__)
Write a program to map two lists into a dictionary.
Solution:
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Write a program to count the frequency of words appearing in a string using a dictionary.
Solution:
test_string=input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Write a program to create a dictionary with key as first character and value as words starting with that character.
Solution:
test_string=input("Enter string:")
l=test_string.split()
d={}
for word in l:
if(word[0] not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,":",v)
Write a program to count the number of vowels present in a string using sets.
Solution:
s=input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Write a program to check common letters in the two input strings.
Solution:
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Write a program to display which letters are in the first string but not in the second string.
Solution:
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
print(i)
Write a program to display which letters is present in both the strings.
Solution:
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)
Write a program to determine whether a given number is even or odd recursively.
Solution:
def check(n):
if (n < 2):
return (n % 2 == 0)
return (check(n - 2))
n=int(input("Enter number:"))
if(check(n)==True):
print("Number is even!")
else:
print("Number is odd!")
Write a program to determine how many times a given letter occurs in a string recursively.
Solution:
def check(string,ch):
if not string:
return 0
elif string[0]==ch:
return 1+check(string[1:],ch)
else:
return check(string[1:],ch)
string=input("Enter string:")
ch=input("Enter character to check:")
print("Count is:")
print(check(string,ch))
Write a program to find the fibonacci series using recursion.
Solution:
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print (fibonacci(i))
Write a program to find the factorial of a number using recursion.
Solution:
def factorial(n):
if(n <= 1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
Write a program to find the sum of elements in a list recursively.
Solution:
def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter the number of elements for list:"))
a=[]
for i in range(0,n):
element=int(input("Enter element:"))
a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
Write a program to find the binary equivalent of a number recursively.
Solution:
l=[]
def convert(b):
if(b==0):
return l
dig=b%2
l.append(dig)
convert(b//2)
a=int(input("Enter a number: "))
convert(a)
l.reverse()
print("Binary equivalent:")
for i in l:
print (i)
Write a program to find the LCM of two numbers using recursion.
Solution:
def lcm(a,b):
lcm.multiple=lcm.multiple+b
if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)):
return lcm.multiple;
else:
lcm(a, b)
return lcm.multiple
lcm.multiple=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
LCM=lcm(b,a)
else:
LCM=lcm(a,b)
print(LCM)
Write a program to find the GCD of two numbers using recursion.
Solution:
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Write a program to read the contents of a file.
Solution:
a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
Write a program to count the number of words in a text file.
Solution:
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Write a program to count the number of lines in a text file.
Solution:
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:")
print(num_lines)
Write a program to read a string from the user and appends it into a file.
Solution:
fname = input("Enter file name: ")
file3=open(fname,"a")
c=input("Enter string to append: \n");
file3.write("\n")
file3.write(c)
file3.close()
print("Contents of appended file:");
file4=open(fname,'r')
line1=file4.readline()
while(line1!=""):
print(line1)
line1=file4.readline()
file4.close()
Write a program to count the occurrences of a word in a text file.
Solution:
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Write a program to copy the contents of one file into another.
Solution:
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
Write a program to count the occurrences of a letter in a text file.
Solution:
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
Write a program to read a text file and print all numbers present in the text file.
Solution:
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter)
Write a program to append the contents of one file to another file.
Solution:
name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()
Write a program to count the number of blank spaces in a text file.
Solution:
fname = input("Enter file name: ")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Write a program to read a file and capitalize the first letter of every word in the file.
Solution:
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
l=line.title()
print(l)
Write a program to read the contents of a file in reverse order.
Solution:
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Write a program to find the area of a rectangle using classes.
Solution:
class rectangle():
def __init__(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
return self.breadth*self.length
a=int(input("Enter length of rectangle: "))
b=int(input("Enter breadth of rectangle: "))
obj=rectangle(a,b)
print("Area of rectangle:",obj.area())
print()
Write a program to append, delete and display elements of a list using classes.
Solution:
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)
obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List: ",obj.dis())
elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())
elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Write a program to implement a binary heap.
Solution:
class BinaryHeap:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def parent(self, i):
return (i - 1)//2
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def get(self, i):
return self.items[i]
def get_max(self):
if self.size() == 0:
return None
return self.items[0]
def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)
def swap(self, i, j):
self.items[i], self.items[j] = self.items[j], self.items[i]
def insert(self, key):
index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p
bheap = BinaryHeap()
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(bheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation == 'quit':
break
Write a program to implement a binomial tree.
Solution:
class BinomialTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0
def add_at_end(self, t):
self.children.append(t)
self.order = self.order + 1
trees = []
print('Menu')
print('create <key>')
print('combine <index1> <index2>')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'create':
key = int(do[1])
btree = BinomialTree(key)
trees.append(btree)
print('Binomial tree created.')
elif operation == 'combine':
index1 = int(do[1])
index2 = int(do[2])
if trees[index1].order == trees[index2].order:
trees[index1].add_at_end(trees[index2])
del trees[index2]
print('Binomial trees combined.')
else:
print('Orders of the trees need to be the same.')
elif operation == 'quit':
break
print('{:>8}{:>12}{:>8}'.format('Index', 'Root key', 'Order'))
for index, t in enumerate(trees):
print('{:8d}{:12d}{:8d}'.format(index, t.key, t.order))
Write a program to implement Tower of Hanoi.
Solution:
def hanoi(disks, source, auxiliary, target):
if disks == 1:
print('Move disk 1 from peg {} to peg {}.'.format(source, target))
return
hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from peg {} to peg {}.'.format(disks, source, target))
hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter number of disks: '))
hanoi(disks, 'A', 'B', 'C')
Write a program to implement birthday dictionary.
Solution:
if __name__ == '__main__':
birthdays = {
'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
print('Welcome to the birthday dictionary. We know the birthdays of:')
for name in birthdays:
print(name)
print('Who\'s birthday do you want to look up?')
name = input()
if name in birthdays:
print('{}\'s birthday is {}.'.format(name, birthdays[name]))
else:
print('Sadly, we don\'t have {}\'s birthday.'.format(name))
Write a program to implement guess letters.
Solution:
if __name__ == '__main__':
print("Welcome to hangman!!")
word = "EVAPORATE"
guessed = "_" * len(word)
word = list(word)
guessed = list(guessed)
lstGuessed = []
letter = input("guess letter: ")
while True:
if letter.upper() in lstGuessed:
letter = ''
print("Already guessed!!")
elif letter.upper() in word:
index = word.index(letter.upper())
guessed[index] = letter.upper()
word[index] = '_'
else:
print(''.join(guessed))
if letter is not '':
lstGuessed.append(letter.upper())
letter = input("guess letter: ")
if '_' not in guessed:
print("You won!!")
break
Write a program to implement password generator.
Solution:
import random
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = 8
p = "".join(random.sample(s,passlen ))
print (p)
Write a program to display calendar of the given month and year.
Solution:
# importing calendar module
import calendar
yy = 2014 # year
mm = 11 # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
Write a program to add two matrices.
Solution:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Write a program to transpose a matrix.
Solution:
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
***Write a program to multiply two matrices. ***
Solution:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Write a program to remove punctuations from a string.
Solution:
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)
Write a program to find the hash of a file and display it.
Solution:
import hashlib
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash object
h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest
return h.hexdigest()
message = hash_file("languages.txt")
print(message)
Write a program to find the size (resolution) of a image.
Solution:
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
Write a program to read website source code.
Solution:
import sys
if sys.version_info[0] == 3:
from urllib.request import urlopen
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlopen
# Your code where you can use urlopen
with urlopen("http://www.myw3schools.com") as url:
s = url.read()
print(s)
Write a program to get IP address of your computer.
Solution:
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
Write a program to get all links from a webpage.
Solution:
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
req = Request("http://www.myw3schools.com")
html_page = urlopen(req)
soup = BeautifulSoup(html_page, "lxml")
links = []
for link in soup.findAll('a'):
links.append(link.get('href'))
print(links)
Write a program to illustrate Dice Roll Simulator.
Solution:
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling the dices...")
print ("The values are....")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = input("Roll the dices again?")
- A Peephole Optimizer for Python
- Compiling Little Languages in Python
- Securing Your Collaborative Jupyter Notebooks in the Cloud using Container and Load Balancing Services
- Quasi-orthonormal Encoding for Machine Learning Applications
- MatLab vs. Python vs. R
- modernizing PHCpack through phcpy
- Bloscpack: a compressed lightweight serialization format for numerical data
- CATOS: Computer Aided Training/Observing System
- High-Content Digital Microscopy with Python
- PySTEMM: Executable Concept Modeling for K-12 STEM Learning
- Performance of Python runtimes on a non-numeric scientific code
- Computing an Optimal Control Policy for an Energy Storage
- JyNI – Using native CPython-Extensions in Jython
- SfePy - Write Your Own FE Application
- Mining online social networks with Python to study urban mobility
- PyFAI: a Python library for high performance azimuthal integration on GPU
- Wyrm, A Pythonic Toolbox for Brain-Computer Interfacing
- SPySort: Neuronal Spike Sorting with Python
- Using Python to Dive into Signalling Data with CellNOpt and BioServices
- Py3DFreeHandUS: a library for voxel-array reconstruction using Ultrasonography and attitude sensors
- SClib, a hack for straightforward embedded C functions in Python
- Predictive Modelling of Toxicity Resulting from Radiotherapy Treatments of Head and Neck Cancer
- pyFRET: A Python Library for Single Molecule Fluorescence Data Analysis
- Enhancing SfePy with Isogeometric Analysis
- A Python-based Post-processing Toolset For Seismic Analyses
- Numerical simulation of liver perfusion: from CT scans to FE model
- Temperature diagnostics of the solar atmosphere using SunPy
- Python vs. R: A Text Mining Approach for analyzing the Research Trends in Scopus Database
- Partial Pole Placement via Delay Action: A Python Software for Delayed Feedback Stabilizing Design
- Meta-analysis parameters computation: a Python approach to facilitate the crossing of experimental conditions
- ExoTiC-ISM: A Python package for marginalised exoplanet transit parameters across a grid of systematic instrument models
- MKLpy: a python-based framework for Multiple Kernel Learning
- ARC 3.0: An expanded Python toolbox for atomic physics calculations
- PyR@TE 3
- PyXtal FF: a Python Library for Automated Force Field Generation
- multivar horner: a python package for computing Horner factorisations of multivariate polynomials
- DyPy: A Python Library for Simulating Matrix-Form Games
- Automated Unit Test Generation for Python
- PyKEEN 1.0: A Python Library for Training and Evaluating Knowledge Graph Embeddings
- Biomedical and Clinical English Model Packages in the Stanza Python NLP Library
- Towards a Sustainable Microgrid on Alderney Island Using a Python-based Energy Planning Tool
- FitsGeo: Python package for PHITS geometry development
- PyMGRIT: A Python Package for the parallel-in-time method MGRIT
- SEDBYS: A python-based SED Builder for Young Stars
- Introducing students to research codes: A short course on solving partial differential equations in Python
- TAPsolver: A Python package for the simulation and analysis of TAP reactor experiments
- SPInS, a pipeline for massive stellar parameter inference: A public Python tool to age-date, weigh, size up stars, and more
- reval: a Python package to determine the best number of clusters with stability-based relative clustering validation
- A Python Library for Exploratory Data Analysis and Knowledge Discovery on Twitter Data
- TB2J: a python package for computing magnetic interaction parameters
- SimpleSBML: A Python package for creating, editing, and interrogating SBML models: Verison 2.0
- PySAD: A Streaming Anomaly Detection Framework in Python
- TorchKGE: Knowledge Graph embedding in Python and PyTorch
- Development of a computational software in Python, used to study the materials resistance in beams
- Atomic Data Assessment with PyNeb
- MicroAnalyzer: A Python Tool for Automated Bacterial Analysis with Fluorescence Microscopy
- munuSSM: A python package for the μ-from-ν Supersymmetric Standard Model
- BOML: A Modularized Bilevel Optimization Library in Python for Meta Learning
- Extendible and Efficient Python Framework for Solving Evolution Equations with Stabilized Discontinuous Galerkin Methods
- PyROQ: a Python-based Reduced Order Quadrature Building Code for Fast Gravitational Wave Inference
- EZFF: Python Library for Multi-Objective Parameterization and Uncertainty Quantification of Interatomic Forcefields for Molecular Dynamics
- Scipp: Scientific data handling with labeled multi-dimensional arrays for C++ and Python
- Fast fully-reproducible streamlined serial/parallel Monte Carlo/MCMC simulations and visualizations via ParaMonte::Python library
- DIETERpy: a Python framework for The Dispatch and Investment Evaluation Tool with Endogenous Renewables
- Pyg4ometry: a Python library for the creation of Monte Carlo radiation transport physical geometries
- TextAttack: Lessons learned in designing Python frameworks for NLP
- The Dusty Evolved Star Kit (DESK): A Python package for fitting the Spectral Energy Distribution of Evolved Stars
- PYMT5: multi-mode translation of natural language and PYTHON code with transformers
- Network Security using Python
- On the performance of the Python programming language for serial and parallel scientific computations
- A Primer on Python for Life Science Researchers
- Introducing Python Programming for Engineering Scholars
- A facility for creating Python extensions in C++
- A Python Based Production System for High Volume Electronic Publishing
- Parallel High Performance Bootstrapping in Python
- A Computational Framework for Plasmonic Nanobiosensing
- Cloudknot: A Python Library to Run your Existing Code on AWS Batch
- Expert RF Feature Extraction to Win the Army RCO AI Signal Classification Challenge
- Deep and Ensemble Learning to Win the Army RCO AI Signal Classification Challenge
- Keeping the Chandra Satellite Cool with Python
- Fitting Human Decision Making Models using Python
- Astrodata
- Will Millennials Ever Get Married?
- Accelerating the Advancement of Data Science Education
- A Technical Anatomy of SPM.Python, a Scalable, Parallel Version of Python
- Dynamic Social Network Modeling of Diffuse Subcellular Morphologies
- Functional Uncertainty Constrained by Law and Experiment
- pgmpy: Probabilistic Graphical Models using Python
- Total Recall: flmake and the Quest for Reproducibility
- Equity, Scalability, and Sustainability of Data Science Infrastructure
- Fluctuation X-ray Scattering real-time app
- Composable Multi-Threading and Multi-Processing for Numeric Libraries
- Divisi: Learning from Semantic Networks and Sparse SVD
- DMTCP: Bringing Checkpoint-Restart to Python
- Converting Python Virtual Machine Code to C
- Scientific Computing with SciPy for Undergraduate Physics Majors
- Multidimensional Data Exploration with Glue
- Generalized earthquake classification
- Theano: A CPU and GPU Math Compiler in Python
- Hyperopt: A Python Library for Optimizing the Hyperparameters of Machine Learning Algorithms
- SkData: Data Sets and Algorithm Evaluation Protocols in Python
- Analyzing Particle Systems for Machine Learning and Data Visualization with freud
- Using Python to Study Rotational Velocity Distributions of Hot Stars
- HOOMD-blue version 3.0 A Modern, Extensible, Flexible, Object-Oriented API for Molecular Simulations
- Fitting and Estimating Parameter Confidence Limits with Sherpa
- SPORCO: A Python package for standard and convolutional sparse representations
- cesium: Open-Source Platform for Time-Series Inference
- Python as a First Programming Language for Biomedical Scientists
- librosa: Audio and Music Signal Analysis in Python
- UConnRCMPy: Python-based data analysis for Rapid Compression Machines
- Crab: A Recommendation Engine Framework for Python
- The Econ-ARK and HARK: Open Source Tools for Computational Economics
- CAF Implementation on FPGA Using Python Tools
- PyEDA: Data Structures and Algorithms for Electronic Design Automation
- Developing a Graph Convolution-Based Analysis Pipeline for Multi-Modal Neuroimage Data: An Application to Parkinson’s Disease
- Storing Reproducible Results from Computational Experiments using Scientific Python Packages
- Python Tools for Reproducible Research on Hyperbolic Problems
- BCE: Berkeley's Common Scientific Compute Environment for Research and Education
- A High Performance Robot Vision Algorithm Implemented in Python
- Measuring rainshafts: Bringing Python to bear on remote sensing data
- Compyle: a Python package for parallel computing
- Scientific Data Analysis and Visualization with Python, VTK, and ParaView
- gpustats: GPU Library for Statistical Computing in Python
- Python's Role in VisIt
- Using the Global Arrays Toolkit to Reimplement NumPy for Distributed Computation
- Netlist Analysis and Transformations Using SpyDrNet
- datreant: persistent, Pythonic trees for heterogeneous data
- Creating a Real-Time Recommendation Engine using Modified K-Means Clustering and Remote Sensing Signature Matching Algorithms
- Comparison of machine learning methods applied to birdsong element classification
- Practical Applications of Astropy
- Vision Spreadsheet: An Environment for Computer Vision
- Unusual Relationships: Python and Weaver Birds
- Constructing scientific programs using SymPy
- EarthSim: Flexible Environmental Simulation Workflows Entirely Within Jupyter Notebooks
- Safe handling instructions for missing data
- Java vs. Python Coverage of Introductory Programming Concepts: A Textbook Analysis
- Text and data mining scientific articles with allofplos
- pyjanitor: A Cleaner API for Cleaning Data
- Evolutionary Prototyping: "Add Later" Static Types for Python
- Automating Quantitative Confocal Microscopy Analysis
- Weather Forecast Accuracy Analysis
- Detection and characterization of interactions of genetic risk factors in disease
- Exploring Network Structure, Dynamics, and Function using NetworkX
- Interval Arithmetic: Python Implementation and Applications
- Experiences Using SciPy for Computer Vision Research
- The SciPy Documentation Project (Technical Overview)
- Matplotlib Solves the Riddle of the Sphinx
- The SciPy Documentation Project
- Pysynphot: A Python Re-Implementation of a Legacy App in Astronomy
- How the Large Synoptic Survey Telescope (LSST) is using Python
- Realtime Astronomical Time-series Classification and Broadcast Pipeline
- Analysis and Visualization of Multi-Scale Astrophysical Simulations Using Python and NumPy
- Mayavi: Making 3D Data Visualization Reusable
- Finite Element Modeling of Contact and Impact Problems Using Python
- Circuitscape: A Tool for Landscape Ecology
- Summarizing Complexity in High Dimensional Spaces
- Converting Python Functions to Dynamically Compiled C
- unPython: Converting Python Numerical Programs into C
- Cython tutorial
- Fast numerical computations with Cython
- High-Performance Code Generation Using CorePy
- Convert-XY: type-safe interchange of C++ and Python containers for NumPy extensions
- Parallel Kernels: An Architecture for Distributed Parallel Computing
- PaPy: Parallel and distributed data-processing pipelines in Python
- PMI - Parallel Method Invocation
- Sherpa: 1D/2D modeling and fitting in Python
- The FEMhub Project and Classroom Teaching of Numerical Methods
- Exploring the future of bioinformatics data sharing and mining with Pygr and Worldbase
- Nitime: time-series analysis for neuroimaging data
- Multiprocess System for Virtual Instruments in Python
- Neutron-scattering data acquisition and experiment automation with Python
- Progress Report: NumPy and SciPy Documentation in 2009
- The State of SciPy
- Python as a Discrete Event Simulation environment
- Codebraid: Live Code in Pandoc Markdown
- Introduction to Geometric Learning in Python with Geomstats
- Network visualizations with Pyvis and VisJS
- Rebuilding the Hubble Exposure Time Calculator
- Pythran: Enabling Static Optimization of Scientific Python Programs
- Using Python with Smoke and JWST Mirrors
- Sparse: A more modern sparse array library
- Adapted G-mode Clustering Method applied to Asteroid Taxonomy
- Modeling Sudoku Puzzles with Python
- Boost-histogram: High-Performance Histograms as Objects
- Case study: Real-world machine learning application for hardware failure detection
- LabbookDB: A Wet-Work-Tracking Database Application Framework
- The James Webb Space Telescope Data Calibration Pipeline
- Circumventing The Linker: Using SciPy's BLAS and LAPACK Within Cython
- Is Python an Appropriate Programming Language for Teaching Programming in Secondary Schools?
- Python – The Fastest Growing Programming Language
- Self-driving Lego Mindstorms Robot
- Bitmap Indices for Data Warehouses
- PyModel: Model-based testing in Python
- The Reference Model for Disease Progression
- Fcm - A python library for flow cytometry
- Learning from evolving data streams
- Mesa: An Agent-Based Modeling Framework
- PyHRF: A Python Library for the Analysis of fMRI Data Based on Local Estimation of the Hemodynamic Response Function
- Solving Polynomial Systems with phcpy
- HoloViews: Building Complex Visualizations Easily for Reproducible Science
- Ginga: an open-source astronomical image viewer and toolkit
- AI Based Voice Assistant Using Python
- Awkward Array: JSON-like data, NumPy-like idioms
- Bringing ipywidgets Support to plotly.py
- MONTE Python for Deep Space Navigation
- Structural Cohesion: Visualization and Heuristics for Fast Computation with NetworkX and matplotlib
- SciSheets: Providing the Power of Programming With The Simplicity of Spreadsheets
- Automated Image Quality Monitoring with IQMon
- The Climate Modelling Toolkit
- Beyond: A Portable Virtual World Simulation Framework
- Tell Me Something I Don't Know: Analyzing OkCupid Profiles
- PyRK: A Python Package For Nuclear Reactor Kinetics
- Teaching numerical methods with IPython notebooks and inquiry-based learning
- The Sacred Infrastructure for Computational Research
- Project-based introduction to scientific computing for physics majors
- Hyperopt-Sklearn: Automatic Hyperparameter Configuration for Scikit-Learn
- Automation of Inertial Fusion Target Design with Python
- Exploring Collaborative HPC Visualization Workflows using VisIt and Python
- Python Coding of Geospatial Processing in Web-based Mapping Applications
- PyTeCK: a Python-based automatic testing package for chemical kinetic models
- WrightSim: Using PyCUDA to Simulate Multidimensional Spectra
- Python Vuh: Mayan Calendrical Mathematics with Python
- Scaling Polygon Adjacency Algorithms to Big Data Geospatial Analysis
- Optimizing Python-Based Spectroscopic Data Processing on NERSC Supercomputers
- Hurricane Prediction with Python
- High-performance operator evaluations with ease of use: libCEED's Python interface
- FigureFirst: A Layout-first Approach for Scientific Figures
- IMUSim - Simulating inertial and magnetic sensor systems in Python
- VisPy: Harnessing The GPU For Fast, High-Level Visualization
- Python Machine Learning Projects
- Parallel Analysis in MDAnalysis using the Dask Parallel Computing Library
- Mailman – An Extensible Mailing List Manager Using Python
- Using Python to Construct a Scalable Parallel Nonlinear Wave Solver
- MatchPy: A Pattern Matching Library
- Spectral Analysis of Mitochondrial Dynamics: A Graph-Theoretic Approach to Understanding Subcellular Pathology
- White Noise Test: detecting autocorrelation and nonstationarities in long time series after ARIMA modeling
- A Real-Time 3D Audio Simulator for Cognitive Hearing Science
- Matched Filter Mismatch Losses in MPSK and MQAM Using Semi-Analytic BEP Modeling
- Exploring the Extended Kalman Filter for GPS Positioning Using Simulated User and Satellite Track Data
- Real-Time Digital Signal Processing Using pyaudio_helper and the ipywidgets
- pyDEM: Global Digital Elevation Model Analysis
- Widgets and Astropy: Accomplishing Productive Research with Undergraduates
- Dask: Parallel Computation with Blocked algorithms and Task Scheduling
- Organic Molecules in Space: Insights from the NASA Ames Molecular Database in the era of the James Webb Space Telescope
- Having your cake and eating it: Exploiting Python for programmer productivity and performance on micro-core architectures using ePython
- Building a Framework for Predictive Science
- Data Structures for Statistical Computing in Python
- Protein Folding with Python on Supercomputers
- PySPLIT: a Package for the Generation, Analysis, and Visualization of HYSPLIT Air Parcel Trajectories
- TrendVis: an Elegant Interface for dense, sparkline-like, quantitative visualizations of multiple series using matplotlib
- pulse2percept: A Python-based simulation framework for bionic vision
- Optimised finite difference computation from symbolic equations
- Causal Bayesian NetworkX
- Linting science prose and the science of prose linting
- SpacePy - A Python-based Library of Tools for the Space Sciences
- Campaign for IT literacy through FOSS and Spoken Tutorials
- SunPy: Python for Solar Physicists
- Harnessing the Power of Scientific Python to Investigate Biogeochemistry and Metaproteomes of the Central Pacific Ocean
- An intelligent shopping list based on the application of partitioning and machine learning algorithms
- Python meets systems neuroscience: affordable, scalable and open-source electrophysiology in awake, behaving rodents
- Python: a programming language for software integration and development
- PyStream: Compiling Python onto the GPU
- Geodynamic simulations in HPC with Python
- pandera: Statistical Data Validation of Pandas Dataframes
- Accelerating Scientific Python with Intel Optimizations
- MDAnalysis: A Python Package for the Rapid Analysis of Molecular Dynamics Simulations
- Combining Physics-Based and Data-Driven Modeling for Pressure Prediction in Well Construction
- Numerical Pyromaniacs: The Use of Python in Fire Research
- Validating Function Arguments in Python Signal Processing Applications
- Parameter Estimation Using the Python Package pymcmcstat
- Scikit-learn: Machine Learning in Python
- Reproducible Documents with PythonTeX
- Spreading the Adoption of Python in India: the FOSSEE Python Project
- PySPH: a reproducible and high-performance framework for smoothed particle hydrodynamics
- Binder 2.0 - Reproducible, interactive, sharable environments for science at scale
- Python for research and teaching economics
- Pydra - a flexible and lightweight dataflow engine for scientific analyses
- PyFront: Conversion of Python to C Extension Modules
- PyLZJD: An Easy to Use Tool for Machine Learning
- Python for Unified Research in Econometrics and Statistics
- Qiita: report of progress towards an open access microbiome data analysis and visualization platform
- A Programmatic Interface for Particle Plasma Simulation in Python
- Parkinson's Classification and Feature Extraction from Diffusion Tensor Images
- Leading magnetic fusion energy science into the big-and-fast data lane
- PySPH: A Python Framework for Smoothed Particle Hydrodynamics
- Python in Data Science Research and Education
- Audio-Visual Speech Recognition using SciPy
- lpEdit: an editor to facilitate reproducible analysis via literate programming
- PyDDA: A new Pythonic Wind Retrieval Package
- QuTiP: A framework for the dynamics of open quantum systems using SciPy and Cython
- SHADOW: A workflow scheduling algorithm reference and testing framework
- Validated numerics with Python: the ValidiPy package
- Creating a browser-based virtual computer lab for classroom instruction
- Relation: The Missing Container
- Better and faster hyperparameter optimization with Dask
- Statsmodels: Econometric and Statistical Modeling with Python
- Software Engineering as Research Method: Aligning Roles in Econ-ARK
- Visualizing physiological signals in real-time
- Spatio-temporal analysis of socioeconomic neighborhoods: The Open Source Longitudinal Neighborhood Analysis Package (OSLNAP)
- Visualization of Bioinformatics Data with Dash Bio
- Bringing Parallel Performance to Python with Domain-Specific Selective Embedded Just-in-Time Specialization
- PMDA - Parallel Molecular Dynamics Analysis
- cphVB: A System for Automated Runtime Optimization and Parallelization of Vectorized Applications
- N-th-order Accurate, Distributed Interpolation Library
- Implementing the SMS server, or why I switched from Tcl to Python
- Google App Engine Python
- Statistics and Machine Learning in Python
- TracPy: Wrapping the Fortran Lagrangian trajectory model TRACMASS
- OpenMG: A New Multigrid Implementation in Python
- Design and Implementation of pyPRISM: A Polymer Liquid-State Theory Framework
- Improving efficiency and repeatability of lake volume estimates using Python
- Modeling the Earth with Fatiando a Terra
- A Bayesian's journey to a better research workflow
- Frequentism and Bayesianism: A Python-driven Primer
- Scalable Feature Extraction with Aerial and Satellite Imagery
- Virtual Method Tables in Python
- signac: A Python framework for data and workflow management
- Blaze: Building A Foundation for Array-Oriented Computing in Python
- ChiantiPy: a Python package for Astrophysical Spectroscopy
- Yaksh: Facilitating Learning by Doing
- Building a Cloud Service for Reproducible Simulation Management
- Launching Python Applications on Peta-scale Massively Parallel Systems
- Falsify your Software: validating scientific code with property-based testing
- Towards an Unsupervised Spatiotemporal Representation of Cilia Video Using A Modular Generative Pipeline
- Simulating X-ray Observations with Python
- Time Series Analysis in Python with statsmodels
- 5 Best Python Libraries for Machine Learning
- Big Data and Sentiment Analysis Using Python
- Chatbot for Medical Treatment using NLTK Lib
- Importance of Learning Python Programming in the Field of Mechanical Engineering
- Introduction To Text Analysis with Python And The Natural Language Toolkit
- Learning Pandas: Python Tools for Data Munging, Data Analysis, and Visualization
- Linear Regression Python
- OpenCV-Python Tutorials Documentation
- Python Algorithms
- Python Machine Learning
- Python programming | exercises
- Python's Fake Increment and Decrement Operators
- Time Series Data Price Variation ShiftingGroupBy
- Development of a computational software in Python, used to study the materials resistance in beams
Books:
- Automate the Boring Stuff with Python: Practical Programming for Total Beginners
- Coding Projects in Python
- Deep Learning with Python
- Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!
- Learn Python in One Day and Learn It Well Python for Beginners with Hands-on Project
- Learning Python
- Python and Tkinter Programming
- Python Crash Course: A Hands-on, Project-based Introduction to Programming
- Python for Data Analysis
- Python Programming for the Absolute Beginner
- Python Tricks: The Book
- A Python Book: Beginning Python, Advanced Python, and Python Exercises
- Python For Dummies
- Python Tutorial
- Python Programming: An Introduction to Computer Science
- Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming
- Think Python
- Fluent Python
- Hacking with Python: The Ultimate Beginner's Guide
- Natural Language Processing with Python