Implement Multithreaded Queue with Python

Kiran P
Updated on 10-Nov-2020 05:39:02

3K+ Views

Introduction..In this example, we will create a task queue that holds all the tasks to be executed and a thread pool that interacts with the queue to process its elements individually.We will begin with the question, what is a Queue?. A queue is a data structure that is a collection of different elements maintained in a very specific order. Let me explain by taking a real life example.Assume you stand in line to pay your grocery billat a grocery shop counter, (don't ask me which grocery shop)In a line of people waiting to pay their bills, you will notice the ... Read More

Scan for a String in Multiple Document Formats with Python

Kiran P
Updated on 10-Nov-2020 05:36:10

838 Views

Problem..Assume you have a directory full of files with different formats, to search for a particular keyword.Getting ready..Install below packages.1. beautifulsoup42. python-docxHow to do it...1. Write a function to search for a string in CSV format. I will be using csv.reader module to go through the file and search for the string and return True when found else False.Exampledef csv_stringsearch(input_file, input_string): """ Function: search a string in csv files. args: input file , input string """ with open(input_file) as file: for row in csv.reader(file): for column in row: if input_string in column.lower(): return True return False2. Function to search a ... Read More

Make Argument Optional in Python

Kiran P
Updated on 10-Nov-2020 05:32:52

383 Views

Introduction..Sometimes, the programs require optional arguments when supplied will use them else go back to default declarations. We will see in this example on how to use them.The parameters that start with dashes (--) are identified as optional, so they can be left out, and they may have default values.Parameters that don’t start with dashes are positional and are usually required, so they do not have default values.How to do it...Exampleimport argparse parser = argparse.ArgumentParser(description='Optional Argument Example') parser.add_argument('-n', '--name', metavar='name', default='World', help='Say Hello to ') args = parser.parse_args() print(f"Hello {args.name}")The “metavar” will show up in the usage to describe the ... Read More

Combine Multiple Graphs in Python

Kiran P
Updated on 10-Nov-2020 05:28:29

19K+ Views

IntroductionMatplotlib allows to add more than one plot in the same graph. In this tutorial, I will show you how to present data in the same plot, on two different axes.How to do it..1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib.import matplotlib.pyplot as plt2. Prepare the data to be displayed.import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone', 'Galaxy', 'Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016', 12, 8, 6), ('2017', 14, 10, ... Read More

Match Text at the Start or End of a String in Python

Kiran P
Updated on 10-Nov-2020 05:24:29

959 Views

Problem..Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this.Startswith() methodA simple way to check the beginning of a string is by using startswith() method.Exampletext = "Is USA colder than Australia?" print(f"output {text.startswith('Is')}")OutputTrueExamplefilename = "Hello_world.txt" print(f"output {filename.startswith('Hello')}")OutputTrueExamplesite_url = 'https://www.something.com' print(f"output {site_url.startswith('http:')}")OutputFalseExampleprint(f"output {site_url.startswith('https:')}")OutputTrueendswith() Method.A simple way to check the ending of a string is by using endswith() method.Outputtext = "Is USA colder than Australia?" print(f"output ... Read More

Search and Replace Text in Python

Kiran P
Updated on 10-Nov-2020 05:22:42

715 Views

ProblemYou want to search for and replace a text pattern in a string.If we have a very simple literal patterns, using the str.replace() method is an optimal solution.Exampledef sample(): yield 'Is' yield 'USA' yield 'Colder' yield 'Than' yield 'Canada?' text = ' '.join(sample()) print(f"Output {text}")OutputIs USA Colder Than Canada?Let us first see how to search a text.# search for exact text print(f"Output {text == 'USA'}")OutputFalseWe can search for the text using the basic string methods, such as str.find(), str.endswith(), str.startswith().# text start with print(f"Output {text.startswith('Is')}")OutputTrue# text ends with print(f"Output {text.startswith('Is')}")OutputTrue# search text with find print(f"Output ... Read More

Implement Priority Queue in Python

Kiran P
Updated on 10-Nov-2020 05:20:13

528 Views

Introduction...The queue module provides a first-in, first-out (FIFO), Last-in, First out (LIFO) data structure suitable for multi-threaded programming. Queues can be used to pass data or any wide range of information e.g. session details, paths, variables, .. between creator and consumer threads safely. Locking is generally handled for the caller.Note : This discussion assumes you already understand the general nature of a queue. If you do not, you may want to read some of the references before continuing.1. Let us implement a basic FIFO Queue.import queue fifo = queue.Queue() # put numbers into queue for i in range(5): fifo.put(i) ... Read More

Find Largest or Smallest Items in Python

Kiran P
Updated on 10-Nov-2020 05:10:16

424 Views

This article is aimed at developers who want to find the largest or smallest items with Python. I will show a few methods touse and will conclude the best method for you.Method – 1: Slice approach on a ListIf you are simply trying to find the single smallest or largest item i.e N = 1, it is faster to use min() and max().Let us begin by generating some random integers.import random # Create a random list of integers random_list = random.sample(range(1, 10), 9) random_listOutput[2, 4, 5, 1, 7, 9, 6, 8, 3] FINDING THE SMALLEST & LARGEST ITEM (N=1) # ... Read More

Identify Most Frequently Occurring Items in a Sequence with Python

Kiran P
Updated on 10-Nov-2020 05:03:25

313 Views

ProblemYou need to identify the most frequently occurring items in a sequence.SolutionWe can use counter to keep track of the items in a sequence.What is a Counter ?The “Counter” is a mapping that holds an integer count for each key. Updating an existing key adds to its count. This Objectis used for counting the instances of hashable objects or as a multiset.The “Counter” is one of your best friends when you are performing data analysis.This object has been present in Python for quite some time, and so for a lot of you, this will be a quick review.We will start ... Read More

Wrap Object Properties of Type String with Arrays in JavaScript

AmitDiwan
Updated on 09-Nov-2020 11:17:24

550 Views

For this, use Object.keys() along with reduce(). To display the result, we will also use concat().ExampleFollowing is the code −var details = { name: ["John", "David"], age1: "21", age2: "23" },    output = Object       .keys(details)       .reduce((obj, tempKey) =>          (obj[tempKey] = [].concat(details[tempKey]), obj), {}) console.log(output)  To run the above program, you need to use the following command −node fileName.js.Here, my file name is demo302.js.OutputThis will produce the following output on console −PS C:\Users\Amit\javascript-code> node demo302.js { name: [ 'John', 'David' ], age1: [ '21' ], age2: [ '23' ] }

Advertisements