如何删除一行字母中的最后一个字母?



在我的程序计算了所有的数字之后,我在删除在我的两行中不断弹出的一个额外的字母时遇到了一点麻烦。

它应该产生什么:

Nick向前走了多少步:4

Nick倒退了多少步:2

Bill向前走了多少步:5

Bill后退了多少步:3

完成游戏需要多少步骤:13

尼克FFFFBBFFFFBBF =距起点5步

法案FFFFFBBBFFFFF =距起点7步

13步后Bill领先

它产生了什么:

Nick向前走了多少步:4

Nick倒退了多少步:2

Bill向前走了多少步:5

Bill后退了多少步:3

完成游戏需要多少步骤:13

尼克FFFFBBFFFFBBFB =距起点5步

法案FFFFFBBBFFFFFB =距起点7步

13步后Bill领先

总的来说,这个问题不是什么大问题,因为程序的其余部分工作得很好,但是如果有人有解决这个问题的办法,我洗耳恭听。

我的代码:

#Enter how many steps Nick and Bill went forward and backward, and how many paces are needed to finish the game
A = int(input("How many steps did Nick take forwards: "))
B = int(input("How many steps did Nick take backwards: "))
C = int(input("How many steps did Bill take forwards: "))
D = int(input("How many steps did Bill take backwards: "))
S = int(input("How many steps were needed to finish the game: "))
#Counters to track how far Nick and Bill go, and how many paces they made to finish the game
counter = 0
counter2 = 0
paces = 0
paces2 = 0
#Check how many steps Nick and Bill made, and how many paces he took
print("nNick")
while(counter < S):
F = 0
while(F < A):
print("F", end="")
F = F + 1
paces = paces + 1
counter = counter + 1
if counter >= S:
break
b = 0
while(b < B):
print("B", end="")
b = b + 1
paces = paces - 1
counter = counter + 1
if counter >= S:
break
print(" =",paces + 1 ,"paces from the start")     
#Check how many steps Bill made, and how many paces he took
print("nBill")
while(counter2 < S):
F2 = 0
while(F2 < C):
print("F", end="")
F2 = F2 + 1
paces2 = paces2 + 1
counter2 = counter2 + 1
if counter2 >= S:
break
b2 = 0
while(b2 < D):
print("B", end="")
b2 = b2 + 1
paces2 = paces2 - 1
counter2 = counter2 + 1
if counter2 >= S:
break
print(" =",paces2 + 1 ,"paces from the start") 
#Display who won, and by how much
if paces > paces2:
print("nNick is Ahead after",S,"steps")
elif paces < paces2:
print("nBill is Ahead after",S,"steps")
elif paces == paces2:
print("nBill and Nick are Tied after",S,"steps")

在你的代码中,你使用计数器的步骤数,你有一个break语句输出值并增加计数器。

应该把移到之前.

你的错误是一个非常经典的off-by-one错误;)

改变:

while(F < A):
print("F", end="")
F = F + 1
paces = paces + 1
counter = counter + 1
if counter >= S:
break

为:

while(F < A):
if counter >= S:
break
print("F", end="")
F = F + 1
paces = paces + 1
counter = counter + 1

并且在其他3个类似循环中相同。

NB。我想借此机会告诉您,虽然您的代码逻辑很好,但是您有很多重复的代码。对于两个孩子来说几乎是一样的,对于每个孩子来说前进和后退几乎是一样的。

你现在应该做的是重构您的代码避免重复的逻辑。例如,你可以使用一个主循环来遍历子循环和向前/向后或更好的使用函数将代码分解为原子任务。

You loopwhile counter < S

在两个循环结束时,你有counter = 12,外循环再次开始。

现在,你向前一步,意识到counter >= S,并打破内部的while F < A循环。但是你仍然进入下一个while b < B循环检查counter的值之前。

相反,您应该检查counter的值作为两个内循环的条件,进入内循环之前。

A, B, S = 4, 2, 13
print("nNick")
while(counter < S):
F = 0
while F < A and counter < S:
print("F", end="")
F = F + 1
paces = paces + 1
counter = counter + 1

b = 0
while b < B and counter < S:
print("B", end="")
b = b + 1
paces = paces - 1
counter = counter + 1

print(" =",paces + 1 ,"paces from the start")

给了:

Nick
FFFFBBFFFFBBF = 6 paces from the start

最新更新