我怎样才能缩短这段代码

我怎样才能缩短这段代码

本文介绍了我怎样才能缩短这段代码? (Python 3.3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为一个名为Codebreaker的项目完成了一小段代码,其中生成了一个数字并且必须猜测。您的猜测与名为Code的生成数组进行比较。目前,我编程的部分是程序在猜测中输出错误位置的正确数字的AMOUNT。有没有办法缩短或将其变成子程序?



如果guess1 == code [1]:
wronPlace =(wronPlace + 1)
如果guess1 == code [2]:
wronPlace =(wronPlace + 1)
如果guess1 == code [3]:
wronPlace =(wronPlace + 1)

如果guess2 == code [0]:
wronPlace =(wronPlace + 1)
如果guess2 == code [2]:
wronPlace =(wronPlace + 1)
如果guess2 == code [3]:
wronPlace =(wronPlace + 1)

如果guess3 == code [0]:
wronPlace =(wronPlace + 1)
如果guess3 == code [1]:
wronPlace =(wronPlace + 1)
if guess3 == code [3]:
wronPlace =(wronPlace + 1)

如果guess4 == code [0]:
wronPlace =(wronPlace + 1)
如果guess4 == code [1]:
wronPlace =(wronPlace + 1)
如果guess4 =代码[2]:
wronPlace =(wronPlace + 1)





我尝试了什么:



我试图将其变成子程序或手动缩短它但没有运气。任何人都可以帮忙吗?

解决方案



仔细阅读你的代码!

你检查 guess1 3次,

然后你检查 guess2 3次,

然后你检查 guess3 3次,

此时,人们可以指望你检查 guess4 3次但是,

你检查 guess4 1次, guess3 2次。

是吗你想要什么?



[更新]



好​​的。所以你的代码是完全错误的,因为当代码或猜测中有2个相同的数字时你就不会处理。

示例:代码是1123,猜测是3211,你的程序会说有6个错位数字。

您必须重新考虑逻辑。



I have finished a small piece of code for a project called Codebreaker where a number is generated and one has to guess. Your guess is compared to the generated array named "Code". Currently the part I have programmed is where the program outputs the AMOUNT of correct digits in the wrong place within your guess. Is there a way to shorten this or turn it into a sub-routine?

if guess1== code[1]:
    wronPlace= (wronPlace+1)
if guess1== code[2]:
    wronPlace= (wronPlace+1)
if guess1== code[3]:
    wronPlace= (wronPlace+1)

if guess2== code[0]:
    wronPlace= (wronPlace+1)
if guess2== code[2]:
    wronPlace= (wronPlace+1)
if guess2== code[3]:
    wronPlace= (wronPlace+1)

if guess3== code[0]:
    wronPlace= (wronPlace+1)
if guess3== code[1]:
    wronPlace= (wronPlace+1)
if guess3== code[3]:
    wronPlace= (wronPlace+1)

if guess4== code[0]:
    wronPlace= (wronPlace+1)
if guess4== code[1]:
    wronPlace= (wronPlace+1)
if guess4= code[2]:
    wronPlace= (wronPlace+1)



What I have tried:

I've tried to turn it into a sub-routine or shorten it manually but have had no luck. Could anyone help?

解决方案


Read carefully your code!
you check guess1 3 times,
then you check guess2 3 times,
then you check guess3 3 times,
at this point, one can expect you to check guess4 3 times but,
you check guess4 1 time and guess3 2 times.
Is it what you want?

[Update]


OK. So your code is plain wrong because you don't handle when there is 2 identical digits in code or guesses.
Example: code is 1123 and guess is 3211, your program will say there is 6 wrong placed digits.
You have to rethink the logic.



这篇关于我怎样才能缩短这段代码? (Python 3.3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:33