hephaes
hephaes

Reputation: 167

Create a 'dynamic list' during iteration in python

Background

Let there be a set of integers

trialinteg = [231,355,112,1432,2434,5235,7896,7776,27421,42342]

Then it is possible to classify them into different equivalence classes modulo 6

Problem

Could we create an algorithm to classify all these integers into their respective equivalence class and store the results in a dictionary in python?

For example

d = {"class0": [112,1432,..], "class1": [231,...], ...}

More importantly, can we make d changes its size and names of the keys as the integer by which we define equivalence class (in this example, 6) changes?

Progress

It is possible to store all integers of equivalence class 0 modulo 6 in a list. But it is not clear how one can create a 'dynamic' dictionary that adjusts its size and names of the key when the integer in question changes (for example from 6 to 121).

moduloclasszero=[]
for num in trialinteg:
    while num % 6 != 0:

        print(f"{num} is not of class 0")
        print(f"But {num} is of class {num % 6}")
        print("now proceed to restore it to 0")

        num = num + (6-(num % 6))
    else: 
        print(f"{num} is of class 0")
        moduloclasszero.append(num)

Upvotes: 1

Views: 339

Answers (2)

Prune
Prune

Reputation: 77857

Use the class value itself for your dictionary key.

my_mod = 6
for num in trialinteg:
    d[num % my_mod].append(num)

I'll assume that you can already handle initializing the dict; if not, look at supporting questions on this site.

A dict comprehension can do this in a single assignment statement:

trial = [231,355,112,1432,2434,5235,7896,7776,27421,42342]
d = {equi: [i for i in trial if i%my_mod == equi] 
     for equi in range(my_mod)}

Resulting value of d:

{0: [7896, 7776, 42342],
 1: [355, 27421],
 2: [],
 3: [231, 5235],
 4: [112, 1432, 2434],
 5: [] }

Upvotes: 0

Austin
Austin

Reputation: 26039

You could use collections.defaultdict:

from collections import defaultdict

trialinteg = [231,355,112,1432,2434,5235,7896,7776,27421,42342]

d = defaultdict(list)

for x in trialinteg:
    d[f'class{x % 6}'].append(x)

print(d)
# defaultdict(<class 'list'>, {'class3': [231, 5235], 'class1': [355, 27421], 'class4': [112, 1432, 2434], 'class0': [7896, 7776, 42342]})

Upvotes: 3

Related Questions