簡體   English   中英

將整數拆分為數字以計算ISBN校驗和

[英]Split an integer into digits to compute an ISBN checksum

我正在編寫一個程序,計算ISBN號碼的校驗位。 我必須將用戶的輸入(一個ISBN的9位數字)讀入一個整數變量,然后將最后一位數字乘以2,將第二位最后一位乘以3,依此類推。 我如何將整數“拆分”為其組成位數? 由於這是一項基本的家庭作業,因此我不應該使用列表。

只需創建一個字符串即可。

myinteger = 212345
number_string = str(myinteger)

夠了 現在您可以對其進行迭代:

for ch in number_string:
    print ch # will print each digit in order

或者,您可以將其切片:

print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit

或更妙的是,不要將用戶的輸入轉換為整數(用戶鍵入字符串)

isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
    print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)

有關更多信息,請閱讀教程

while number:
    digit = number % 10

    # do whatever with digit

    # remove last digit from number (as integer)
    number //= 10

在循環的每次迭代中,它都會從number中刪除最后一位,並將其分配給digit 相反,從最后一位開始,以第一個結尾

list_of_ints = [int(i) for i in str(ISBN)]

將給您一個有序的整數列表。 當然,給定鴨子的類型,您也可以使用str(ISBN)。

編輯:如評論中所述,此列表未按升序或降序排序,但確實有定義的順序(理論上python中的集合,字典等沒有,盡管在實踐中該順序傾向於相當可靠)。 如果要排序:

list_of_ints.sort()

是你的朋友。 請注意,sort()會按位置排序(例如,實際上會更改現有列表的順序),並且不會返回新列表。

在舊版本的Python上...

map(int,str(123))

在新版本3k上

list(map(int,str(123)))
(number/10**x)%10

您可以在循環中使用它,其中number是整數,x是循環的每次迭代(0,1,2,3,...,n),n是停止點。 x = 0給出一個位,x = 1給出十,x = 2給出百,依此類推。 請記住,這將給出從右到左的數字值,因此對於ISBN來說可能不是,但仍會隔離每個數字。

遞歸版本:

def int_digits(n):
    return [n] if n<10 else int_digits(n/10)+[n%10]

轉換為str肯定要慢一些,然后再除以10。

map比列表理解慢得多:

convert to string with map 2.13599181175
convert to string with list comprehension 1.92812991142
modulo, division, recursive 0.948769807816
modulo, division 0.699964046478

這些時間是由筆記本電腦上的以下代碼返回的:

foo = """\
def foo(limit):
    return sorted(set(map(sum, map(lambda x: map(int, list(str(x))), map(lambda x: x * 9, range(limit))))))

foo(%i)
"""

bar = """\
def bar(limit):
    return sorted(set([sum([int(i) for i in str(n)]) for n in [k *9 for k in range(limit)]]))

bar(%i)
"""

rac = """\
def digits(n):
    return [n] if n<10 else digits(n / 10)+[n %% 10]

def rabbit(limit):
    return sorted(set([sum(digits(n)) for n in [k *9 for k in range(limit)]]))

rabbit(%i)
"""

rab = """\
def sum_digits(number):
  result = 0
  while number:
    digit = number %% 10
    result += digit
    number /= 10
  return result

def rabbit(limit):
    return sorted(set([sum_digits(n) for n in [k *9 for k in range(limit)]]))

rabbit(%i)
"""


import timeit

print "convert to string with map", timeit.timeit(foo % 100, number=10000)
print "convert to string with list comprehension", timeit.timeit(bar % 100, number=10000)
print "modulo, division, recursive", timeit.timeit(rac % 100, number=10000)
print "modulo, division", timeit.timeit(rab % 100, number=10000)

將其轉換為字符串並使用int()函數在其上進行映射。

map(int, str(1231231231))

使用此循環的主體可對數字進行任何操作

for digit in map(int, str(my_number)):

