2016-11-22 45 views
0

我只需要在如何將我加起來只有奇數位置號碼的想法加起來奇數位置的數字。例如,如果我有,我只需要添加0,2,4,6,8等等。我目前擁有的基本上是一個模塊(尚未完成),而且此程序要求我添加valadiate UPC-12數字。我完全困惑,因爲我不完全確定我在做什麼。我還沒有學會「len」(類似那樣)。你怎麼只在UPC-12驗證

# Gets the digit of the number using the specified position 
def get_digit(number, position): 
    return number/(10**position) % 10 



    def is_UPC12(number): 
      sum_odd = 0 
      sum_even = 0 

      #loops through the UPC code and checks every odd position and adds the numbers 
      for num in range(1, 13, 2): 
       sum_odd += get_digit(number, num) 

      sum_odd *= 3 

      #loops through the UPC code and checks every even position and adds the numbers 
      for num in range(2, 13, 2): 
        sum_of_even += even 

      sum_even += get_digit(number, num)  

      Sum = sum_of_odd + sum_of_even_two 

      #subtracts 10 from the last digit of the sum, and if it's equal to the last digit of number then it returns True. 
      if 10 - get_digit(Sum , 0) == get_digit(number , 0): 
       return True 
      elif 10 - get_digit(Sum , 0) == 10 and get_digit(number , 0) == 0: 
       return True 
      else: 
       return False 
+0

基本上,我要創建一個驗證UPC-12號的功能 – kden

回答

0

您是否考慮過使用模數%運算符?防爆。 x%2 = 0是一個偶數。

0

一種方法(不一定是最好的)是:

# get the number to be tested 
test_number = raw_input("Enter number to validate: ") 

# set an initial 'sum' value at zero 
sum = 0 

# iterate through the characters in the input string, only selecting odd position characters 
for i in range((len(test_number)+1)/2): 
    # a test print statement to check that it's working 
    print test_number[i*2] 
    # add the value of the character (as int) to 'sum' 
    # note that this doesn't deal with exceptions 
      # (if the input is not numeric, it will throw an error) 
    sum += int(test_number[i*2]) 

# get the final sum 
print "sum: " + str(sum) 

編輯 - 替代方法

另一種方法是:

test_number = raw_input("Enter number to validate: ") 
sum = 0 
odd_numbers = test_number[::2] 
for char in odd_numbers: 
    sum += int(char) 
print "sum: " + str(sum) 

其中 「odd_numbers」 是組成一個新的字符串來自原始字符串的替代字符(使用步長爲2的切片方法)。