Saturday 9 March 2019

Working with Lists in Python

lists
A list is a data-structure, or it can be considered a container that can be used to store multiple data at once. The list will be ordered and there will be a definite count of it. The elements are indexed according to a sequence and the indexing is done with 0 as the first index. Each element will have a distinct place in the sequence and if the same value occurs multiple times in the sequence, each will be considered separate and distinct element. A more detailed description on lists and associated data-types are covered in this blog.

In this blog you will come to know of the about how to create python lists and the common paradigms for a python list. Lists are great if you want to preserve the sequence of the data and then iterate over them later for various purposes. We will cover iterations and for loops in our tutorials on for loops.

How to create a list:-

To create a list, you separate the elements with a comma and enclose them with a bracket “[]”. For example, you can create a list of company names containing “hackerearth”, “google”, “facebook”. This will preserve the order of the names.

>>> companies = ["hackerearth", "google", "facebook"] >>> # get the first company name >>> print(companies[0]) 'hackerearth' >>> # get the second company name >>> print(companies[1]) 'google' >>> # get the third company name >>> print(companies[2]) 'facebook' >>> # try to get the fourth company name >>> # but this will return an error as only three names >>> # have been defined. >>> print(companies[3]) Traceback (most recent call last): File "stdin", line 1, in module IndexError: list index out of range

Trying to access elements outside the range will give an error. You can create a two-dimensional list. This is done by nesting a list inside another list. For example, you can group “hackerearth” and “paytm” into one list and “tcs” and “cts” into another and group both the lists into another “master” list.

>>> companies = [["hackerearth", "paytm"], ["tcs", "cts"]] >>> print(companies) [['hackerearth', 'paytm'], ['tcs', 'cts']]

Methods over Python Lists

Python lists support common methods that are commonly required while working with lists. The methods change the list in place. (More on methods in the classes and objects tutorial). In case you want to make some changes in the list and keep both the old list and the changed list, take a look at the functions that are described after the methods.

How to add elements to the list:

1.list.append(elem) - will add another element to the list at the end.
>>> # create an empty list >>> companies = [] >>> # add “hackerearth” to companies >>> companies.append(“hackerearth”) >>> # add "google" to companies >>> companies.append("google") >>> # add "facebook" to companies >>> companies.append("facebook") >>> # print the items stored in companies >>> print(companies) ['hackerearth', 'google', 'facebook']

Note the items are printed in the order in which they youre inserted. 2.list.insert(index, element) - will add another element to the list at the given index, shifting the elements greater than the index one step to the right. In other words, the elements with the index greater than the provided index will increase by one. For example, you can create a list of companies ['hackerearth', 'google', 'facebook'] and insert “airbnb” in third position which is held by “facebook”.

>>> # initialise a preliminary list of companies >>> companies = ['hackerearth', 'google', 'facebook'] >>> # check what is there in position 2 >>> print(companies[2]) facebook >>> # insert “airbnb” at position 2 >>> companies.insert(2, "airbnb") >>> # print the new companies list >>> print(companies) ['hackerearth', 'google', 'airbnb', 'facebook'] >>> # print the company name at position 2 >>> print(companies[2]) airbnb

3.list.extend(another_list) - will add the elements in list 2 at the end of list

For example, you can concatenate two lists ["haskell", "clojure", "apl"] and ["scala", "F#"] to the same list langs. >>> langs = ["haskell", "clojure", "apl"] >>> langs.extend(["scala", "F#"]) >>> print(langs) ['haskell', 'clojure', 'apl', 'scala', 'F#'] 3.list.index(elem) - will give the index number of the element in the list. For example, if you have a list of languages with elements ['haskell', 'clojure', 'apl', 'scala', 'F#'] and you want the index of “scala”, you can use the index method. >>> index_of_scala = langs.index("scala") >>> print(index_of_scala) 3

How to remove elements from the list:

1. list.remove(elem) - will search for the first occurrence of the element in the list and will then remove it. For example, if you have a list of languages with elements ['haskell', 'clojure', 'apl', 'scala', 'F#'] and you want to remove scala, you can use the remove method.
>>> langs.remove("scala") >>> print(langs) ['haskell', 'clojure', 'apl', 'F#']
2. list.pop() - will remove the last element of the list. If the index is provided, then it will remove the element at the particular index. For example, if you have a list [5, 4, 3, 1] and you apply the method pop, it will return the last element 1 and the resulting list will not have it.
>>> # assign a list to some_numbers >>> some_numbers = [5, 4, 3, 1] >>> # pop the list >>> some_numbers.pop() 1 >>> # print the present list >>> print(some_numbers) [5, 4, 3] Similarly, try to pop an element from a random index that exists in the list. >>> # pop the element at index 1 >>> some_numbers.pop(1) 4 >>> # check the present list >>> print(some_numbers) [5, 3]

