Search

Python Programming Filter

How to Implement a Python Stack

Whether you want to reverse a string or create a language processing application, stacks are very useful. It can be used to solve a wide variety of problems. In fact most of the programming languages including the operating systems are dependent on stack to function.The name Stack data structure totally resembles a pile of objects, stack of papers, or a tower of blocks, where adding and removing of items occur only at the top of the pile. It is similar to removing a quarter in the middle of a stack of coins without destroying the entire thing. In this article we will understand stack operations and look into the various ways to implement stack in Python. You may also get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is a Stack?A Stack is an abstract linear data type that serves as a collection of objects. Unlike queues, they use the Last In First Out or LIFO  technique to insert and delete elements. The insert and delete operations are referred to as push and pop in stack.Stacks and Queues are both linear collections of items. However, in a queue, the least recently added item is removed first, following the First In First Out or FIFO  manner. On the other hand, in a stack, the most recently added item is removed in the beginning following the LIFO. Stack stores the data elements in a similar fashion as a bunch of plates that are kept one above the other in a kitchen. It allows operations (push or pop) only from one end, often called as top. You can add or remove elements only from the top of the stack.A real-life example of a stack is a pile of heavy and precious plates, all kept on top of the other. If you wish to add a plate or remove one, you can do that only from the top. However, if you want to remove a lower plate from the stack, you have to remove the topmost plates one by one, in order to remove the desired one. Other examples are a deck of cards or a pile of books etc.What are the basic operations performed in Stack?Basic Operations performed in Stack - Push, POP, PeekThe basic operations which are performed in the stack are mentioned below:Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.Peek or Top: Returns top element of stack.isEmpty: Returns true if stack is empty, else false.Applications of StackStacks are considered as the backbone of Data Structures. Most of the algorithms and applications are implemented using stacks.Some of the key applications of stacks are—They are used to reverse a string. Each of the characters are pushed in and then popped off, which results in a reversed string.It is used in Expression Evaluation and Expression Conversion (infix to postfix, infix to prefix, postfix to infix, prefix to infix).It is used for forward and backward features in web browsers.It is used for recursive parsing in Natural Language Processing.It is used in syntax parsing and parenthesis checking.It is used for Backtracking like finding paths to a maze or exhaustive searching.It is used in Algorithms like Tower of Hanoi, tree traversals, histogram problem and also in graph algorithms like Topological Sorting.Understanding Stack OperationsThere are mainly two types of primitive stack operations:Push: It is performed to insert and store an element in the stack. However, when you try to insert an element in a stack which is full, the Overflow condition occurs.Pop: It is used to remove an element from the stack. However, when the stack is empty, the Underflow condition occurs.PushLet’s consider editing a Python file using the undo feature in your editor so you can have a clear understanding of the stack operations. At first, a new function called Insert is added. The push operation adds the Insert function into the stack:Now, a word Delete is removed from any of the comments. This word also gets added to the stack:The Delete is added to the top of the stack. Finally, let us indent a Comment to align things appropriately which is also inserted into the stack:Note that the commands entered are all stored in the stack just like a pile with each command on top of the other. This operation of adding new elements into the stack is called push.PopNow to perform the pop operations, let us make use of the undo feature. When we first hit the undo, it removes the top-most element of the stack (here, which is Comment):The editor removes the indented Comment and the stack is now left with two commands. When the next undo is hit again, the next command is removed from the stack:Now Delete is also removed and the stack is left with only one operation. When the undo is hit again, the last element remaining in the stack is also popped off and the stack becomes empty as it was in the first place:Since the stack is now empty, if we again hit undo, it will result into an Underflow condition causing no effect.Implementing Stack in PythonPython gives you a lot of options for implementing a Python stack. You can do so by using lists, tuples or by using third-party modules or packages. However, there are some basic implementations of Python stack that will fulfil most of your needs.Some of those implementations are as follows:listcollections.dequequeue.LifoQueueUsing ListList is a built-in structure that can be used as stack in Python. We use lists often to write Python programs. They are implemented as internal dynamic arrays in Python which means whenever elements are added or removed, the storage area is resized every time accordingly.You can use .append() to add elements and .pop() to remove them:>>> my_first_stack = [] >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack ['Alex', 'Bob', 'Charlie'] >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> my_first_stack.pop() Traceback (most recent call last):   File "<#pyshell>", line 1, in <module> IndexError: pop from empty listNotice that an IndexError is raised. This is because .pop() is called on an empty stack.Though lists work very efficiently in implementing stacks, yet it comes with some drawbacks. There might be situations where your stack might grow bigger than the current block of memory  it holds. Since lists are used for faster access to random elements, in such situations, speed issues occur. Python starts allocating memory implicitly which leads to longer .append() calls.Speed issues also occur when you use .insert() to add elements in your stack.Using ArrayIt is quite easy to implement stack using Python Lists. However, you can implement stack using arrays as well if you assume that lists are like arrays. You can follow the algorithm mentioned below to understand how it works.Algorithm:Declare a list and an integer MaxSize, and denote the maximum size of the StackInitially set the Top to 0.Push operation:Check if the MaxSize of the Stack is greater than TopIf yes, append data to stack and increase top by 1If no, print stack full messagePop operation:Check if Top is greater than 0:If yes, pop the last element from the list and decrement top by 1If no, print stack empty messageSize operation: The size of the Stack is the value of the Top pointer.class Stack:     #Constructor     def __init__(self):         self.stack = list()         self.maxSize = 8         self.top = 0     #Adds element to the Stack     def push(self,data):         if self.top>=self.maxSize:             return ("Stack Full!")         self.stack.append(data)         self.top += 1         return True     #Removes element from the stack     def pop(self):         if self.top<=0:             return ("Stack Empty!")         item = self.stack.pop()         self.top -= 1         return item             #Size of the stack     def size(self):         return self.top s = Stack() print(s.push(1))#prints True print(s.push(2))#prints True print(s.push(3))#prints True print(s.push(4))#prints True print(s.push(5))#prints True print(s.push(6))#prints True print(s.push(7))#prints True print(s.push(8))#prints True print(s.push(9))#prints Stack Full! print(s.size())#prints 8       print(s.pop())#prints 8 print(s.pop())#prints 7 print(s.pop())#prints 6 print(s.pop())#prints 5 print(s.pop())#prints 4 print(s.pop())#prints 3 print(s.pop())#prints 2 print(s.pop())#prints 1 print(s.pop())#prints Stack Empty!Note: Element 9 was not added and hence size remains 8.Using collections.dequePython contains a module named collections. This comprises of the deque class which is a double-ended queue that supports inserting and removing elements from either ends.The method of deque is similar to the lists:>>> from collections import deque >>> my_first_stack = deque() >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack deque(['Alex', 'Bob', 'Charlie']) >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> myStack.pop() Traceback (most recent call last):   File "<#pyshell>", line 1, in <module> IndexError: pop from an empty dequeThe objects of the deque class has a consistent performance because they are implemented in the form of doubly linked lists.Using queue.LifoQueueThe Python Standard Library comprises of another class called queue.LifoQueue class to implement stack. It supports multiple simultaneous producers and consumers.Python Threading is used for executing multiple tasks and function calls at the same time and independently of other codes. If your program involves threads, it is recommended not to use list and deque because they behave very differently in such cases.list is not thread-safe. On the other hand, though, .append() and .pop() are atomic in nature, it is nearly impossible to build a Python stack using deque that is fully thread-safe. This is because of the reason that in a threaded environment, there are other deque class methods that are neither atomic nor they are thread-safe and might lead to race conditions.So the last option we’re left with is the queue.LifoQueue class that is specially designed to be fully thread-free.Adding and removing elements are performed in this class are using .put() and .get():>>> from queue import LifoQueue >>> my_first_stack = LifoQueue() >>>my_first_stack.put('Alex') >>>my_first_stack.put('Bob') >>>my_first_stack.put('Charlie') >>> my_first_stack <queue.LifoQueue object at 0x0000026E4C69DFD0> >>> my_first_stack.get() 'Charlie' >>> my_first_stack.get() 'Bob' >>> my_first_stack.get() 'Alex' >>> my_first_stack.get_nowait() Traceback (most recent call last):   File "<pyshell#8>", line 1, in <module>     my.get_nowait() _queue.Empty >>> my_first_stack.get()  # Waits foreverThe queue module might be helpful when you are working with multiple threads or with parallel computing. However, for general purpose stack implementation, it is recommended to use lists or deque.deque: An excellent choice for implementing a Python StackIf you’re not interested in handling explicit locking and unlocking and also not looking for parallel processing support, then your choice for choosing the right Python stack implementation narrows down to list and deque. However, they both have different implementations of data structures in their working.Operations like indexing and slicing work very well with lists because it is built upon contiguous blocks of memory. The elements in the list are stored in a dynamic array system making it easier for Python to find any element in the memory.However, this type of layout system raises speed issues in situations like when the contiguous block is full, it needs to get another block which in turn increases the execution time.On the other hand, deque is a doubly linked list in which each entry is linked to both the previous and next entry in the list. This allows adding elements to both the ends of the list. In this type of linked list, each memory has its own memory block. Thus, combining all these reasons, deque is a much better choice than list when implementing stacks in Python.ConclusionLet us sum up what we’ve learnt in this article so far:What is a Stack and what are its applications.What do Stack operations look like.When should a data structure like Stack be used.Different ways of implementing Stack in Python.How to select the right implementation depending upon your problem.Stacks are simple data structures that allows us to store and retrieve data in a sequential fashion. They are very useful in real world cases. Having a clear understanding of stacks would help us in solving data storage problems in an efficient manner.If you wish to know more about data structures and other aspects of Python, you can go through the Python tutorial. You may also join the certification course on Python.

How to Implement a Python Stack

8344
How to Implement a Python Stack

Whether you want to reverse a string or create a language processing application, stacks are very useful. It can be used to solve a wide variety of problems. In fact most of the programming languages including the operating systems are dependent on stack to function.

The name Stack data structure totally resembles a pile of objects, stack of papers, or a tower of blocks, where adding and removing of items occur only at the top of the pile. It is similar to removing a quarter in the middle of a stack of coins without destroying the entire thing. In this article we will understand stack operations and look into the various ways to implement stack in Python. You may also get certified and learn more about Python Programming and apply those skills and knowledge in the real world.

What is a Stack?

A Stack is an abstract linear data type that serves as a collection of objects. Unlike queues, they use the Last In First Out or LIFO  technique to insert and delete elements. The insert and delete operations are referred to as push and pop in stack.

Stacks and Queues are both linear collections of items. However, in a queue, the least recently added item is removed first, following the First In First Out or FIFO  manner. On the other hand, in a stack, the most recently added item is removed in the beginning following the LIFO

Stack stores the data elements in a similar fashion as a bunch of plates that are kept one above the other in a kitchen. It allows operations (push or pop) only from one end, often called as top. You can add or remove elements only from the top of the stack.

A real-life example of a stack is a pile of heavy and precious plates, all kept on top of the other. If you wish to add a plate or remove one, you can do that only from the top. However, if you want to remove a lower plate from the stack, you have to remove the topmost plates one by one, in order to remove the desired one. Other examples are a deck of cards or a pile of books etc.

What are the basic operations performed in Stack?

The basic operations performed in Stack are Push, POP and PeekBasic Operations performed in Stack - Push, POP, Peek

The basic operations which are performed in the stack are mentioned below:

  • Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.
  • Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.
  • Peek or Top: Returns top element of stack.
  • isEmpty: Returns true if stack is empty, else false.

Applications of Stack

Stacks are considered as the backbone of Data Structures. Most of the algorithms and applications are implemented using stacks.

Some of the key applications of stacks are—

  • They are used to reverse a string. Each of the characters are pushed in and then popped off, which results in a reversed string.
  • It is used in Expression Evaluation and Expression Conversion (infix to postfix, infix to prefix, postfix to infix, prefix to infix).
  • It is used for forward and backward features in web browsers.
  • It is used for recursive parsing in Natural Language Processing.
  • It is used in syntax parsing and parenthesis checking.
  • It is used for Backtracking like finding paths to a maze or exhaustive searching.
  • It is used in Algorithms like Tower of Hanoi, tree traversals, histogram problem and also in graph algorithms like Topological Sorting.

Understanding Stack Operations

There are mainly two types of primitive stack operations:

  • Push: It is performed to insert and store an element in the stack. However, when you try to insert an element in a stack which is full, the Overflow condition occurs.
  • Pop: It is used to remove an element from the stack. However, when the stack is empty, the Underflow condition occurs.

