Slide Puzzle Python Code Examples

  1. Python Coding Puzzles
  2. Basic Python Code Examples

One such puzzle type was a sliding block puzzle game that presented the player with walls, movable blocks, and targets that you had to place the blocks on. The blocks could be moved an infinite amount of times, but once put into motion, they would continue until they hit either a wall or another block. Python-pptx’s API supports this process quite simply as long as you know a few things about your template. Before diving into some code samples, there are two key components you need to understand: Slide Layouts and Placeholders. In the images below you can see an example of two different layouts as well as the template’s placeholders where. As stated by Gareth, the problem is comparable to the 8-tile puzzle and so the code is based on the magnificient solution of Keith Randall and thus in Python. This solution can solve all 5 test cases with a total sum of less than 400 moves, and other puzzles, too. Hi, I found this code on the internet, I changed and added some lines to it to make it the way I like. I am very weak in using functions and even worse in using classes, I appreciate it if some one can change this code into functions or classes. ' this is a slide puzzle game.

OpenSlide Python is a Python interface to the OpenSlide library.

OpenSlide is a C library that provides a simple interface for readingwhole-slide images, also known as virtual slides, which are high-resolutionimages used in digital pathology. These images can occupy tens of gigabyteswhen uncompressed, and so cannot be easily read using standard tools orlibraries, which are designed for images that can be comfortablyuncompressed into RAM. Whole-slide images are typically multi-resolution;OpenSlide allows reading a small amount of image data at the resolutionclosest to a desired zoom level.

OpenSlide can read virtual slides in several formats:

  • Aperio (.svs, .tif)

  • Hamamatsu (.ndpi, .vms, .vmu)

  • Leica (.scn)

  • MIRAX (.mrxs)

  • Philips (.tiff)

  • Sakura (.svslide)

  • Trestle (.tif)

  • Ventana (.bif, .tif)

  • Generic tiled TIFF (.tif)

OpenSlide Python is released under the terms of the GNU Lesser GeneralPublic License, version 2.1.

Basic usage¶

OpenSlide objects¶

class openslide.OpenSlide(filename)

An open whole-slide image.

If any operation on the object fails, OpenSlideError is raised.OpenSlide has latching error semantics: once OpenSlideError israised, all future operations on the OpenSlide, other thanclose(), will also raise OpenSlideError.

close() is called automatically when the object is deleted.The object may be used as a context manager, in which case it will beclosed upon exiting the context.

Parameters

filename (str) – the file to open

Raises
  • OpenSlideUnsupportedFormatError – if the file is not recognized byOpenSlide

  • OpenSlideError – if the file is recognized but an error occurred

classmethod detect_format(filename)

Return a string describing the format vendor of the specified file.This string is also accessible via the PROPERTY_NAME_VENDORproperty.

If the file is not recognized, return None.

Parameters

filename (str) – the file to examine

level_count

The number of levels in the slide. Levels are numbered from 0(highest resolution) to level_count-1 (lowest resolution).

dimensions

A (width,height) tuple for level 0 of the slide.

level_dimensions

A list of (width,height) tuples, one for each level of the slide.level_dimensions[k] are the dimensions of level k.

level_downsamples

A list of downsample factors for each level of the slide.level_downsamples[k] is the downsample factor of level k.

properties

Metadata about the slide, in the form of aMapping from OpenSlide property name toproperty value. Property values are always strings. OpenSlideprovides some standard properties, plusadditional properties that vary by slide format.

associated_images

Images, such as label or macro images, which are associated with thisslide. This is a Mapping from imagename to RGBA Image.

Unlike in the C interface, these images are not premultiplied.

read_region(location, level, size)

Return an RGBA Image containing thecontents of the specified region.

Unlike in the C interface, the image data is not premultiplied.

Parameters
  • location (tuple) – (x,y) tuple giving the top left pixel inthe level 0 reference frame

  • level (int) – the level number

  • size (tuple) – (width,height) tuple giving the region size

get_best_level_for_downsample(downsample)

Return the best level for displaying the given downsample.

Parameters

downsample (float) – the desired downsample factor

get_thumbnail(size)

Return an Image containing an RGB thumbnailof the slide.

Parameters

size (tuple) – the maximum size of the thumbnail as a(width,height) tuple

close()

Close the OpenSlide object.

Standard properties¶

The openslide module provides attributes containing the names ofsome commonly-used OpenSlide properties.

openslide.PROPERTY_NAME_COMMENT

The name of the property containing a slide’s comment, if any.

openslide.PROPERTY_NAME_VENDOR

The name of the property containing an identification of the vendor.

openslide.PROPERTY_NAME_QUICKHASH1

The name of the property containing the “quickhash-1” sum.

openslide.PROPERTY_NAME_BACKGROUND_COLOR

The name of the property containing a slide’s background color, if any.It is represented as an RGB hex triplet.

openslide.PROPERTY_NAME_OBJECTIVE_POWER

The name of the property containing a slide’s objective power, if known.

openslide.PROPERTY_NAME_MPP_X

The name of the property containing the number of microns per pixel inthe X dimension of level 0, if known.

openslide.PROPERTY_NAME_MPP_Y

The name of the property containing the number of microns per pixel inthe Y dimension of level 0, if known.

openslide.PROPERTY_NAME_BOUNDS_X
Slide puzzle python code examples for beginners

The name of the property containing the X coordinate of the rectanglebounding the non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_Y

The name of the property containing the Y coordinate of the rectanglebounding the non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_WIDTH

The name of the property containing the width of the rectangle boundingthe non-empty region of the slide, if available.

openslide.PROPERTY_NAME_BOUNDS_HEIGHT

The name of the property containing the height of the rectangle boundingthe non-empty region of the slide, if available.

Python Coding Puzzles

Exceptions¶

exception openslide.OpenSlideError

An error produced by the OpenSlide library.

Once OpenSlideError has been raised by a particularOpenSlide, all future operations on that OpenSlide(other than close()) will also raiseOpenSlideError.

exception openslide.OpenSlideUnsupportedFormatError

OpenSlide does not support the requested file. Subclass ofOpenSlideError.

Wrapping a PIL Image¶

class openslide.ImageSlide(file)

A wrapper around an Image object thatprovides an OpenSlide-compatible API.

Parameters

file – a filename or Image object

Raises

IOError – if the file cannot be opened

openslide.open_slide(filename)

Return an OpenSlide for whole-slide images and anImageSlide for other types of images.

Parameters

filename (str) – the file to open

Raises
  • OpenSlideError – if the file is recognized by OpenSlide but anerror occurred

  • IOError – if the file is not recognized at all

Deep Zoom support¶

OpenSlide Python provides functionality for generating individualDeep Zoom tiles from slide objects. This is useful for displayingwhole-slide images in a web browser without converting the entire slide toDeep Zoom or a similar format.

class openslide.deepzoom.DeepZoomGenerator(osr, tile_size=254, overlap=1, limit_bounds=False)

A Deep Zoom generator that wraps anOpenSlide orImageSlide object.

Parameters
  • osr – the slide object

  • tile_size (int) – the width and height of a single tile. For bestviewer performance, tile_size+2*overlap should be a power of two.

  • overlap (int) – the number of extra pixels to add to each interior edgeof a tile

  • limit_bounds (bool) – True to render only the non-empty slideregion

level_count

The number of Deep Zoom levels in the image.

tile_count

The total number of Deep Zoom tiles in the image.

level_tiles

A list of (tiles_x,tiles_y) tuples for each Deep Zoom level.level_tiles[k] are the tile counts of level k.

level_dimensions

A list of (pixels_x,pixels_y) tuples for each Deep Zoom level.level_dimensions[k] are the dimensions of level k.

get_dzi(format)

Return a string containing the XML metadata for the Deep Zoom .dzifile.

Parameters

format (str) – the delivery format of the individual tiles(png or jpeg)

get_tile(level, address)

Return an RGB Image for a tile.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

get_tile_coordinates(level, address)

Return the OpenSlide.read_region() arguments corresponding to thespecified tile.

Most applications should use get_tile() instead.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

get_tile_dimensions(level, address)

Return a (pixels_x,pixels_y) tuple for the specified tile.

Parameters
  • level (int) – the Deep Zoom level

  • address (tuple) – the address of the tile within the level as a(column,row) tuple

Example programs¶

Several Deep Zoom examples are included with OpenSlide Python:

deepzoom_server.py

A basic server for a single slide. It serves a web page with a zoomableslide viewer, a list of slide properties, and the ability to viewassociated images.

deepzoom_multiserver.py

A basic server for a directory tree of slides. It serves an index pagewhich links to zoomable slide viewers for all slides in the tree.

deepzoom_tile.py

A program to generate and store a complete Deep Zoom directory tree for aslide. It can optionally store an HTML page with a zoomable slide viewer,a list of slide properties, and the ability to view associated images.

This program is intended as an example. If you need to generate Deep Zoomtrees for production applications, consider using VIPS instead.

Introduction

Love it or loathe it, PowerPoint is widely used in most business settings. Thisarticle will not debate the merits of PowerPoint but will show you how to usepython to remove some of the drudgery of PowerPoint by automating the creation ofPowerPoint slides using python.

Fortunately for us, there is an excellent python library for creating andupdating PowerPoint files: python-pptx. The API is very well documented so itis pretty easy to use. The only tricky part is understanding the PowerPoint documentstructure including the various master layouts and elements. Once youunderstand the basics, it is relatively simple to automate the creation of yourown PowerPoint slides. This article will walk through an example of reading inand analyzing some Excel data with pandas, creating tables and building a graphthat can be embedded in a PowerPoint file.

PowerPoint File Basics

Python-pptx can create blank PowerPoint files but most people are going toprefer working with a predefined template that you can customize with your own content.Python-pptx’s API supports this process quite simply as long as you know a fewthings about your template.

Before diving into some code samples, there are two key components you need tounderstand: Slide Layouts and Placeholders. In the images below you can seean example of two different layouts as well as the template’s placeholders whereyou can populate your content.

In the image below, you can see that we are using Layout 0 and there is one placeholderon the slide at index 1.

In this image, we use Layout 1 for a completely different look.

In order to make your life easier with your own templates, I created a simplestandalone script that takes a template and marks it up with the various elements.

I won’t explain all the code line by line but you can see analyze_ppt.py ongithub. Here is the function that does the bulk of the work:

The basic flow of this function is to loop through and create an example ofevery layout included in the source PowerPoint file. Then on each slide, it willpopulate the title (if it exists). Finally, it will iterate through all of theplaceholders included in the template and show the index of the placeholder aswell as the type.

If you want to try it yourself:

Refer to the input and output files to see what you get.

Creating your own PowerPoint

For the dataset and analysis, I will be replicating the analysis inGenerating Excel Reports from a Pandas Pivot Table. The article explainsthe pandas data manipulation in more detail so it will be helpful to make sureyou are comfortable with it before going too much deeper into the code.

Let’s get things started with the inputs and basic shell of the program:

After we create our command line args, we read the source Excel file into apandas DataFrame. Next, we use that DataFrame as an input to create thePivot_table summary of the data:

Consult the Generating Excel Reports from a Pandas Pivot Table if this doesnot make sense to you.

The next piece of the analysis is creating a simple bar chart of sales performanceby account:

Here is a scaled down version of the image:

We have a chart and a pivot table completed. Now we are going to embed that informationinto a new PowerPoint file based on a given PowerPoint template file.

Before I go any farther, there are a couple of things to note. You need to know whatlayout you would like to use as well as where you want to populate your content.In looking at the output of analyze_ppt.py we know that the title slideis layout 0 and that it has a title attribute and a subtitle at placeholder 1.

Basic Python Code Examples

Here is the start of the function that we use to create our output PowerPoint:

This code creates a new presentation based on our input file, adds asingle slide and populates the title and subtitle on the slide. It looks like this:

Pretty cool huh?

The next step is to embed our picture into a slide.

From our previous analysis, we know that the graph slide we want to use islayout index 8, so we create a new slide, add a title then add a picture intoplaceholder 1. The final step adds a subtitle at placeholder 2.

Here is our masterpiece:

For the final portion of the presentation, we will create a table for eachmanager with their sales performance.

Here is an image of what we’re going to achieve:

Creating tables in PowerPoint is a good news / bad news story. The good newsis that there is an API to create one. The bad news is that you can’t easilyconvert a pandas DataFrame to a table using the built in API. However, weare very fortunate that someone has already done all the hard work for usand created PandasToPowerPoint.

This excellent piece of code takes a DataFrame and converts it to a PowerPointcompatible table. I have taken the liberty of including a portion of it inmy script. The original has more functionality that I am not using so Iencourage you to check out the repo and use it in your own code.

The code takes each manager out of the pivot table and builds a simple DataFramethat contains the summary data. Then uses the df_to_table to convertthe DataFrame into a PowerPoint compatible table.

If you want to run this on your own, the full code would look something like this:

All of the relevant files are available in the github repository.

Conclusion

One of the things I really enjoy about using python to solve real world businessproblems is that I am frequently pleasantly surprised at the rich ecosystem of verywell thought out python tools already available to help with my problems. In this specific case,PowerPoint is rarely a joy to use but it is a necessity in many environments.

After reading this article, you should know that there is some hope for you next timeyou are asked to create a bunch of reports in PowerPoint. Keep this article in mind andsee if you can find a way to automate away some of the tedium!

Slide Puzzle Python Code Examples

Comments