Other useful list methods

1.list.sort() - will sort the list in-place. For example, if you have an unsorted list [4,3,5,1], you can sort it using the sort method.
>>> # initialise an unsorted list some_numbers >>> some_numbers = [4,3,5,1] >>> # sort the list >>> some_numbers.sort() >>> # print the list to see if it is sorted. >>> some_numbers [1, 3, 4, 5]

2.list.reverse() - will reverse the list in place For example, if you have a list [1, 3, 4, 5] and you need to reverse it, you can call the reverse method.
>>> # initialise a list of numbers that >>> some_numbers = [1, 3, 4, 5] >>> # Try to reverse the list now >>> some_numbers.reverse() >>> # print the list to check if it is really reversed. >>> print(some_numbers) [5, 4, 3, 1]

Functions over Python Lists:
1.You use the function “len” to get the length of the list. For example, if you have a list of companies ['hackerearth', 'google', 'facebook'] and you want the list length, you can use the len function.

>>> # you have a list of companies >>> companies = ['hackerearth', 'google', 'facebook'] >>> # you want the length of the list >>> print(len(companies)) 3

2. If you use another function “enumerate” over a list, it gives us a nice construct to get both the index and the value of the element in the list. For example, you have the list of companies ['hackerearth', 'google', 'facebook'] and you want the index, along with the items in the list, you can use the enumerate function.
>>> # loop over the companies and print both the index as youll as the name. >>> for indx, name in enumerate(companies): ... print("Index is %s for company: %s" % (indx, name)) ... Index is 0 for company: hackerearth Index is 1 for company: google Index is 2 for company: facebook
In this example, you use the for loop. For loops are pretty common in all programming languages that support procedural constructs.
3. sorted function will sort over the list Similar to the sort method, you can also use the sorted function which also sorts the list. The difference is that it returns the sorted list, while the sort method sorts the list in place. So this function can be used when you want to preserve the original list as well.
>>> # initialise a list >>> some_numbers = [4,3,5,1] >>> # get the sorted list >>> print(sorted(some_numbers)) [1, 3, 4, 5] >>> # the original list remains unchanged >>> print(some_numbers) [4, 3, 5, 1]

Android Application Development For Dummies

The Android OS continues to rapidly expand offering app developers access to one of the largest platforms available, and this easy–to–follow guide walks you through the development process step by step. In this new edition of the bestselling Android Application Development For Dummies, Android programming experts Michael Burton and Donn Felker explain how to download the SDK, get Eclipse up and running, code Android applications, and share your finished products with the world.
 Buy :

PDF Download :


Featuring two sample programs, this book explores everything from the simple basics to advanced aspects of Android application development.

  • Walks you through all the steps in developing applications for the Android platform, including the latest Android features like scrollable widgets, enhanced UI tools, social media integration, and new calendar and contact capabilities
  • Starts off with downloading the SDK, then explains how to bring your applications to life and submit your work to the Android Market
  • Includes real–world advice from expert programmers Donn Felker and Michael Burton, who break every aspect of the development process down into practical, digestible pieces

Whether you′re new to Android development or already on your way, Android Application Development For Dummies, 2nd Edition is the guide you need to dig into the app dev process!

Thursday 7 March 2019

Borland C++ Builder: The Complete Reference by Herbert Schildt

C++ Builder 5 is an integrated development enviroment for building standalone, client/server, distributed and Internet-enabled Windows applications. This resource provides an introduction to the operation of the Intergrated Development Enviroment (IDE), the various tools, the debugger, the C++ language and libaries. It also gives coverage of the standard template library (STL) and Windows programming.

Buy :-

Borland C++ Builder: The Complete Reference by Herbert Schildt 

PDF Download :-

Borland C++ Builder: The Complete Reference 




Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days

In only 21 days, you'll have all the skills you need to get up and running efficiently. With this complete tutorial, you'll master the basics of database programming and then move on to the more advanced features and concepts. Understand the fundamentals of database programming in Visual C++. Master all the new and advanced database features that Visual C++6 offers. Learn how to effectively use the latest tools and features of Visual C++ for database programming by following practical, real-world examples. Get expert tips from a leading authority for programming your databases with Visual C++ 6 in the corporate environment. 

