pythonbg
pythonbg

Reputation: 29

isPrime function in one line

Good afternoon. I need to write numbers in one line and print results also in one line. What I need to do to fix this code? At the moment code working only for one number.

def test_prime(n):
    if (n==1):
        return False
    elif (n==2):
        return True;
    else:
        for x in range(2,n):
            if(n % x==0):
                return False
        return True   

Upvotes: 0

Views: 309

Answers (5)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

You would need to write a function is_prime which will call the function test_prime for each number in the string you input, calculates if it is prime or not, and return the resultant string.

def test_prime(n):
    if (n==1):
        return False
    elif (n==2):
        return True;
    else:
        for x in range(2,n):
            if(n % x==0):
                return False
        return True  

def is_prime(s):
    #Create list of numbers
    nums = [int(n) for n in s.split()]
    output = []
    #Call test_prime for each number
    for n in nums:
        output.append(test_prime(n))
    #Make a string out of results
    result = ' '.join([str(op) for op in output ])
    return result

s = input("Input numbers>>")
print(is_prime(s))

Here your output will be

Input numbers>>3 4 5
True False True

Upvotes: 0

blue note
blue note

Reputation: 29089

is_prime = lambda n: not any(n % i == 0 for i in range(2, n))
print([f'{i}: {is_prime(i)}' for i in range(1, 100)])

Note

  • any is lazy, it will not iterate the whole range unless needed
  • you can change the range to range(2, n**0.5) it you care about speed

Upvotes: 1

Jonas Byström
Jonas Byström

Reputation: 26179

>>> [print(i,test_prime(i),end=', ') for i in (1,2,3,4,5,6,10,100,1000,1013)]
1 False, 2 True, 3 True, 4 False, 5 True, 6 False, 10 False, 100 False, 1000 False, 1013 True,

Upvotes: 0

rikisa
rikisa

Reputation: 311

To print in just a single line just use

for i in range(10):
    print(test_prime(i), end=' ')

Mind the end keyword argument for print, which defaults to '\n'. Passing some other string will prevent a newline after printing. See also here: print()

You can also generate a list and then use str.join() which would look something like this:

results = [test_prime(i) for i in range(10)]
print(', '.join(results))

Upvotes: 0

glhr
glhr

Reputation: 4537

If you have a list of numbers like this:

numbers = [3,4,5]

You can use map() to apply your test_prime() function to each value in the list:

isprime = list(map(test_prime,numbers))

And to print the result on one line with no commas/brackets:

>> print(*isprime, sep = ' ')
True False True

Edit: since you mentioned that you want to enter the numbers in one line with no commas, you can do:

>>> numbers = input().split()
1 2 3 4 5
>>> numbers
['1', '2', '3', '4', '5']

Upvotes: 1

Related Questions