## Python In-Place Assignment Operators

In-place assignment operators (also called compound assignment operators) perform an operation in-place on a variable provided as first operand. They overwrite the value of the first operand variable with the result of the operation when performing the operator without assignment. For example, x += 3 is the same as x = x + 3 of

## [Review] Learn to Code by Solving Problems – by Prof. Daniel Zingaro

In this article, I’ll review the book “Learn to Code by Solving Problems: A Python Programming Primer” by Prof. Daniel Zingaro. The book is available here: Amazon NoStarch This is an independent review. I didn’t include any affiliate link, so I won’t get compensated if you decide to purchase the book. Although I know Daniel

## Python In-Place Bitwise Left-Shift Operator

Python’s in-place bitwise left-shift operator x <<= y calculates the left-shift operation x << y, and assigns the result to the first operands variable name x. You can set up the in-place left-shift behavior in your own class by overriding the magic “dunder” method __ilshift__(self, other) in your class definition. The expression x <<= y

## How to Classify Star Wars Lego Images using CNN and Transfer Learning

This tutorial is about training deep learning (DL) models to classify Star Wars Lego images. We use the TensorFlow library to create and compare the image classifiers. Are you looking for interesting deep learning projects that are suitable for beginners? Do not worry, this is not another MNIST image classification tutorial. Instead, we are going

## Python In-Place Bitwise XOR Operator

Python’s in-place bitwise XOR operator x ^= y calcualtes bitwise XOR x ^ y and assigns the result to the first operand x. To set this up for your own class, override the magic “dunder” method __ixor__(self, other) in your class definition. The expression x ^= y is syntactical sugar for the longer-form x =

## A Simple Guide To Remove Multiple Spaces In A String

Table of Contents Introduction🔦Method 1: Using Regular Expressions📌re.sub()🔦Method 2: Using The split() Method🔦Method 3: Using The replace() Method🔦Method 4: Using A For LoopConclusionRelated Posts Introduction Have you ever come across strings in Python that have unnecessary spacing between the words or characters? If so then you are at the correct place to find the solutions

## [Cheat Sheet] 6 Pillar Machine Learning Algorithms

This machine learning cheat sheet gives you a visual overview of 6 must-know machine learning algorithms (and where to learn more). Linear Regression: train your linear model to predict output values. K-Means Clustering: apply it on unlabeled data to find clusters and patterns in your data. K-Nearest Neighbors: use a similarity metric to find the

## Logistic Regression in Python Scikit-Learn

Logistic regression is a popular algorithm for classification problems (despite its name indicating that it is a “regression” algorithm). It belongs to one of the most important algorithms in the machine learning space. Table of Contents Linear Regression BackgroundLogistic Regression and Sigmoid FunctionLogistic Regression with sklearn.linear_modelLogisticsRegression MethodsConclusionPython One-Liners Book: Master the Single Line First!Related Posts

## How To Execute System Commands With Python?

In this article, we will learn numerous ways to execute system commands in Python. ➥ Problem: Given an external command that can run on your operating system, how to call the command using a Python script? ➥ Example: Say you want to ping a remote server using your operating system’s ping command—all from within your Python program. How

## Python In-Place Bitwise Right-Shift Operator

Python’s in-place bitwise right-shift operator x >>= y calculates the right-shift operation x >> y, and assigns the result to the first operands variable name x. You can set up the in-place right-shift behavior in your own class by overriding the magic “dunder” method __irshift__(self, other) in your class definition. The expression x >>= y

## Python In-Place Bitwise AND Operator

Python’s in-place bitwise AND operator x &= y calcualtes bitwise-and x & y and assigns the result to the first operand x. To set it up for your own class, override the magic “dunder” method __iand__(self, other) in your class definition. The expression x &= y is syntactical sugar for the longer-form x = x

## Python In-Place Exponentiation Operator

Python provides the in-place exponentiation operator x **= y that raises x to the power of y using x ** y and assigns the result to the first operands variable name x. You can set up the in-place exponentiation behavior for your own class by overriding the magic “dunder” method __ipow__(self, other) in your class

## Python In-Place Integer Division Operator

Python’s in-place integer division operator x //= y divides two objects in-place by calculating x // y and assigning the result to the first operands variable name x. Set up in-place integer (or floor) division for your own class by overriding the magic “dunder” method __floordiv__(self, other) in your class definition. The expression x /=

## Python In-Place Modulo Operator

Python provides the operator x %= y to calculate the modulo operation x % y, and assign the result in-place to the first operands variable x. You can set up the in-place modulo behavior for your own class by overriding the magic “dunder” method __imod__(self, other) in your class definition. The expression x %= y

## Python In-Place Division Operator

Python’s in-place division operator x /= y divides two objects in-place by calculating x / y and assigning the result to the first operands variable name x. Set up in-place division for your own class by overriding the magic “dunder” method __truediv__(self, other) in your class definition. The expression x /= y is syntactical sugar

## Python In-Place Multiplication Operator

Python provides the operator x *= y to multiply two objects in-place by calculating the product x * y and assigning the result to the first operands variable name x. You can set up the in-place multiplication behavior for your own class by overriding the magic “dunder” method __imul__(self, other) in your class definition. The

## Python In-Place Subtraction Operator

Python provides the operator x -= y to subtract two objects in-place by calculating the difference x – y and assigning the result to the first operands variable name x. You can set up the in-place subtraction behavior for your own class by overriding the magic “dunder” method __isub__(self, other) in your class definition. The

## Python Count Characters Except Empty Spaces

In Python, a string includes not only the alphanumeric characters and symbols, but also all whitespaces. Consider this simple example: We have a variable called mystring, and it is assigned to 3 characters a, b, and c. Note we have separated each character with a space, so when calling the len() function we get the

## Random Forest Classifier with sklearn

Does your model’s prediction accuracy suck but you need to meet the deadline at all costs? Try the quick and dirty “meta-learning” approach called ensemble learning. In this article, you’ll learn about a specific ensemble learning technique called random forests that combines the predictions (or classifications) of multiple machine learning algorithms. In many cases, it

## Python In-Place Addition Operator

Python provides the operator x += y to add two objects in-place by calculating the sum x + y and assigning the result to the first operands variable name x. You can set up the in-place addition behavior for your own class by overriding the magic “dunder” method __iadd__(self, other) in your class definition. The

## How to Generate Random Integers in Python?

The most idiomatic way to create a random integer in Python is the randint() function of the random module. Its two arguments start and end define the range of the generated integers. The return value is a random integer in the interval [start, end] including both interval boundaries. For example, randint(0, 9) returns an integer

## Understanding Namespaces in Python

A namespace is a filing system used by Python to track all the names given to objects when you write a program. When I first began trying to understand namespaces in Python, the tutorials I came across were confusing and less than helpful in their descriptions. Today I will take you on a logical and

## [Google Interview] How To Find The Majority Element In An Array?

Company Tags: Google, Amazon, Yahoo, Microsoft This is one of the Google interview questions and one of the most commonly asked questions during many interviews. So, can you give the optimal solution to this problem? Table of Contents Problem Formulation📖Examples🖊️Method 1: Brute Force Approach🖊️Method 2: Using A Python Dictionary🖊️Optimized Solution: Boyer–Moore Majority Vote AlgorithmConclusionRelated Posts Problem

## What Are Differences Between type() and isinstance()?

The main difference between type() and isinstance() is that type(object) returns the type of an object and isinstance(object, class) returns True if the object argument is an instance of the class argument or in a direct or indirect subclass relationship. To strengthen your understanding, let’s quickly recap the syntactical definitions of both functions: type(object) –

## SVM sklearn: Python Support Vector Machines Made Simple

Support Vector Machines (SVM) have gained huge popularity in recent years. The reason is their robust classification performance – even in high-dimensional spaces: SVMs even work if there are more dimensions (features) than data items. This is unusual for classification algorithms because of the curse of dimensionality – with increasing dimensionality, data becomes extremely sparse

## How to Fill a Python String with Spaces?

