Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 减少行数或使此代码更高效_Python_Python 3.x_Memory Efficient - Fatal编程技术网

Python 减少行数或使此代码更高效

Python 减少行数或使此代码更高效,python,python-3.x,memory-efficient,Python,Python 3.x,Memory Efficient,在我不断增长的求知欲中,我想知道是否有任何方法可以减少行数或提高代码的效率。这是我制作的一款游戏,我向自己提出了挑战,让它尽可能短,(在最初的版本中,它的长度大约是这个的两倍:D) 随机导入 游戏寿命,提示,赢游戏,关卡,获奖者,关卡范围=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50100200250400500] def有效(猜测): 尝试: 猜测=int(猜测) 返回真值,猜猜看 除: 打印(“再试一次,

在我不断增长的求知欲中,我想知道是否有任何方法可以减少行数或提高代码的效率。这是我制作的一款游戏,我向自己提出了挑战,让它尽可能短,(在最初的版本中,它的长度大约是这个的两倍:D)

随机导入
游戏寿命,提示,赢游戏,关卡,获奖者,关卡范围=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50100200250400500]
def有效(猜测):
尝试:
猜测=int(猜测)
返回真值,猜猜看
除:
打印(“再试一次,不是数字”)
重复=1
def游戏级别(范围、游戏寿命、级别、提示):
生命,提示,目标编号,重复=游戏生命,提示,随机。随机数(1,1),1
打印(“级别{}\n思考…”格式(级别))
如果级别>1:
打印(“你现在还有{}条生命”。格式(游戏生命))
如果级别==10:
打印(“欢迎进入最难级别\n最终级别不授予生命奖励”)
打印(“此数字介于1和“+str(范围))
当repeat==1时:
猜测=输入(“你的猜测是什么?”)
猜,重复,targetnumber=guess.lower(),0,str(targetnumber)
如果猜测==“提示”:
如果级别>=3:
如果提示=1:
targetnumber=int(targetnumber)
打印(“数字在{}和{}之间”。格式((targetnumber//10)*10,(targetnumber//10+1)*10))
重复,提示=1,提示-1
其他:
打印(“对不起,您没有提示了:(”)
重复=1
其他:
打印(“提示在第3级之前不可用”)
重复=1
elif guess==目标编号:
打印(“干得好,你猜到我的号码了!”)
回归生命、回归暗示
elif guess!=目标编号:
如果有效(猜测)=真:
打印(“对不起,那不是我的号码,你失去了一条生命:”)
targetnumber,寿命,重复=整数(targetnumber),寿命-1,1

如果lifes这是我用同样的方式获得程序的最小值,在问题中代码是63行,我设法将它减少到29行

import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(y):
    try:y=int(y);return True
    except:print("Try again, not a number")
def GameLevel(Range,gameLives,level,hints):
    lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
    if level>1:print("You now have {} lives remaining".format(gameLives))
    if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
    print("This number is between 1 and "+str(Range))
    while True:
        guess=input("What is your guess? ");targetnumber=str(targetnumber)
        if guess.lower()=="hint":
            if level>=3:
                if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
                else:print("Sorry you have ran out of hints :(")
            else:print("Hints are not available until level 3")
        elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
        elif guess!=targetnumber and is_valid(guess)==True:
            print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
            if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
            print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
for level in levels:
    gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
    if gameLives>0 and wonGame!=int(levels[-1]):
        if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
        wonGame+=1
    a,b=a+1,b+1
input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))
import random;游戏寿命、提示、赢得游戏、关卡、获奖生活、关卡范围=3,6,0、[1,2,3,4,5,6,7,8,9,10]、[1,3,5,7,10,12,15,20,0,0]、[5,10,20,50100200250300400500]
def有效(y):
try:y=int(y);返回True
除了:打印(“重试,不是数字”)
def游戏级别(范围、游戏寿命、级别、提示):
生命,提示,目标编号=游戏生命,提示,随机.randint(1,范围);打印(“级别{}\n提示…”。格式(级别))
如果等级>1:打印(“你现在还有{}条生命”。格式(游戏生命))
如果等级==int(等级[-1]):打印(“欢迎进入最难的等级\n最终等级不授予额外寿命”)
打印(“此数字介于1和“+str(范围))
尽管如此:
猜测=输入(“你的猜测是什么?”);targetnumber=str(targetnumber)
如果guess.lower()=“提示”:
如果级别>=3:
如果提示!=1:targetnumber,则提示=int(targetnumber),提示-1;打印(“数字在{}和{}之间”。格式((targetnumber//10)*10,(targetnumber//10+1)*10))
else:print(“对不起,您没有提示了:(”)
其他:打印(“提示在第3级之前不可用”)
elif guess==targetnumber:print(“干得好,你猜到我的号码了!”);回归生活,提示
elif guess!=目标编号且有效(guess)=真:
打印(“对不起,那不是我的号码,你失去了生命。:”;猜,targetnumber,lifes=int(猜),int(targetnumber),lifes-1
if lives0:print(“你获得了{}个额外生命”。格式(AwardedLifes[b]);gameLives+=AwardedLifes[b]
wonGame+=1
a、 b=a+1,b+1
输入(“计算你的分数。\n你的分数是{}。做得好!”。格式(游戏生活+10*(提示-1)))

如果这项工作正常,则属于CR或code Golf。您可以将源代码提交给。如果您稍微增加行数,您的程序将更易于阅读。不要像那样将所有内容塞满,请添加一些空格!函数定义的上下应该有一个空行,运算符和等号should两侧各有一个空格,等等。请参见。也不要使用“裸”的
,除了
:最好给出实际的异常名称(如
ValueError
)@J.Piquard虽然这可能是一个很好的建议去回答这类问题的地方,但我们应该摆脱在那里发送提问者的习惯。请阅读元帖子以获得澄清。@PM2Ring,我刚刚回答了TigerhawkT3来解码CR的意思。关于你建议的元帖子,因为ion要求“使代码更高效”和“工作无误”,代码审查似乎是适当的。
import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(y):
    try:y=int(y);return True
    except:print("Try again, not a number")
def GameLevel(Range,gameLives,level,hints):
    lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
    if level>1:print("You now have {} lives remaining".format(gameLives))
    if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
    print("This number is between 1 and "+str(Range))
    while True:
        guess=input("What is your guess? ");targetnumber=str(targetnumber)
        if guess.lower()=="hint":
            if level>=3:
                if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
                else:print("Sorry you have ran out of hints :(")
            else:print("Hints are not available until level 3")
        elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
        elif guess!=targetnumber and is_valid(guess)==True:
            print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
            if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
            print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
for level in levels:
    gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
    if gameLives>0 and wonGame!=int(levels[-1]):
        if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
        wonGame+=1
    a,b=a+1,b+1
input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))