fp/lambda question

Jozef jozef at jozef.joz
Fri Apr 12 19:58:00 EDT 2002


I was reading on functional programming in Python and wanted to test
myself by writing a function:

functional_euler = lambda n: \
	len(filter(lambda i: gcd(i, n) == 1, range(1, n + 1)))

(gcd is the greatest common divisor function). It gives the following
error: <stdin>:1: SyntaxWarning: local name 'n' in 'lambda' shadows use of
'n' as global in nested scope 'lambda'

I am not really sure even what this means... does lambda create a new
scope or something? Is there another way to write this?

Below is the gcd function I used and two other versions of the euler
function that do work as expected.

def gcd(a, b): # Greatest Common Divisor
	if b == 0: return a
	else: return gcd(b, a % b)

def imperative_euler(n):
	xs = []
	for i in range(1, n + 1):
		if gcd(i, n) == 1: xs.append(i)
	return len(xs)

def list_euler(n):
	return len([x for x in range(1, n + 1) if gcd(x, n) == 1])



More information about the Python-list mailing list