Table of Contents Problem FormulationMethod 1: str.ljust()Method 2: Literal String Interpolation Left JustifyMethod 3: Literal String Interpolation Space PaddingMethod 4: String ConcatenationSummaryPython One-Liners Book: Master the Single Line First!Related Posts Problem Formulation Given a Python string s with length k<=n. How to fill the string with n-k empty spaces on the left so that the

## How to Kill a While Loop with a Keystroke in Python?

To end a while loop prematurely in Python, press CTRL-C while your program is stuck in the loop. This will raise a KeyboardInterrupt error that terminates the whole program. To avoid termination, enclose the while loop in a try/except block and catch the KeyboardInterrupt. You can see the idea in the following code snippet: The

## Python Bitwise Left-Shift << Operator

The Python bitwise left-shift operator x << n shifts the binary representation of integer x by n positions to the left. For a positive integer, it inserts a 0 bit on the right and shifts all remaining bits by one position to the left. For example, if you left-shift the binary representation 0101 by one

## [Google Interview] The Gas Station Problem

🏗️ Company Tags: Google, Facebook, Amazon Are you gearing up for your coding interview? If your answer is yes, then here’s a very interesting interview question for you. Numerous programmers have claimed that they came across this interview question. Hence, there is a high probability that you might come across it as well in your interview. Will you be able

## Python Bitwise Right-Shift >> Operator

The Python bitwise right-shift operator x >> n shifts the binary representation of integer x by n positions to the right. It inserts a 0 bit on the left and removes the right-most bit. For example, if you right-shift the binary representation 0101 by one position, you’d obtain 0010. Semantically, the bitwise right-shift operator is

## Python Scikit-Learn Decision Tree [Video + Blog]

Decision Trees are powerful and intuitive tools in your machine learning toolbelt. Decision trees are human-readable – in contrast to most other machine learning techniques. You can easily train a decision tree and show it to your supervisors who do not need to know anything about machine learning in order to understand how your model

## Python Bitwise NOT Operator

Python’s bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1. For example, the bitwise NOT expression ~0 becomes -1, ~9 becomes -10, and ~32 becomes -33. As you go over the

## How to Convert a Boolean Array to an Integer Array in Python?

Table of Contents Problem FormulationMethod 1: Don’t Do ItMethod 2: Multiplication with 1Method 3: Use array.astype(int)Related Posts Problem Formulation Given a NumPy array consisting of Boolean values. How to convert it to an integer array? Convert each True value to integer 1, and Convet each False value to integer 0. Here’s an example Boolean array:

## How to Add a Second x-axis in Python Matplotlib?

Table of Contents Problem FormulationSolution: Matplotlib Axis.twiny()Related Posts Problem Formulation Given some data. How to plot the data in the same 2D plot but using two x-axes instead of only one? You want to have on top axis and one bottom axis. You want to be able to customize the ticks and labels of both

## Neural Networks with SKLearn MLPRegressor

Neural Networks have gained massive popularity in the last years. This is not only a result of the improved algorithms and learning techniques in the field but also of the accelerated hardware performance and the rise of General Processing GPU (GPGPU) technology. In this article, you’ll learn about the Multi-Layer Perceptron (MLP) which is one

## Python’s time.clock() Vs. time.time() – A Detailed Comparison

Table of Contents Introduction⏰time.time()⏰time.clock()➥Difference In Execution Speed✨REMEMBER: Benchmarking in Python❖ The timeit Module ConclusionRelated Posts Introduction Before we get into the detailed comparison between time.clock() vs. time.time(), there are some prerequisites that you need to focus upon. It is important to have knowledge about the various types of time in the computing world. Don’t worry if

## Creating a Port Scanner with Python Networking Sockets

This is in continuation of the first part of Python networking with sockets. In this blog post we will further learn how to use more socket API’s. We will dig deeper into what a networking port is. Then we start implementing a simple port scanner. Finally, we will enhance this port scanner further. For Part

## Python Bitwise XOR ^ Operator

Python’s bitwise XOR operator x ^ y performs logical XOR on each bit position on the binary representations of integers x and y. Each output bit evaluates to 1 if and only if exactly one of the two input bits at the same position are 1. For example, the integer expression 4 ^ 3 is

## Python Bitwise OR | Operator

Python’s bitwise OR operator x | y performs logical OR on each bit position on the binary representations of integers x and y. Each output bit evaluates to 1 if and only if at least one of the two input bits at the same position are 1. For example, the integer expression 4 | 3

## How to Remove Control Characters from a String in Python?

Table of Contents Problem FormulationWhat is a Control Character?Solution Based on Unicode CategoryRelated Posts Problem Formulation Given a string s. Create a new string based on s with all control characters such as ‘\n’ and ‘\t’ removed. What is a Control Character? A control character, also called non-printing character (NPC), is a character that doesn’t

## Python Delete File [Ultimate Guide]

Table of Contents Python Delete FilePython Delete Files in FolderPython Delete File shutilPython Delete Files WildcardPython Delete Files in Folder with ExtensionRelated Posts Python Delete File To delete a file in Python, import the os module with import os and run os.remove(filename) in your script. The following code removes the file ‘file.dat’ from the current

## How to Get the Current Time in Python?

Table of Contents Introduction⚽Method 1: Using The time Module❖ strftime❖ ctime⚽Method 2: Using The datetime Object⚽Method 3: Using The pytz Library⚽Method 4: Using The Pendulum ModuleConclusionRelated Posts Introduction As a programmer, you need to work on different time-based tasks in your program like logging and saving the records to the database and accessing the documents.

## Как преобразовать строку Юникода в строковый объект в Питоне?

Это руководство покажет вам, как преобразовать строку Юникода в строку в Питоне. Если вы уже знаете о Юникоде, вы можете пропустить следующий раздел, посвященный справочной информации, и сразу же погрузиться в проблему. Table of Contents Истоки ЮникодаФормулировка проблемыМетод 1. StringМетод 2. Repr()Метод 3. Модуль Unicodedata, функция normalizeМетод 4. Список и str.joinМетод 5. Библиотека ftfyМетод 6.

## Python Convert Unicode to Int, Python Convert Unicode to Float

In the previous article, we got acquainted with Unicode and methods of processing input Unicode strings, different ways of processing and converting them into a readable form – string objects in Python. Let’s look at ways of converting to other types of output data and applying different encodings to them. Table of Contents Problem FormulationFunction

## Конвертация символов Юникода в целое число и число с плавающей точкой в Питоне

В предыдущей статье мы познакомились с Юникодом и способами обработки входных юникодных строк, разным способам обработки и преобразования их в читаемый вид – объекты типа стринг в Питоне. Рассмотрим способы преобразования в другие типы выходных данных и применение различных кодировок к ним. Table of Contents Формулировка задачиФункция ord.Конвертация символов Юникода в число с плавающей точкойФункция

## Python Convert Unicode to Bytes, ASCII, UTF-8, Raw String

Table of Contents Python Convert Unicode to BytesMethod 1 Built-in function bytes()Method 2 Built-in function encode()Python Convert Unicode to ASCIIMethod 1 Built-in function decode()Method 2 Module unidecode()Python Convert Unicode to UTF-8Method 1 Built-in function encode() and decode()Method 2 Module unidecodeRelated Posts Python Convert Unicode to Bytes Converting Unicode strings to bytes is quite common these

## [Google Interview] The Two Sum Problem

🏗️ Company Tags: Google, Facebook, Amazon Are you gearing up for your coding interview? If your answer is yes, then here’s a very important and commonly asked interview question for you. Numerous programmers have claimed that they came across this interview question. Hence, there is a high probability that you might come across it as

## Python Bitwise AND Operator &

Python’s bitwise AND operator x & y performs logical AND on each bit position on the binary representations of integers x and y. Thus, each output bit is 1 if both input bits at the same position are 1, otherwise, it’s 0. For example, the integer expression 4 & 3 is translated to binaries 0100

## How to Count the Number of Occurrences of a Character in a Python String?

Table of Contents Problem FormulationMethod 1: str.count()Method 2: Regular ExpressionMethod 3: List Comprehension + len()Related Posts Problem Formulation Given a string s, and Given a character c. How many times does character c occur in the string s? Consider the following examples: INPUT s = ‘hello world’ c = ‘l’ OUTPUT 3 INPUT s =

