1

私がやろうとしているのは、変数 "FGlasgow" から食べ物を取り、それを変数 "食べ物" に追加することです. 素晴らしくシンプルです. しかし、FGlasgow が負になったときでも、スクリプトはさらに多くの時間がかかることに気付きました. Glasgow < 0 で食べ物を追加して乱数を取ります。問題は、これを短縮できるかどうか、そして私の方法が正しいかどうかです。

import random

def RandomNo():
    Random = random.randint(0,50)
    return Random

Food = 1
FGlasgow = 100


while True:
    Random = RandomNo()
    Food += Random
    FGlasgow -= Random
    while FGlasgow < 0:
        Food -= Random
        FGlasgow += Random
        Random = RandomNo()
        Food += Random
        FGlasgow -= Random
    print "You have found" , Random , "units of food"

助けてくれてありがとう:)どんな提案も素晴らしいでしょう:)

4

3 に答える 3

1

変数名を変更したことがわかります。それらはPEP-8に従って変更されました。

コードに関しては、はい、短縮できます。外側の while ループは必要ありません。f_glasgowまた、が 0 を下回らないようにしたい場合は、次のようにします。

import random

def randomNo(limit):
    return random.randint(0,min(50,limit))

food = 1
f_glasgow = 100

while f_glasgow >= 0:
    x = randomNo(f_glasgow)
    food += x
    f_glasgow -= x
print "You have found" , food , "units of food"
于 2013-03-13T18:02:47.573 に答える
0

最初のwhileループをスキップしないのはなぜですか?また、なぜ2番目のランダム計算を行っているのか混乱しています。それは潜在的に最初のものを否定することができませんでしたか?単純にしないのはなぜですか。

def RandomNo():
    Random = random.randint(0,FGlasgow)
    return Random

if (FGlasgow > 0):
    Random = RandomNo()
    Food += Random
    FGlasgow -= Random
于 2013-03-13T17:41:42.153 に答える
0

FGlasgowRandomがより大きい場合にのみ負になりFGlasgowます。したがって、それが発生しないようにする場合は、使用する引数を変更して、randint()次よりも大きい値を取得できないようにしますFGlasgow

import random

def RandomNo(upper=50):
    Random = random.randint(1, min(50, upper))
    return Random

Food = 1
FGlasgow = 100

while FGlasgow > 0:
    Random = RandomNo(FGlasgow)
    Food += Random
    FGlasgow -= Random
    print "You have found" , Random , "units of food"

あなたのコードと私の両方で最終的FGlasgowに0に達することに注意してください、あなたのコードは無限のループで立ち往生するでしょう、それが私がwhile最終的に停止するように条件を変更した理由です。

于 2013-03-13T17:41:54.633 に答える