我真的不知道如何解釋它,但我需要撰寫一個應該輸出以下內容的 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
有人可以幫助我并解釋我該怎么做嗎?
謝謝 :)
uj5u.com熱心網友回復:
好的,一種解決方案如下:
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, 4, 8)您可以使用[2**n for n in range(1,max_exp 1)]where max_expis a input of your selection
uj5u.com熱心網友回復:
看起來這個程式需要像這樣運行:
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
想一想這里的模式,看看你能不能解決它!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/376329.html
