0

以下是我的代码的一部分。基本上,它的作用是在运行时创建具有随机数和给定货币代码和信用卡限额的信用卡。信用卡是一个类,它存储的钱也是一个类(为了简洁起见,我没有在此处包括在内,因为我认为它们与我的问题无关。)然而,我的代码中发生的是我的取消声明效果很好,但如果我在一个列表中有两张信用卡并且我尝试取消第二张信用卡,它将再次打印出 NO_SUCH_CARD。无论如何,如果它在列表中,它就会被删除。我的猜测是他的发生是因为 for 循环遍历列表并且它首先检测到一张卡的编号与给定的卡不同,这就是它不打印这样的卡的原因,但我不知道如何解决这个问题。帮助将不胜感激。

PATH = 'saved_cards.txt'
creditcard_list = []
import decimal
import ast
import collections
import os
import random


def currency_dictionary():
    '''Initialized at the start of the program. It finds and reads a currency.txt
       file and stores those in a dictionary'''
    final_dict = collections.defaultdict(list)
    with open("currency.txt", 'r') as f:
        currency_lines = f.readlines()
    for item in currency_lines:
        m = item.split(' ')
        final_dict[m[0]] = [int(m[1]), decimal.Decimal(m[2])]
    return final_dict





class Money():
    def __init__(self, money_amount: decimal, currency_code: str):
        self.m = decimal.Decimal(money_amount)
        self.c = str(currency_code)
        self.d = currency_dictionary()


def __repr__(self):
    return 'Money({}, {})'.format(self.m, self.c)

def __eq__(self, other):
    if type(other) != Money:
        return False

    elif self.c == other.c:
        return self.m == other.m

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor = dictionary_key2[1]
        y = other.m / conversion_factor

        return x == y

def __ne__(self, other):
    if type(other) != Money:
        return True

    elif self.c == other.c:
        return self.m != other.m

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor = dictionary_key2[1]
        y = other.m / conversion_factor

        return x != y

def __add__(self, other):
    if self.c == other.c:
        return Money((self.m + other.m), self.c)

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor2 = dictionary_key2[1]
        y = other.m / conversion_factor2

        total = x + y
        return Money((total * conversion_factor1), self.c)


def __sub__(self, other):
    if self.c == other.c:
        return Money((self.m - other.m), self.c)

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor2 = dictionary_key2[1]
        y = other.m / conversion_factor2

        total = x - y
        return Money((total * conversion_factor1), self.c)

class Credit_Card():
    def __init__(self, card_number, money_amount: Money, card_limit: int):
        if type(money_amount) != Money or type(card_limit) != int:
            raise TypeError('one of the types of the parameters entered is not valid')
        self.number = card_number
        self.amount = money_amount
        self.limit = card_limit

def __repr__(self):
    return 'Card#{}({}, {})'.format(self.number, self.amount, self.limit)

def user_interface():
    boolean = True

    while boolean:
        temp_list = []
        command = input()
        if command.split()[0] == 'ISSUE':
            if len(command.split()) == 3:
                x = "%0.5d" % random.randint(0,99999)
                currency_code = command.split()[1]
                card_limit = int(command.split()[2])
            if card_limit < 0:
                print("NEGATIVE_LIMIT")
            elif not currency_dictionary()[currency_code]:
                print("NO_SUCH_CURRENCY")
            else:
                for card in creditcard_list:
                    temp_list.append(card.number)
                if x not in temp_list and currency_dictionary()[currency_code]:
                    creditcard_list.append(Credit_Card(x, Money(0, currency_code), card_limit))
                    print('ISSUED', x)
                    print(creditcard_list)

        else:
            print("INVALID_ISSUE_COMMAND")


    elif command.split()[0] == 'CANCEL':
        templist2 = []
        if len(command.split()) == 2:
            card_number = command.split()[1]

            for card in creditcard_list:
                templist2.append(card)
            for i, card in enumerate(templist2):
                if card_number not in templist2[i].number:
                    print('NO_SUCH_CARD')
                elif templist2[i].amount.m != 0:
                    print('NONZERO_BALANCE')
                elif templist2[i].number == command.split()[1] and card.amount.m == 0:
                    del creditcard_list[i]
                    print('CANCELLED', card_number)


            print(creditcard_list)


    elif command.split()[0] == 'PURCHASE':
        if len(command.split()) == 4:
            card_number = command.split()[1]
            currency_code = command.split()[2]
            amount = int(command.split()[3])
            if currency_code not in currency_dictionary().keys():
                print('NO_SUCH_CURRENCY')
            elif amount < 0:
                print('NONPOSITIVE_AMOUNT')
            else:
                for i, card in enumerate(creditcard_list):
                    if card.number == card_number and 0 <= amount <= card.limit :
                        x = card.amount + Money(amount, currency_code)
                        creditcard_list[i] = Credit_Card(card.number, x, card.limit)
                    elif creditcard_list[i].number != card_number:
                        print('NO_SUCH_CARD')
                    elif amount > creditcard_list[i].limit:
                        print('OVER_LIMIT')

    elif command.split(0) == 'PAYMENT':


            print(creditcard_list)



if __name__ == '__main__':
    user_interface()

我的取消命令的输出基本上是这样的,我很确定一旦我弄清楚了,我就可以处理剩下的了。粗体为输入,非粗体为输出。

**ISSUE USD 5000**
ISSUED 50695
[Card#50695(Money(0, USD), 5000)]
**ISSUE RON 3000**
ISSUED 25282
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
**CANCEL 25282**
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
*NO_SUCH_CARD*
CANCELLED 25282
[Card#50695(Money(0, USD), 5000)]

请注意,这些列表仅为我打印出来以跟踪当前主列表中的卡片,我最终将删除这些打印语句。我已经将我遇到问题的输出斜体。

4

1 回答 1

0

问题似乎是您creditcard_list在迭代它的同时进行修改。您应该首先创建列表的临时副本以进行迭代,然后从实际列表中删除项目。

编辑:啊,它在列表中的第一张卡片上打印“NO_SUCH_CARD”!不是在第二个。因此,在您的示例中,您遍历了两个列表;它首先访问卡#50695,它等于2582,所以它打印“NO_SUCH_CARD”。然后它访问 25282,将其删除,并打印“CANCELED”。它正在做你写它要做的事情。取而代之的是,只需循环播放,如果找到卡片就删除它,然后默默地跳过任何不匹配的卡片。最后,如果没有找到卡,打印“NO_SUCH_CARD”

编辑2:这是一个例子:

        found = False
        for card in templist2:
            if card_number == card.number:
                if card.amount.m != 0:
                    print('NONZERO_BALANCE')
                else:
                    del creditcard_list[i]
                    print('CANCELLED', card_number)
                found = True
                break
        if not found:
            print('NO_SUCH_CARD')
于 2013-07-08T09:12:02.950 回答