#itertools

Alexandre B A Villares 🐍villares@ciberlandia.pt
2025-02-09
Capture of a page of the book at https://wesmckinney.com/book/python-builtin#generators_itertools that including a groupby example and quick reference table of other itertools functions:

itertools module

The standard library itertools module has a collection of generators for many common data algorithms. For example, groupby takes any sequence and a function, grouping consecutive elements in the sequence by return value of the function. Here’s an example:

In [220]: import itertools

In [221]: def first_letter(x):
   .....:     return x[0]

In [222]: names = ["Alan", "Adam", "Wes", "Will", "Albert", "Steven"]

In [223]: for letter, names in itertools.groupby(names, first_letter):
   .....:     print(letter, list(names)) # names is a generator
A ['Alan', 'Adam']
W ['Wes', 'Will']
A ['Albert']
S ['Steven']

See Table 3.2 for a list of a few other itertools functions I’ve frequently found helpful. You may like to check out the official Python documentation for more on this useful built-in utility module.
Table 3.2: Some useful itertools functions

Function 	Description

chain(*iterables) 	Generates a sequence by chaining iterators together. Once elements from the first iterator are exhausted, elements from the next iterator are returned, and so on.

combinations(iterable, k) 	Generates a sequence of all possible k-tuples of elements in the iterable, ignoring order and without replacement (see also the companion function combinations_with_replacement).

[the table continues]
2024-12-02

