Home > Software engineering >  [python]number prime partition with 2
[python]number prime partition with 2

Time:09-30

i want to make function(use 'def') prime_partition(n,k) n is number, k is number of the tuple

my code is...

def partition(n,k):
    result=[]
    for i in range(1,n 1):
        if isprime(i) and isprime(n-i) == True:
            result.append([i, n-i])
        while len(result) >= k:
            break
        print(result)

but i have two problem.

  1. partition(100,6) do not make 6 partition but makes all partition.

  2. In partition(100,6), there exists two same partition [3, 97],[97,3]. i want to exclude one '[97,3]'

CodePudding user response:

Use if not while. Also better return the result rather than printing it. You can always print after if needed.

def partition(n,k):
    result=[]
    for i in range(1,n 1):
        if isprime(i) and isprime(n-i):
            result.append([i, n-i])
        if len(result) >= k:
            return result

example:

>>> partition(30,3)
[[7, 23], [11, 19], [13, 17]]

example to print:

print(partition(30, 3))

CodePudding user response:

In your code, there is an error in the line while len(result)>k. And to avoid duplicates you can iterate only to n//2

def isprime(n):
    if n==1:
        return False
    if n==2:
        return False
    for i in range(2,n):
        if n%i==0:
            return False
    return True

def partition(n,k):
    result=[]
    for i in range(1,n//2):
        if isprime(i) and isprime(n-i):
            result.append([i, n-i])
        if len(result) >= k:
            break
    print(result)
partition(30,3)
  • Related