So close yet I can't figure out whats wrong

319 views Asked by At

I am taking a course through school and have this challenge on Codio:

For your final challenge in this unit, you will load two files:
The first file F1 will have information about some accounts. It will be pipe-delimited and have one record per line, with these fields:

ACCOUNT NUMBER | PIN CODE | BALANCE

The second file F2 will contain instructions: one on each line. The instructions will look like this:

COMMAND | AMOUNT | ACCOUNT NUMBER | PIN CODE

COMMAND will be either add or sub. If the command is add, you will add AMOUNT to the BALANCE in the account files F1. If the command is sub, you will subtract.

However, there are a number of reasons for which you may need to reject the transaction. If you are asked to subtract an amount that would put the account below zero or if the pin code you are provided does not match the pin code in the account record, the transaction is ignored.

Account Transactions Given pipe-delimited files F1 and F2 where F1 contains accounts with fields ACCOUNT NUM|PIN|BALANCE and F2 contains transaction instructions COMMAND|AMOUNT|ACCOUNT NUM|PIN, execute the transactions, storing the results back in F1.

The COMMAND field will be add or sub indicating addition or subtraction from the account.

Transactions which do not provide the correct PIN code or attempt to put the account below zero should be ignored.

This is my code for the challenge:

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

This is what I'm getting for output which is off by one number.

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

Can someone point me in the direction of where I'm going wrong? Thanks.

2

There are 2 answers

0
Hoxha Alban On

Your code is really messy, i can advise you to delete all and restart from an empty file:

the following lines are meaningless:

for row in records and records2:


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

If you know how to use dictionaries, they might help a bit:

Here there is some pseudo code of a possible type of solution:

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
0
DarrylG On

Assume amount and balance are integer-valued.

For float change int(...) to float(...) in Code

Code

# 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')

Test

Prior to running

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

After running

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