Tuesday 15 January 2013

Swap first and last letter of a string in Python -


I hope I am clarifying something here, but I was playing with Python codingbat site, and the problem Found:

has been passed for a string, swap it with your first and last characters, if the length of the string is greater than 1.

I have come up with a single line solution that I thought would be sufficient, but coding.Bat has refused to accept it, with an index class error.

I played in IWEE (64 bit window edition) and I boiled down the problem:

  lane (str)   

The odd problem is that str = '' returns:

  'doh / doh'   

This lane is not ('') should not be in the form of 0, but str = 'a' returns:

  'a'   

and str = 'abc' returns:

  Doh abc / doh '  

I expected ...

So my question is really; Why is the "lane" being examined for the turnarial operator or status, but the <0> len ('') running on the console return 0, which is clearly less than 2?

Edit:

This solution actually works, however:

  def front_back (str): If len (str) & lt; 2: Return Strength: Return str [-1] + str [1: -1] + str [0]   

to 'mtadd'; Thank you for your reply, but it is not logical and / or it is a dragon ternary operator:

  return (statement) and & lt; Statement was correct & gt; Or & lt; Statement is false & gt;   

This is similar to C #:

  return statement? TrueValue: falseValue;    

It's a matter of.

Expression, the inherent order is as follows:

  ((lenan (str) <2) and str) or ('doh' + str + '/ doh ')   

In the case of str = "" , lane (str) & lt; 2 evaluates true , but str , an empty string, incorrect , thus and Expression is , therefore the correct operation of or binary opus becomes the result of expression.

str = "ABC" , lane (str) & lt; 2 is incorrect , therefore the expression and as the short-circuit incorrect , and the expression on the right side of or < / Code> results.

str = "ab" , len (str) & lt; 2 is true, so the and expression or binary operator passes its right operand, and since bool ("ab") == true The value of , str becomes the result of expression.

As you can see, and / or will not work with triangle operators of other languages ​​if the result of your code is True condition is equal to False , for example true and 0 or 1 yield 1 , while 0 is used True while doing second 1 yields 0 .

I recommend using Python's Thread if / other expression, such as:

  str if len (str) & lt; 2 other 'die' + str + '/ dom'    

No comments:

Post a Comment