Python - 仅显示 4 位序列的二次曲线序列

Python - displaying conic sequence with only 4 digit sequencing

我正在编写一个程序来确定用户输入数据集的二次曲线序列,例如 - [0000,1,2222,9999],

我一直在努力仅使用 4 位分类而不是典型的 8/16 二进制方法对圆锥序列进行排序。


我试过这个:

for t in permutations(numbers, 4):
print(''.join(t))

但它不会为输入的数据分配唯一值,而是覆盖以前的值。

我该怎么做?

由于您的列表仅包含数字 0 到 9,并且您正在遍历该列表,边打印边打印内容,它只会打印 0 到 9。

由于正常十进制数字的所有可能组合(或者更确切地说是排列,因为这就是你要问的)只是数字 0 到 9999,你可以改为这样做:

for i in range(10000):
    print(i)

有关 range() 的更多信息,请参阅 https://docs.python.org/3/library/functions.html#func-range

但这不会将“0”之类的数字打印为“0000”。为此(在 Python 3 中,这可能是您应该使用的):

for i in range(10000):
    print(f"{i:04d}")

有关 f 弦的更多信息,请参阅 https://docs.python.org/3/reference/lexical_analysis.html#f-strings

当然,如果你需要数字以外的东西的排列,你不能使用这种方法。你会做这样的事情:

from itertools import permutations

xs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

for t in permutations(xs, 4):
    print(''.join(t))

有关 permutations() 的更多信息以及与 combinations() 的区别,请参阅 https://docs.python.org/3/library/itertools.html#itertools.permutations

如果你想在未来更改一些信息,你也可以这样做:

import math

NUMBERS = [0,1,2,3,4,5,6,7,8,9]
DIGITS = 4
MAX_ITERS = int(math.pow(len(NUMBERS), DIGITS))

for i in range(MAX_ITERS):
    print(f"{i:04d}")