【问题标题】:How do I refactor this code to make it shorter?如何重构此代码以使其更短?
【发布时间】:2016-10-11 18:30:23
【问题描述】:
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
w=0
while w == 5:
print("Would you like to *work out* a missing letter in a GTIN-8 code, or *check* a code?")
response = input(":")
if response == 'work out':
    print("Input a 7 digit GTIN-8 code and I'll work out the 8th")
    c1 = int(input("Enter FIRST number: "))
    c2 = int(input("Enter SECOND number: "))
    c3 = int(input("Enter THIRD number: "))
    c4 = int(input("Enter FOURTH number: "))
    c5 = int(input("Enter FIFTH number: "))
    c6 = int(input("Enter SIXTH number: "))
    c7 = int(input("Enter SEVENTH number: "))

    y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
    ru2=roundup(y)
    GTIN8 = ru2-y
    print("Your GTIN8 Code would be: "+str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(GTIN8))
    print("Wanna work out another?") 
if response == 'check':
    print("Input a 8 digit GTIN-8 code and I'll check if it's correct")
c1 = int(input("Enter FIRST number: "))
c2 = int(input("Enter SECOND number: "))
c3 = int(input("Enter THIRD number: "))
c4 = int(input("Enter FOURTH number: "))
c5 = int(input("Enter FIFTH number: "))
c6 = int(input("Enter SIXTH number: "))
c7 = int(input("Enter SEVENTH number: "))
c8 = int(input("Enter EIGTH number: "))
y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
ru2=roundup(y)
GTIN8 = ru2-y
if GTIN8 != c8:
    print("Nope that product code is incorrect!")
    reply=input("Want to know the correct answer to your code? Type yes if so: ")
if reply == 'yes':
    print("The correct answer would have been: "+str(GTIN8))
if GTIN8 == c8:
    print("That code is correct!")

问题是我一次又一次地尝试让这段代码更小。

即使将“响应”作为字符串输入,也可以让用户一次性输入代码。

如果您还不知道,这是 GTIN-8 产品代码的代码,我知道还有其他各种 GTIN-8 代码,但我就是做不到,更不用说复制了。

【问题讨论】:

  • 你想要改进的功能代码可以提交到代码审查stackexchange
  • 创建一个输入 7 个数字的函数,然后在这两种情况下重复使用该函数。对于需要第 8 个输入的那个,要么保留你现在拥有的行,要么让你的函数接受一个布尔值,表示它是否需要输入 8。然后你可以返回一个包含所有值的列表。跨度>
  • 我建议你在codereview.stackexchange.com

标签: python-3.x reduction


【解决方案1】:

为了让您开始,这里有一种减少行数的简单方法

c = [int(x) for x in input("Input a 8 digit GTIN-8 code and I'll check if it's correct").split("")]

现在您可以使用c[n] 访问每个字符。

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多