I'm try learning to Python and I need given a list of integers, return true if the length of the list is greater than 1 and the first element and the last element are equal. Here is my code:
class Solution:
def solve(self, nums):
nums = []
if len(nums) > 1 and nums[0]== nums[-1]:
return True
return False
But I get this error:
if len(nums) > 1 and nums[0]== nums[-1]:IndentationError: unexpected indent
You could write it like
class Solution:
def solve(self, nums):
return (len(nums) > 1 and nums[0] == nums[-1])
You were initializing the nums
again and again to have zero elements plus the indention was wrong.
You got it almost right, if
statement should be nested inside the solve
method, however since you are returning True
or False
you can skip that and you don't need the nums list
either, so do this:
class Solution:
def solve(self, nums):
return len(nums) > 1 and nums[0]== nums[-1]
try this:
class Solution:
def solve(self, nums):
if len(nums) > 1 and nums[0]== nums[-1]:
return True
The error you got is an indentation error. In python, you should use either space or tab to represent body of a function or class ,like curly braces in c++ or javascript. It is important to note that you should keep equal indentation for each line inside a body segment. ie, if you start writing a function by giving 2 spaces as indentation,you should use 2 spaces for all the lines in the function body. The best way is to use tab instead of spaces so that you may not be confused with the number of spaces. Please take into account that you cannot use space and tab at a time. I have edited your code as,
class Solution:
def solve(self, nums):
return (len(nums) > 1 and nums[0]== nums[-1])
you can call the function as,
obj=Solution()
obj.solve([1,2,3,4,1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.