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

I am trying to find the highest divisor of a integer N from a list D in python

I am a student who is beginner at programming and I have been asked to find the highest divisor of a integer N from a list D in python.

This I the code I have so far:

N = int(input("Enter the value N: "))
D = list(input("Enter the list D: "))

def highest_divisor(N, D):
    # Check if N is an integer and D is a list
    if not isinstance(N, int):
        print("Error: N must be an integer.")
        return
    if not isinstance(D, list):
        print("Error: D must be a list.")
        return
    
    # Find divisors of N in D
    divisors = [divisor for divisor in D if N % divisor == 0]
    
    # Check if there are any divisors
    if not divisors:
        print(f"No divisors of {N} found in the list D.")
        return
    
    # Return the highest divisor
    return max(divisors)

result = highest_divisor(N, D)
if result is not None:
    print(f"The highest divisor of {N} in the list D is: {result}")

This is what I get:

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

unsupported operand type(s) for %: 'int' and 'str'

>Solution :

The issue arises because input() function returns a string, not an integer. You need to convert the elements of list D into integers. Modify your code like this:

N = int(input("Enter the value N: "))
D = list(map(int, input("Enter the list D: ").split()))

def highest_divisor(N, D):
    # Check if N is an integer and D is a list
    if not isinstance(N, int):
        print("Error: N must be an integer.")
        return
    if not isinstance(D, list):
        print("Error: D must be a list.")
        return
    
    # Find divisors of N in D
    divisors = [divisor for divisor in D if N % divisor == 0]
    
    # Check if there are any divisors
    if not divisors:
        print(f"No divisors of {N} found in the list D.")
        return
    
    # Return the highest divisor
    return max(divisors)

result = highest_divisor(N, D)
if result is not None:
    print(f"The highest divisor of {N} in the list D is: {result}")
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