[Formations #Python] Dernière formation de l'année "Les structures avancées avec #Python"

N'hésitez pas à nous contacter pour vous inscrire

📅 le 16 décembre en ligne

#python#pythonscientifique #machinelearning #Pythonavancées
#données #algorithmique #ai #algo
#itertools #generateur #decorateur

Les structures avancées de Python
2024-06-26

@pokateo use of python `itertools` to map `shapely` functions onto geometric linear and point objects

#python #shapely #Itertools

Python Ireland - old accountpythonie
2024-06-13

Mia Bajić: The Standard Library Tour @ PyCon Ireland 2023

youtu.be/ZId-JEMSCQ8

The Standard Library Tour is designed to provide attendees with an understanding of Python's standard library less known features. Have you ever found yourself writing complex code only to discover that Python has tools available within its library that could have made your job easier? Then this talk is for you!

2023-12-05

#ArtAdventCalendar Day 4.

I started working through the book "Indra's Pearls" by David Mumford, Caroline Series, and David Wright. And by working, I mean implementing the pseudo-code in #python. It's fun when you recognize that a messy triple-nested loop algorithm in the book can be replaced by a single `itertools.product` followed by a `filter` call - which makes one appreciate the ease of coding in Python!

This is a "Theta-Schottky group" fractal inspired by Exercise 4.2 in the book.

#indraspearls #fractal #schottkygroup #itertools

Four filled circles, blue, red, turquoise, and orange, are placed at the cardinal points. Each circle contains a projection of the 3 other circles. Each projected circle contains projections of the other circles.. and so on, in typical self-similar fractal fashion.
PyCon CZ :python: 🇨🇿pyconcz@floss.social
2023-09-08

♻️ Master the art of efficient looping! Join Pratibha Jagnere in the talk "Itertools – iterators for efficient looping" and level up your Python skills. 🚀🔁 Don't miss it: cz.pycon.org/2023/program/talk
#Python #Itertools #PyConCZ23

Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-07-29

Ano passado eu gravei um curso em vídeo de introdução ao desenho com código, usando #Python + #Processing (#py5) para o HomeostasisLab, está disponível *totalmente de graça* em:

homeostasislab.org/cursos/info

Parece que uma centena de pessoas acessaram esse #cursoGrátis de #ProgramaçãoCriativa, mas eu não tive retorno. Estranhei que deveria ter legendas em inglês mas não as encontrei :((

Adoraria que mais gente visse e que me mandassem comentários (de preferência construtivos). Assisti ontem um trechinho em que eu tento explicar #itertools #combinations #permutations e #ItertoolsProduct e achei que estava bem razoável.

Se você gosta do meu trabalho, pode me apoiar em gumroad.com/villares, com PayPal (paypal.com/cgi-bin/webscr?cmd=) ou PIX (chave: 46c37783-5edb-4f1c-b3a8-1309db11488c)

Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-06-22

#Processing #py5 #Python #itertools 120 combinations of 2 elements from a 4x4 grid. #CreativeCoding #Loop #GIF

Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-06-19

sketch_2022_06_19 #Processing #Python #py5 #itertools #combinations github.com/villares/sketch-a-d

UPDATE: No need to use that cumbersome lambda, it was there because of some previous experiments... I refactored it out:
...
for z, positions in zip(range(-100, 101, 20), cs):
py5.fill((255 + z + i * 20) % 255, 200, 200)
for pos in positions:
element(pos + (z,))

GripNewsGripNews
2023-06-09

🌗 函數式編程 HOWTO — Python 3.11.4 文件
➤ Python 的函數式編程特性
docs.python.org/3/howto/functi
本文介紹 Python 的函數式編程特性,包括迭代器、生成器、itertools 和 functools 等庫模塊。函數式編程將問題分解為一組函數,並鼓勵使用純函數,即只接受輸入並生成輸出,不修改內部狀態。函數式編程具有形式化可證明、模塊化、可組合、易於調試和測試等優點。
+ 很好的介紹了 Python 的函數式編程特性,讓我更好地理解了函數式編程的概念和優點。
+ 這篇文章很有用,尤其是對於那些想學習函數式編程的 Python 開發人員來說。

musicmatze :rust: :nixos:musicmatze@social.linux.pizza
2023-05-08

Today I implemented some neat optimizations for my current project at work: the problem I found was that the #rust #itertools library does not ensure minimal allocation size for the partition_result adaptor.

I made a custom implementation of this adaptor that does not allocate itself, but receives preallocated collections for the partitions.

Was a pretty nice experience.

Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-03-19

Ano passado eu gravei umas aulas em vídeo para o HomeostasisLab, é de graça, sobre desenhar com #Python e #py5 e um pouquinho de #itertools homeostasislab.org/cursos/info

Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-02-25

sketch_2022_02_25 #Processing #Python #py5 #itertools github.com/villares/sketch-a-day

# Imagem formada por pontos de um hexágono conectados todos entre si por linhas "tracejadas" que alternam azul e amarelo
# Também aparece o código abaixo e o fundo de tela do XFCE (ratinho)

from itertools import combinations

combos = []

def setup():
    size(600, 600)
    n = 6
    step = TWO_PI / n
    pts = []
    for i in range(n):
        a = HALF_PI + i * step
        # radius 250 causes weird diagonal behaviour!
        x = 300 + 256 * cos(a)
        y = 300 + 256 * sin(a) 
        pts.append((x, y))
    combos[:] = list(combinations(pts, 2))

def draw():
    background(200)
    stroke_weight(3)
    for c, s in (('yellow', True), ('darkblue', False)):
        stroke(c)
        for (ax, ay), (bx, by) in combos:
            dashed(ax, ay, bx, by, solid_start=s)


def dashed(ax, ay, bx, by, u=20, solid_start=True):
    d = dist(ax, ay, bx, by)     # Line length
    if d:
        ux, uy = (bx - ax) / d, (by - ay) / d  # A "unit vector" of the line
        n = d // u
        if n == 0:
           solid_start = True  
        elif n % 2 == 0:
           n = n - 1            
        ru = d - u * n
        x, y = ax + ux * ru /  2, ay + uy * ru / 2
        if solid_start:
            line(ax, ay, x, y) 
        for i in range(int(n)):
            if i % 2 == (1 if solid_start else 0):
                xd, yd = x + ux * u, y + uy * u
                line(x, y, xd, yd)
            x += ux * u
            y += uy * u
        if solid_start:
            line(x, y, bx, by)
Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-02-22

sketch_2022_02_21 #Processing #Python #py5 #itertools combinações de 7 pontos de um heptágono ligados dois a dois por linhas tracejadas.

# a imagem mostra o código abaixo à esquerda no Thonny IDE, ao fundo um desktop ccom o ratinho do XFCE
# à direita a imagem produzida pelo código, 7 pontos formando um heptágono com todos os pontos ligados entre si por linha tracejadas em um fundo cinza.

from itertools import combinations

combos = []

def setup():
    size(600, 600)
    n = 7
    step = TWO_PI / n
    pts = []
    for i in range(n):
        a = HALF_PI + i * step
        x = 300 + 200 * cos(a)
        y = 300 + 200 * sin(a)
        pts.append((x, y))
    combos[:] = list(combinations(pts, 2))

def draw():
    background(200)
    for (ax, ay), (bx, by) in combos:
        dashed(ax, ay, bx, by)

def dashed(ax, ay, bx, by, u=20, a=0.5):
    d = dist(ax, ay, bx, by)               # Line length
    ux, uy = (bx - ax) / d, (by - ay) / d  # A "unit vector" of the line
    nx, ny = uy, -ux                       # Normal direction
    n = d // u
    stroke(0)
    ru = min(u * a, (d - u * n)) 
    x, y = ax, ay
    for i in range(int(n)):
        xd, yd = x + ux * u * a, y + uy * u * a
        line(x, y, xd, yd)
        x += ux * u
        y += uy * u
    stroke(0, 0, 100)
    line(x, y, x + ux * ru, y + uy * ru)
Alexandre B A Villares 🐍villares@ciberlandia.pt
2023-02-16

Will I get the hang of using #py5 on #JupyterLab ? Trying the py5bot kernel...

#Python #creativeCoding #itertools

# screenshot of a jupyter notebook

# first cell

%%python

from itertools import product, combinations 
 
pos = list(product((0, 1, 2, 3), repeat=2)) 
 
def draw_base(): 
    for i, j in pos: 
        x = 100 + i * 100 
        y = 100 + j * 100 
        rect(x, y, 100, 100) 
 
def draw_combo(combo): 
    for i, j in combo: 
        x = 100 + i * 100 
        y = 100 + j * 100 
        push_matrix() 
        translate(x + 50, y + 50, 50) 
        box(100) 
        pop_matrix() 

combos = list(combinations(pos, 2)) 
print(len(combos)) 

# second cell
size(600, 600, P3D) 
lights()
s = 12
scale(1/s)
    
x = y = 0
for combo in combos:
    no_fill()
    stroke(255, 0, 0)
    stroke_weight(s)
    draw_base() 
    fill(255)
    stroke(0)
    draw_combo(combo)
    translate(width, 0)
    x += width
    if x > width * s - width:
        translate(-width * s, height)
        x = 0
    
# partially visible output is a grid of many red 4x4 square grids with two white boxes on to of each
Alexandre B A Villaresvillares
2022-11-08

O meu curso com no vai ser amanhã, quarta-feira 9/11, 19h, horário de Brasília, inscreva-se em homeostasislab.org/cursos/info :D

Client Info

Server: https://mastodon.social
Version: 2025.04
Repository: https://github.com/cyevgeniy/lmst