我真的不知道如何解释它,但我需要编写一个Python程序,它应该输出如下:
1
2
1-2
3
4
3-4
1-2-3-4
5
6
5-6
7
8
7-8
5-6-7-8
1-2-3-4-5-6-7-8有人能帮我解释一下怎么做吗?
谢谢您:)
发布于 2021-12-08 06:34:00
好的,一个解决方案是:
lst = list(range(1,9))
def func(l):
lst_str = list(map(str, lst))
for i in l:
print(i)
for dvd in (2, 4, 8):
if i % dvd == 0:
print("-".join(lst_str[i-dvd:i]))
func(lst)输出
1
2
1-2
3
4
3-4
1-2-3-4
5
6
5-6
7
8
7-8
5-6-7-8
1-2-3-4-5-6-7-8对于其他系列,这可能会失败,所以也许我们要检查元素在列表中的位置,而不是元素本身。例如:
lst = list(range(9,17))
def func(l):
lst_str = list(map(str, lst))
for n, i in enumerate(l):
print(i)
n += 1
for dvd in (2, 4, 8):
if n % dvd == 0:
print("-".join(lst_str[n-dvd:n]))
func(lst)输出
9
10
9-10
11
12
11-12
9-10-11-12
13
14
13-14
15
16
15-16
13-14-15-16
9-10-11-12-13-14-15-16您可以将其扩展到更大的2倍,因此,您可以使用[2**n for n in range(1,max_exp + 1)],而不是仅针对[2**n for n in range(1,max_exp + 1)]进行迭代,而max_exp是您选择的输入。
发布于 2021-12-08 05:59:38
看起来这个程序需要这样运行:
output first number
output second number
output first-second numbers
output third number
output fourth number
output third-fourth numbers
output first to fourth numbers
(same for five to eight)
output all eight考虑一下这里的模式,看看你能不能解决它!
发布于 2021-12-08 10:24:54
我意识到这个问题已经解决了,并且选择了一个答案,但是我想到了一个更通用的算法,我觉得这是我不得不分享的。我们反复地连接以前的模式(由“-”分隔),这种连接发生在迭代次数可被除以的每个完美的2次方的1倍。因此,通过一些位检查和堆栈操作,我们可以很容易地将问题抽象成一个解决方案,它可以与任意大小的输入、任何字符集等一起工作,甚至可以在两个大小的非幂输入上表现良好。
def print_patterns(alphabet, delimiter="-"):
stack = []
def push(pattern):
print(pattern)
stack.append(pattern)
def pop():
pat1 = stack.pop()
pat2 = stack.pop()
return f"{pat2}{delimiter}{pat1}"
for index, char in enumerate(alphabet, 1):
push(char)
for bit in reversed(bin(index)):
if bit != '0':
break
push(pop())示例输出:
>>> print_patterns("12345678")
1
2
1-2
3
4
3-4
1-2-3-4
5
6
5-6
7
8
7-8
5-6-7-8
1-2-3-4-5-6-7-8还有一个边缘案件:
>>> print_patterns("abcdef", "*")
a
b
a*b
c
d
c*d
a*b*c*d
e
f
e*fhttps://stackoverflow.com/questions/70270560
复制相似问题