Reputation: 35
Python function partition() that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise.
I tried this Code, But this is not working for all test cases!! For Example - with the input of "185" the output should be "False", But This Code returns "True"
def partition(num):
primelist = primes(num)
for x in primelist:
y= num-x
if y in primelist:
return True
else:
return False
def primes(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) != 0:
primelist.append(i)
return primelist
print(partition(185))
Upvotes: 1
Views: 188
Reputation: 106618
You should determine that a number is prime only after the loop finishes without finding a number that can divide the given number:
def primes(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
return primelist
Likewise, you should determine that a number is not partitionable by two primes only after the loop finishes:
def partition(num):
primelist = primes(num)
for x in primelist:
y= num-x
if y in primelist:
return True
return False
Upvotes: 3