[Tutor] Writing Function Definitions

Alan Gauld alan.gauld at btinternet.com
Wed Oct 9 11:06:22 CEST 2013


On 08/10/13 23:50, Connor Hood wrote:

> # isPrime(m): I -> Bool
> # If m is an integer, then isPrime(m) if and only if m is prime.
> def isPrime(m):
>      return False if m <= 1 else isPrimeItr(1,0,m)
>
> # isPrimeItr(i,a,m): I x I x I -> Bool
> def isPrimeItr(i,a,m):
>      return False if a> 2 else True if a == 2 and i == m +1 else
> isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m)

While the above looks like it is valid Python it is not very readable.
I'd suggest splitting your functions into multiple lines rather than 
trying to cram everything into a single line. Also, because recursion 
runs into memory limits this solution will not always work for large 
numbers.

I've tried to disentangle your single line above to show what I mean

def isPrimeItr(i,a,m):
     if a > 2: return False
     elif  a == 2 and i == m+1: return True
     elif  m % i == 0: return isPrimeItr(i+1,a+1,m)
     else return isPrimeItr(i+1,a,m)

It's subjective of course but I think that makes it easier
to see the algorithm. I don't know if it works for testing
primes but at least I could think about it if I had the time.
For now I'll assume you've tested it and it works.


> # prompt the user for a value for m
> m = eval(input("Enter an integer value for m: "))

This is bad practice, it makes the program vulnerable to security 
exploits. Avoid the use of eval() for this type of task
and instead use float()) or int() to convert the input
from input().

ie.
m = int(input(....))

Its always best to get into good habits early.

> ------------------------------------------------------------------------------------------------------------------------
>
> These are the problems I am having problem with:
>
> If m and n are integers, then anyPrimes(m,n) iff there are any prime
> numbers in the interval [m,n).

Do you understand loops?
If so then you can test each number in the range using your isPrime() 
function above and stop if you find any primes.

> If m and n are integers, then countPrimes(m,n) is the number of prime
> numbers in the interval [m,n).

Same here except you need to test all numbers and keep a running count.

Try those suggestions and come back if you get stuck.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list