While working on a simple coding question, writing a function findPeakElement
, I came across the following code:
def findPeakElement(self, nums):
size = len(nums)
for x in range(1,size-1):
if nums[x] > nums[x-1] and nums[x] > nums[x+1]:
return x
return [0,size-1][nums[0]<nums[size-1]]
What is the meaning of last line?
In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world" nums = [1, 2, 3, 4] print(hello[::-1])
When you see the % symbol, you may think "percent". But in Python, as well as most other programming languages, it means something different. The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.
edited Nov 27, 2020 by hari_sh. It acts as an indicator in the format method that if you want it to be replaced by the first parameter(index zero) of format. Example : print(42+261={0}.format(303)) Here, {0} will be replaced by 303.
string[::4] reads “default start index, default stop index, step size is four—take every fourth element“. string[2::2] reads “start index of two, default stop index, step size is two—take every second element starting from index 2“.
That last row is an obscure way of writing an if then else
expression.
[0, size-1]
creates a list of two elements.nums[0] < nums[size-1]
returns either True
or False
True/False
is implicitly converted into 1
or 0
.size-1
or 0
is picked from the list.A clearer way to write it is:
return size - 1 if nums[0] < nums[size - 1] else 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With