Buy :-
Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days) 

PDF Download :-


Sams Teach Yourself Database Programming with Visual C++ 6 in 21 Days (Sams Teach Yourself in Days)


C++ Programming in easy steps, 5th Edition by Mike McGrath

C++ Programming in easy steps, 5th Edition begins by explaining how to install a free C++ compiler so you can quickly begin to create your own executable programs by copying the book’s examples. It demonstrates all the C++ language basics before moving on to provide examples of Object Oriented Programming (OOP).

C++ is not platform-dependent, so programs can be created on any operating system. Most illustrations in this book depict output on the Windows operating system purely because it is the most widely used desktop platform. The examples can also be created on other platforms such as Linux or macOS.

The book concludes by demonstrating how you can use your acquired knowledge to create programs graphically using a modern C++ Integrated Development Environment (IDE), such as Microsoft’s Visual Studio Community Edition.

C++ Programming in easy steps, 5th Edition has an easy-to-follow style that will appeal to:


anyone who wants to begin programming in C++
programmers moving from another programming language
students who are studying C++ Programming at school or college
those seeking a career in computing who need a fundamental understanding of object oriented programming
This book makes no assumption that you have previous knowledge of any programming language so it is suitable for the beginner to programming in C++, whether you know C or not.

Contents:

Getting started
Performing operations
Making statements
Handling strings
Reading and writing files
Pointing to data
Creating classes and objects
Harnessing polymorphism
Processing macros
Programming visually
Buy:-

C++ Programming in easy steps, 5th Edition by Mike McGrath 


 
 PDF Download :-

C++ Programming in easy steps, 5th Edition Kindle Edition by Mike McGrath




Wednesday 6 March 2019

Python Closures

Before seeing what a closure is, we have to first understand what are nested functions and non-local variables.

Nested functions in Python
A function which is defined inside another function is known as nested function. Nested functions are able to access variables of the enclosing scope.

In Python, these non-local variables can be accessed only within their scope and not outside their scope. This can be illustrated by following example:

# Python program to illustrate
# nested functions
def outerFunction(text):
text = text
def innerFunction():
print(text)
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')

As we can see innerFunction() can easily be accessed inside the outerFunction body but not outside of it’s body. Hence, here, innerFunction() is treated as nested Function which uses text as non-local variable.

Python Closures
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.

1.It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.

2.A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

# Python program to illustrate
# closures
def outerFunction(text):
text = text
def innerFunction():
print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()

Output:
Hey!
1.As observed from above code, closures help to invoke function outside their scope.
2.The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope

# Python program to illustrate
# closures
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info('Running "{}" with arguments {}'.format(func.__name__, args))
# Necessary for closure to work (returning WITHOUT parenthesis)
return log_func
def add(x, y):
return x+y
def sub(x, y):
return x-y
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)

Output:
6
9
5
10

When and why to use Closures:
1.As closures are used as callback functions, they provide some sort of data hiding. This helps us to reduce the use of global variables. 2.When we have few functions in our code, closures prove to be efficient way. But if we need to have many functions, then go for class (OOP).

Precision Handling in Python

Precision Handling in Python
Python in its definition allows to handle precision of floating point numbers in several ways using different functions. Most of them are defined under the “math” module. Some of the most used operations are discussed in this article.

1. trunc() :- This function is used to eliminate all decimal part of the floating point number and return the integer without the decimal part.
2. ceil() :- This function is used to print the least integer greater than the given number.
3. floor() :- This function is used to print the greatest integer smaller than the given integer.

# Python code to demonstrate ceil(), trunc()
# and floor()
# importing "math" for precision function
import math
# initializing value
a = 3.4536
# using trunc() to print integer after truncating
print ("The integral value of number is : ",end="")
print (math.trunc(a))
# using ceil() to print number after ceiling
print ("The smallest integer greater than number is : ",end="")
print (math.ceil(a))
# using floor() to print number after flooring
print ("The greatest integer smaller than number is : ",end="")
print (math.floor(a))

Output:
The integral value of number is : 3
The smallest integer greater than number is : 4
The greatest integer smaller than number is : 3

Setting Precision

There are many ways to set precision of floating point value. Some of them is discussed below.
1. Using “%” :- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.
2. Using format() :- This is yet another way to format the string for setting precision.
3. Using round(x,n) :- This function takes 2 arguments, number and the number till which we want decimal part rounded.
# Python code to demonstrate precision
# and round()
# initializing value
a = 3.4536
# using "%" to print value till 2 decimal places
print ("The value of number till 2 decimal place(using %) is : ",end=" ")
print ('%.2f'%a)
# using format() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using format()) is : ",end=" ")
print ("{0:.2f}".format(a))
# using round() to print value till 2 decimal places
print ("The value of number till 2 decimal place(using round()) is : ",end=" ")
print (round(a,2))

Output:
The value of number till 2 decimal place(using %) is : 3.45
The value of number till 2 decimal place(using format()) is : 3.45
The value of number till 2 decimal place(using round()) is : 3.45

Tuesday 5 March 2019

Beginning PHP 5 and MySQL 5: From Novice to Professional (Beginning Series: Open Source) by W. Gilmore (Author)

Beginning PHP and MySQL 5: From Novice to Professional, Second Edition offers comprehensive information about two of the most prominent open source technologies on the planet: the PHP scripting language and the MySQL database server. Essentially three books in one, this second edition covers PHP 5, MySQL 5, and how these two popular open source technologies work together to create powerful websites. The book is packed with practical examples and insight into real-world challenges. It is based on the author's 7 years of experience working with these technologies. You will repeatedly refer to this book as a valuable instructional tool and reference guide.


Yield Instead of return in Python

When to use yield instead of return in Python?

The yield statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather them computing them at once and sending them back like a list.
Let’s see with an example:

# A Simple Python program to demonstrate working
# of yield
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)

Output:
1
2
3

Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.

Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

# A Python program to generate squares from 1
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)

Output:
1
4
9
16
25
36
49
64
81
100

Empty Function in Python

In C/C++ and Java, we can write empty function as following
// An empty function in C/C++/Java

void fun() { }
In Python, if we write something like following in Python, it would produce compiler error.
# Incorrect empty function in Python
def fun():

Output:
IndentationError: expected an indented block
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement.

# Correct way of writing empty function
# in Python
def fun():
pass

We can use pass in empty while statement also.
# Empty loop in Python
mutex = True
while (mutex == True) :
pass

We can use pass in empty if else statements.
# Empty in if/else in Python
mutex = True
if (mutex == True) :
pass
else :
print("False")

Monday 4 March 2019

Function Decorator in Python

Following are important facts about functions in Python that are useful to understand decorator functions.

1.In Python, we can define a function inside another function.
2.In Python, a function can be passed as parameter to another function (a function can also return another function).

# A Python program to demonstrate that a function
# can be defined inside another function and a
# function can be passed as parameter.
# Adds a welcome message to the string
def messageWithWelcome(str):
# Nested function
def addWelcome():
return "Welcome to "
# Return concatenation of addWelcome()
# and str.
return addWelcome() + str
# To get site name to which welcome is added
def site(site_name):
return site_name
print messageWithWelcome(site("PythonWorld"))

Output:
Welcome to PythonWorld

Function Decorator
A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again. For example, above code can be re-written as following.
We use @func_name to specify a decorator to be applied on another function.
# Adds a welcome message to the string
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
# Nested function def addWelcome(site_name):
return "Welcome to " + fun(site_name)
# Decorator returns a function
return addWelcome
@decorate_message
def site(site_name):
return site_name;
# Driver code # This call is equivalent to call to # decorate_message() with function # site("GeeksforGeeks") as parameter print site("PythonWorld")

Output:
Welcome to PythonWorld

Iterators in Python

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.

1.__iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.

Below is a simple Python program that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.

# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# Cosntructor
def __init__(self, limit):
self.limit = limit
# Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3,
# we should replace next with __next__
def next(self):
# Store current value of x
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)

Output:
10
11
12
13
14
15

Accessing Counters in Python

Once initialized, counters are accessed just like dictionaries. Also, it does not raise the Key Value error (if key is not present) instead the value’s count is shown as 0.

Example:
# Python program to demonstrate accessing of
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])

Output:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0

elements()
The elements() method returns an iterator that produces all of the items known to the Counter. Note : Elements with count <= 0 are not included.

Example:
# Python example to demonstrate elements() on
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))

Output:
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']

most_common() :
most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts.
# Python example to demonstrate most_elements() on
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))

Output:
f: 219
d: 120
c: 3

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (212) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses