关于python:减少行数或提高代码效率

Reduce line count or make this code more efficient

在我不断追求知识的过程中,我想知道是否有任何方法可以减少行数或提高代码的效率。这是我做的一个游戏,我挑战自己尽可能短(在最初的游戏中,它的长度是这个的两倍:d)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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(guess):
    try:
        guess=int(guess)
        return True,guess
    except:
        print("Try again, not a number")
        repeat=1
def GameLevel(Range,gameLives,level,hints):
    lives,hints,targetnumber,repeat=gameLives,hints,random.randint(1,1),1
    print("LEVEL {}\
Thinking..."
.format(level))
    if level>1:
        print("You now have {} lives remaining".format(gameLives))
    if level==10:
        print("Welcome to the hardest level\
No bonus lives are awarded for the final level"
)
    print("This number is between 1 and"+str(Range))
    while repeat==1:
        guess=input("What is your guess?")
        guess,repeat,targetnumber=guess.lower(),0,str(targetnumber)
        if guess=="hint":
            if level>=3:
                if hints!=1:
                    targetnumber=int(targetnumber)
                    print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
                    repeat,hints=1,hints-1
                else:
                    print("Sorry you have ran out of hints :(")
                    repeat=1
            else:
                print("Hints are not available until level 3")
                repeat=1
        elif guess==targetnumber:
            print("Well done, You have guessed my number!")
            return lives,hints
        elif guess!=targetnumber:
            if is_valid(guess)==True:
                print("Sorry that is not my number, you have lost a life. :(")
                targetnumber,lives,repeat=int(targetnumber),lives-1,1
                if lives<=0:
                    print("You have lost all your lives, so this means I win\
The program will now end"
)
                    input("")
                    exit()
                if guess<targetnumber:
                    print("The target number is higher")
                else:
                    print("The target number is lower")
            else:
                repeat=1
print("Welcome to my number guessing game!\
I will think of a number between a certain range and you have to guess it.\
Each time you guess my number I will think of a harder one.\
You will start with {} lives and {} hints, Good Luck!\
To use your hint you will have to enter the word hint\
Extra lives will be awarded for each completed level"
.format(gameLives,(hints-1)))
a,b=0,0
for level in levels:
    Range=levelRange[a]
    gameLives,hints=GameLevel(Range,gameLives,level,hints)
    if gameLives>0 and wonGame!=10:
        addLives=awardedLives[b]
        if addLives!=0:
            print("You have gained {} extra lives".format(addLives))
            gameLives+=addLives
        wonGame+=1
    a,b=a+1,b+1
score=gameLives+10*(hints-1)
print("Calculating your score.\
Your score is {} . Well done!"
.format(score))


这是我用同样的方法获得程序的最小代码,问题是代码是63行,我设法将其减少到29行;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 {}\
Thinking..."
.format(level))
    if level>1:print("You now have {} lives remaining".format(gameLives))
    if level==int(levels[-1]):print("Welcome to the hardest level\
No 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\
The program will now end\
"
))
            print("The target number is {}".format("higher" if (guess<targetnumber) else"lower"))
print("Welcome to my number guessing game!\
I will think of a number between a certain range and you have to guess it.\
Each time you guess my number I will think of a harder one.\
You will start with {} lives and {} hints, Good Luck!\
To use your hint you will have to enter the word hint\
Extra 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.\
Your score is {} . Well done!"
.format(gameLives+10*(hints-1)))