sarah campolt sarah campolt - 20 days ago 5
Python Question

Changing numbers in a file, cannot use .split

def process_body(infile, outfile, modification):
'''
changing the numbers to the outfile
'''


for line in infile.readline():
line = line.strip()
input()
num = ""
for char in line:
if modification == "negate":
if char != " ":
#concatenate "digits"
num += char
else:
#convert already concatenated "digits"
negate_line = negate(num)
print(negate_line)
#clear for next number
num = ""


Here is my negate function

def negate(num):
'''
absolute value of RGB value - 255
'''

num = int(num)
negate_line = abs(num - 255)
negate_line_out = str(negate_line)
return negate_line_out


This is code that should read in numbers from a file and subtract 255 and print to the outfile. I am not allowed to use
split
. Here is some code from the infile

0 44 89 0 44 89 0 44 89 0 44 89 1 45 90
1 45 90 1 45 90 1 45 90 1 45 92 1 45 92
1 55 101 0 54 100 0 54 100 0 53 99 0 53 99
0 54 101 0 54 101 0 54 101 0 54 101 0 54 101
0 54 101 0 54 101 0 54 101 0 53 103 0 53 103


Right now my error is
these are the numbers I am getting returned

255 251 246 255 251 246 255 251 246 255 251 246 254 250


But these are the numbers I need

255 211 166 255 211 166 255 211 166 255 211 166 254 210 165


Is there a reason the numbers are processing incorrectly?

Answer

You have to keep (concatenated) digits/number in different variable than char and use negate with this variable when char is " "

data = '''0 44 89 0 44 89 0 44 89 0 44 89 1 45 90 
1 45 90 1 45 90 1 45 90 1 45 92 1 45 92
1 55 101 0 54 100 0 54 100 0 53 99 0 53 99 
0 54 101 0 54 101 0 54 101 0 54 101 0 54 101 
0 54 101 0 54 101 0 54 101 0 53 103 0 53 103 '''

modification = "negate"

for line in data.split('\n'):
    line = line.strip()

    # to keep concatenated "digits"
    num = ''

    for char in line: 
        if modification == "negate": 
            if char != " ":
                # concatenate "digits"
                num += char
            else:
                # convert already concatenated "digits"
                negate_line = negate(num)
                print(negate_line)
                # clear for next number
                num = ''

def negate(num):
    num = int(num)
    negate_line = abs(num - 255)
    negate_line_out = str(negate_line)
    return negate_line_out