Home > Software engineering >  Python: Add values to dictionary
Python: Add values to dictionary

Time:08-04

Let say we have an array of positive integers and some integer x/

Each element in the array represents a missions and it's difficulty level and we want to find the minimum number of days to complete all the missions.

The difference between the difficult level of any two mission performed on the same day should not be greater than an integer x.

For example:

Arr = [5,8,2,7]
x = 3

5 and 8 can be performed in the first day 2 on the second day and 7 in the last day

I would like to get the following result:

dict = {key1:[5,8],key2:[2],key3:[3]}

CodePudding user response:

Here's my implementation:

def missions_to_dict(arr, x):
    curr_key = 1
    last_mission = arr[0]
    dict = {"key1": [last_mission]}

    # Loop through all missions
    for curr_mission in arr[1:]:
        # Check to see if current mission is x away from last mission
        if abs(curr_mission - last_mission) <= x:
            # Add it to same key as last mission
            dict[f"key{curr_key}"].append(curr_mission)
        # Otherwise, need to create new key
        else:
            curr_key  = 1
            dict[f"key{curr_key}"] = [curr_mission]
        # Set current mission to last mission
        last_mission = curr_mission
    
    return dict

CodePudding user response:

your question is a little vague as to what the answer could be, did you want a value to return true if this is the case? did you want to gauruntee a way to fill the dictionary in a way where your condition is true?

if you want to check that your condition is true, try:

bool_dict = {}
for key, val in dict.items():
    if max(val)-min(val)>x:
        bool_list[key]=False

    else: bool_dict[key]=True

print(bool_dict)
        
  • Related