mad_accountant
mad_accountant

Reputation: 41

Need to repeat the same loop within each loop an unknown number of times in python

I am new to programming and really don't know how to express my problem, so here is the code:

mapping_dict = {
    0: [1, 2, 3, 4, 5, 6],
    1: [7, 8, 9],
    2: [10, 11, 12],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [13, 14],
    8: [],
    9: [],
    10: [],
    11: [], 
    12: [],
    13: [],
    14: []
}
proper_id_list = []

The keys and values in the mapping_dict may be strings too. I need something like this:

proper_id_list = [0,1,7,13,14,8,9,2,10,11,12,3,4,5,6]

Whats going on here is that each list must be appended right after their keys.

So far, the code I could come up with, is as follows:

for a in mapping_dict[0]:
    proper_id_list.append(a)
    for a in mapping_dict[0]:
        proper_id_list.append(a)
        for a in mapping_dict[0]:
            proper_id_list.append(a)  # ... this will keep repeating, God knows how many times

I have hard coded these loops a 20 times and they work but I know this is poor design, restricted to 20 levels and the top level key in the mapping_dict must be a 0.

I hope this makes sense. Please help!

Upvotes: 0

Views: 362

Answers (1)

wjandrea
wjandrea

Reputation: 33179

You actually only need a single loop. Start with the lowest key, sort the keys, find them in the list, and insert their respective values.

proper_id = [min(mapping_dict)]
for k in sorted(mapping_dict):
    i = proper_id.index(k)
    proper_id[i+1:i+1] = mapping_dict[k]

print(proper_id)
# -> [0, 1, 7, 13, 14, 8, 9, 2, 10, 11, 12, 3, 4, 5, 6]

However, based on the comments about depth-first search, I might be missing the point. This might not generalize, or might be very slow for large datasets since it's O(n**2).

Upvotes: 1

Related Questions