Python程序检查组合数组所有元素形成的数字是否为回文
给定一个数组 arr[],任务是按顺序组合数组中的所有元素并检查它是否是回文。
例子:
Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1}
Output: palindrome
Explaination: The number formed by combining all the elements is “1695445961” which is a palindrome
Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2}
Output: not palindrome
Explaination: The number formed by combining all the elements is “2739559962” which is not a palindrome
方法一:使用 map() 和 join()
- 使用将列表的每个元素转换为字符串 map()函数。
- 使用加入列表 加入()函数。
- 检查它是否是回文。
- 如果是,则打印回文。
- 如果没有打印,则不是回文。
下面是上述方法的实现:
Python3
# function to check palindrome
def checkPalindrome(string):
# reverse the string
rev = string[::-1]
# checking if string is equal to reverse
if(string == rev):
return True
else:
return False
# function to convert list to single number string
def joinArray(lis):
# convert the elements of list to string
lis = list(map(str, lis))
# converting list to string
number = ''.join(lis)
# checking if it is palindrome
if(checkPalindrome(number)):
return True
else:
return False
# Driver code
lis = [1, 76, 39, 93, 67, 1]
if(joinArray(lis)):
print("Palindrome")
else:
print("not Palindrome")
Python3
# function to check palindrome
def checkPalindrome(string):
# reverse the string
rev = string[::-1]
# checking if string is equal to reverse
if(string == rev):
return True
else:
return False
# function to convert list to single number string
def joinArray(lis):
# defining empty string as number
number = ""
# convert the elements of list to string using type conversion
for i in lis:
# converting to string
i = str(i)
# concat this to string
number = number + i
# checking if it is palindrome
if(checkPalindrome(number)):
return True
else:
return False
# Driver code
lis = [1, 76, 39, 93, 67, 1]
if(joinArray(lis)):
print("Palindrome")
else:
print("not Palindrome")
输出:
Palindrome
时间复杂度: O(n)
方法 2:使用类型转换和字符串连接
- 取一个空字符串说str。
- 遍历列表并使用类型转换将每个元素转换为字符串
- 使用字符串连接将此添加到str
- 检查str是否为 回文
下面是上述方法的实现:
蟒蛇3
# function to check palindrome
def checkPalindrome(string):
# reverse the string
rev = string[::-1]
# checking if string is equal to reverse
if(string == rev):
return True
else:
return False
# function to convert list to single number string
def joinArray(lis):
# defining empty string as number
number = ""
# convert the elements of list to string using type conversion
for i in lis:
# converting to string
i = str(i)
# concat this to string
number = number + i
# checking if it is palindrome
if(checkPalindrome(number)):
return True
else:
return False
# Driver code
lis = [1, 76, 39, 93, 67, 1]
if(joinArray(lis)):
print("Palindrome")
else:
print("not Palindrome")
输出:
Palindrome