Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Even values from lists into a set

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading