简体   繁体   中英

Find the last element (digit) on each line and sum all that are even python 3

Hi there Stack Overflow!

I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.

The task is to: Find the last element (digit) on each line, if there are any, and sum all that are even.

I have started to do something like this:

result = 0
counter = 0
handle = open('httpd-access.txt')
for line in handle:
    line = line.strip()
    #print (line)
    if line[:-1].isdigit():
        print(line[:-1].isdigit())
        digitFirst = int(line[counter].isdigit())
        if digitFirst % 2 == 0:
            print("second")
            result += digitFirst
    else:
        print("else")


    ANSWER = result

But this code doesnt work for me, I don't get any data in result. What is it that i'm missing? Think one problem is that I'm not going through the line element by element, just the whole line.

Here is an example of how I line in the file can look:

37.58.100.166--[02/Jul/2014:16:29:23 +0200]"GET/kod-exempel/source.php?dir=codeigniter/user_guide_src/source/_themes/eldocs/static/asset HTTP/1.1"200867

So the thing I want to retrieve is the 7. And then I want to do a check if the seven is a even or odd number. If it's even, I save it in the a variable.

Don't even bother with the isdigit . Go ahead and try the conversion to int and catch the exception if it fails.

result = 0
with open('httpd-access.txt') as f:
    for line in f:
        try:
            i = int(line.strip()[-1:])

            if(i % 2 == 0):
                result += i

        except ValueError:
            pass

print('result = %d' % result)

isdigit() return True or False , which is assigned to digitFirst (try print it!).
True and False are evaluated as 0 and 1 (respectively) in math operations.
So, it always pass the if digitFirst % 2 == 0 when digitFirst is 0 , which means 0 always gets added to result .

Also, notice that counter is always 0 during the for loop and gets raised to 1 only after it, which means you are always working with the first letter of every line.

The purpose of counter is unclear as it only used as "the index of the letter you get" each line.

result = []
with open('https-access.txt') as fin:
    for line in fin:
        l = line.strip()
        if l[-1].isdigit():
            if int(l[-1]) % 2 == 0:
                result.append(int(l[-1]))
ANSWER = sum(result)

How does your file look? You want to calculate the last digit on each line if it's even number. In your code "line[counter]" will catch the first index of each line.

For example if data in file is as follows:

some_data 2

since counter is set to 0, therefore line['counter'] in your code will always check the first index which will be 's' in the example above.

If you can post a few lines from the file that you will be opening, I may be able to suggest something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM