Featured Posts

Most selected posts are waiting for you. Check this out

stack in python

stack in python

 

stack in python

 

How to Implement a Python Stack


Introduction to stacks and Queue data structures, which organized computer storage for efficiently access and manipulate data.

The stacks and queue are very simple to learn and execute with ease, and their usage is very common.

Stacks follows the LIFO principle that is last in first out. The last element will be removed or pop first.

Two operations are therein, one is pushed, which adds an element to the top of the stack, and the second one is pop, which removes the element at the top of the stack.

stack in python

So let us begin with implementing stacks, using lists in python. Let us first create an empty list name[].

We are going to add elements to the list, name [] using the append () method.

# create an empty list name

name=[]

# add elements into the list with append method in the list as Stack

name.append('Siraz')

name.append('Dhoni')

name.append('Shami')

name.append('Kholi')

name.append('Rahul')

name.append('Bumrah')

print(name)

Adding elements to the list using the append() method ensures the push operation of the stack.

Now let us try removing elements from the list.

name.pop()

It will delete the Bumrah as it is entered last

['Siraz', 'Dhoni', 'Shami', 'Kholi', 'Rahul']

Let us try to delete the item again from the list for which we have to write the same syntax

name.pop()

The above code deletes Rahul from the list, and we are left with only

['Siraz', 'Dhoni', 'Shami', 'Kholi']

Stack using deque in python

Implementing push with the help of append() method of the deque, We have to import deque from python collection library as follows

 from collections import deque

# We can initialize a deque with a list

name = deque()

 

# Use append like before to add elements

name.append ('Siraz')

name.append ('Dhoni')

name.append ('Shami')

name.append ('Kholi')

name.append ('Rahul')

name.append ('Bumrah')

 so when we print the print(name), it will print as follows

deque(['Siraz', 'Dhoni', 'Shami', 'Kholi', 'Rahul', 'Bumrah'])

 

Now using pop() of deque, we can implement stack pop operation as follows

name.pop()

print (name)

deque(['Siraz', 'Dhoni', 'Shami', 'Kholi', 'Rahul'])

The last element is Bumrah is deleted first

name.pop()

print (name)

deque(['Siraz', 'Dhoni', 'Shami', 'Kholi'])

The second last element Rahul is removed second and so on.

 

Implementation using python queue module

In the Python queue module there is a LIFO Queue, which is basically nothing but Stack. Element is inserted into the queue using put() method that act as PUSH and get () remove data out from the queue that act as POP operation of stack.

from queue import LifoQueue

 

# Initializing the stack with maxsize is 10

stack = LifoQueue(maxsize = 10)

 

# qsize() show the number of elements

# in the stack

print(“Initial size of  ”stack.qsize())

 

# put() function to push

# element in the stack

stack.put ('Siraz')

stack.put ('Dhoni')

stack.put ('Shami')

stack.put ('Kholi')

stack.put ('Rahul')

stack.put ('Bumrah')

print("Full is over or not : ", stack.full())

print("Total size of the stack:  ", stack.qsize())

 

# This get() method to act as pop operation of stack in

# LIFO order that is (Last in First Out)

print ('\nPoped operation from the stack')

print (stack.get())

print (stack.get())

print (stack.get())

 

print("\nStack Empty or not : ", stack.empty())

 

Output

Initial size of  0

Full:  False

Size:  6

 

Elements poped from the stack

Bumrah

Rahul

Kholi

Empty:  False


Python Articles


60 Python Interview Questions Answers

60 Python Interview Questions Answers

 

60 Python Interview Questions and Answers

Top 60 Python Interview Questions and Answers

1. Who developed the Python?

Python was initially designed by Guido Van Rossum in 1991 and developed by Python Software Foundation.

2. Python is which type of programming language?

Python is an object-oriented programming language.

3. What are the main features of Python?

  • Python is very easy to learn
  • It is an interpreter based language
  • Dynamic and versatile language
  • Lots of libraries are there for programmers
  • It is an object-oriented language that supports all the features of OOP’s and for this reason, we can build any kind of application.

4. What is the difference between interactive mode and script mode in Python?

When the user runs one single line code or one block of code then it is Interactive mode and the user runs a set of lines as a block then it is called script mode.

5 . What do you mean by IDLE in Python?

IDLE is Integrated Development Environment for editing and running Python programs. It is installed with a Python interpreter. It has a number of features to help programmers to develop python code with powerful syntax.

6. What are the benefits of Python?

Python is a very easy-to-learn language and we can do all kinds of programs including data science, artificial intelligence, data analytics with the help of different libraries. It is also open source so we can do the thing according to our own ease and use it to our advantage.

7.Can keywords be used as identifier?

No, keywords can not be used as identifiers or variables.

8. Write down the available token in Python.

  • Identifier
  • Punctuator
  • Keywords
  • Literals
  • Operators

9 . What do mean by Rvalue and Lvalue?

  • Rvalue: Pulls or fetches the value stored in a variable or constant.
  • Lvalue: It is usually an identifier or variable where value assign.

10 . Python is dynamically typed. Explain it.

A dynamically typed language is associated with run-time values and not named variables. So as a programmer we can write a little quicker because you do not have to specify types every time. Python does not know about the type of the variable until the code is run, that is why the declaration is not used. It stores the value at the same memory location and then binds that variable name to that memory location or container.

10. How is memory managed in Python?

Python memory manager handled the memory management. The Python memory manager allocates the memory in the form of private heap space. All the objects are stored in heap memory and it is not accessible to the programmer. Python provides some APIs to work with heap memory. Above all python has build Garbage collection clears out unused space.

11. What is the difference between a module and a package in Python?

A module in Python is a file containing a set of methods whereas a package in python provides the programmer with the application development tools (API) by providing a hierarchical directory structure in which sub-package and modules contain.

12. What is PEP 8?

The PEP 8(Python Enhancement Proposal) is defined as documentation that helps us to give the guidelines on how to write the Python code. Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001 were the writers of PEP8. It is for the improvement and readability of Python code.

13.  What are the built-in types available in Python?

There are six built-in types available in Python, which are as follows

The mutable types:

1.     List

2.     Sets

3.     Dictionaries

The immutable types:

1.     Tuples

2.     Strings

3.     Numbers

14. Explain the difference between a list and a tuple?

  • Both are heterogeneous types but the list is mutable and a tuple is immutable.
  • List declare in square brackets and Tuple declare in parenthesis ().

15. What is String?

A sequence of characters is known as String. String is immutable

16. What is the difference between /, //, and % operators?

/ Operator is used to finding quotient while % operator is used to finding reminder and // is used for integer division (Quotient).

 17. What is the difference between = and == operators?

The single equal to ‘=’ is the assignment operator and ‘==’ is equality (Relation operator) operator

18. What is an identity operator?

Identity operators in Python is used to determine whether a value is of a certain class or type.

19. What is String replication operator?

The star sign ‘*’ is a string replication operator and it is used print string repetitively as follows

St=’Hello ’

Print(st * 3)

Output

Hello Hello Hello

20. What do you mean by debugging?

It is a process by which we remove errors from the program and make it bug-free.

21. How many types of compile-time error?

There are two compile-time types  error

  • First is Syntax Error
  • Second Semantic Error

22. Difference between testing and debugging.

Debugging is the process of correcting errors in a program and testing is the process to find the error

23. what do mean by list in Python?

The list is a data structure that is a type container and it stores multiple data (heterogeneous data) at the same time. It is mutable.

22. What is traversing a list?

Traversing a list is a technique to access an individual element of a list.

23. What is the use of the list() method?

The List() method has converted a sequence like a tuple into the list.

24. What is the difference between remove() and pop() function in python?

The remove() method remove the given data from the list and pop() method delete the data from the list by the given index.

25. What do you mean by membership operators in Python?

 The membership operator are of two types

‘in’ operator and ‘not in’ operator

And it is used to check whether a value or variable exists in the sequence or not like say list as follows

Li = [3, 5, 6, 7, 8]

Print(3 in Li) – It will give true because 3 is there in the list if not then it will print false.

26.What is Packing and Unpacking in Python tuple?

In packing, we put data into a new tuple while in unpacking we extract those values into a single variable.

For example

Tup = (60, 70, ‘Hi’, ‘Bye’, 89)

a, b, c, d, e = Tup

print(a) will print 60

print(b) will print 70

print(c) will print Hi etc

27. What is a dictionary?

A dictionary in python is an order collection of data that stores key and value as an element and { } the bracket is used for it.

For example

Dict1 = {1 : ’Koma’, 2 : ‘Kamal’, 3 : ‘Sachine}

28.How many ways are there to iterate over a dictionary?

There are three ways to iterate over a dictionary as

  • Iterate through all keys
  • Iterate through all values
  • Iterate through all keys and values

28. What is the scope of a variable?

The scope of a variable refers to the part of the module or function where it can be used. A variable can be global or local scope.

 29. What is the Pickle module?

This module is used for serializing and de-serializing a Python object structure. This module serializes the first before writing data to file. Pickling is a way to convert a python object such as dict, list, tuple into a character stream and then saved it to the disk. 

30.What is Python Anonymous/ Lambda Function?

The nameless property function is called a lambda function or anonymous. It is used to create a new method object and return them at runtime.

 function.Syntax of lambda function:

lambda: argument_list:expression

Add 20 to argument a, and return the result:

x = lambda a : a + 20

print(x(5))

Ans: 25 

31. What are decorators in Python?

A decorator in python is a function that changes a specific syntax for the easy alteration of functions basically it add functionalities to an existing function, object, or code without modifying its structure permanently 

32. What is the difference between generators and iterators?

Iterator is used in python to iterate over a group of elements such as list, tuple.

For example

li = [2, 4, 5, 6, 8]
iterator = iter(li)
print(next (iterator))
print(next (iterator))
print(next (iterator))

In python, a generator is an exceptional type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. A yield statement is used instead of a return statement. The following is a simple generator function.

For example

def printValue():

    for i in range(20):
        if (i % 2 == 0):
            yield i
# Function call using for loop
for i in printValue():
    print(i, end=' ')

output : 0 2 4 6 8 10 12 14 16 18 

All the even number is printed.

33. What is the range() function and what are its parameters?

The Python range() the function is to generate a sequence of numbers starting from the given start integer to the stop integer. A range is a built-in function object is generally used for a loop.

Syntax

range(start, stop[, step])

start: It is the starting position, generally, it starts from zero (0)

stop: Stop position

step: Specify the increment value

# Generate numbers between 0 to 10
for i in range(10):
    print(i, end=' ')

Output : 0 1 2 3 4 5 6 7 8 9

# Generate even numbers between 2 to 18
for i in range(2, 20, 2):
    print(i, end=' ')

Output: 2 4 6 8 10 12 14 16 18

35. What is the zip() function in Python?

The zip() function in Python returns a zip object, which combines the contents of two or more iterables. It returns an iterator of tuples. Actually, it accepts iterable items and merges them into a single tuple.

 36. How do garbage collection in python?

The garbage collection in Python is automatic means it allocation and de-allocation method is automatic. The user does not have to do pre-allocate or de-allocate memory as it is used C or C++.
Python has two strategies for memory allocation:

  • Reference counting
  • Garbage collection

37. Is Python an object-oriented language?

Yes, Python is an object-oriented language. An object-oriented language using classes and objects

38. What is a class and an object in Python?

Class is a blueprint of an object and an object is an instance of a class.

39. What is a constructor and its usage?

A constructor is a function and it is called or executes automatically when an object is being created.

The main usage of the constructor is to declare and initialize instance variables. __init()__ method is called the constructor in Python. In other words, the name of the constructor should be __init__(self).


40. How many types of constructors are there?


There are two types of constructors in Python.

  • Non-parameterized: This is called default too. The Python constructors in which have no parameter is known as a non-parameterized constructor. The no parameterized constructor uses when we do not want to just initializes the instance variable and it has self.
  • Parameterized Constructor: The Python constructor which has parameters is known as a parameterized constructor. The parameterized constructor has multiple parameters along with the self.

41. What is PYTHONPATH?

Python provides PYTHONPATH which is used to add different directories when a module or package is imported. The Python interpreter uses PYTHONPATH to determine which module to load.

42. What is the difference between Python arrays and lists?

  • Both Array and List store data. But an array containing elements of same data type and list contain different data types.
  • The array is homogenous whereas List is Heterogeneous
  • Array consumes less memory than the list.
43. Python supports negative indexes. What are they and why are they used?
In Python List, Tuple and String act as a sequence and it consists of the index as positive and negative.
  • From left to right or we can say positive index starts from zero (0) and that index runs till n-1. 
  • And negative index start from -1 and second is -2 and so on and starts from right to left.
This positive and negative indexing is eased us to traverse the sequence.

44. What is docstring?

It is a documentation string. We define docstring with triple single quotes or triple double-quotes. It is a multiple lines string. If we want to define multi-line document in a variable then we have to create docstring.

Example

docstr="""Python is a modern programming Language

It is a very easy language to learn

We can do different types of program

It is an object-oriented language

"""

print(docstr)


45. What is the difference between .pyc and .py files?

  • .pyc is a bytecode file whereas .py file is a Python source file.
  • .pyc is load before .py files  and save the time to re-compile

More Article

How to Remove Duplicates Items from a Python List

How to Implement a Python Stack

Multithreading in Java with example

Multithreading in Java with example

 

Multithreading in Java

Multithreading in Java

 When we want to run multiple programs or tasks simultaneously is known as multitasking. For example running VLC, Word, and Browser at a given time is an example of multitasking. Every program in memory is known as a process and each process has taken a single unit of time.

 The multitasking can be achieved by

  • Multiprocessing which is based on process and associated with operating system level.
  • Multitasking is based on thread and it is associated with programmer.

 
Multitasking

What is Thread in java?

A thread is a subpart of a process which lightweight and it is the smallest sequence of a program or a process. Each thread has some priority and the higher the priority higher the chances of executing preference.

The life cycle of thread

The JVM controlled the life cycle of a thread and it has five states 1. New, 2. Runnable, 3. Running, 4. Non-Runnable (Blocked) and last 5. Terminated.

How to create a thread in java?

We can thread in java by two method

First, With Thread class extending and second with implementing Runnable interface.

Java provides predefine API to implement thread, a few of commonly used API as follows

  • thread () Create a new thread
  • Thread (Runnable target)
  • Thread (String name)
  • Thread (Runnable target, String name)
  • Thread (ThreadGroup g, Runnable target)

To create a thread we used two way first by extending Thread class and second by implementing Runnable interface and this done by overriding the run() method. After then start() is called.


By implementing Runnable interface

public class RunnableInteface implements Runnable

{ 

    public void run()

    { 

        System.out.println("thread is running.. by Runnable interface"); 

    } 

    public static void main(String args[])

    { 

        RunnableInteface ob=new RunnableInteface(); 

        Thread t1 =new Thread(ob); 

        t1.start(); 

    } 

}

Output

thread is running.. by Runnable interface

In the above program, we implement a Runnable interface. And override the run() method and then create an object of the class and that object passed in the Thread class constructor as Thread(ob).


By extending class Thread

public class ExtendingThread extends Thread

{ 

    public void run()

    { 

        System.out.println("thread is running..by extending class Thread."); 

    } 

    public static void main(String args[])

    { 

        ExtendingThread t1=new ExtendingThread(); 

        t1.start(); 

    } 

} 

Output

thread is running..by extending class Thread.


Another example

public class DemoThread extends Thread

{

    public void run()

    {

        for(int i=0; i<5; i++)

        {

            System.out.println(getName() + "i=" + i);

        }

    }

    DemoThread() // constructor

    {

        start();

    }  

    public static void main(String args[])

    {

        DemoThread ob1 = new DemoThread();

        DemoThread ob2 = new DemoThread();

    }

}

In the above program run() method override and invoked by its constructor method, a loop is run from 0 to 4 and print the thread name with the help of getThread() method. In main() method two objects are created. It will print the following output

Thread-1 i=0

Thread-1 i=1

Thread-1 i=2

Thread-1 i=3

Thread-1 i=4

Thread-0 i=0

Thread-0 i=1

Thread-0 i=2

Thread-0 i=3

Thread-0 i=4


Difference between Daemon and User Threads


The main difference between Daemon and User threads is, a Daemon thread is low priority thread and User thread is a high priority thread.

Daemon thread is used in the background supporting task and User thread is used in the foreground.

Daemon thread life depends on the User thread whereas User Thread are independent.

 

Creating of Daemon Thread

public class Daemon extends Thread {

 

    @Override

    public void run()

    {

        System.out.println("User Thread or Non-Daemon Thread");

    }

}

class DaemonThread

{

    public static void main(String[] args)

    { 

        Daemon daemon = new Daemon();

        daemon.start(); 

        System.out.println("Main Thread"); 

        System.out.println("Is " + daemon.getName() + " a Daemon Thread: " + daemon.isDaemon()); 

        System.out.println("Is " + Thread.currentThread().getName() + " a Daemon Thread: "

        + Thread.currentThread().isDaemon());

    }

}

Inter-Thread communication

When a process communicates with synchronized threads is known as inter-thread communication. It is used to check thread pooling in java. This can be achieved by notify(), notifyAll() and wait() method.


Few points about the thread

  • A thread is the smallest unit of execution
  • Multiple tasks execution is multitasking from the user perspective and from multithreading from an operating system perspective
  • Thread is lightweight
  • Thread is a part of the process and it is an instance of a program
  • Java thread can be created either by class Thread or by interface Runnable
  • in a thread a run() method override
  • The start() method automatically invoke the run() method
  • The yield method of thread provides a chance to wait for another thread
  • join() method is used to wait till the thread finishes its execution
  • sleep() method is used to delay in execution
  • Suspending a thread can be resume again later on by resuming it
  • stop() method stop the thread and make it dead, it can not be resume again
  • synchronized can be used to synchronize the thread

More Java programs