Push

Let’s consider editing a Python file using the undo feature in your editor so you can have a clear understanding of the stack operations. At first, a new function called Insert is added. The push operation adds the Insert function into the stack:

Insert function into the stack using push operation

Now, a word Delete is removed from any of the comments. This word also gets added to the stack:

adding delete word to the stack by push operation

The Delete is added to the top of the stack. Finally, let us indent a Comment to align things appropriately which is also inserted into the stack:

Indenting "comment" to the stack using Push operation

Note that the commands entered are all stored in the stack just like a pile with each command on top of the other. This operation of adding new elements into the stack is called push.

Pop

Now to perform the pop operations, let us make use of the undo feature. When we first hit the undo, it removes the top-most element of the stack (here, which is Comment):

First undo removes the top-most element of the stack

The editor removes the indented Comment and the stack is now left with two commands. When the next undo is hit again, the next command is removed from the stack:

The next undo will remove the next command from the stack, which is called POP operation

Now Delete is also removed and the stack is left with only one operation. When the undo is hit again, the last element remaining in the stack is also popped off and the stack becomes empty as it was in the first place:

The last undo will remove the last element of the stack and the stack becomes empty. This removal of elements from a stack is called POP operation

Since the stack is now empty, if we again hit undo, it will result into an Underflow condition causing no effect.

Implementing Stack in Python

Python gives you a lot of options for implementing a Python stack. You can do so by using lists, tuples or by using third-party modules or packages. However, there are some basic implementations of Python stack that will fulfil most of your needs.

Some of those implementations are as follows:

  • list
  • collections.deque
  • queue.LifoQueue

Using List

List is a built-in structure that can be used as stack in Python. We use lists often to write Python programs. They are implemented as internal dynamic arrays in Python which means whenever elements are added or removed, the storage area is resized every time accordingly.

You can use .append() to add elements and .pop() to remove them:

>>> my_first_stack = []
>>> my_first_stack.append('Alex')
>>> my_first_stack.append('Bob')
>>> my_first_stack.append('Charlie')
>>> my_first_stack
['Alex', 'Bob', 'Charlie']
>>> my_first_stack.pop()
'Charlie'
>>> my_first_stack.pop()
'Bob'
>>> my_first_stack.pop()
'Alex'
>>> my_first_stack.pop()
Traceback (most recent call last):
  File "<#pyshell>", line 1, in <module>
IndexError: pop from empty list

Notice that an IndexError is raised. This is because .pop() is called on an empty stack.

Though lists work very efficiently in implementing stacks, yet it comes with some drawbacks. There might be situations where your stack might grow bigger than the current block of memory  it holds. Since lists are used for faster access to random elements, in such situations, speed issues occur. Python starts allocating memory implicitly which leads to longer .append() calls.

Speed issues also occur when you use .insert() to add elements in your stack.

Using Array

It is quite easy to implement stack using Python Lists. However, you can implement stack using arrays as well if you assume that lists are like arrays. You can follow the algorithm mentioned below to understand how it works.

Algorithm:

  1. Declare a list and an integer MaxSize, and denote the maximum size of the Stack
  2. Initially set the Top to 0.
  3. Push operation:
    • Check if the MaxSize of the Stack is greater than Top
      • If yes, append data to stack and increase top by 1
      • If no, print stack full message
  4. Pop operation:
    • Check if Top is greater than 0:
      • If yes, pop the last element from the list and decrement top by 1
      • If no, print stack empty message
  5. Size operation: The size of the Stack is the value of the Top pointer.