我已經制作了這個程序,這是一些實際計算程序中校驗位的代碼

    #Get the 10 digit number
    number=input("Please enter ISBN number: ")

    #Explained below
    no11 = (((int(number[0])*11) + (int(number[1])*10) + (int(number[2])*9) + (int(number[3])*8) 
           + (int(number[4])*7) + (int(number[5])*6) + (int(number[6])*5) + (int(number[7])*4) +
           (int(number[8])*3) + (int(number[9])*2))/11)

    #Round to 1 dp
    no11 = round(no11, 1)

    #explained below
    no11 = str(no11).split(".")

    #get the remainder and check digit
    remainder = no11[1]
    no11 = (11 - int(remainder))

    #Calculate 11 digit ISBN
    print("Correct ISBN number is " + number + str(no11))

它的代碼行很長,但是它會將數字相除,將數字乘以適當的數量,將它們加在一起,然后在一行代碼中將它們除以11。 .split()函數僅創建一個列表(以小數點分隔),因此您可以將列表中的第二項取為11來查找校驗位。 通過更改以下兩行,還可以提高效率:

    remainder = no11[1]
    no11 = (11 - int(remainder))

對此:

    no11 = (11 - int(no11[1]))

希望這可以幫助 :)

類似於答案,但更多的“ pythonic”方式遍歷digis將是:

while number:
    # "pop" the rightmost digit
    number, digit = divmod(number, 10)

答案: 165

方法:蠻力! 這是一小部分Python(2.7版)代碼,可以用來計算全部內容。

from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
    if n % 11 and is_ps(sum(map(int, str(n)))):
        count += 1
        print "#%i: %s" % (count, n)

僅假設您要從整數x中獲得第i個最低有效位,就可以嘗試:

(abs(x)%(10**i))/(10**(i-1))

希望對您有所幫助。

單行數字列表如何...

ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)

經過自己的勤奮搜索,我發現了幾種解決方案,每種解決方案都有其優點和缺點。 使用最適合您的任務。

所有示例均在GNU / Linux Debian 8操作系統上使用CPython 3.5進行了測試。


使用遞歸

def get_digits_from_left_to_right(number, lst=None):
    """Return digits of an integer excluding the sign."""

    if lst is None:
        lst = list()

    number = abs(number)

    if number < 10:
        lst.append(number)
        return tuple(lst)

    get_digits_from_left_to_right(number // 10, lst)
    lst.append(number % 10)

    return tuple(lst)

演示版

In [121]: get_digits_from_left_to_right(-64517643246567536423)
Out[121]: (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)

In [122]: get_digits_from_left_to_right(0)
Out[122]: (0,)

In [123]: get_digits_from_left_to_right(123012312312321312312312)
Out[123]: (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)

使用函數divmod

def get_digits_from_right_to_left(number):
    """Return digits of an integer excluding the sign."""

    number = abs(number)

    if number < 10:
        return (number, )

    lst = list()

    while number:
        number, digit = divmod(number, 10)
        lst.insert(0, digit)

    return tuple(lst)

演示版

In [125]: get_digits_from_right_to_left(-3245214012321021213)
Out[125]: (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)

In [126]: get_digits_from_right_to_left(0)
Out[126]: (0,)

In [127]: get_digits_from_right_to_left(9999999999999999)
Out[127]: (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)

使用構造tuple(map(int, str(abs(number)))

In [109]: tuple(map(int, str(abs(-123123123))))
Out[109]: (1, 2, 3, 1, 2, 3, 1, 2, 3)

In [110]: tuple(map(int, str(abs(1412421321312))))
Out[110]: (1, 4, 1, 2, 4, 2, 1, 3, 2, 1, 3, 1, 2)

In [111]: tuple(map(int, str(abs(0))))
Out[111]: (0,)

使用功能re.findall

In [112]: tuple(map(int, re.findall(r'\d', str(1321321312))))
Out[112]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)

In [113]: tuple(map(int, re.findall(r'\d', str(-1321321312))))
Out[113]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)

In [114]: tuple(map(int, re.findall(r'\d', str(0))))
Out[114]: (0,)

使用模塊decimal

In [117]: decimal.Decimal(0).as_tuple().digits
Out[117]: (0,)

In [118]: decimal.Decimal(3441120391321).as_tuple().digits
Out[118]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)

In [119]: decimal.Decimal(-3441120391321).as_tuple().digits
Out[119]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM