Python Pool: Numpy Sin in Python with Illustrated Examples(11 hours, 27 minutes ago)

Hello coders!! In this article, we will be learning about NumPy sin in Python. We will be looking into certain examples and will use the function in different ways. So, without wasting any moment, let us begin.

Syntax:

It is a mathematical function, used to calculate the trigonometric sine for all x, where x is an array.

numpy.sin(x[, out]) = ufunc ‘sin’) 

Parameters:

  • array: array elements in radians.
2pi Radians = 360 degrees

Return Value:

  • An array with trigonometric sine of x for all x

Does numpy sin take radians or degrees?

The np.sin() function help to find the sine value of the angle in degree and radian. To get the sine value of the angle in radians, need to multiply the angle with np.pi/180.

Illustrated Examples:

example 1: Numpy sin with a single value:

np.sin(np.pi/2.)
1.0

As you can see, we calculated the value of sin(pi/2) using the sin() method of the NumPy module.

example 2: with an array of values:

import numpy as np 
inp = [0, np.pi / 2, np.pi / 3, np.pi] 
print ("Input array : \n", inp) 

opt = np.sin(inp) 
print ("\nSine values : \n", opt) 
With An Array Of ValuesOutput

In this example, we have used an array of elements as input. The different elements are:

  • 0
  • pi / 2
  • np.pi / 3
  • pi

We have then used the np sin method to calculate the sin value of all the corresponding elements. As said earlier, this method gives the sin value of each element of the array, thus giving the output as:

  • 0.00000000e+00
  • 1.00000000e+00
  • 8.66025404e-01
  • 1.22464680e-16

Example 4:  numpy sin degrees:

 np.sin(np.deg2rad(90))
1.0

To use the angles in degrees rather than radians, we have used the np.deg2rad() method. This method is used to convert angles from degrees to radians.

Syntax:

numpy.deg2rad(x[, out]) = ufunc ‘deg2rad’) 

example 5: numpy sin squared:

import numpy as np 
inp = [0, np.pi / 2, np.pi / 3, np.pi] 
print ("Input array : \n", inp) 

opt = np.sin(in_array) ** 2
print ("\nSine Square values : \n", opt) 
Numpy Sin SquaredOutput

In this example, we have squared the sine values by raising it to power 2 and stored the output in an array. We then printed the array to get the desired output.

example 6: np sin fit:

from scipy import optimize
x_data = np.linspace(-5, 5, num=50)
y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50)

def test_func(x, a, b):
    return a * np.sin(b * x)

pars, pars_co = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2])

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, test_func(x_data, pars[0], pars[1]))
plt.show()
Np Sin FitOutput

As you can see, in this example, we have used the numpy functions to create the data. We then used the sin method for the value of the y-axis. We then optimize the curve and fit the sine curve to get the desired output.

example 7: numpy generate sin wave plot:

import numpy as np 
import matplotlib.pyplot as plt 

inp = np.linspace(-np.pi, np.pi, 12) 
opt = np.sin(inp) 

plt.plot(inp, opt, color = 'green', marker = "o") 
plt.title("numpy.sin()") 
plt.show() 

Numpy Generate Sin Wave PlotOutput

Here, we have plotted the sine graph using the sin method, thus getting the sine graph as output.

Python np sin inverse:

numpy.arcsin() function helps user to calculate inverse sine for all x.

Syntax:

numpy.arcsin(x[, out]) = ufunc ‘arcsin’) 

Parameters:

  • array : elements in radians
  • out : array of same shape as x.

Return Value:

  • An array with inverse sine of x.
import numpy as np 

inp = [0, 1, 0.3, -1] 
print ("Input array : \n", inp) 

opt = np.arcsin(inp) 
print ("\nInverse Sine values : \n", opt) 
Python np sin inverseOutput

In this example, we have used the np.arcsin() method to find the inverse sin value of the elements of the array.

Numpy sin vs Math sin:

math.sin works on a single number, the numpy version works on numpy arrays and is tremendously faster due to the benefits of vectorization. 

Math SinNumPy Sin
works on a single numberworks on numpy arrays
relatively slowertremendously faster due to the benefits of vectorization
Syntax: math.sin(x)
x -> The number to find the sine of
Syntax: numpy.sin(x[, out]) = ufunc ‘sin’)
array -> array elements in radians.
import math
print(math.sin(math.radians(30)))
print(math.sin(math.radians(90)))
import numpy as np
inp = [0, np.pi / 2, np.pi / 3, np.pi]
opt = np.sin(inp)
print(opt)
0.49999999999999994
1.0
[0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]

Must Read

Conclusion:

With this, we come to an end with this article. I hope that this article clarified the concept of NumPy sin.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

The post Numpy Sin in Python with Illustrated Examples appeared first on Python Pool.

Mike Driscoll: PySimpleGUI – How to Draw Shapes on an Image with a GUI(12 hours, 25 minutes ago)

Drawing shapes on images is neat. But wouldn’t it be nice if you could draw the shapes interactively? That is the point of this tutorial. You will create a user interface using PySimpleGUI to allow you to draw shapes on images!

The purpose of this user interface is to show you how you can make a GUI that wraps some of the shapes that Pillow supports. The GUI won’t support all of them though. In fact, this GUI only supports the following:

  • ellipse
  • rectangle

The reason for this is that these two shapes take the same arguments. You can take on the challenge yourself to add the other shapes to the GUI!

When your GUI is finished, it will look like this:

PySimpleGUI Image Shape GUIPySimpleGUI Image Shape GUI

Getting Started

You will need PySimpleGUI and Pillow to be able to follow along with this tutorial. Here’s how to install them with pip:

python3 -m pip install PySimpleGUI pillow

Now you’re ready to create your GUI!

Creating the GUI

Now open up your Python editor and create a new file named drawing_gui.py. Then add this code to your new file:

# drawing_gui.py

import io
import os
import PySimpleGUI as sg
import shutil
import tempfile

from PIL import Image, ImageColor, ImageDraw

file_types = [("JPEG (*.jpg)", "*.jpg"), ("All files (*.*)", "*.*")]
tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg").name


def get_value(key, values):
    value = values[key]
    if value.isdigit():
        return int(value)
    return 0


def apply_drawing(values, window):
    image_file = values["-FILENAME-"]
    shape = values["-SHAPES-"]
    begin_x = get_value("-BEGIN_X-", values)
    begin_y = get_value("-BEGIN_Y-", values)
    end_x = get_value("-END_X-", values)
    end_y = get_value("-END_Y-", values)
    width = get_value("-WIDTH-", values)
    fill_color = values["-FILL_COLOR-"]
    outline_color = values["-OUTLINE_COLOR-"]

    if os.path.exists(image_file):
        shutil.copy(image_file, tmp_file)
        image = Image.open(tmp_file)
        image.thumbnail((400, 400))
        draw = ImageDraw.Draw(image)
        if shape == "Ellipse":
            draw.ellipse(
                (begin_x, begin_y, end_x, end_y),
                fill=fill_color,
                width=width,
                outline=outline_color,
            )
        elif shape == "Rectangle":
            draw.rectangle(
                (begin_x, begin_y, end_x, end_y),
                fill=fill_color,
                width=width,
                outline=outline_color,
            )
        image.save(tmp_file)

        bio = io.BytesIO()
        image.save(bio, format="PNG")
        window["-IMAGE-"].update(data=bio.getvalue())


