Powersets in Python using itertools

itertools functions return iterators, objects that produce results lazily, on demand. You could either loop over the object with a for loop, or turn the result into a list by calling list() on it: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return … Read more

Interactive pixel information of an image

There a couple of different ways to go about this. You can monkey-patch ax.format_coord, similar to this official example. I’m going to use a slightly more “pythonic” approach here that doesn’t rely on global variables. (Note that I’m assuming no extent kwarg was specified, similar to the matplotlib example. To be fully general, you need … Read more

Why are str.count(”) and len(str) giving different outputs when used on an empty string?

str.count() counts non-overlapping occurrences of the substring: Return the number of non-overlapping occurrences of substring sub. There is exactly one such place where the substring ” occurs in the string ”: right at the start. So the count should return 1. Generally speaking, the empty string will match at all positions in a given string, … Read more

FastAPI python: How to run a thread in the background?

Option 1 You should start your Thread before calling uvicorn.run, as uvicorn.run is blocking the thread. import time import threading from fastapi import FastAPI import uvicorn app = FastAPI() class BackgroundTasks(threading.Thread): def run(self,*args,**kwargs): while True: print(‘Hello’) time.sleep(5) if __name__ == ‘__main__’: t = BackgroundTasks() t.start() uvicorn.run(app, host=”0.0.0.0″, port=8000) You could also start your thread using … Read more

Plotting 3D Polygons

I think you’ve almost got it. Is this what you want? from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig, auto_add_to_figure=False) fig.add_axes(ax) x = [0,1,1,0] y = [0,0,1,1] z = [0,1,0,1] verts = [list(zip(x,y,z))] ax.add_collection3d(Poly3DCollection(verts)) plt.show() You might also be interested in art3d.pathpatch_2d_to_3d.