Home > Blockchain >  Even values from lists into a set
Even values from lists into a set

Time:11-24

Here is the given assignment code:

Write a function even_value_set(list1, list2, list3), which receives three lists containing integer items as arguments. The function creates and returns a set that contains all items with even value from all three lists.

def test():
    l = [[],[],[]]
    
    for i in range(3):
        for j in range(random.randint(7,14)):
            l[i].append(random.randint(1,35))
        print ("List"   str(i   1)  ":",l[i])
        
    print ("")
    s = even_value_set(l[0],l[1],l[2])
    print ("Return type:", str(type(s)).replace("<","").replace(">",""))
    print ("Set with even values only:", end = "")
    print (set(sorted(list(s))))
    
test()

import random

I tried using .union() and making adding lists into another before turning them into sets, but didn't have any luck.

CodePudding user response:

You can do this in a simply pythonic way. This function can be written as a simple oneliner using comprehension

def even_value_set(list1, list2, list3):
    return set([num for num in list1 list2 list3 if num % 2 == 0])

Basically, what we did here is concatenated all lists, fitered even numbers and then made it into a set.

CodePudding user response:

You can union lists (with duplicates) with the operation.

union_list = list1   list2   list3

If you only want the unique values you can call set on this list.

unique_set = set(union_list)

Now you can create a new empty set and iterate over the unqiue_set and add all the even values:

solution = set()
for v in unique_set:
    if v%2==0:
        solution.add(v)

CodePudding user response:

def even_value_set(*lsts):
    s = set()
    for lst in lsts:
        s |= {x for x in lst if x % 2 == 0}
    return s

Also you can use starring

def even_value_set(*lsts):
    return set().union(*[{x for x in lst if x % 2 == 0} for lst in lsts])

And solution with concatenation (more memory). set comprehension is more effective than set()

def even_value_set(l1, l2, l3):
    return {x for x in l1 l2 l3 if x % 2 == 0}

CodePudding user response:

You can make the union of lists using , like list1 list2. Then just walk through the result list checking if the number is even and adding in another list.

def even_value_set(list):
  result = set()
  for val in list:
    if val%2 == 0:
      result.add(val)
  return result

def test():
l = [[],[],[]]

for i in range(3):
    for j in range(random.randint(7,14)):
        l[i].append(random.randint(1,35))
    print ("List"   str(i   1)  ":",l[i])
    
print ("")
uni = l[0]   l[1]   l[2]
s = even_value_set(uni)
print ("Return type:", str(type(s)).replace("<","").replace(">",""))
print ("Set with even values only:", end = "")
print (set(sorted(list(s))))

test()

import random

Is it what you want? I think your question is confusing.

  • Related