class Stack:
    #Constructor
    def __init__(self):
        self.stack = list()
        self.maxSize = 8
        self.top = 0
    #Adds element to the Stack
    def push(self,data):
        if self.top>=self.maxSize:
            return ("Stack Full!")
        self.stack.append(data)
        self.top += 1
        return True
    #Removes element from the stack
    def pop(self):
        if self.top<=0:
            return ("Stack Empty!")
        item = self.stack.pop()
        self.top -= 1
        return item
       
    #Size of the stack
    def size(self):
        return self.top

s = Stack()
print(s.push(1))#prints True
print(s.push(2))#prints True
print(s.push(3))#prints True
print(s.push(4))#prints True
print(s.push(5))#prints True
print(s.push(6))#prints True
print(s.push(7))#prints True
print(s.push(8))#prints True
print(s.push(9))#prints Stack Full!
print(s.size())#prints 8      
print(s.pop())#prints 8
print(s.pop())#prints 7
print(s.pop())#prints 6
print(s.pop())#prints 5
print(s.pop())#prints 4
print(s.pop())#prints 3
print(s.pop())#prints 2
print(s.pop())#prints 1
print(s.pop())#prints Stack Empty!

Note: Element 9 was not added and hence size remains 8.

Using collections.deque

Python contains a module named collections. This comprises of the deque class which is a double-ended queue that supports inserting and removing elements from either ends.

The method of deque is similar to the lists:

>>> from collections import deque
>>> my_first_stack = deque()
>>> my_first_stack.append('Alex')
>>> my_first_stack.append('Bob')
>>> my_first_stack.append('Charlie')
>>> my_first_stack
deque(['Alex', 'Bob', 'Charlie'])
>>> my_first_stack.pop()
'Charlie'
>>> my_first_stack.pop()
'Bob'
>>> my_first_stack.pop()
'Alex'
>>> myStack.pop()
Traceback (most recent call last):
  File "<#pyshell>", line 1, in <module>
IndexError: pop from an empty deque

The objects of the deque class has a consistent performance because they are implemented in the form of doubly linked lists.

Using queue.LifoQueue

The Python Standard Library comprises of another class called queue.LifoQueue class to implement stack. It supports multiple simultaneous producers and consumers.

Python Threading is used for executing multiple tasks and function calls at the same time and independently of other codes. If your program involves threads, it is recommended not to use list and deque because they behave very differently in such cases.

list is not thread-safe. On the other hand, though, .append() and .pop() are atomic in nature, it is nearly impossible to build a Python stack using deque that is fully thread-safe. This is because of the reason that in a threaded environment, there are other deque class methods that are neither atomic nor they are thread-safe and might lead to race conditions.

So the last option we’re left with is the queue.LifoQueue class that is specially designed to be fully thread-free.

Adding and removing elements are performed in this class are using .put() and .get():

>>> from queue import LifoQueue
>>> my_first_stack = LifoQueue()
>>>my_first_stack.put('Alex')
>>>my_first_stack.put('Bob')
>>>my_first_stack.put('Charlie')
>>> my_first_stack
<queue.LifoQueue object at 0x0000026E4C69DFD0>
>>> my_first_stack.get()
'Charlie'
>>> my_first_stack.get()
'Bob'
>>> my_first_stack.get()
'Alex'
>>> my_first_stack.get_nowait()
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    my.get_nowait()
_queue.Empty
>>> my_first_stack.get()  # Waits forever

The queue module might be helpful when you are working with multiple threads or with parallel computing. However, for general purpose stack implementation, it is recommended to use lists or deque.

deque: An excellent choice for implementing a Python Stack

If you’re not interested in handling explicit locking and unlocking and also not looking for parallel processing support, then your choice for choosing the right Python stack implementation narrows down to list and deque. However, they both have different implementations of data structures in their working.

Operations like indexing and slicing work very well with lists because it is built upon contiguous blocks of memory. The elements in the list are stored in a dynamic array system making it easier for Python to find any element in the memory.

However, this type of layout system raises speed issues in situations like when the contiguous block is full, it needs to get another block which in turn increases the execution time.

On the other hand, deque is a doubly linked list in which each entry is linked to both the previous and next entry in the list. This allows adding elements to both the ends of the list. In this type of linked list, each memory has its own memory block. Thus, combining all these reasons, deque is a much better choice than list when implementing stacks in Python.

Conclusion

Let us sum up what we’ve learnt in this article so far:

  • What is a Stack and what are its applications.
  • What do Stack operations look like.
  • When should a data structure like Stack be used.
  • Different ways of implementing Stack in Python.
  • How to select the right implementation depending upon your problem.

Stacks are simple data structures that allows us to store and retrieve data in a sequential fashion. They are very useful in real world cases. Having a clear understanding of stacks would help us in solving data storage problems in an efficient manner.

If you wish to know more about data structures and other aspects of Python, you can go through the Python tutorial. You may also join the certification course on Python.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

1 comments

Nilesh 16 Aug 2019

Excellent article on how to implement a python stack thanks for the useful information.

Suggested Blogs

9 Stupendous Technologies You Might Be Using In Near Future

Our lives have made a 360 degree turn in the past decade. Technology is making us move at break neck speed and our lives are all about going somewhere and getting things done. The internet brought the world closer and it has been predicted that it will lead to the democratization of the world. While until a few years back we needed our PCs and laptops to get online, today we can do so with the touch of a button on our smartphones. Indeed, the smartphone has now become the most popular device in many parts of the world. Mobile technology is exactly what the name implies; technology that is mobile, portable and you can carry around in your pocket. A smartphone with an internet connection is all you need to get all your work done. Android and iOS are changing the way we live, eat, sleep, work and even travel. As consumerism grows so does the mobile technology, giving us better, richer and safer experiences than ever before. You will no longer be standing in a checkout line: The future of easy shopping is upon us. With the right app, you will soon be scanning your product and getting it delivered across to your address, which is already stored in the app and the payment would be deducted from your account which is already linked to this app. Of course, the app knows all about your shopping preferences and would suggest possible online stores if you do not get in at the store. Wearable technology: Google Glass and Apple Watch are not the only wearable technology out there. Medical wearable trends are fast changing the landscape of healthcare with such things as computer pills that when ingested send a patient’s medical information to a health centre wirelessly or artificial pancreas that monitor a patient’s glucose levels and also injects insulin at defined intervals. In fact, the future might be even more high-tech with a camera for a contact lens and a microphone under the skin. Your vehicle, a Wi-Fi hotspot: Your car might soon be an escape into a sci-fi movie. GPS enabled location trackers are already widely used but now your vehicle might have wi-fi and enhanced location guidance that may be displayed on the windshield. Data transfer between devices: You are working on your laptop, now on your phone and now on your tablet. There will soon be apps that will allow you to seamlessly move between devices without disrupting your work. No keys future: How many times have you locked yourself out of your house or your car? If carrying a hundred keys around is not exactly your cup of tea then you might as well make your smartphone your best friend since it might be all that you need to open your house, locker, car, safe or any other lock. No more charging: A charge less phone is a complete killjoy. But what if your phone charged by itself without a charger? This ‘”dream come true” situation might soon become a reality with a phenomenon called Piezoelectricity that converts mechanical movements into electric current. So your phone will charge as you are texting or talking. Now that is really a dream come true! Don’t like to type? Then just think: Technology that uses electroencephalography (EEG) might soon hit the market where in devices will be able to read your brain waves and allow interaction with phones or computers or other devices. Advent of the 5G: Once in every 5 years, cellular standards take a quantum leap and the 5G promises to be the most futuristic of them all in terms of power and functionality. This standard is expected to deliver higher speed internet services and greater levels of AI capabilities. No communication barriers: You will soon understand as many languages as you want due to the instant translation apps that will be available on your phone. Global communication barriers will be brought down as people can connect across geographies and text each other in multiple languages. The number of mobile users is expected to reach 5 billion by the year 2020 and this means better connectivity and infrastructure even in the remotest parts of the world. Technology is bringing the world closer and with such advances as interactive t-shirts, USB drives in ornaments and ear patches with voice recognition, the future of mobile technology will be you!
9 Stupendous Technologies You Might Be Using In Ne...

Our lives have made a 360 degree turn in the past ... Read More

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3973
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

20% Discount