def create_coords_elements(label, begin_x, begin_y, key1, key2):
    return [
        sg.Text(label),
        sg.Input(begin_x, size=(5, 1), key=key1, enable_events=True),
        sg.Input(begin_y, size=(5, 1), key=key2, enable_events=True),
    ]


def save_image(values):
    save_filename = sg.popup_get_file(
        "File", file_types=file_types, save_as=True, no_window=True
    )
    if save_filename == values["-FILENAME-"]:
        sg.popup_error(
            "You are not allowed to overwrite the original image!")
    else:
        if save_filename:
            shutil.copy(tmp_file, save_filename)
            sg.popup(f"Saved: {save_filename}")


def main():
    colors = list(ImageColor.colormap.keys())
    layout = [
        [sg.Image(key="-IMAGE-")],
        [
            sg.Text("Image File"),
            sg.Input(
                size=(25, 1), key="-FILENAME-"
            ),
            sg.FileBrowse(file_types=file_types),
            sg.Button("Load Image"),
        ],
        [
            sg.Text("Shapes"),
            sg.Combo(
                ["Ellipse", "Rectangle"],
                default_value="Ellipse",
                key="-SHAPES-",
                enable_events=True,
                readonly=True,
            ),
        ],
        [
            *create_coords_elements(
                "Begin Coords", "10", "10", "-BEGIN_X-", "-BEGIN_Y-"
            ),
            *create_coords_elements(
                "End Coords", "100", "100", "-END_X-", "-END_Y-"
            ),
        ],
        [
            sg.Text("Fill"),
            sg.Combo(
                colors,
                default_value=colors[0],
                key="-FILL_COLOR-",
                enable_events=True,
                readonly=True
            ),
            sg.Text("Outline"),
            sg.Combo(
                colors,
                default_value=colors[0],
                key="-OUTLINE_COLOR-",
                enable_events=True,
                readonly=True
            ),
            sg.Text("Width"),
            sg.Input("3", size=(5, 1), key="-WIDTH-", enable_events=True),
        ],
        [sg.Button("Save")],
    ]

    window = sg.Window("Drawing GUI", layout, size=(450, 500))

    events = [
        "Load Image",
        "-BEGIN_X-",
        "-BEGIN_Y-",
        "-END_X-",
        "-END_Y-",
        "-FILL_COLOR-",
        "-OUTLINE_COLOR-",
        "-WIDTH-",
        "-SHAPES-",
    ]
    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break
        if event in events:
            apply_drawing(values, window)
        if event == "Save" and values["-FILENAME-"]:
            save_image(values)
    window.close()


if __name__ == "__main__":
    main()

That’s a bunch of code! To make things easier, you will go over this code in smaller chunks.

The first chunk is the code at the top of the file:

# drawing_gui.py

import io
import os
import PySimpleGUI as sg
import shutil
import tempfile

from PIL import Image, ImageColor, ImageDraw

file_types = [("JPEG (*.jpg)", "*.jpg"), ("All files (*.*)", "*.*")]
tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg").name

These lines of code define the imports of the packages and modules that you need. It also sets up two variables:

  • file_types – Which you will use for browsing and saving your images
  • tmp_file – A temporary file that is created to save your intermediate image file

Now you can take a look at your first function:

def get_value(key, values):
    value = values[key]
    if value.is_digit():
        return int(value)
    return 0

This function is used to convert strings to integers. If you enter an alphabetical character or a special character, it will cause this code to throw an error. Feel free to catch those kinds of things here or implement a filter to prevent users from entering anything other than integers.

If the user empties the Element of its contents, you force it to return a zero. This allows the user interface to continue to function. Another improvement that you could add here is to take the image bounds into account. You could make it so that the user cannot enter negative numbers or numbers that are larger than the image.

The next function is a meaty one:

def apply_drawing(values, window):
    image_file = values["-FILENAME-"]
    shape = values["-SHAPES-"]
    begin_x = get_value("-BEGIN_X-", values)
    begin_y = get_value("-BEGIN_Y-", values)
    end_x = get_value("-END_X-", values)
    end_y = get_value("-END_Y-", values)
    width = get_value("-WIDTH-", values)
    fill_color = values["-FILL_COLOR-"]
    outline_color = values["-OUTLINE_COLOR-"]

    if image_file and os.path.exists(image_file):
        shutil.copy(image_file, tmp_file)
        image = Image.open(tmp_file)
        image.thumbnail((400, 400))
        draw = ImageDraw.Draw(image)
        if shape == "Ellipse":
            draw.ellipse(
                (begin_x, begin_y, end_x, end_y),
                fill=fill_color,
                width=width,
                outline=outline_color,
            )
        elif shape == "Rectangle":
            draw.rectangle(
                (begin_x, begin_y, end_x, end_y),
                fill=fill_color,
                width=width,
                outline=outline_color,
            )
        image.save(tmp_file)

        bio = io.BytesIO()
        image.save(bio, format="PNG")
        window["-IMAGE-"].update(data=bio.getvalue())

This code is used for creating the two shapes you want to draw on your image. It gets all the various settings that you need to create an ellipse or a rectangle. The settings that you can change are:

  • The image filename
  • The shape combobox
  • The beginning coordinates (-BEGIN_X-, -BEGIN_Y-)
  • The ending coordinates (-END_X-, -END_Y-)
  • The width of the outline
  • The fill color to be used (uses color names)
  • The outline color (uses color names)

If the user has opened up an image, then your code will automatically draw a shape using the default settings. When you edit any of those settings, this function will get called and the image will update.

Note: The drawing is applied to a thumbnail version of the image rather than a copy of the image. This is done to keep the image visible in your GUI. Many photos have a higher resolution than can be shown on a typical monitor.

The next function to look at is called create_coords_elements():

def create_coords_elements(label, begin_x, begin_y, key1, key2):
    return [
        sg.Text(label),
        sg.Input(begin_x, size=(5, 1), key=key1, enable_events=True),
        sg.Input(begin_y, size=(5, 1), key=key2, enable_events=True),
    ]

This function returns a Python list that contains three Elements in it. One label (sg.Text) and two text boxes (sg.Input). Because these elements are in a single list, they will be added as a horizontal row to your user interface.

Now you’re ready to go on to the save_image() function:

def save_image(values):
    save_filename = sg.popup_get_file(
        "File", file_types=file_types, save_as=True, no_window=True
    )
    if save_filename == values["-FILENAME-"]:
        sg.popup_error(
            "You are not allowed to overwrite the original image!")
    else:
        if save_filename:
            shutil.copy(tmp_file, save_filename)
            sg.popup(f"Saved: {save_filename}")

This function asks the user where to save your file. It will also prevent the user from trying to overwrite the original image.

The last function is your main() one:

