Server Side Programming Articles - Page 1477 of 2650

How to unpack using star expression in Python?

Kiran P
Updated on 09-Nov-2020 10:44:25

2K+ Views

IntroductionOne of the basic limitation of unpacking is that you must know the length of the sequences you are unpacking in advance.How to do it..random_numbers = [0, 1, 5, 9, 17, 12, 7, 10, 3, 2] random_numbers_descending = sorted(random_numbers, reverse=True) print(f"Output *** {random_numbers_descending}")Output*** [17, 12, 10, 9, 7, 5, 3, 2, 1, 0]If I now wanted to find out the largest and second largest from the numbers, we will get an exception "too many values to unpack".print(f"Output *** Getting the largest and second largest") largest, second_largest = random_numbers_descendingOutput*** Getting the largest and second largest--------------------------------------------------------------------------- ValueError Traceback (most recent call last) ... Read More

Program to find number of subsequences with i, j and k number of x, y, z letters in Python

Arnab Chakraborty
Updated on 09-Nov-2020 10:41:06

191 Views

Suppose we have a string s with "x", "y" and "z"s, we have to find the number of subsequences that have i number of "x" characters, followed by j number of "y" characters and followed by k number of "z" characters where i, j, k ≥ 1.So, if the input is like s = "xxyz", then the output will be 3, as we can make two "xyz" and one "xxyz"To solve this, we will follow these steps:n := size of sx := 0, y := 0, z := 0for i in range 0 to n, docount := 0if s[i] is ... Read More

How to perform Calculations with Dictionaries in Python?

Kiran P
Updated on 09-Nov-2020 10:41:18

2K+ Views

ProblemYou want to perform various calculations (e.g., minimum value, maximum value, sorting, etc.) on a dictionary of data.Solution.We will create a dictionary with tennis players and their grandslam titles.PlayerTitles = {    'Federer': 20,    'Nadal': 20,    'Djokovic': 17,    'Murray': 3,    'Theim' : 1,    'Zverev': 0 }1.We have a dictionary with player names and the grandslam titles won by each player. Now let us try to find out the player with least number of titles#type(PlayerTitles) print(f"Output *** The minimum value in the dictionary is {min(PlayerTitles)} ")Output*** The minimum value in the dictionary is Djokovic2. This is ... Read More

How to compare two DataFrames in Python Pandas with missing values

Kiran P
Updated on 09-Nov-2020 10:36:56

2K+ Views

IntroductionPandas uses the NumPy NaN (np.nan) object to represent a missing value. This Numpy NaN value has some interesting mathematical properties. For example, it is not equal to itself. However, Python None object evaluates as True when compared to itself.How to do it..Let us see some examples to understand how np.nan behaves.import pandas as pd import numpy as np # Python None Object compared against self. print(f"Output *** {None == None} ")Output*** True# Numpy nan compared against self. print(f"Output *** {np.nan == np.nan} ")Output*** False# Is nan > 10 or 1000 ? print(f"Output *** {np.nan > ... Read More

How to write functions in Python that accept any number of arguments

Kiran P
Updated on 09-Nov-2020 10:32:00

2K+ Views

ProblemYou want to write a function that accepts any number of input arguments.SolutionThe * argument in python can accepts any number of arguments. We will understand this with an example of finding out the average of any given two or more numbers. In the below example, rest_arg is a tuple of all the extra arguments (in our case numbers) passed. The function treats the arguments as a sequence in performing average calculation.# Sample function to find the average of the given numbers def define_average(first_arg, *rest_arg): average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg)) print(f"Output *** The average for ... Read More

Program to find next board position after sliding the given direction once in Python

Arnab Chakraborty
Updated on 09-Nov-2020 10:36:31

190 Views

Suppose we have a 2048 game board representing the initial board and a string direction representing the swipe direction, we have to find the next board state. As we know in the 2048 game, we are given a 4 x 4 board of numbers (some of them are empty, represented in here with 0) which we can swipe in any of the 4 directions ("U", "D", "L", or "R"). When we swipe, all the numbers move in that direction as far as possible and identical adjacent numbers are added up exactly once.So, if the input is likedirection = "L", then ... Read More

How to use the Subprocess Module in Python?

Kiran P
Updated on 09-Nov-2020 10:29:33

1K+ Views

Understanding Process -When you code and execute a program on Windows, MAC or Linux, your Operating System creates a process(single).It uses system resources like CPU, RAM, Disk space and also data structures in the operating system’s kernel. A process is isolated from other processes—it can’t see what other processes are doing or interfere with them.Note: This code has to be run on Linux like sytems. When executed on windows might throw exceptions.Goals of Operating System -The main twin goals of OS are to spread the work of the process fairly and be responsive to the user. These are acheived by ... Read More

How to process iterators in parallel using ZIP

Kiran P
Updated on 09-Nov-2020 10:27:45

369 Views

IntroductionList comprehensions make it easy to take a source list and get a derived list by applying an expression. For example, say that I want to multiply each element in a list with 5. Here, I do this by using a simple for loop.a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] multiply_by_5 = [] for x in a: multiply_by_5.append(x*5) print(f"Output *** {multiply_by_5}")Output*** [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]With a list comprehension, I can achieve the same outcome by specifying the expression and the input sequence to loop over.# List comprehension multiply_by_5 ... Read More

How to implement Concurrency with Threads in Python?

Kiran P
Updated on 09-Nov-2020 10:20:23

287 Views

IntroductionPython has different approaches like using threads, subprocesses, generators and other tricks for concurrent programming.Before we go on and implement threads, let us understand what exactly is concurrency.Concurrency is a piece of logic Within a single program that allows to open up many distinct paths of execution, including separate streams of I/O, running SQL queries, so on in a way that the execution seems to be both simultaneous and independent of each other.How to do it..First we create a single thread to go through the site urls and later look at how to use threading concepts to speed up the ... Read More

Program to convert each element in row and column to zero for zero values in Python

Arnab Chakraborty
Updated on 09-Nov-2020 10:28:02

528 Views

Suppose we have a 2D matrix of numbers, now for each zero in the given matrix and replace all values in its row and column with zero, and return the final matrix.So, if the input is like matrix, then the output will be matrix as the 0th, 2nd and 3rd rows contain 0 and the final matrix contains 0 in those rows. Similarly 0th, 1st and 2nd columns contain 0 and the final matrix contains 0 in those columns.To solve this, we will follow these steps:n := row count, m := column count res := make a matrix of size ... Read More

Advertisements