Question:
Write a program to perform shell sort on [85,63,0,12,47,96,52]
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
def shellSort (numbers,array_size): increment = array_size / 2; while (increment > 0): for i in range (0,array_size): j = i; temp = numbers[i]; while ((j >= increment) and (numbers[j-increment] > temp)): numbers[j] = numbers[j - increment]; j = j - increment; numbers[j] = temp; if (increment == 2): increment = 1; else : increment = increment * 5 / 11; numbers=[85,63,0,12,47,96,52] array_size=len(numbers) shellSort ( numbers,array_size) print numbers |
Explanation:
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 4 − Repeat until complete list is sorted
Output:
1 |
[0, 12, 47, 52, 63, 85, 96] |
Question:
Write a program to perform merge sort on [85,63,0,12,47,96,52]
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist) alist = [85,63,0,12,47,96,52] mergeSort(alist) print(alist) |
Explanation:
Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Splitting [85, 63, 0, 12, 47, 96, 52] Splitting [85, 63, 0] Splitting [85] Merging [85] Splitting [63, 0] Splitting [63] Merging [63] Splitting [0] Merging [0] Merging [0, 63] Merging [0, 63, 85] Splitting [12, 47, 96, 52] Splitting [12, 47] Splitting [12] Merging [12] Splitting [47] Merging [47] Merging [12, 47] Splitting [96, 52] Splitting [96] Merging [96] Splitting [52] Merging [52] Merging [52, 96] Merging [12, 47, 52, 96] Merging [0, 12, 47, 52, 63, 85, 96] [0, 12, 47, 52, 63, 85, 96] |
Question:
Write a program to sort ‘GlobalSQA’ lexiographically
Program:
1 2 3 4 |
def lexicographi_sort(s): return sorted(sorted(s), key=str.upper) print(lexicographi_sort('GlobalSQA')) |
Explanation:
The lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographical product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters. The sorted function sorts it for you.
Output:
1 |
['A', 'a', 'b', 'G', 'l', 'l', 'o', 'Q', 'S'] |
Question:
Write a program to perform bubble sort on [85,63,0,12,47,96,52]
Program:
1 2 3 4 5 6 7 8 9 10 11 |
def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = [85,63,0,12,47,96,52] bubbleSort(alist) print(alist) |
Explanation:
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.
Output:
1 |
[0, 12, 47, 52, 63, 85, 96] |
Question:
Write a program to perform insertion sort on [85, 63, 0, 12, 47, 96, 52]
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue alist = [85, 63, 0, 12, 47, 96, 52] insertionSort(alist) print(alist) |
Explanation:
Step 1 − If it is the first element, it is already sorted. return 1
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Output:
1 |
[0, 12, 47, 52, 63, 85, 96] |
Question:
Write a program to reverse a number
Program:
1 2 3 4 5 6 7 8 9 10 11 |
num = (input("Enter any number: ")) reverse = 0 try: val = int(num) while val > 0: reminder = val % 10 reverse = (reverse * 10) + reminder val //= 10 print('Reverse of given number is : ', reverse) except ValueError: print("That's not a valid number, Try Again !") |
Explanation:
The while loop contains the statements to isolate or separate the digits of a number ,which is then multiplied to 10 and sums the reminder. Thus you get the reverse.
Let’s try it out
Say n=366
while val>0//True, then reminder is 6,reverse also 6 and val is 36
while 36>0//True, then reminder is 6, reverse is (6*10)+6 =66, and val is 3
while 3>0// True, then reminder is 3,reverse is (66*10)+3=663 and val is 0
Hence reverse is 663
Output:
1 2 |
Enter any number: 895 Reverse of given number is : 598 |
Question:
Fetch all links from google home page
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import urllib2 import re req=urllib2.Request('https://www.google.com') #connect to a URL website = urllib2.urlopen(req) #read html code html = website.read() #use re.findall to get all the links links = re.findall('"((http|ftp)s?://.*?)"', html) for i in links: print i |
Explanation:
The urllib2
module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.
re module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
('http://schema.org/WebPage', 'http') ('https://www.google.co.in/imghp?hl=en&tab=wi', 'http') ('https://maps.google.co.in/maps?hl=en&tab=wl', 'http') ('https://play.google.com/?hl=en&tab=w8', 'http') ('https://www.youtube.com/?gl=IN&tab=w1', 'http') ('https://news.google.co.in/nwshp?hl=en&tab=wn', 'http') ('https://mail.google.com/mail/?tab=wm', 'http') ('https://drive.google.com/?tab=wo', 'http') ('https://www.google.co.in/intl/en/options/', 'http') ('http://www.google.co.in/history/optout?hl=en', 'http') ('https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.co.in/%3Fgfe_rd%3Dcr%26ei%3D83RYWbugK9WkvwT7j4SwCA', 'http') ('http://www.google.co.in/services/', 'http') ('https://plus.google.com/104205742743787718296', 'http') ('https://www.google.co.in/setprefdomain?prefdom=US&sig=__xO-fFja9LlrL0EjCUtIDcyG3flI%3D', 'http') |
Below is a list of the top 20 Open Source Libraries. Note that the list is neither exhaustive or stagnant. In a strong community as that Python has, the list is prone to change. The list has been prepared on the basis of popularity, no of users, python community feedback etc. The 20 below does not fall in any specific order and arrangement is quite random.
At the end of the day, it’s not which library you use. It’s how well you get the job done.
So here goes the list!
Zappa is a system for running “serverless” Python web applications using AWS Lambda and AWS API Gateway. It handles all of the configuration and deployment automatically . Now it is easy to deploy an infinitely scalable application to the cloud with a just single command at the least possible cost often just a small fraction of the cost of a traditional web server.
OpenCV is a cross-platform library using which we can develop real-time computer vision applications.Originally developed by Intel, it was later supported by Willow Garage and is now maintained by Itseez.It was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django takes care of the repetitive work for you so that you don’t have to reinvent the wheel all over again.
Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It is an incredible tool for pulling out information from a webpage. You can use it to extract tables, lists, paragraph and you can also put filters to extract information from web page.
TensorFlow is an open source software library for machine learning across a range of tasks, and developed by Google to meet their needs for systems capable of building and training neural networks to detect and decipher patterns and correlations, analogous to the learning and reasoning which humans use. Checkout SQL cheatsheet by clicking here
NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries, and an active discussion forum.
Requests is an elegant and simple Apache2 licensed HTTP library for PythonIt is designed to be used by humans to interact with the language. This means you don’t have to manually add query strings to URLs, or form-encode your POST data.
NumPy is the fundamental package for scientific computing with Python. It contains a powerful N-dimensional array object,sophisticated (broadcasting) functions,tools for integrating C/C++ and Fortran code,useful linear algebra, Fourier transform, and random number capabilities and much more. The handy tool for any scientific computing.
Flask is a BSD licensed microframework for Python based on Werkzeug, Jinja 2 and good intentions. With simplified and easy to write and maintain code, flask has certainly won a lot of hearts.
SQLAlchemy is an open-source Python Database toolkit, which is also an ORM Mapper.It allows you to write easy to read programs and remove the necessity of writing tedious and error-prone raw SQL statements. Checkout SQL cheatsheet by clicking here
Pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Checkout Pandas cheatsheet by clicking here
Cryptography is a method of storing and transmitting data in a particular form so that only those for whom it is intended can read and process it. It has become a highly important function in the modern world where security of data means everything.Cryptography is an actively developed library in python that provides cryptographic recipes and primitives.It is divided into two layers of recipes and hazardous materials (hazmat) catering it’s best to your various cryptographic needs.
Scrapy is an open source and collaborative framework for extracting the data you need from websites in a fast, simple, yet extensible way.Comparing with Beautiful Soup, you need to provide a specific url, and Beautiful Soup will help you get the data from that page. You can give Scrapy a start url, and it will go on, crawling and extracting data, without having to explicitly give it every single URL.Also scrapy is a website scraping tool that uses Python, because Scrapy can crawl the contents of your webpage prior to extracting
Marshmallow is a lightweight library for converting complex datatypes to and from native Python datatypes.It is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.
Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code.
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits. Checkout Matplotlib cheatsheet by clicking here
The pillow is one of the core libraries for image manipulation in Python. Now there’s an actively developed fork of PIL called Pillow which is making quite a good round in the python community.
Bokeh is a Python interactive visualization library that targets modern web browsers for presentation. It’s goal is to provide elegant, concise construction of novel graphics in the style of D3.js, and to extend this capability with high-performance interactivity over very large or streaming datasets.
The easy to handle python library for all your CSV needs.CSV stands for Comma Separated Variables.They are like incredibly simplified spreadsheets whose contents are just plain text. Python’s CSV library makes working with them extremly simplified.
Milk is a machine learning toolkit for python. It’s focus is on supervised classification.Several classifiers available:SVMs (based on libsvm), k-NN, random forests, decision trees. It also performs
feature selection.
There are a lot more amazing libraries in Python that would come of as as a huge boon such as Asyncpg, urllib2,Theano,Tkinder, Pycrypto, Pygame etc. Want to add more to this list. Comment your suggestion below. We love hearing from you!
Question:
Write a Program to encrypt text by replacing each character by it’s successor.
Program:
1 2 3 4 5 6 7 8 9 |
plain_text = "GlobalSQA" encrypted_text = "" for c in plain_text: x = ord(c) x = x + 1 c2 = chr(x) encrypted_text = encrypted_text + c2 print(encrypted_text) |
Output:
1 |
HmpcbmTRB |
Question:
Using Magic Methods, overload the + operator so that length of varying units can be added.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Length: __metric = {"mm" : 0.001, "cm" : 0.01, "m" : 1, "km" : 1000, "in" : 0.0254, "ft" : 0.3048, "yd" : 0.9144, "mi" : 1609.344 } def __init__(self, value, unit = "m" ): self.value = value self.unit = unit def Converse2Metres(self): return self.value * Length.__metric[self.unit] def __add__(self, other): l = self.Converse2Metres() + other.Converse2Metres() return Length(l / Length.__metric[self.unit], self.unit ) def __str__(self): return str(self.Converse2Metres()) def __repr__(self): return "Length(" + str(self.value) + ", '" + self.unit + "')" if __name__ == "__main__": x = Length(4) print(x) y = eval(repr(x)) z = Length(7.9, "yd") + Length(2) print(repr(z)) print(z) |
Explanation:
What are magic methods? They’re everything in object-oriented Python. They’re special methods that you can define to add “magic” to your classes, that is you won’t have to call them manually. They are called automatically behind the scenes.
Output:
1 2 3 |
4 Length(10.0872265967, 'yd') 9.22376 |
Question:
Write a python program to find sum of natural numbers using recursion
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python program to find the sum of natural numbers up to n using recursive function def rsum(n): if n <= 1: return n else: return n + rsum(n-1) num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: print("The sum is",rsum(num)) |
Explanation:
A recursive function (DEF) is a function which either calls itself or is in a potential cycle of function calls.
Output:
1 |
('The sum is', 15) |
Question:
Write a python program to find ASCII character of a variable
Program:
1 2 3 |
c = input("Enter a character: ") print("The ASCII value of '" + c + "' is",ord(c)) |
Explanation:
ASCII (American Standard Code for Information Interchange) is the most common format for text files in computers and on the Internet. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined.
Output:
1 2 |
Enter a character: H ("The ASCII value of 'H' is", 72) |
Question:
Use anonymous and filter functions and print a list of numbers divisible by 13 from the list [79, 65, 54, 39, 555, 339,623,]
Program:
1 2 3 4 5 6 7 |
my_list = [79, 65, 54, 39, 555, 339,623,] # use anonymous function to filter result = list(filter(lambda x: (x % 13 == 0), my_list)) # display the result print "Numbers divisible by 13 are",result |
Explanation:
The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
Output:
1 |
Numbers divisible by 13 are [65, 39] |
Question:
Write a iterator function to work like xrange()
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class yrange: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): return self def next(self): if self.i < self.n: i = self.i self.i += 1 return i else: raise StopIteration() print list(yrange(input("Enter the number:"))) |
Explanation:
The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence. Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files.
Output:
1 2 |
Enter the number:3 [0, 1, 2] |
Question:
Write a python program to print only those lines in a list of files that has a particular word
Here, I am looking for a word ‘print’ in a list of python files.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def readfiles(filenames): for f in filenames: for line in open(f): yield line def grep(pattern, lines): return (line for line in lines if pattern in line) def printlines(lines): for line in lines: print line, def main(pattern, filenames): lines = readfiles(filenames) lines = grep(pattern, lines) printlines(lines) main('print',['factorial.py','GCD.py','LCM.py','password.py','rect.py']) |
Explanation:
Generator Expressions are generator version of list comprehensions. They look like list comprehensions, but returns a generator back instead of a list.
Output:
1 2 3 4 5 6 7 |
print "Sorry, factorial does not exist for negative numbers" print "The factorial of 0 is 1" print "The factorial of",num,"is",factorial(num) print "The H.C.F. of", n1,"and", n2,"is",HCF(n1, n2) print "The L.C.M. of", nos1,"and", nos2,"is", lcm(nos1, nos2) print "Valid passwords",value print "Area of rectangle:",obj.area() |
Question:
Write a program to trace all calls to the below function
1 2 3 4 5 |
def fib(n): if n is 0 or n is 1: return 1 else: return fib(n-1) + fib(n-2) |
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def fib(n): if n is 0 or n is 1: return 1 else: return fib(n-1) + fib(n-2) def trace(f): f.indent = 0 def g(x): print '| ' * f.indent + '|--', f.__name__, x f.indent += 1 value = f(x) print '| ' * f.indent + '|--', 'return', repr(value) f.indent -= 1 return value return g fib = trace(fib) print fib(input("Enter the limit:")) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
Enter the limit:3 |-- fib 3 | |-- fib 2 | | |-- fib 1 | | | |-- return 1 | | |-- fib 0 | | | |-- return 1 | | |-- return 2 | |-- fib 1 | | |-- return 1 | |-- return 3 3 |
Question:
Write a python program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 1500 and 3000 (both included).
Program:
1 2 3 4 5 6 |
l=[] for i in range(1500, 3001): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
: 1512,1519,1526,1533,1547,1554,1561,1568,1582,1589,1596,1603,1617,1624,1631,1638, 1652,1659,1666,1673,1687,1694,1701,1708,1722,1729,1736,1743,1757,1764,1771,1778, 1792,1799,1806,1813,1827,1834,1841,1848,1862,1869,1876,1883,1897,1904,1911,1918, 1932,1939,1946,1953,1967,1974,1981,1988,2002,2009,2016,2023,2037,2044,2051,2058, 2072,2079,2086,2093,2107,2114,2121,2128,2142,2149,2156,2163,2177,2184,2191,2198, 2212,2219,2226,2233,2247,2254,2261,2268,2282,2289,2296,2303,2317,2324,2331,2338, 2352,2359,2366,2373,2387,2394,2401,2408,2422,2429,2436,2443,2457,2464,2471,2478, 2492,2499,2506,2513,2527,2534,2541,2548,2562,2569,2576,2583,2597,2604,2611,2618, 2632,2639,2646,2653,2667,2674,2681,2688,2702,2709,2716,2723,2737,2744,2751,2758, 2772,2779,2786,2793,2807,2814,2821,2828,2842,2849,2856,2863,2877,2884,2891,2898, 2912,2919,2926,2933,2947,2954,2961,2968,2982,2989,2996 |
Question;
With two given lists ([6,5,6,2,2]) and ([9,5,6,7,9,2,7,0]), write a python program to make a list whose elements are intersection of the another list.
Program:
1 2 3 4 5 |
set1=set([6,5,6,2,2]) set2=set([9,5,6,7,9,2,7,0]) set1 &= set2 li=list(set1) print (li) |
Explanation:
Use set() and “&=” to do set intersection operation.
Output:
1 |
[2, 5, 6] |
Question:
Write a python program to find whether a given year is a leap year or not
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Python program to check if the input year is a leap year or not year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
Explanation:
A leap year is a calendar year containing one additional day added to keep the calendar year synchronized with the astronomical or seasonal year. 2016 is a leap year, which means that it has 366 days instead of the usual 365 days that an ordinary year has. An extra day is added in a leap year—February 29 —which is called an intercalary day or a leap day.
Output:
1.
1 2 |
Enter a year: 2010 2010 is not a leap year |
2.
1 2 |
Enter a year: 2012 2012 is a leap year |
Question:
Write a program which can filter even numbers in a list by using filter function. The list is: [11,12,13,14,15,16,17,18,19,20]. Use filter() to filter some elements in a list. Use lambda to define anonymous functions.
Program:
1 2 3 |
li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers |
Explanation:
The function filter(function, list) offers an elegant way to filter out all the elements of a list for which the function function returns True.
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True, the element of the list be included in the result list.
Output:
1 |
[12, 14, 16, 18, 20] |