x = 64
root = 0
for pwr in range(2,6):
if x > 1:
while root <= x:
root = 1
if root**pwr == x:
print('root = ', root, ' and pwr = ', pwr)
root = 0
elif x < 0:
while root >= x:
root -= 1
if root**pwr == x:
print('root = ', root, ' and pwr = ', pwr)
root = 0
elif x == 0:
print('There is no such pair')
break
我收到的輸入是: root = 8 和 pwr = 2 root = 4 和 pwr = 3
但是,如果可用,我只想獲得最高的根答案。
所以我希望我的輸入只是:
根 = 8 和 pwr = 2
反之亦然......如果我只想顯示它該怎么辦:root = 4 and pwr = 3
謝謝!
uj5u.com熱心網友回復:
您應該創建新變數max_root, max_pwr,root然后在計算時檢查它是否更大max_root并替換max_root, max_pwr或保留舊值。
而且你應該只在所有計算之后顯示
x = 64
root = 0
max_root = 0
max_pwr = 0
for pwr in range(2,6):
if x > 1:
while root <= x:
root = 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
if root > max_root:
max_root = root
max_pwr = pwr
root = 0
elif x < 0:
while root >= x:
root -= 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
if root > max_root:
max_root = root
max_pwr = pwr
root = 0
elif x == 0:
print('There is no such pair')
break
# after `for`-loop
print('root = ', max_root, ' and pwr = ', max_pwr)
類似的方法你可以為其他結果做,但你可能需要<而不是>in lineroot > max_root并且你需要max_root在開始時設定 big - 即。99999。
x = 64
root = 0
max_root = 99999
max_pwr = 0
for pwr in range(2,6):
if x > 1:
while root <= x:
root = 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
if root < max_root:
max_root = root
max_pwr = pwr
root = 0
elif x < 0:
while root >= x:
root -= 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
if root < max_root:
max_root = root
max_pwr = pwr
root = 0
elif x == 0:
print('There is no such pair')
break
# after `for`-loop
print('root = ', max_root, ' and pwr = ', max_pwr)
為所有結果創建串列并在計算后過濾結果并僅顯示您需要的結果的其他方法。
x = 64
root = 0
all_results = []
for pwr in range(2,6):
if x > 1:
while root <= x:
root = 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
all_results.append( [root, pwr] )
root = 0
elif x < 0:
while root >= x:
root -= 1
if root**pwr == x:
#print('root = ', root, ' and pwr = ', pwr)
all_results.append( [root, pwr] )
root = 0
elif x == 0:
print('There is no such pair')
break
# after `for`-loop
#print(all_results)
max_result = max(all_results, key=lambda x:x[0])
max_root, max_pwr = max_result
print('MAX: root = ', max_root, ' and pwr = ', max_pwr)
min_result = min(all_results, key=lambda x:x[0])
min_root, min_pwr = min_result
print('MIN: root = ', min_root, ' and pwr = ', min_pwr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322690.html
上一篇:生成字典并不總是有效
