[英]Nested loops with different and dependant steps
我需要制定一個算法來執行具有 2 個 while 循環的任務。 我將解釋我想要實現的目標。 我需要根據 h 值的長度進行循環。 那么循環應該與 f.ex 一起邁出一大步。 3 或 2 或 4,while 或 for 循環中的項目應檢查條件或方程式。 我需要檢查何時或哪個項目的值給方程中的 n 賦予零值。 當 n 值達到零時,我需要使用 0.1 執行更小的步驟。 因為我需要更精確。 沒有必要在開始時以小步長開始循環,它會減慢執行時間,並且知道 item 的精確小值會給出零到 n 方程的值是很有趣的。 當 n 方程接近零值時,這是正確的。
舉例說明:循環 1 開始並邁出大步。
h = 50
st = 10
loop 1 starts
0 , 3, 6, 9, 12, 15, 18, 21, 24 ………………… #<-------- steps from h value
25.0 , 22.0 , 19.0, 16.0, 13.0, 10.0, 7.0, 4.0, 1.0 ………………… #<-------- calculate values from n equation
If n <= 2 or n>= -2:
|_____ loop 2 starts with:
24.0, 23.9 , 23.8, 23.7, 23.6, …………….. #<-------- small steps iterate with hj = 24+st
0.4, 0.3 , 0.1, 0.0, -1.0, …………….. #<-------- calculate values from n equation
Calculate n values from n equation
M = 2 + n
If (n <= 0 or n>= -1) and M==2 : #<-------- If statement is fullfilled then return some values and quit loop 2 and loop 1.
Return n, itemstep from loop 2, M
Elif (n <= 0 or n>= -1) and M!=2:
Quit loop 2 and 1 #<-------- If statement is not fullfilled then quit loop 2 and loop 1.
n >= -1的原因,因為我們可以從 50 開始逐步下降到 0,並且 n 值也可以是負數。 我試圖用下面的代碼來解決它,但它似乎不起作用,這是在 while 或 for 循環中生成此類代碼的一種方法。
M = 2 #<---------- to check conditions
j = 0
st = 10
h = 50 #<---------- to iterate over length h
n = h/2 - j #<---------- to calculate n values (n equation)
result =[]
while j <=h: #<---------- loop 1
n = h/2 - j
if n <= 3 or n >= -3: #<---------- if this is satisified then start loop2
print(n)
i=j
while i < 10+st: #<---------- loop 2
n = h/2-i
M = 2+n
if (n <= 0 or n>= -1) and M==2:
result.append(n, i, M) #<---------- return values
i = 70+j #<---------- stop loop 2 and loop 1
j = h+70
elif (n <= 0 or n>= -1) and M!=2: #<---------- if this is not satisified then quit loop2 and loop 1
i = 70+j #<---------- stop loop 2 and loop 1
j = h+70
i +=0.1
j += i
j += 3
這可能會對你有所幫助。 (不完全是你想要的,但這是一個開始)
j = 0
h = 50
while j <= h:
n = h/2 - j
if -3 <= n <= 3:
i = j
while i < j + 10:
n = h/2 - i
if n <= 0:
j = h + 70
print(n)
break
i += 0.1
j += 3
或者你可以這樣做。
j = 0
h = 50
while j <= h:
n = h/2 - j
if -3 <= n <= 3:
break
j += 3
i = j
while i < j + 10:
n = h/2 - i
if n <= 0:
print(n)
break
i += 0.1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.