def main():
    colors = list(ImageColor.colormap.keys())
    layout = [
        [sg.Image(key="-IMAGE-")],
        [
            sg.Text("Image File"),
            sg.Input(
                size=(25, 1), key="-FILENAME-"
            ),
            sg.FileBrowse(file_types=file_types),
            sg.Button("Load Image"),
        ],
        [
            sg.Text("Shapes"),
            sg.Combo(
                ["Ellipse", "Rectangle"],
                default_value="Ellipse",
                key="-SHAPES-",
                enable_events=True,
                readonly=True,
            ),
        ],
        [
            *create_coords_elements(
                "Begin Coords", "10", "10", "-BEGIN_X-", "-BEGIN_Y-"
            ),
            *create_coords_elements(
                "End Coords", "100", "100", "-END_X-", "-END_Y-"
            ),
        ],
        [
            sg.Text("Fill"),
            sg.Combo(
                colors,
                default_value=colors[0],
                key="-FILL_COLOR-",
                enable_events=True,
                readonly=True
            ),
            sg.Text("Outline"),
            sg.Combo(
                colors,
                default_value=colors[0],
                key="-OUTLINE_COLOR-",
                enable_events=True,
                readonly=True
            ),
            sg.Text("Width"),
            sg.Input("3", size=(5, 1), key="-WIDTH-", enable_events=True),
        ],
        [sg.Button("Save")],
    ]

    window = sg.Window("Drawing GUI", layout, size=(450, 500))

This is one of the most complex user interfaces you have written. It adds lots of Elements in rows. You can also see that you are using a special syntax to extract items from a list:

  • *create_coords_elements()

When you call create_coords_elements(), it returns a list. But you want both the beginning and ending coordinates on the same line. So you extract the elements from the list.

This little code example illustrates what is happening:

>>> def get_elements():
...     return ["element_one", "element_two"]
... 
>>> [*get_elements()]
['element_one', 'element_two']

If you don’t use the asterisk, you will end up with a nested list instead of a list that has three elements in it.

Here are the last few lines of code from the main() function:

    events = [
        "Load Image",
        "-BEGIN_X-",
        "-BEGIN_Y-",
        "-END_X-",
        "-END_Y-",
        "-FILL_COLOR-",
        "-OUTLINE_COLOR-",
        "-WIDTH-",
        "-SHAPES-",
    ]
    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break
        if event in events:
            apply_drawing(values, window)
        if event == "Save" and values["-FILENAME-"]:
            save_image(values)
    window.close()

if __name__ == "__main__":
    main()

The first line defines the events that you use to know when to update the drawing. The last conditional will save the image where the user chooses. Give your new GUI a try. Then you can start planning how you will improve it!

Wrapping Up

Now you have a handy tool for testing out a couple of Pillow’s drawing functions. You can make this GUI even better by adding some of Pillow’s other shapes to the mix. You could do that by adding a tabbed interface with the different options under different tabs, for example.

Give it a try and see what you can come up with!

Related Reading

Pillow: Image Processing with Python

Purchase now on Leanpub

 

 

The post PySimpleGUI – How to Draw Shapes on an Image with a GUI appeared first on Mouse Vs Python.

John Ludhi/nbshare.io: Python Lambda(16 hours, 50 minutes ago)

Python Lambda

The lambdas are anonymous one line functions in Python that can be used to perform tasks which don't require regular Python functions. Some of the most useful features of Python lambdas are...

  1. Lambda function can take any number of arguments
  2. Lambda functions are very short although can be very encryptic
  3. Lambda functions can be used to return function objects
  4. Lambda functions are restricted to only a single expression

Below snippet shows the basic syntax of a Python function. The below function takes "argument" and returns it back.

In [1]:
# normal function that returns a value
def functionName(argument):
    return argument

Lambda Function Definion

Example of above function "functionName" using Lambda

In [2]:
lambda argument : argument
Out[2]:
<function __main__.<lambda>(argument)>

Note the syntax of the above function. Lambda functions have no name. They are defined and used on the fly. We can't reuse them in the form defined above. The first 'argument' is the argument of the function and the 2nd 'argument' is the returned value.

Example: - Lambda function that returns the twice of the given input.

In [3]:
lambda x : x * 2
Out[3]:
<function __main__.<lambda>(x)>

But you must be wondering, how to provide the input to above lambda function!

Calling the Lambda Function

To use the function, you can surround it with parenthesis and provide the parameters between paranthesis as shown below.

In [4]:
(lambda x : x * 2) (5)
Out[4]:
10

This is how it works...

In [5]:
# (lambda x: x * 2 )(5) = lambda 5 : 5 * 2 = 5 * 2 = 10

There is another way to provide an argument to the lambda function. We can assign the lambda function to a variable and then pass the argument to that variable as shown below...

In [6]:
double = lambda x : x * 2
# and call it like so : 
double(5)
Out[6]:
10

Ofcourse above lambda function and below function are equivalent.

In [7]:
# the function double is equivalent to : 
def double(x):
    return x * 2

Lambda Functions With Mutiple Arguments

Python Lambda functions can have multipe parameters separated by commas (,) here is an example...

In [8]:
pairs = lambda  x , y : "P( x = "+str(x)+" , y = "+ str(y)+" )"
pairs(1,2)
Out[8]:
'P( x = 1 , y = 2 )'

There is a shorthand way of calling Python lambdas function that is without assigning a name to the function.

You can simply do this :

In [9]:
lambda a , b : a * b
Out[9]:
<function __main__.<lambda>(a, b)>

There will be no conflict and you can call the above lambda function with the arguments like this...

In [10]:
_(2,3)
Out[10]:
6

Note the underscore in the above syntax. Underscore refers to the lambda function that we just described above.

Ofcourse, you can use IIFE ( Immediately Invoked Function Expression ) syntax too.

In [11]:
(lambda a , b : a * b) (2,3)
Out[11]:
6

High order Functions

We can use function inside lambda. Below snippet is an example of lambda function inside another lambda function.

In [12]:
# we can use a function as a parameter of lambda : 
myfunction = lambda  param , func : param + func(param)
# and call it like so : 
myfunction(3,lambda  x : x**2)
Out[12]:
12

In the above snippet, we passed outer lambda function two parameters - param and another lambda function (func)

In [13]:
myfunction(4,lambda x : x - 1)
Out[13]:
7

Python lambda and Regular Functions

In [14]:
import dis
div = lambda x,y : x / y
type(div)
Out[14]:
function
In [15]:
dis.dis(div)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 BINARY_TRUE_DIVIDE
              6 RETURN_VALUE
In [16]:
div
Out[16]:
<function __main__.<lambda>(x, y)>
In [17]:
# applaying same thing for a normal function: 
import dis
def div(x,y):
    return x / y
type(div)
Out[17]:
function
In [18]:
dis.dis(div)
div
  4           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 BINARY_TRUE_DIVIDE
              6 RETURN_VALUE
Out[18]:
<function __main__.div(x, y)>

Lambda function Restrictions

Lambda functions throws similar errors as Python regular functions do. For example, below snippet will throw string multiplication error "can't multiply sequence by non-int of type 'str'"

In [19]:
type_error = lambda str1,str2 : str1 * str2
type_error("hello","world")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-17effbb67a31> in <module>
      1 type_error = lambda str1,str2 : str1 * str2
----> 2 type_error("hello","world")

<ipython-input-19-17effbb67a31> in <lambda>(str1, str2)
----> 1 type_error = lambda str1,str2 : str1 * str2
      2 type_error("hello","world")

TypeError: can't multiply sequence by non-int of type 'str'

Statements inside Lambda Function

We can't add statments in lambda function as shown below.

In [20]:
(lambda x : assert x > 0)(1)
  File "<ipython-input-20-9947f5245b98>", line 1
    (lambda x : assert x > 0)(1)
                     ^
SyntaxError: invalid syntax

However we can use parenthesis to achieve the statement effect.

In below snippet, note expression (x>0 and + or '-') would translate to if x > 0 then return '+' otherwise return '-'

In [21]:
(lambda x :  (x>0 and '+' or '-'))(-5)
Out[21]:
'-'

Type Annotation

Hinting doesn't work on lambda functions. It only works on normal functions.

Below regular Python function takes 'string' and 'integer' as two parameters but returns output as string.

In [22]:
def function(param:str,i : int)-> str:
    return param * str(i)

In lambda function, if you specify type hints, you will end up getting a syntaxError...

In [23]:
lambda param:str , i : int : param * i
  File "<ipython-input-23-c1c4c22920e0>", line 1
    lambda param:str , i : int : param * i
                               ^
SyntaxError: invalid syntax

*args and **kwargs in Python Lambda

As we described above in the 'multiple arguments section' of this post, Python lambda function can take multiple arguments but lambda functions can also take arguments using *arg and **kwargs

In [24]:
(lambda p1 , p2 , p3 : (p1 + p2  + p3)/3)(1,2,3)
Out[24]:
2.0
In [25]:
(lambda p1 , p2 , p3 = 3 : (p1 + p2  + p3)/3)(1,2)
Out[25]:
2.0

*args example

In [26]:
(lambda *args : sum(args)/len(args))(1,2,3)
Out[26]:
2.0

**kwargs example

In [27]:
(lambda **kwargs : sum(kwargs.values())/len(kwargs))(one = 1, two = 2, three = 3)
Out[27]:
2.0

Python lambdas initialize arguments example

In [28]:
(lambda p1 , p2=0 , p3=0 : (p1 + p2  + p3)/3 ) ( 1 , p2=2 , p3=3)
Out[28]:
2.0

Decorator in Python Lambda Function

Let us see first, how decorators in regular Python functions work. Here is an example...

In [29]:
# Defining a decorator
def trace(f):
    def wrap(*args, **kwargs):
        print(f"[TRACE] function name: {f.__name__}, arguments: {args}, kwargs: {kwargs}")
        return f(*args, **kwargs)

    return wrap

# Applying decorator to a function
@trace
def double(x):
    return x * 2

# Calling the decorated function
double(3)
[TRACE] function name: double, arguments: (3,), kwargs: {}
Out[29]:
6

Check out below example of application of decorator to a lambda function. Notice in the below snippet, how we have wrapped the lambda function inside the trace decorator function. Order of brackets is very important.

In [30]:
print((trace(lambda x: x * 2))(3))
[TRACE] function name: <lambda>, arguments: (3,), kwargs: {}
6

Python lambda with map and filter

Lambda is regularly used with built-in functions like map or filter.

Python map

map iterates the function through a list or set. The function could be regular Python function or lambda function.

In the below example,lambda function x: x + 5 is applied on list of numbers (0,4)

In [31]:
list(map(lambda x : x + 5 ,range(5)))
Out[31]:
[5, 6, 7, 8, 9]

Python filter

In the below example,lambda function x: x > 0 is applied on list of numbers [-5,-2,1,0,3,5]

In [32]:
list(filter(lambda x : x>0,[-5,-2,1,0,3,5]))
Out[32]:
[1, 3, 5]

Decorators in lamda with Python map

In below snippet, map() is taking two arguments. The first one is the decorator function around lambda function i.e.

trace(lambda x: x * 2) and second argument is range(3).

The map() will run the decorated lambda function 3 times as shown below.

In [33]:
list(map(trace(lambda x: x * 2), range(3)))
[TRACE] function name: <lambda>, arguments: (0,), kwargs: {}
[TRACE] function name: <lambda>, arguments: (1,), kwargs: {}
[TRACE] function name: <lambda>, arguments: (2,), kwargs: {}
Out[33]:
[0, 2, 4]

Testing Python Lambda with Unittest

In [ ]:
import unittest
double = lambda x : x * 2

class Test(unittest.TestCase):
    def test_1(self):
        self.assertEqual(double(1),2)
    
    def test_2(self):
        self.assertEqual(double(2),4)
    
    def test_10(self):
        self.assertEqual(double(10),11) # this test will fail

if __name__ == '__main__':
    unittest.main(verbosity=2)
In [36]:
double = lambda x : x * 2
double.__doc__ = """Doubles the number entred in the parameters :
>>> double(1)
2

>>> double(2.0)
4.0

>>> double(10)
20
"""

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)
Trying:
    double(1)
Expecting:
    2
ok
Trying:
    double(2.0)
Expecting:
    4.0
ok
Trying:
    double(10)
Expecting:
    20
ok
16 items had no tests:
    __main__
    __main__.Test
    __main__.Test.test_1
    __main__.Test.test_10
    __main__.Test.test_2
    __main__._16
    __main__._2
    __main__._3
    __main__._9
    __main__.div
    __main__.function
    __main__.functionName
    __main__.myfunction
    __main__.pairs
    __main__.trace
    __main__.type_error
1 items passed all tests:
   3 tests in __main__.double
3 tests in 17 items.
3 passed and 0 failed.
Test passed.

Python Lambda raise Exception

Here is how regular Python function raises exception.

In [37]:
def throw(excep): 
    raise excep

Here is how lambda functions can raise exception.

In [38]:
(lambda : throw(Exception("my error")))()
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-38-2dcbdacea675> in <module>
----> 1 (lambda : throw(Exception("my error")))()

<ipython-input-38-2dcbdacea675> in <lambda>()
----> 1 (lambda : throw(Exception("my error")))()

<ipython-input-37-5de1b89d45c1> in throw(excep)
      1 def throw(excep):
----> 2     raise excep

Exception: my error

Lambda Cryptic Code Using underscore

Let us look at below example. In here (lambda : * 2) _ refers to a variable or parameter.

In [39]:
(lambda _ : _  * 2)(11)
Out[39]:
22

Let us take at following more cryptic code example. In below code, there are two Python lambda functions. The parameter _ is being used inside both lambda functions.

In [40]:
(lambda _ : list(map(lambda _ : _  * 2,_)))(range(11))
Out[40]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [41]:
# the underscore (_) is the variable 
# to simplify, the function should be like this : 
(lambda myList : list(map(lambda element : element  * 2,myList)))(range(11))
Out[41]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Here is how it works.

lambda 0 : list(map(lambda : *2,0)) \ lambda 0 : list(0) \ 0

lambda 1: list(map(lambda : *2, 1)) \ lambda 1: list(2) \ 2 \ ....

Here is the above code in a regular Pythonic way...

In [42]:
# regular functions will make it easy due to their multiline format
def doubleItems(myList):
    double = lambda x : x * 2
    return map(double , myList)
list(doubleItems(range(11)))
Out[42]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Python lambda using Key function

In [43]:
# let's sort a list of strings that have a char a space and an int based ont he value of the integer
myList =["a 1","b 45","x 11","r 16"]
print(sorted(myList))
print(sorted(myList,key = lambda x : int(x[2:])))
['a 1', 'b 45', 'r 16', 'x 11']
['a 1', 'x 11', 'r 16', 'b 45']

