阿伦森序列

2024-04-27 01:02:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现阿伦森的序列(“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


Tags: theinforifinit字母序列temp
1条回答
网友
1楼 · 发布于 2024-04-27 01:02:59

我认为这段代码满足了wiki page对这个序列的要求。请注意,它与代码的输出不同。你知道吗

from num2words import num2words
import re

def Aronson_Sequence(letter, term_limit):
    sentence = letter + ' is the '
    start = 0
    while term_limit > 0:
        index = re.sub('[\W_]', '', sentence).find(letter, start)
        if index < 0:
            break
        if index != 0:
            sentence += ', '
        sentence += num2words(index+1, to='ordinal')
        term_limit -= 1
        start = index+1
    return sentence + ' letter in this sentence'

print(Aronson_Sequence('t', 10))    
print(Aronson_Sequence('g', 10))
print(Aronson_Sequence('r', 10))

输出为:

t is the first, fourth, eleventh, sixteenth, twenty-fourth, twenty-ninth, thirty-third, thirty-fifth, thirty-ninth, forty-fifth letter in this sentence
g is the first letter in this sentence
r is the first, ninth letter in this sentence

相关问题 更多 >