Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Problem with returning prime number in a simple calculation program

Reply
Thread Tools

Problem with returning prime number in a simple calculation program

 
 
QHorizon@gmail.com
Guest
Posts: n/a
 
      03-03-2007
Hello, I'm new to Python (I've learned everything up to iterators so
far) and fairly new to Programming. This would be my first real
program:

#Coordinate Geometry (The whole program is not shown)

import math
import sys

print "Welcome to the Coordinate Geometry Calculator!"
print "Type 'terms' for a list of commands"

def main():
print
command = raw_input("Command? ")
if command == "terms":
terms()
main()
elif command == "distance":
distance()
main()
elif command == "slope":
slope()
main()
elif command == "endpoint":
endpoint()
main()
elif command == "midpoint":
midpoint()
main()
elif command == "prime":
prime()
main()
elif command == "quit":
sys.exit
else:
print "Not a valid command"
main()

#...Declaring functions here...

def prime():
num = input("Number ")
i = num - 1
divcounter = 0
while i > 1:
if num % i != 0:
divcounter += 1
i -= 1
if divcounter == num - 2:
print num, "is a prime number"
else:
print num, "is not a prime number"

#Start the program
main()

As it says in the title, I'm having trouble with the prime number
function. It will print the sentence if the number is prime, but it
if isn't, the program goes into a state in the terminal where the
program never ends and you can just keep on typing. Maybe the else
statement is ineffective? Any ideas on how to fix this?

 
Reply With Quote
 
 
 
 
Bjoern Schliessmann
Guest
Posts: n/a
 
      03-03-2007
wrote:
> [reformatted indentation]
> def prime():
> num = input("Number ")
> i = num - 1
> divcounter = 0
> while i > 1:
> if num % i != 0
> divcounter += 1
> i -= 1
> if divcounter == num - 2:
> print num, "is a prime number"
> else:
> print num, "is not a prime number"
> [...]
> As it says in the title, I'm having trouble with the prime number
> function. It will print the sentence if the number is prime, but
> it if isn't, the program goes into a state in the terminal where
> the program never ends and you can just keep on typing.


Sure thing. You designed the function to behave this way.

Look at the while loop -- especially think what happens if
(num % i == 0). i will never be decremented then and the function
will not terminate.

Try inserting print statements for debugging if you don't get what I
meant here.

> Maybe the else statement is ineffective?


No one can read your thoughts. In which way effective?

Regards,


Björn

--
BOFH excuse #86:

Runt packets

 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      03-04-2007
On Sat, 03 Mar 2007 15:36:36 -0800, QHorizon wrote:

> Hello, I'm new to Python (I've learned everything up to iterators so
> far) and fairly new to Programming. This would be my first real
> program:
>
> #Coordinate Geometry (The whole program is not shown)
>
> import math
> import sys
>
> print "Welcome to the Coordinate Geometry Calculator!"
> print "Type 'terms' for a list of commands"
>
> def main():


[snip big boring series of if...elif... statements]

You're eventually going to run into a run time recursion error if you run
that for long enough. Can you see why?

A better way to do a command loop is something like this:


def bad_command():
# called when the user enters an unrecognized command
print "Unknown command, please try again"

class QuitException(Exception):
# used for exiting the loop
pass


def main():
# Make a "dispatch table" that maps the name of a command
# (as typed by the user) with a function to call.
dispatcher = {'slope': do_slope,
'primes': do_primes,
'quit': do_quit,
# ... and more here
}
try:
# loop forever (until we jump out of it)
while True:
cmd = get_command_from_user()
# you have to write get_command_from_user yourself
func = dispatcher.get(cmd, bad_command)
result = func()
print result
except QuitException:
print "Goodbye, come again soon!"


Now you just need to define your individual functions do_slope, do_primes,
etc. The only "special" one is do_quit.

def do_quit():
raise QuitException


Now let's look at the do_primes function. (You call it "prime".)

> def prime():
> num = input("Number ")


That's a good way to have malicious users do really, really really bad
things to your PC.

Safer is to do this:

num = int(raw_input("Number "))

> i = num - 1
> divcounter = 0
> while i > 1:
> if num % i != 0:
> divcounter += 1
> i -= 1


That's an inefficient algorithm, if it even works. I'm not sure that it
works, and I'm too lazy to find out


> if divcounter == num - 2:
> print num, "is a prime number"
> else:
> print num, "is not a prime number"


This will only work if divcounter happens to equal the original number
less two. If it equals something else, nothing will be printed.

Here's a simple algorithm to check if a number is prime.

# Warning: untested.
def do_primes():
num = int(raw_input("Number ")
if num <= 1:
return "%n is not prime" % num
if num == 2:
return "%n is prime" % num
elif num % 2 == 0:
# even numbers other than 2 aren't prime
return "%n is not prime" % num
for i in range(3, num, 2):
if num % i == 0:
return "%n is not prime" % num
return "%n is prime" % num


Now, this is deliberately not an efficient algorithm. There are things you
can do to make it more efficient, or you can re-write it completely.
The thing to remember is, don't PRINT the result, RETURN it. Your
do_primes() function should only calculate the result, and pass that
result up to the main loop for printing (or writing to a text file, or
emailing, or whatever).

Have fun!



--
Steven.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Program to compute and print 1000th prime number Robert P. J. Day Python 5 01-17-2011 10:02 PM
returning calculation results in perl scripts spanish26@gmail.com Perl Misc 2 01-21-2009 04:19 PM
Shortest prime number program swisscheese Python 19 02-13-2006 05:49 PM
Prime numbers: addative property modulo p, where p is prime Jeremy Fischer Perl Misc 0 01-16-2005 05:53 PM
prime number routine don C++ 11 02-11-2004 04:38 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57