def num_sequence (num1, num2):
#This function takes the lower and upper bound and builds a list.
array = []
for i in range(num2 + 1):
if i >= num1:
array.append(i)
return array
def inverted_sequence (array):
#This function takes the previous and list inverts the numbers in every element.
for i in range(len(array)):
if array[i] > 10:
array[i] = str(array[i])
#Converts the i element of the array to a string.
array[i] = array[i][::-1]
#Inverts the the position of the numbers in every element.
array[i] = int(array[i])
#Converts the i element of the array to an integer.
return array
def main ():
#Main program.
lower = int(input("Type the lower bound: "))
upper = int(input("Type the upper bound: "))
sequence = num_sequence(lower, upper)
inv_sequence = sequence[:]
inv_sequence = inverted_sequence(inv_sequence)
print (sequence)
print (inv_sequence)
"""While loop inside the for loop that checks if the number is a palindrome.
if to check if it is a palindrome return True, else return False"""
pal_count = 0
seq_sum = []
for i in range(len(sequence)):
if sequence[i] != inv_sequence[i]:
while sequence[i] != inv_sequence[i]:
seq_sum.append(sequence[i] + inv_sequence[i])
sequence = seq_sum
inv_sequence = inverted_sequence(inv_sequence)
print (seq_sum)
if sequence[i] == inv_sequence[i]:
pal_count *= 1
print (pal_count)
main()
我正在尝试制作一个程序,找到一系列数字中的所有回文,如果它们不是回文数,则将数字反转并将其添加到原始数据中,直到它成为回文数据。在我的代码中,我创建了一个带有两个输入的数字列表,并将列表序列命名。 inv_sequence是前一个列表,但每个元素的数字都相反。当我尝试添加sequence [i]和inv_sequence [i]时,程序会抛出一个错误,指出列表超出范围。我正在测试程序,下限为5,上限为15。
答案 0 :(得分:0)
我认为你的意思是你希望最终列表包含由序列中前一个数字的总和和反转序列中前一个数字的结果形成的序列中的最低回文。
如果是这样,这里有一些代码(不是防弹):
#checks if a number is a palindrome by comparing the string written fowards
#with the string written backwards
def is_pal(x):
if str(x)==str(x)[::-1]:
return True
return False
#iterates a number by adding and reversing until it is a palindrom
def iter_pal(x):
while not is_pal(x):
x+=int(str(x)[::-1]) #adds the number's reverse to itself
return x
#main program
def main():
#gets input
lower = int(input("Type the lower bound: "))
upper = int(input("Type the upper bound: "))
#uses range to make the sequence of numbers
sequence = list(range(lower,upper+1))
#iterates through the list performing iter_pal
for i in range(upper-lower+1):
sequence[i]=iter_pal(sequence[i])
#prints the final sequence
print(sequence)
main()
我不确定你会对Lychrel numbers做些什么。