我试图实现阿伦森的序列(“t是第一,第四,第十一,第十六。。。作为一个函数,接收任何开头字母和词条限制(否则句子可能是无止境的),并返回序列。你知道吗
我已经设法用无限(t是第一个,第四个…)和有限(g是这句话的第一个字母)序列分别实现了这一点,但是在同时实现这两个序列时遇到了很多困难(换句话说,让函数与任何字母一起工作!)。你知道吗
我很感激你能帮我弄明白怎么做!你知道吗
这是最初的顺序:
import num2words # pip install num2words in terminal
def Aronson_Sequence(letter, term_limit):
term_num = 1
init_seed = letter + ' is the '
while term_num <= term_limit:
temp_seed = init_seed.replace(' ', '') # we aren't counting spaces
for i in range(len(temp_seed)):
if term_num > term_limit: # if term limit is exceeded within for loop
break
if (temp_seed[i] == letter) and ((num2words.num2words(i+1, to='ordinal') in init_seed) != True): # if letter matches and ordinal ('first') hasn't appeared yet
init_seed += num2words.num2words(i+1, to='ordinal') + ', '
term_num += 1
#if init_seed.replace(' ', '') == temp_seed:
#break (these commands break out of an infinite while loop, but they hurt infinite sentences because the for loop range isn't modified from inside)
init_seed = init_seed[:-2] + ' letter in this sentence.'
return init_seed
print(Aronson_Sequence('t', 10)) # first ten terms for an Aronson sequence beginning with the letter 't'
t is the first, fourth, eleventh, seventeenth, twenty-sixth, thirty-fourth, thirty-eighth, forty-first, forty-fifth, fifty-first letter in this sentence
我认为这段代码满足了wiki page对这个序列的要求。请注意,它与代码的输出不同。你知道吗
输出为:
相关问题 更多 >
编程相关推荐