微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在一个范围内将 16 位数字的前 15 位加 1

如何解决在一个范围内将 16 位数字的前 15 位加 1

背景

我正在努力确保生成唯一的 credit card numbercredit card number 需要 16 位长,最后一位数字等于 checksum,在本例中为 self.checksum = 1

credit card number 的前 6 位数字必须是 400000

由于在这种情况下最后一位数字必须等于 checksum1,我相信我需要在我的代码中实现一个范围以指示 maximum credit card number has been issued.在这种情况下,最大值 credit card number40000009999999991。之后的任何事情都会改变前 6 位数字。

虽然当前的解决方案“有效”,但它只需将 10 添加到在 credit card number 中初始化为 __init__ 的第一个可能的 self.credit_card_number = 4000000000000001

需要帮助

我正在寻求帮助,获取我现有的代码并实现某种范围,该范围可以在范围中的最后一个 credit card number 发出时发出警报。

from random import randrange


class Accounts:
    def __init__(self):
        self.accounts_list = []
        self.all_accounts = dict()
        self.balance = 0
        # Initial credit card number
        self.credit_card_number = 4000000000000001
        # Checksum is the last digit (16th) in the credit card number.
        self.checksum = 1
        # Pin number is generated in account_creation
        self.pin = None

    def main_menu(self):
        while True:
            main_menu_choice = input('1. Create an account\n'
                                     '2. Log into account\n'
                                     '0. Exit\n')
            if main_menu_choice == '1':
                self.account_creation()

    def account_creation(self):
        # Create credit card number ensuring it is unique by adding 1 to initialized value.
        if len(self.accounts_list) == 0:
            self.credit_card_number = self.credit_card_number
        else:
            self.credit_card_number = self.credit_card_number
            self.credit_card_number = self.credit_card_number + 10
        # Create pin number.
        pin = int(format(randrange(0000,9999),'04d'))
        # Add credit card number to list used in the above if statement.
        self.accounts_list.append(self.credit_card_number)
        # Add the credit card number,pin,and balance to dictionary.
        self.all_accounts[self.credit_card_number] = {'pin': pin,'balance': self.balance}
        # Print the output to make sure everything is OK.
        print(self.accounts_list)
        # Print the output to make sure everything is OK.
        print(self.all_accounts)
        print(f'\n'
              f'Your card has been created\n'
              f'Your card number:\n'
              f'{self.credit_card_number}\n'
              f'Your card PIN:\n'
              f'{pin}'
              f'\n')


Accounts().main_menu()

解决方法

您能否更新您的 init 以生成信用卡:

def __init__(self):

    # do you stuff

    self.credit_card_first_6 = '400000'
    self.checksum = '1'

    # this will be used to create a unique credit card
    self.count = 0

    # middle numbers MUST be smaller than this
    self.max_count = 1000000000


def account_creation(self):
    #### do your stuff

    # for this user they have a unique 9 digits in the middle
    # this is then zero padded using zfill
    unique_id = str(self.count).zfill(9)

    # create the full credit card number
    # note: store each bit as a str so we can concat then convert to int
    credit_card_number = int(self.credit_card_first_6 + unique_id + checksum)

    self.count += 1

    # update your init values when your limit is reached
    if self.count >= self.max_count:

        self.count = 0
        self.credit_card_first_6 = str(int(self.credit_card_first_6) + 1)
,

由于您将 Matt 的答案标记为有效,我添加了一个快速重构,其中包含一些可能对您有用的额外代码。

class Account:
    balance = 0
    __pin = None     # this are
    __number = None  # private members

    def __eq__(self,other):
        return self.__number == other

    def is_pin(self,pin):
        return self.__pin == pin

    def number(self):
        return self.__number

    # adding a 'is not none' makes
    # it a 'write only once' variable,# if a 'none' text is added as a input
    # text is added not a None type
    def set_pin(self,pin):
        if self.__pin is None:
            self.__pin = pin
            return True
        return False

    def set_number(self,num):
        if self.__number is None \
                and len(str(num)) == 16:
            self.__number = num
            return True
        return False

    # eeextra simple checksum
    def checksum(self):
        ck_sum = 0
        for i in str(self.__number):
            ck_sum += int(i)
        return int(str(ck_sum)[-1])

class Accounts:

    base_num = 4000000000000000

    def __init__(self):
        self.accounts = []
        self.num_offset = 0

    @staticmethod
    def dialog_choice():
        choice = input(
            '1. Create an account\n'
            '2. Log into account\n'
            '0. Exit \n \n'
        )
        return choice

    def next_card_num(self):
        self.num_offset += 1
        return self.base_num + self.num_offset

    def dialog_acount_creation(self):
        card_pin = input('New pin ->')
        card_num = self.next_card_num()
        print('Card number ->',card_num)
        return card_num,card_pin

    @staticmethod
    def dialog_login():
        card_num = input('Card number ->')
        card_pin = input('Card pin ->')
        return int(card_num),card_pin

    @staticmethod
    def dialog_error(*args):
        print('Error on acount',args[0])

    def main_loop(self):
        dia_map = {
            '1': self.dialog_acount_creation,'2': self.dialog_login,}
        cho_map = {
            '1': self.account_creation,'2': self.account_login,}
        err_map = {
            '1': self.dialog_error,'2': self.dialog_error,}
        while True:
            o = self.dialog_choice()
            if o == '0':
                break
            if o in cho_map:
                q_dialog = dia_map[o]()
                q_done = cho_map[o](*q_dialog)
                if not q_done:
                    err_map[o](*q_dialog)
            else:
                print('Invalid option')

    def account_login(self,num,pin):
        for acc in self.accounts:
            if acc == num and acc.is_pin(pin):
                print('You are logged in !')
                return True
        return False

    def account_creation(self,pin):
        new_accaunt = Account()
        new_accaunt.set_number(num)
        new_accaunt.set_pin(pin)
        self.accounts.append(new_accaunt)
        return True


if __name__ == '__main__':
    h_acc = Accounts()
    h_acc.account_creation(4000000000000000,'1234')
    h_acc.main_loop()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。