2015-10-16 85 views
2

我知道有很多瘋狂的捷徑用Python做很多事情,這是我在介紹CIS類中遇到這個項目時遇到的問題。我搜索了我的問題的變體,但沒有運氣..所以:在Python上繪製帶有龜圖形的條形碼

該項目是讓我們的「烏龜」使用一個ZIP將繪製條形碼將進入命令行。我做了大量的結構工作,比如:對特定數字進行編碼,並告訴龜多長時間繪製特定數字的條形圖。但是,現在我堅持寫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 /分析器的東西在開頭和結尾是給我們。

我知道這下一行將有所幫助,我查了地圖功能,我知道我需要將編碼轉換爲字符串整數。

map(list,str(zip))

謝謝!

+0

歡迎來到StackOverflow。請記住閱讀並遵守幫助文檔中的發佈準則。 http://stackoverflow.com/help/mcve在這裏會有特別的幫助。 – Prune

回答

2

您需要遍歷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技術縮短代碼,但這很容易理解。

+0

修剪......你搖滾!總是有意義的。隨着所有額外的東西在開始/結束時給予我們一個新手程序員的壓力。謝謝! – KDupree

+0

很高興提供幫助。你所做的大部分工作將涉及兩種分解:(1)將一項長期任務分解爲更短的任務,按順序執行:步驟A,步驟B,步驟C等。(2)將重複性工作分解爲「做它一次「循環體和一個」如何重複「包裝(通常包括幾行設置和下班後)。 – Prune

+0

,這很有意義。感謝您的幫助..我在這個項目上得到了相當不錯的成績感謝您:) – KDupree