Timeit lambda function

In [44]:
from timeit import timeit
timeit(lambda :sum(range(99999)), number=10)
# this silution is cleaner and more readable
Out[44]:
0.013398005161434412

TestDriven.io: Running Flask on Docker Swarm(20 hours, 2 minutes ago)

This post looks at how to run a Flask app on Docker Swarm.

PyCoder’s Weekly: Issue #461 (Feb. 23, 2021)(23 hours ago)

#461 – FEBRUARY 23, 2021
View in Browser »

The PyCoder’s Weekly Logo


Python Concurrency: The Tricky Bits

An exploration of threads, processes, and coroutines in Python, with interesting examples that illuminate the differences between each.
HAMEL HUSAIN

Why You Really Need to Upgrade Pip

If you’re using an old version of pip, installing the latest version of a Python package might fail—or install in a slower, more complex way. Learn what the problem is exactly, how to solve it, and what causes it.
ITAMAR TURNER-TRAURING

Monitor Python Application Metrics and Distributes Traces in Real Time with Datadog APM

alt

Datadog’s APM generates detailed flame graphs that will help your teams identify bottlenecks and latency. If an error is spotted, you can easily pivot to related logs and metrics in seconds to troubleshoot without switching tools or contexts. Visualize Python metrics end-to-end with a free trial →
DATADOG sponsor

12 Requests Per Second in Python

How much should we trust framework benchmarks? And to what extent should they influence your choice of technology?
SUADE.ORG

Python & APIs: A Winning Combo for Reading Public Data

Learn what APIs are and how to consume them using Python. You’ll also learn some core concepts for working with APIs, such as status codes, HTTP methods, using the requests library, and much more.
REAL PYTHON

How Python Strings Work

Learn the ins and outs of how Python strings work, with a focus on how text is encoded and represented internally.
VIKTOR SKVORTSOV

Python 3.X Through 3.9.1 Has a Buffer Overflow That May Lead to Remote Code Execution

Upgrade to 3.8.8 or 3.9.2 to avoid the issue.
NIST.GOV

Discussions

Happy Birthday, Python!

REDDIT

A Look Back at Python’s First Beta Release

In celebration of Python’s 30th anniversary, Stefane Fermigier has posted the code for Python’s first beta release on GitHub.
TWITTER.COM/SFERMIGIER

From print('Hello World!') to Getting My First Job

REDDIT

Python Jobs

alt

How Strong Is Your Resume?

sponsor

Get a free, confidential review from a resume expert →

Senior Backend Developer (Berlin, Germany)

orderbird AG

Advanced Python Engineer (Newport Beach, CA, USA)

Research Affiliates

Senior Python Engineer (Remote)

EAB

Web developer (Berlin, Germany)

der Freitag Mediengesellschaft mbh & Co. KG

More Python Jobs >>>

Articles & Tutorials

Happy Birthday, Python, You’re 30 Years Old This Week!

Via interviews with Armin Ronacher, Brett Cannon, and Ewa Jodloski, this piece of technical journalism takes a look at where Python has been, where it is, and where it is going.
THOMAS CLABURN

Python Programming and Numerical Methods: A Guide for Engineers and Scientists

This open-source book from Berkeley discusses numerical methods with Python. Numerical methods are essential for engineering and science, making this book a fantastic resource for folks in STEM fields.
QINGKAI KING, TIMMY SIAUW, ALEXANDRE BAYEN

Last chance! Download Your Free Digital Copy of Distributed Tracing in Practice

alt

February 28 is the last day to download a digital copy of Distributed Tracing in Practice, published by O’Reilly Media and available at no cost, compliments of Lightstep →
LIGHTSTEP sponsor

Abstract Syntax Trees in Python

Learn about abstract syntax trees (ASTs), some of their use cases, and how to use the ast module in the Python standard library.
ALESSANDRO FINAMORE • Shared by Bob Belderbos

Stochastic Gradient Descent and Deploying Your Python Scripts on the Web

Do you know the initial steps to get your Python script hosted on the web? You may have built something with Flask, but how would you stand it up so that you can share it with others? This week on the show, guest Martin Breuss shares his recent article titled, “Python Web Applications: Deploy Your Script as a Flask App”. David Amos also returns, and he’s brought another batch of PyCoder’s Weekly articles and projects.
REAL PYTHON podcast

Automating Code Performance Testing Now Possible

Performance is a feature, test it as such. Test performance in CI/CD. Validate production deploys. Blackfire offers a robust way to run test scenarios and validate code changes, automatically. Discover Blackfire Builds now. Free 15 days trial.
BLACKFIRE sponsor

Dictionaries and Arrays: Selecting the Ideal Data Structure

Learn about two of Python’s data structures: dictionaries and arrays. You’ll look at multiple types and classes for both of these and learn which implementations are best for your specific use cases.
REAL PYTHON course

Functional Programming in Python: When and How to Use It

Learn what functional programming is, how it’s supported in Python, and how you can use it in your Python code.
REAL PYTHON

Understand Django: Test Your Apps

Learn how to use automated tests to verify the correctness of your Django site.
MATT LAYMAN • Shared by Matt Layman

Adding Charts to Django with Chart.js

Learn how to add interactive charts to Django with Chart.js.
NIK TOMAZIC • Shared by Michael Herman

Projects & Code

scikit-image: Image Processing in Python

GITHUB.COM/SCIKIT-IMAGE

python-precisely: Better Assertions for Python Tests

GITHUB.COM/MWILLIAMSON

Freewire: An Experiment With “Freely” Wired Neural Networks

GITHUB.COM/NOAHTREN

CompreFace: Free and Open-Source Face Recognition System

GITHUB.COM/EXADEL-INC

eth2.0-specs: Ethereum 2.0 Specifications

GITHUB.COM/ETHEREUM

metaflow: Build and Manage Real-Life Data Science Projects With Ease

GITHUB.COM/NETFLIX

ptpython: A Better Python REPL

GITHUB.COM/PROMPT-TOOLKIT

orator: A Simple Yet Beautiful ActiveRecord Implementation

GITHUB.COM/SDISPATER

Events

Real Python Office Hours (Virtual)

February 24, 2020
REALPYTHON.COM

Python Web Conference 2021 (Virtual)

March 22 – 26, 2021
PYTHONWEBCONF.COM

PyCon Israel 2021 (Virtual)

May 2 – 3, 2021
PYCON.ORG.IL

PyCon 2021 (Virtual)

May 12 – 18, 2021
PYCON.ORG

DjangoCon Europe 2021 (Virtual)

June 2 – 6, 2021
DJANGOCON.EU


Happy Pythoning!
This was PyCoder’s Weekly Issue #461.
View in Browser »

alt

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Mike Driscoll: Drawing Shapes on Images with Python and Pillow(1 day, 2 hours ago)

Pillow provides a drawing module called ImageDraw that you can use to create simple 2D graphics on your Image objects. According to Pillow’s documentation, “you can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.”

If you need more advanced drawing capabilities than what is included in Pillow, you can get a separate package called aggdraw.

You will focus on what comes with Pillow in this article. Specifically, you will learn about the following:

  • Common Parameters
  • Drawing Lines
  • Drawing Arcs
  • Drawing Chords
  • Drawing Ellipses
  • Drawing Pie Slices
  • Drawing Polygons
  • Drawing Rectangles

When drawing with Pillow, it uses the same coordinate system that you have been using with the rest of Pillow. The upper left corner is still (0,0), for example. If you draw outside of the image bounds, those pixels will be discarded.

If you want to specify a color, you can use a series of numbers or tuples as you would when using PIL.Image.new(). For “1”, “L”, and “I” images, use integers. For “RGB” images, use a 3-tuple containing integer values. You may also use the color names that are supported by Pillow that you learned about in chapter 2.

Common Parameters

When you go to use the various drawing methods, you will discover that they have a lot of common parameters that they share. Rather than explain the same parameters in every section, you will learn about them up-front!

xy

Most of the drawing methods have an xy parameter that sets a rectangular area in which to draw a figure. This can be defined in the following two ways:

  • ((upper left x, upper left y), (lower right x, lower right y)) or simply ((x1, y1), (x2, y2))
  • A box tuple of (x1, y1, x2, y2)

When it comes to drawing a line, polygon, or point, multiple coordinates are specified in either of these ways:

  • (x1, y1, x2, y2, x3, y3...)
  • ((x1, y1), (x2, y2), (x3, y3)...)

The line() method will draw a straight line, connecting each point. The polygon() will draw a polygon where each point is connected. Finally, the point() will draw a point of 1-pixel at each point.

fill

The parameter, fill, is used to set the color that will fill the shape. The way you set the fill is determined by the mode of the image:

  • RGB: Set each color value (0-255) using (R, G, B) or a color name
  • L (grayscale): Set a value (0-255) as an integer

The default is None or no fill.

outline

The outline sets the border color of your drawing. Its specification is the same as the one you use for fill.

The default is None, which means no border.

Now that you know about the common parameters, you can move on and learn how to start drawing!

Drawing Lines

The first type of drawing you will learn about is how to draw lines in Pillow. All shapes are made up of lines. In Pillow’s case, a line is drawn by telling Pillow the beginning and ending coordinates to draw the line between. Alternatively, you can pass in a series of XY coordinates and Pillow will draw lines to connect the points.

Following is the line() method definition:

def line(self, xy, fill=None, width=0, joint=None):
    """Draw a line, or a connected sequence of line segments."""

You can see that it accepts several different parameters. You learned what some of these parameters mean in the previous section. The width parameter is used to control the width of the lines.

Before you learn how to use joint, you should learn how to draw lines without it. But first, you will need an image to draw on. You will use this image of one of the Madison County bridges:

Madison County Covered BridgeMadison County Covered Bridge

Now go open up your Python editor and create a new file named draw_line.py  and add this code to it:

# draw_line.py

import random
from PIL import Image, ImageDraw


def line(image_path, output_path):
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)
    colors = ["red", "green", "blue", "yellow",
              "purple", "orange"]

    for i in range(0, 100, 20):
        draw.line((i, 0) + image.size, width=5, 
                  fill=random.choice(colors))

    image.save(output_path)

if __name__ == "__main__":
    line("madison_county_bridge_2.jpg", "lines.jpg")

Here you open up the image in Pillow and then pass the Image object to ImageDraw.Draw(), which returns an ImageDraw object. Now you can draw lines on your image. In this case, you use a for loop to draw five lines on the image. The beginning image starts at (0,0) in the first loop. Then the X position changes in each iteration. The endpoint is the size of the image.

You use the random module to choose a random color from a list of colors. When you run this code, the output will look something like this:

Lines drawn on an imageLines drawn on an image

Now you can try creating a series of points and drawing lines that way. Create a new file named draw_jointed_line.py and put this code in your file:

# draw_jointed_line.py

from PIL import Image, ImageDraw


def line(output_path):
    image = Image.new("RGB", (400, 400), "red")
    points = [(100, 100), (150, 200), (200, 50), (400, 400)]
    draw = ImageDraw.Draw(image)
    draw.line(points, width=15, fill="green", joint="curve")
    image.save(output_path)

if __name__ == "__main__":
    line("jointed_lines.jpg")

This time you create an image using Pillow rather than drawing on one of your own. Then you create a list of points. To make the line connections look nicer, you can set the joint parameter to “curve”. If you look at the source code for the line() method, you will find that “curve” is the only valid value to give it other than None. This may change in a future version of Pillow.

When you run this code, your image will look like this:

 

Jointed linesDrawing jointed lines

Now try removing the joint parameter from your code and re-run the example. Your output will now look like this:

Lines without jointsLines without joints

By setting joint to “curve”, the output will be slightly more pleasing to the eye.

Now you’re ready to learn about drawing arcs with Pillow!

Drawing Arcs

An arc is a curved line. You can draw arcs with Pillow too. Here is the arc() method specification:

def arc(self, xy, start, end, fill=None, width=1):
    """Draw an arc."""

An arc() can also be made using xy points. The start parameter defines the starting angle, in degrees. The end parameter tells Pillow what the ending angle is, which is also in degrees. The other two parameters are ones that have already been introduced.

To see how you might draw an arc, create a new file named draw_arc.py and add this code to it:

# draw_arc.py

from PIL import Image, ImageDraw


def arc(output_path):
    image = Image.new("RGB", (400, 400), "white")
    draw = ImageDraw.Draw(image)
    draw.arc((25, 50, 175, 200), start=30, end=250, fill="green")

    draw.arc((100, 150, 275, 300), start=20, end=100, width=5, 
             fill="yellow")

    image.save(output_path)

if __name__ == "__main__":
    arc("arc.jpg")

In this code, you create a new image with a white background. Then you create your Draw object. Next, you create two different arcs. The first arc will be filled with green. The second arc will be filled in yellow, but its line width will be 5. When you draw an arc, the fill is referring to the arc’s line color. You aren’t filling the arc itself.

When you run this code, your output image will look like this:

Drawing arcsDrawing arcs

Try changing some of the parameters and re-running the code to see how you can change the arcs yourself.

Now let’s move on and learn about drawing chords!

Drawing Chords

Pillow also supports the concept of chords. A chord is the same as an arc except that the endpoints are connected with a straight line.

Here is the method definition of chord():

def chord(self, xy, start, end, fill=None, outline=None, width=1):
    """Draw a chord."""

The only difference here is that you can also add an outline color. This color can be specified in any of the ways that you can specify a fill color.

Create a new file and name it draw_chord.py. Then add this code so you can see how you make chords yourself:

# draw_chard.py

from PIL import Image, ImageDraw


def chord(output_path):
    image = Image.new("RGB", (400, 400), "green")
    draw = ImageDraw.Draw(image)
    draw.chord((25, 50, 175, 200), start=30, end=250, fill="red")

    draw.chord((100, 150, 275, 300), start=20, end=100, width=5, fill="yellow",
                outline="blue")

    image.save(output_path)

if __name__ == "__main__":
    chord("chord.jpg")

This example will draw two chords on a green image. The first chord is filled in with a red color. The second chord is filled in with yellow but is outlined in blue. The blue outline has a width of 5.

When you run this code, you will create the following image:

Drawing chordsDrawing chords

That looks pretty good. Go ahead and play around with this example too. You’ll soon master chord making with Pillow with a little practice.

Now let’s continue and learn about drawing ellipses!

Drawing Ellipses

An ellipse, or oval, is drawn in Pillow by giving it a bounding box (xy). You have seen this several other times in previous sections.

Here is the ellipse() method definition:

def ellipse(self, xy, fill=None, outline=None, width=1):
    """Draw an ellipse."""

The ellipse() lets you fill it with a color, add a colored border (outline) and change the width of that outline.

To see how you can create an ellipse(), make a new file named draw_ellipse.py and add this code to it:

# draw_ellipse.py

from PIL import Image, ImageDraw


def ellipse(output_path):
    image = Image.new("RGB", (400, 400), "white")
    draw = ImageDraw.Draw(image)
    draw.ellipse((25, 50, 175, 200), fill="red")

    draw.ellipse((100, 150, 275, 300), outline="black", width=5,
                 fill="yellow")

    image.save(output_path)

if __name__ == "__main__":
    ellipse("ellipse.jpg")

In this code, you create a nice white image via the new() method. Then you draw a red ellipse on top of it. Finally, you draw a second ellipse that is filled with yellow and outlined in black where the outline width is set to 5.

When you run this code, the image it creates will look like this:

Drawing ellipsesDrawing ellipses

You can create ovals and circles using ellipse(). Give it a try and see what you can do with it.

Now let’s find out how to create pie slices!

Drawing Pie Slices

A pie slice is the same as arc()), but also draws straight lines between the endpoints and the center of the bounding box.

Here is how the pieslice() method is defined:

def pieslice(self, xy, start, end, fill=None, outline=None, width=1):
    """Draw a pieslice."""

You have used all of these parameters in other drawings. To review, fill adds color to the inside of the pieslice() while outline adds a colored border to the figure.

To start practicing this shape, create a new file named draw_pieslice.py and add this code to your file:

# draw_pieslice.py

from PIL import Image, ImageDraw


def pieslice(output_path):
    image = Image.new("RGB", (400, 400), "grey")
    draw = ImageDraw.Draw(image)
    draw.pieslice((25, 50, 175, 200), start=30, end=250, fill="green")

    draw.pieslice((100, 150, 275, 300), start=20, end=100, width=5, 
                  outline="yellow")

    image.save(output_path)

if __name__ == "__main__":
    pieslice("pieslice.jpg")

In this code, you generate a grey image to draw on. Then you create two pie slices. The first pieslice() is filled in with green. The second one is not filled in, but it does have a yellow outline. Note that each pieslice() has a different starting and ending degree.

When you run this code, you will get the following image:

Drawing pie slicesDrawing pie slices

With a little work, you could create a pie graph using Pillow! You should play around with your code a bit and change some values. You will quickly learn how to make some nice pie slices of your own.

Now let’s find out how to draw polygons with Pillow!

Drawing Polygons

A polygon is a geometric shape that has a number of points (vertices) and an equal number of line segments or sides. A square, triangle, and hexagon are all types of polygons. Pillow lets you create your own polygons. Pillow’s documentation defines a polygon like this: The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate.

Here is the code definition of the polygon() method:

def polygon(self, xy, fill=None, outline=None):
    """Draw a polygon."""

All of these parameters should be familiar to you now. Go ahead and create a new Python file and name it draw_polygon.py. Then add this code:

# draw_polygon.py

from PIL import Image, ImageDraw


def polygon(output_path):
    image = Image.new("RGB", (400, 400), "grey")
    draw = ImageDraw.Draw(image)
    draw.polygon(((100, 100), (200, 50), (125, 25)), fill="green")

    draw.polygon(((175, 100), (225, 50), (200, 25)),
                  outline="yellow")

    image.save(output_path)

if __name__ == "__main__":
    polygon("polygons.jpg")

This code will create a grey image like the last example in the previous section. It will then create a polygon that is filled with the color green. Then it will create a second polygon and outline it in yellow without filling it.

In both of the drawings, you are supplying three points. That will create two triangles.

When you run this code, you will get this output:

Drawing polygonsDrawing polygons

Try changing the code by adding additional points to one or more of the polygons in the code above. With a little practice, you’ll be able to create complex polygons quickly with Pillow.

Drawing Rectangles

The rectangle() method allows you to draw a rectangle or square using Pillow. Here is how rectangle() is defined:

def rectangle(self, xy, fill=None, outline=None, width=1):
    """Draw a rectangle."""

You can pass in two tuples that define the beginning and ending coordinates to draw the rectangle. Or you can supply the four coordinates as a box tuple (4-item tuple). Then you can add an outline, fill it with a color, and change the outline’s width.

Create a new file and name it draw_rectangle.py. Then fill it in with this code so you can start drawing rectangles:

# draw_rectangle.py

from PIL import Image, ImageDraw


def rectangle(output_path):
    image = Image.new("RGB", (400, 400), "blue")
    draw = ImageDraw.Draw(image)
    draw.rectangle((200, 100, 300, 200), fill="red")
    draw.rectangle((50, 50, 150, 150), fill="green", outline="yellow",
                   width=3)
    image.save(output_path)

if __name__ == "__main__":
    rectangle("rectangle.jpg")

This code will create a blue image that is 400×400 pixels. Then it will draw two rectangles. The first rectangle will be filled with red. The second will be filled with green and outlined with yellow.

When you run this code, you will get this image as output:

Drawing rectanglesDrawing rectangles

Aren’t those lovely rectangles? You can modify the rectangle’s points to create thinner or wider rectangles. You could also modify the outline width that you add to the rectangles.

Wrapping Up

You can use Pillow to add shapes to your images. This can be helpful for adding outlines to your images, highlighting one or more portions of your image, and more.

In this article, you learned about the following topics:

  • Common Parameters
  • Drawing Lines
  • Drawing Arcs
  • Drawing Chords
  • Drawing Ellipses
  • Drawing Pie Slices
  • Drawing Polygons
  • Drawing Rectangles

You can do a lot with the shapes that are provided by Pillow. You should take these examples and modify them to test them out with your own photos. Give it a try and see what you can come up with!

Related Reading

 

Pillow: Image Processing with Python

Purchase now on Leanpub

The post Drawing Shapes on Images with Python and Pillow appeared first on Mouse Vs Python.

Real Python: Dictionaries and Arrays: Selecting the Ideal Data Structure(1 day, 4 hours ago)

There are a variety of ways of storing and managing data in your Python programs, and the choice of the right data structure will affect the readability of your code, ease of writing, and performance. Python has a wide variety of built-in mechanisms that meet most of your data structure needs.

This course introduces you to two types of data structures: dictionaries and arrays. There are multiple types and classes for both of these data structures and this course discusses them and provides information on how to choose the ideal one.

In this course you’ll learn about:

  • What are the advantages of using the built-in dict type
  • What are four other types of dictionaries
  • How list and tuple types are arrays
  • What are typed arrays and how can they save memory
  • How strings are arrays and what that implies
  • What are the different arrays for storing binary data
  • What are the practical uses for the different types
  • How to select the ideal data structure for your programs

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Python Software Foundation: Python Developers Survey 2020 Results: Learn about the Community(1 day, 6 hours ago)

We are excited to share the results of the fourth official Python Developers Survey conducted by the Python Software Foundation with the help of JetBrains.