## How to Get the Row with Minimal Variance in NumPy

You may have read about the ‘V’s in Big Data: Volume, Velocity, Variety, Veracity, Value, Volatility. Variance is yet another important ‘V’ (it measures Volatility of a data set). In practice, variance is an important measure with important application domains in financial services, weather forecasting, and image processing. Variance measures how much the data spreads

## How to Return Dictionary Keys as a List in Python?

Short answer: use the expression list(dict.keys()). Table of Contents Problem FormulationSolutionAlternative Solution with UnpackingPython One-Liners Book: Master the Single Line First!Related Posts Problem Formulation Given a dictionary that maps keys to values. Return the keys as a list. For example: Given dictionary {‘Alice’: 18, ‘Bob’, 21, ‘Carl’: 24} Return the keys as a list [‘Alice’,

## How to Concatenate Two NumPy Arrays?

Table of Contents Problem FormulationMethod 1: np.concatenate()Method 2: np.append()Method 3: np.vstack()ConclusionRelated Posts Problem Formulation Given two NumPy arrays a and b. How to concatenate both? Method 1: np.concatenate() NumPy’s concatenate() method joins a sequence of arrays along an existing axis. The first couple of comma-separated array arguments are joined. If you use the axis argument,

## Data Abstraction in Python – Simply Explained

A typical online search queries the meaning of data abstraction in Python. When I began learning Python, the answers I found caused more confusion than they solved. Today I will describe data abstraction in a clear way that will assist you in better understanding the concept. We will then apply that concept in code to

## How to Get the Full Path of the Current File Directory in Python?

Knowing where you are is important, whether you are in the outdoors, stumbling to the toilet in the middle of the night, or simply programming. Dealing with your midnight confusing or outdoors route-finding skills are a little more complicated, but fortunately, it is pretty easy to figure out your current path in Python. 🐍 Method

## [Interview Question] Reverse A Linked List

🏗️ Company Tags: As reported by numerous programmers across the globe, this question has been asked in coding interviews/rounds by companies like- Amazon Accolite Adobe Cisco Cognizant Goldman Sachs VMWare So, if you are preparing for your upcoming coding interview, then you might well come across this question in your coding round. Can you solve

## Python Not Operator

Python’s not operator returns True if the single operand evaluates to False, and returns False if it evaluates to True. Thus, it logically negates the implicit or explicit Boolean value of the operand. As you read through the article, you can also watch my video for supporting explanations: Table of Contents Python Not Operator on

## Reverse A Linked List In Python

#Approach 1: Iterative Approach to Reverse Linked List Test Cases: # Example 1 linked_list = Solution() linked_list.push(5) linked_list.push(4) linked_list.push(3) linked_list.push(2) linked_list.push(1) Output: Given linked list 1 2 3 4 5 Reversed linked list 5 4 3 2 1 # Example 2 linked_list = Solution() linked_list.push(5) linked_list.push(4) linked_list.push(3) linked_list.push(2) linked_list.push(1) Output: Given linked list 1 2

## [Solved] TypeError: method() takes 1 positional argument but 2 were given

From teaching hundreds of thousands of students Python, I found this error to be a classic. I think understanding classes is hard enough, but many coders who’ve just started to learn about Python are rightly confused 😖 about the TypeError that complains about too few positional arguments. Let’s resolve this confusion once and for all,

## How to Open Python .py Files in IDLE with a Doubleclick?

I love tweaking my coding workflow. Small improvements accumulate over time and can lead to a massive productivity increase. Today, I caught myself being annoyed that I always needed to spend three clicks or so just to open a Python file in IDLE, the default Python editor on Windows. Time to change that! Do you

## How to Find Path Where Python is Installed on Windows?

Windows normally installs Python on one of the two locations: C:\Python39 C:\Users\YourUser\AppData\Local\Programs\Python\Python39 For me, it’s the latter. For you, it may be different—this article shows you how to check for yourself! 🙂 For your convenience, I’ve made a short gif that shows how I rushed through the code on my Windows machine: Before you start,