我想做的是用一定数量的字母数。输入是n和x,其中n是要使用的字母数,x是我要数的数字。假设n是3,x是12。它是这样的:'a','b','aa','ab','ba','bb','aaa','aab','aba','abb','baa','bab‘。使用两个数字计数时,‘'bab’是12。我知道有一种数学方法可以做到这一点,但我想不出答案。另一个测试用例是n= 16和x= 248832。它会返回“clkop”。如果以前有人问过这样的问题,我很抱歉,我什么也找不到。另外,让我知道这是否属于一个不同的网站。为了清楚起见,字母的数量可以从1到26个不等。如果是1,那么8将表示为'aaaaaaaa‘。如果字母数为2,8个字母将表示为'aab‘。如果它是3,那么17将被表示为'abc‘等。我认为它将像转换为基n一样简单,但它不是。希望,这是有帮助的。当我写这个问题时,我在javascript中看到了一个类似的问题,但它只处理了26个字母。我不知道如何将javascript代码转换为python代码,我希望能够处理1-26个字母中的任意数量的字母。我知道也有办法用暴力手段,但我不知道怎么做到的
如果这个问题需要进一步澄清,请告诉我。
编辑:我想出了如何将字母字符串转换成给定字母数量的数字。对于16个字母,clkop =3* ( 16 ^4) + 12 * ( 16 ^3) + 11 * ( 16 ^2) + 15 *16+16= 248832 (或x长度,其中v=当前字母在遍历字符串时的值,n=字母数,v* (n^x-1) +v*(n^x-2).希望你能用它做点什么。
发布于 2022-05-05 15:07:42
from string import ascii_lowercase
def alphabetic_counter(n, x):
letterNums = [0]
for i in range(x):
yield ''.join(reversed([ascii_lowercase[l] for l in letterNums]))
letterNums[0] += 1
currIdx = 0
while letterNums[currIdx] == n:
if currIdx == len(letterNums) - 1:
letterNums[currIdx] = 0
letterNums.append(0)
else:
letterNums[currIdx] = 0
currIdx += 1
letterNums[currIdx] += 1
print(list(alphabetic_counter(2,12)))输出:
['a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab']我不得不承认,这不是最漂亮的解决方案,但要么我的日子过得不好,要么比乍一看要难得多。
发布于 2022-05-05 12:57:30
你基本上是在问如何将一个数字转换成一个不同的基,字母是可能的数字:
import string
namespace = string.ascii_lowercase
def convert(base, num):
result = []
while num:
num -= 1
num, mod = divmod(num, base)
result.append(namespace[mod])
return "".join(reversed(result))发布于 2022-05-05 22:04:21
用n个不同的字母,我们可以形成

不同长度的单词最多有k。求y的结果是yth单词有长度。

。
如果我们以0开始计数,空单词“”,计数到x需要x+1不同的单词。
from math import log as ln
from math import ceil
from itertools import chain, product
def xth_word(x, n):
'''returns the xth word over the alphabet consisting of
the first n lowercase letters
The empty word '' is the 0th word
'''
letters = [chr(97 + i) for i in range(n)]
word_length = ceil(ln((x + 1) * (n - 1) + 1) / ln(n))
it = chain.from_iterable((product(letters, repeat=i)\
for i in range(word_length)))
word = next(w for i,w in enumerate(it) if i == x)
return ''.join(word)
print([xth_word(i, 2) for i in range(13)])
print(xth_word(248832, 16)) 输出:
“”、“a”、“b”、“aa”、“ab”、“ba”、“bb”、“aaa”、“aab”、“aba”、“abb”、“baa”、“bab”
clkop
https://stackoverflow.com/questions/72127374
复制相似问题