Will Luce
Will Luce

Reputation: 1841

Python: Adding list items to a dictionary if conditions are met

I'm trying to add the difference between numbers and, until the total difference > 20, append the number to a list that becomes a dictionary value where the key is the number_set. I'm getting a list out of range error right now.

The output should be multiple dictionary entries whose list differences add up to the closest number < 20.

number_set = 1
number_dict = {}

num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

incl_num_list = []
total = 0

for x in range(1, len(num_list)):

    if total < 20:
        total = total + (num_list[x+1] - num_list[x])
        incl_num_list.append(num_list[x])
    else:
        number_dict.update({km: num_list})
        km += 1
        incl_num_list = []
        total = 0

for k, v in number_dict.items():
    print k
    print v

The output should be

1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

Upvotes: 0

Views: 1071

Answers (2)

wim
wim

Reputation: 362786

num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

overflow = 20
total = 0
key = 1
number_dict = {1: [1]}

for left, right in zip(num_list[:-1], num_list[1:]):
    total += right - left
    if total >= overflow:
        key += 1
        number_dict[key] = [right]
        total = 0
    else:
        number_dict[key].append(right)

for k, v in sorted(number_dict.items()):
    print k
    print v

Outputs:

1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

Upvotes: 2

Aaron Hall
Aaron Hall

Reputation: 395125

For one thing, you're using km before it's been assigned to anything.

Traceback (most recent call last):
  File "<pyshell#29>", line 15, in <module>
    number_dict.update({km: num_list})
NameError: name 'km' is not defined

As ndpu points out, your last x will be out of range on your num_list.

Upvotes: 1

Related Questions