Need help streamlining this code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sigkill9
    New Member
    • Jan 2008
    • 15

    #1

    Need help streamlining this code

    Could someone help me streamline this? Like eliminate unnecessary coding and etc?

    I got the script to work, although I couldn't figure out how to handle small prime numbers such as 2 and 3. It wouldn't output "this number is prime" (see script below) so I had to force prime detection. Also, 6 = 3 + 3, and 4 = 2 + 2, but it wouldn't output that either, instead it would just return to the python prompt, so I forced those two.

    Thanks!

    Code:
    import math
    
    def main():
            
        def calcPrime(squareI2t,n):
            if n == 2 or n == 3: # couldnt figure out how to handle these small
                isEvenAndPrime(n)# primes, so I forced prime detection
            elif n == 4 or n == 6:
                print "="*52,"\nFound two prime numbers that sum to",n,"!"
                print n, "=",n/2,"+",n/2,"\n","="*52
            else:
                for x in range(2, squareIt + 1):
                    if n % x == 0:
                        break
                    if x == squareIt:
                        isEvenAndPrime(n)
        def isEvenAndPrime(n):
            print "="*52,"\nERROR:",n,"is already prime."
        def isPrime(p):
            if p == 2:
                return True
            else:
                result = primeTest(p)
                return result 
                return False
        def isEven(num):
            if n %2 == 0:
                return True # is even
            else:
                print "="*52,"\nERROR:",n,"is not even. Please use only even numbers.\n"
                return False
        def primeTest(p):
            stop = int(math.ceil(math.sqrt(p/2)))+1
            for i in range(3, stop, 2):
                #print "testing", i, p, p%i
                if p % i == 0:
                    return False
            return True # is a prime
    
        n = int(raw_input('Enter number to test: '))
        squareIt = int(math.sqrt(n))
        calcPrime(squareIt,n)
        if isEven(n):
            found = 0
            for p in range(3, n/2, 2):
                #print "testing", p, n-p  
                if isPrime(p) and isPrime(n-p):
                    print "="*52,"\nFound two prime numbers that sum to",n,"!"
                    print n, '= %d + %d' % (p, n-p),"\n","="*52
                    found = 1
                    break
    
    if __name__ == '__main__':
        main()
  • Subsciber123
    New Member
    • Nov 2006
    • 87

    #2
    Wow. Before you do anything else, please get rid of
    Code:
    def main():
    line and un-indent everything below it. This may just be my opinion, but it is bad form to put functions inside functions unless absolutely necessary. Only put the code that needs to be called inside the function, not other function declarations.

    Comment

    • sigkill9
      New Member
      • Jan 2008
      • 15

      #3
      Mmkay, done. Is there anything else that could be streamlined?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Separate your user interface code from your functions that perform a function (pun intended). Add 1 to n/2 so 6 will return 3,3. Handle special case 4 to return 2,2. Eliminate import math by using operator **. Use string formatting in your print statements. This is an OOP concept: Send an object to an object and receive a returned object.
        [code=Python]def is_prime(n):
        if n < 2:
        return False
        elif n == 2:
        return True
        elif not n%2:
        return False
        for i in xrange(3, int(n**0.5)+1, 2):
        if not n%i:
        return False
        return True

        def primes_sum(n):
        if n == 4:
        return 2,2
        for p in range(3, n/2+1, 2):
        p1 = n-p
        if is_prime(p) and is_prime(p1):
        return p, p1
        return None

        if __name__ == '__main__':
        while True:
        n = int(raw_input(' Ener number to test: '))
        if n%2:
        print "%d is not even. Please enter only even numbers." % n
        else:
        break
        s = primes_sum(n)
        if s:
        print '%d = %d + %d' % (n,s[0],s[1])
        print "Found two prime numbers that sum to %d" % n
        else:
        print "No primes for number %d" % n[/code]

        Comment

        • sigkill9
          New Member
          • Jan 2008
          • 15

          #5
          Hi and thanks for the help!

          How would I incorporate the prime number check and message into this new code?

          I had it in my old code. If a prime number was entered it would print "this number is already prime" then print another message "this number is not even..." yadda yadda.

          If I could incorporate that into this new code, it will be complete.

          Comment

          • sigkill9
            New Member
            • Jan 2008
            • 15

            #6
            Hi and thanks for the help!

            How would I incorporate the prime number check and message into this new code?

            I had it in my old code. If a prime number was entered it would print "this number is already prime" then print another message "this number is not even..." yadda yadda.

            If I could incorporate that into this new code, it will be complete.

            Comment

            • sigkill9
              New Member
              • Jan 2008
              • 15

              #7
              Not sure why, but it posted 2 of my messages, so I edited this one... sorry.

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Originally posted by sigkill9
                Hi and thanks for the help!

                How would I incorporate the prime number check and message into this new code?

                I had it in my old code. If a prime number was entered it would print "this number is already prime" then print another message "this number is not even..." yadda yadda.

                If I could incorporate that into this new code, it will be complete.
                The only prime number that is even is 2. Just add an elif to test for 2.
                [code=Python]if __name__ == '__main__':
                while True:
                n = int(raw_input(' Ener number to test: '))
                if n%2:
                print "%d is not even. Please enter only even numbers." % n
                elif is_prime(n):
                print "%d is a prime number. Please enter a non-prime number." % n
                else:
                break
                s = primes_sum(n)
                if s:
                print '%d = %d + %d' % (n,s[0],s[1])
                print "Found two prime numbers that sum to %d" % n
                else:
                print "No primes for number %d" % n[/code]

                Comment

                • sigkill9
                  New Member
                  • Jan 2008
                  • 15

                  #9
                  Maybe I wasnt clear enough, sorry.

                  I need the program to detect when a prime number has been entered, then output a "This number is prime!" message, for ALL prime numbers, not just the one even one lol.

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    Originally posted by sigkill9
                    Maybe I wasnt clear enough, sorry.

                    I need the program to detect when a prime number has been entered, then output a "This number is prime!" message, for ALL prime numbers, not just the one even one lol.
                    Take a good look at the code. All you need to do is swap the code following the if statement and the code following the elif statement. What you want is to test for is_prime() first.

                    Comment

                    Working...