如此接近,但我不知道出了什么问题

2024-10-01 04:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学校学习一门课程,在Codio上有一个挑战:

在本单元的最后一个挑战中,您将加载两个文件:
第一个文件F1将包含有关某些帐户的信息。它将以管道分隔,每行有一条记录,包括以下字段:

ACCOUNT NUMBER | PIN CODE | BALANCE

第二个文件F2将包含指令:每行一条。说明如下所示:

COMMAND | AMOUNT | ACCOUNT NUMBER | PIN CODE

COMMAND将是add或sub。如果命令是add,则将金额添加到帐户文件F1中的余额中。如果命令为sub,则将进行减法

但是,您可能需要出于多种原因拒绝交易。如果要求您减去一笔金额,该金额将使帐户低于零,或者如果您提供的pin码与帐户记录中的pin码不匹配,则该交易将被忽略

账户交易 给定管道分隔文件F1和F2,其中F1包含具有字段ACCOUNT NUM|PIN|BALANCE的帐户,F2包含事务指令COMMAND|AMOUNT|ACCOUNT NUM|PIN,执行事务,并将结果存储回F1

COMMAND字段将是add或sub,表示从帐户中进行加法或减法运算

应忽略未提供正确PIN码或试图将帐户设置为零以下的交易

这是我的挑战代码:

records = []

with open(F1,'r') as account_info:
  content = account_info.readlines()
  for row in content:
    recordList = row.strip("\n").split('|')
    records.append(recordList)

records2 = []
with open(F2,'r') as user_input:
  content2 = user_input.readlines()
  for row in content2:
    recordList2 = row.strip("\n").split('|')
    records2.append(recordList2)

for i in range(len(records)):
  row = records[i]
for i in range(len(records2)):
  row = records2[i]

for row in records and records2:
  if records[i][1] == records2[i][3] and records2[i][0] == "add":
    newBalance = int(records[i][2]) + int(records2[i][1])
    records[i][2] = str(newBalance)
  elif records2[i][0] == "sub" and int(records[i][2]) >= int(records2[i][1]):
    newBalance = int(records[i][2]) - int(records2[i][1])
    records[i][2] = str(newBalance)


output_records = ""
i = 0
while i <= len(records):
  output_records += '|'.join(records[i])
  if i != len(records):
    output_records += '\n'
    i += 1
    if i == len(records):
      break

outputFile = open(F1, 'w')
outputFile.write(output_records)
outputFile.close

这就是我得到的输出,它被关闭了一个数字

Your program output did not match the expected output.

Your output:
1000|1234|10000
1020|2222|0
3000|3344|0
2020|1234|90000

Expected output:

1000|1234|11000
1020|2222|0
3000|3344|0
2020|1234|90000

有人能告诉我哪里出了问题吗?谢谢


Tags: 文件inforoutputlenpin帐户account
3条回答

您的代码非常混乱,我建议您删除所有代码并从空文件重新启动:

以下几行没有意义:

for row in records and records2:


for i in range(len(records)):
   row = records[i]
for i in range(len(records2)):
   row = records2[i]

如果您知道如何使用字典,它们可能会有所帮助:

这里有一些可能的解决方案类型的伪代码:

accounts = {}
with open(F1,'r') as f:
    for line in f:
        acc, pin, balance = line.split('|')
        accounts[acc] = {'pin': pin, 'balance': int(balance)}


with open(F2,'r') as f:
    for line in f:
        command, amount, acc, pin = line.split('|')
        amount = int(amount)
        if accounts[acc]['pin'] != pin:
            continue # wrong pin
        if command == 'add':
            accounts[acc]['balance'] += amount
        elif accounts[acc]['balance'] >= amount: # if there is enough balance to sub
            accounts[acc]['balance'] -= amount

假设金额和余额是整数值

对于float,将代码中的int(…)更改为float(…)

代码

# Get Records
with open('file1.txt','r') as f1:
  records = []
  for row in f1:
    row = row.rstrip().split('|')
    # Strip white space and convert balance to float
    row = [x.strip() if i != 2 else int(x.strip()) for i, x in enumerate(row)]
    records.append(row)

# Get Transactions
with open('file2.txt', 'r') as f2:
  transactions = []
  for row in f2:
    row = row.rstrip().split('|')
    # Strip whitespace and convert balance to float
    row = [x.strip() if i != 1 else int(x.strip()) for i, x in enumerate(row)]
    transactions.append(row)

# Perform Transactions
for t in transactions:
  for record in records:
    # check records for matching account & pin
    # Brute force search   okay for records and transactions only in thousands
    if t[2:] == record[:2]: 
      # Found account to update (record account & pin matches transaction)
      if t[0] =='add':
        record[-1] += t[1]  # increment balance
      elif t[0] == 'sub':
        if record[-1] - t[1] >= 0:
          record[-1] -= t[1]  # decrement balance
      break

# Output updated records
with open('file1.txt', 'w') as f3:
  for row in records:
    row = [str(x) for x in row]
    f3.write(' | '.join(row) + '\n')

测试

跑步前

File1.txt
1000 | 1234 | 10000
1020 | 2222 | 2500
3000 | 3344 | 3000
2020 | 1234 | 95000

File2.txt
add    | 1000    | 1000 | 1234
sub    | 1000    | 1020 | 2222
add    | 1000    | 3000 | 3344
sub    | 1000    | 2020 | 1234

跑步后

File1.txt
1000 | 1234 | 11000
1020 | 2222 | 1500
3000 | 3344 | 4000
2020 | 1234 | 94000

我认为问题可能来自以下方面:

for row in records and records2:
  if records[i][1] == records2[i][3] and records2[i][0] == "add":
    newBalance = int(records[i][2]) + int(records2[i][1])
    records[i][2] = str(newBalance)
  elif records2[i][0] == "sub" and int(records[i][2]) >= int(records2[i][1]):
    newBalance = int(records[i][2]) - int(records2[i][1])
    records[i][2] = str(newBalance)

从我看到的情况来看,如果records[i][1] != records2[i][3],它仍然运行elif和减法运算

相关问题 更多 >