views:

108

answers:

3

level: beginner

the following code will print 'False'

def function(x):
    if len(x) == 5: return True
    else: return x[0] == x[-1]

print function('annb')

why does the line "else: return x[0] == x[-1]" print False? i do understand what's happening but i'm having difficulties to put this into plain english...how can this behaviour be described?

is this a commonly / often used "technique"?

I first came across this particular syntax when trying to solve a palindrome exercise recursivley. It seems that the only way to make recursion work is to use this shorthand approach:

def isPalindrome(s):
 if len(s) <= 1: return True
 else: return s[0] == s[-1] and isPalindrome(s[1:-1])

print isPalindrome('anna')

thanks Baba

+5  A: 

Sorry, I'm not entirely sure what you mean, but here think of it this way:

return (x[0] == x[-1])

If you only consider what is within the parenthesis, you realize that, that 'statement' equates to a boolean, right? That's why you can also do:

if x[0] == x[-1]

So basically, what is being returned here is a boolean that says whether or not x[0] is equal to [-1].

One could be more explicit and expand this statement to something like this:

if x[0] == x[-1]: # if this is true
    return True # then return true
else:
    return False

But as you can see, both the condition and what you would like to return are the same value, so one just does it shorthand like you saw:

return x[0] == x[-1]

Sorry if I misunderstood your question.

EDIT: If you referred to the negative index (x[-1]), in Python, negative indices basically 'wrap around', so where as x[0] would be the first element from 'left-to-right' so to speak, x[-1] loops around such that it is the first element from 'right-to-left'.

Jorge Israel Peña
Hi Blaenk, your answer makes this clear to me now. As a beginner i have to make sense of shorthands so thanks for your help!
Baba
+1  A: 

I think the thing you're confused about is the behavior of x[-1]. Negative array indices are relative to the end of the array, so in your example, x[-1] == 'b'. Which is obviously not equal to x[0] == 'a', so the function returns False.

Zack
A: 

On the whole the function of your function is: if length of x equals 5 , return True else if last character of string equals first one return True, else return False

This kind of condition else condition...else return False is best expressed with or statement which return False only if all conditions are False and returns value of first not-False element. Other choice is any function which does basically same with any sequence. Here test of those alternatives for all branches of original if statement:

def function(x):
    if len(x) == 5: return True
    else: return x[0] == x[-1]

def funcor(x):
    return (len(x)==5) or (x[0] == x[-1])

def funcany(x):
    return any((len(x)==5, x[0] == x[-1]))

def funcverbal(sequence):
    ## sequence[0] is the first element of zero based indexed sequence
    ## endswith is string specific function so sequence must be string
    ## if it's length is not 5
    return len(sequence)==5 or sequence.endswith(sequence[0])

## function is normal data type in Python, so we can pass it in as variable
def test(func):
    print('Testing %s function' % func)
    for value in ('12345','annb','ansa','23424242',('1','2','1'), 123, '131'):
        try:
            print ("%r -> %r" % (value,func(value)))
        except:
            print ("Failed to call function with " + repr(value))

    print(10 * '-'+'Finished testing '+str(func) + 10 * '-')

for thisfunction in (function, funcor, funcany, funcverbal):
    test(thisfunction)

(function is hightlighted as reserved word in blue but it is mistake in highlight routine in this website)

In case of the isPalindrome function, the length condition is not arbitrary, but it is necessary to recognize the primitive cases to stop the recursion, in case of 'anna' the palindrome function does:

see if the length of 'anna' is less than 2 (1 or 0), no they are not compare 'a' with 'a' , continue as they are same drop out the compared first and last letter and call isPalindrome with 'nn'

see if the length of 'nn' is less than 2 (1 or 0), no they are not compare 'n' with 'n', continue as they are same drop out the compared first and last letter and call isPalindrome with ''

see if the length of '' is less than 2 (1 or 0), yes. Return True as we found palindrome.

Here is alternative shorte function of palindrome testing based on the fact that palindrome reversed is same as palindrome.

def isPalindrome(s):
    return s==s[::-1]
Tony Veijalainen