我知道用 Python 做很多事情有疯狂的捷径,这就是我在 CIS 入门类(class)的这个项目中遇到麻烦的地方。我已经搜索了我的问题的变体,但没有运气......所以:
该项目是让我们的“turtle ”使用将输入命令行的 ZIP 绘制条形码。我完成了很多结构性工作,即:对特定数字进行编码并告诉 turtle 为特定数字绘制条形图多长时间。但是,现在我坚持编写 for 循环以实际将这两个部分放在一起并获取绘制条形码的程序。
这是我所拥有的:
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
import turtle # Used in your function to print the bar code
## Constants used by this program
SLEEP_TIME = 30 # number of seconds to sleep after drawing the barcode
ENCODINGS = [[1, 1, 0, 0, 0], # encoding for '0'
[0, 0, 0, 1, 1], # encoding for '1'
[0, 0, 1, 0, 1], # encoding for '2'
[0, 0, 1, 1, 0], # encoding for '3'
[0, 1, 0, 0, 1], # encoding for '4'
[0, 1, 0, 1, 0], # encoding for '5'
[0, 1, 1, 0, 0], # encoding for '6'
[1, 0, 0, 0, 1], # encoding for '7'
[1, 0, 0, 1, 0], # encoding for '8'
[1, 0, 1, 0, 0] # encoding for '9'
]
SINGLE_LENGTH = 25 # length of a short bar, long bar is twice as long
def compute_check_digit(digits):
sum = 0
for i in range(len(digits)):
sum = sum + digits[i]
check_digit = 10 - (sum % 10)
if (check_digit == 10):
check_digit = 0
return check_digit
def draw_bar(my_turtle, digit):
my_turtle.left(90)
if digit == 0:
length = SINGLE_LENGTH
else:
length = 2 * SINGLE_LENGTH
my_turtle.forward(length)
my_turtle.up()
my_turtle.backward(length)
my_turtle.right(90)
my_turtle.forward(10)
my_turtle.down()
def draw_zip(my_turtle, zip):
# WHAT DO I DO
print("My code to draw the barcode needs to replace this print statement")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ZIP", type=int)
args = parser.parse_args()
zip = args.ZIP
if zip <= 0 or zip > 99999:
print("zip must be > 0 and < 100000; you provided", zip)
else:
my_turtle = turtle.Turtle()
draw_zip(my_turtle, zip)
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
main()
开始和结束时的argparse/parser 东西是我们开始每个项目时给我们的。
我知道下一行在某些地方会有帮助,我查看了 map 功能,我知道我需要将编码从字符串转换为整数。
map (列表,海峡( zip ))
谢谢!
请您参考如下方法:
您需要遍历 zip 的数字。 对于每个数字,您将遍历 5 个条。
for str_digit in str(zip):
digit = int(str_digit)
for bar_bit in ENCODINGS[digit]:
draw_bar(my_turtle, bar_bit)
<move turtle to next bar's starting point>
我希望这对您来说是可以理解的。您可以使用各种 Python 技术来缩短代码,但这很容易理解。