More than 28,000 Python users from almost 200 countries took part in the survey this past October. With the help of the data collected, we are able to present the summarized results, identify the latest trends, and create a Python developer profile.


View the results of Python Developers Survey 2020!


The survey results cover a broad list of topics, including the main purposes of Python usage, the most popular frameworks, libraries, tools, and languages, among many other insights.


In all likelihood, there are plenty of potential findings that were not included in the report. If you have specific questions that are unanswered, send them to us and we’ll dig into the data for additional analysis. You also have the opportunity to delve deeper into the raw survey data and uncover your own amazing facts.


We’ll be glad to learn about your findings! Please share them on Twitter or other social media, mentioning @jetbrains‏ and @ThePSF with the #pythondevsurvey hashtag. We’re also very open to any suggestions and feedback related to this survey which could help us run an even better one next time. Feel free to open issues here with any comments or questions.


Many thanks to everyone who participated in the survey and helped us map an accurate landscape of the Python world!


Codementor: How To Switch Tabs In A Browser Using Selenium Python?(1 day, 9 hours ago)

Selenium automation has made life much easier for automation testers, especially with cases like Python Selenium switch tab automation. In this blog, we dig deeper into how to perform Selenium switch&hellip;

Python Pool: Understanding Collatz Sequence in Python(1 day, 11 hours ago)

Hello coders!! In this article, we will be learning about the collatz sequence in Python. We will first understand what it means. Then we will follow it by understanding the implementation of the collatz sequence in Python. So, let us get straight into the topic.

What is the collatz sequence?

Suppose there is a positive integer n. Then the next term of the collatz sequence will be as follows:

  • If the previous term is even, the next term is half of the previous term, i.e., n/2
  • If the previous term is odd, the next term is 3 times the previous term plus 1, i.e., 3n+1
  • The conjecture is that no matter what value of n, the sequence will always reach 1

Illustration of collatz sequence:

Let us consider the first number of the sequence to be 3.

2nd Term:

  • The previous term is 3, which is odd.
  • So, the next term will be (3*3 + 1) 10.

3rd Term:

  • The previous term is 10, which is even
  • So, the next term will be (10/2) 5.

4th Term:

  • The previous term is 5, which is odd.
  • So, the next term will be (3*5 + 1) 16.

5th Term:

  • The previous term is 16, which is even
  • So, the next term will be (16/2) 8.

6th Term:

  • The previous term is 8, which is even
  • So, the next term will be (8/2) 4.

7th Term:

  • The previous term is 4, which is even
  • So, the next term will be (4/2) 2.

8th Term:

  • The previous term is 2, which is even
  • So, the next term will be (2/2) 1.

As we have reached the value 1, the sequence is now complete.

 3, 10, 5, 16, 8, 4, 2, 1

Collatz conjecture function in python:

def Collatz(n): 

	while n != 1: 
		print(n, end = ', ') 

		if n &amp; 1: 
			n = 3 * n + 1

		else: 
			n = n // 2
	print(n) 

Collatz(21) 

Output:

21, 64, 32, 16, 8, 4, 2, 1

This is a straightforward code that we have used to implement Python’s collatz sequence. We have defined a function Collatz() that takes in an integer variable as input. Then we have used a while loop to print the sequence. We first check the nth term. If it is even, we change it to n/2. Else, we change it to 3n+1 and print that term. We continue this process till the number becomes 1, giving the desired output.

 Collatz conjecture Python recursion:

def collatz(n):
    list1 = [n]
    if n == 1 :
        return [1]                 
    elif n % 2 == 0 :
        
        list1.extend(collatz(n//2))     
    else:
        list1.extend(collatz(n*3+1))    
    return list1

collatz(21)

Output:

[21, 64, 32, 16, 8, 4, 2, 1]

In this code, we have used recursion to obtain the collatz sequence. We check the parameter that is passed to the collatz() function. If it is 1, i.e., the last term of the sequence, then recursion is stopped, and 1 is returned in the list. Otherwise, if the element is even, the collatz() function is recursively called with the value n/2, and the result is extended to the list. However, if the element is odd, the collatz() function is recursively called with the value 3*n+1, and the result is extended to the list. In the end, the list is returned, giving the desired result.

Longest collatz sequence python:

import time
start = time.time()
# to cache the values
cache = {n: 0 for n in range(1,1000000)}
# initial values
cache[1] = 1
cache[2] = 2
# looping through the numbers
for n in range(3,1000000):
    counter = 0
    current = n
    while n > 1:
        if n < current:
            cache[current] = cache[n] + counter
            break
        if n%2 == 0:
            n = n/2
            counter += 1
        else:
            n = 3*n+1
            counter += 1
print(list(cache.values()).index(max(cache.values()))+1)
print(time.time()-start)
837799
4.36925745010376

In this code, we have used a dictionary to store the pre-calculated values of the collatz sequence. We reduce the time complexity of the program from O(n^2) to O(nlogn). As we have to find the largest sequence between 1 and 1 million, we’ll use the cache to save our time for recalculation. This technique is termed Memoization.

Memoization is the process of storing the results that have already been computed. In this code, we have used the memoization technique in order to optimize our code. We have created a dictionary ‘cache’. Then we iterate the loop to 1 million to find the number that will generate the longest collatz sequence. We store all unique numbers in the dictionary ‘cache’ and finally display the number with the maximum collatz sequence. The time taken by this code to execute is 4.36925745010376 due to optimization using memoization.

Below is the same code done without memoization:

import time
start = time.time()
def collatzSeq(n):
    chainNumber = 1
    current = n
    while current != 1:
        if current % 2 == 0:
            current = current/2
            chainNumber += 1
        else:
            current = (3*current) + 1
            chainNumber += 1
    return [chainNumber, n]
data = []
for i in range(2, 1000000):
    data.append(collatzSeq(i))
print(sorted(data, reverse=True)[:1][0][1])
print('Time:', time.time() - start)
837799 
Time: 27.117942571640015

When the above code is executed, you will notice that it takes around 30 seconds more than the one with the memoization code. So, you can clearly see the difference between the time taken by the two codes.

Collatz Python sequence Infinite loop bug:

def collatz(n):
    if n % 2 == 0:
        n = n // 2
        print(n)
        return n
    elif n % 2 == 1:
        n = n * 3 + 1
        print(n)
        return n

print('Enter an Integer')
n = int(input())
while n > 1:
    collatz(n)

When we run the above code, we see that we get stuck in an infinite loop. This happens because return only holds the new value if you assign it to a variable. To correct this error, we need to format the code as follows:

while n > 1:
    n = collatz(n)

Collatz conjecture number of steps:

We can modify our program of collatz sequence to get the number of steps involved in getting the collatz sequence of a number.

def collatz(n):
    if n == 0:
        return 0
    cnt = 1
    while n != 1:
        n = (n / 2) if n % 2 == 0 else (3 * n + 1)
        cnt += 1
    return cnt

print(collatz(3))
8

As you can see, we have just modified the above code and used a counter variable ‘cnt’ to calculate the number of steps required to get the collatz conjecture.

Must Read

Conclusion:

With this, we come to an end with this article. In this article, we learned about the collatz sequence. We also learned how to implement the collatz sequence in Python both recursively and non-recursively.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

The post Understanding Collatz Sequence in Python appeared first on Python Pool.