Answer to Question #297413 in Python for Mee

Question #297413

write a python function which take list A as input and return five lists, one contains all prime numbers in A, second one contains composite numbers in A, the third list contains all numbers in A which are neither divisible by 2, fourth and fifth list contains number divisible by 3 and 5 respectively.



1
Expert's answer
2022-02-13T14:43:58-0500
def is_prime(n):
    if n <= 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    
    p = 3
    while p*p <= n:
        if n % p == 0:
            return False
        p += 2
    return True


def get5lists(A):
    L1 = [ x for x in A if is_prime(x)]
    L2 = [ x for x in A if abs(x) >  1 and not is_prime(abs(x))]
    L3 = [ x for x in A if x % 2 == 1 ]
    L4 = [ x for x in A if x % 3 == 0 ]
    L5 = [ x for x in A if x % 5 == 0 ]
    return L1, L2, L3, L4, L5


def main():
    import random
    A = [ random.randint(1, 100) for _ in range(20)]
    print('List A:', A)
    L1, L2, L3, L4, L5 = get5lists(A)
    print('List 1: ', L1)
    print('List 2: ', L2)
    print('List 3: ', L3)
    print('List 4: ', L4)
    print('List 5: ', L5)


if __name__ == '__main__':
    main()
    

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS