Home > Net >  How to add or subtract 1 to a sum based on a certain value in a text?
How to add or subtract 1 to a sum based on a certain value in a text?

Time:12-06

After reading a text, I need to add 1 to a sum if I find a ( character, and subtract 1 if I find a ) character in the text. I can't figure out what I'm doing wrong.

This is what I tried at first:

file = open("day12015.txt")

sum = 0
up = "("

for item in file:
    if item is up:
        sum  = 1
    else:
        sum -= 1
print(sum)

I have this long text like the following example (((())))((((( .... If I find a ), I need to subtract 1, if I find a (, I need to add 1. How can I solve it? I'm always getting 0 as output even if I change my file manually.

CodePudding user response:

your for loop only gets all the string in the file so you have to loop through the string to get your desired output.

Example .txt

(((())))(((((

Full Code

file = open("Data.txt")

sum = 0
up = "("

for string in file:
    for item in string:
        if item is up:
            sum  = 1
        else:
            sum -= 1
print(sum)

Output

5

Hope this helps.Happy Coding :)

CodePudding user response:

So you need to sum 1 for "(" character and -1 for ")".

Do it directly specifying what to occur when you encounter this character. Also you need to read the lines from a file as you're opening it. In your code, you are substracting one for every case that is not "(".

file = open("day12015.txt")
total = 0

for line in file:
    for character in line:
        if character == "(":
            total  = 1
        elif character == ")":
            total -= 1

print(sum)

CodePudding user response:

That's simply a matter of counting each character in the text. The sum is the difference between those counts. Look:

from pathlib import Path

file = Path('day12015.txt')

text = file.read_text()

char_sum = text.count('(') - text.count(')')

For the string you posted, for example, we have this:

>>> p = '(((())))((((('
>>> p.count('(') - p.count(')')
5
>>> 

Just for comparison and out of curiosity, I timed the str.count() and a loop approach, 1,000 times, using a string composed of 1,000,000 randoms ( and ). Here is what I found:

import random
from timeit import timeit

random.seed(0)

p = ''.join(random.choice('()') for _ in range(1_000_000))

def f():
    return p.count('(') - p.count(')')


def g():
    a, b = 0, 0
    for c in p:
        if c == '(':
            a = a   1
        else:
            b = b   1
    return a - b


print('f', timeit(f, number=1_000))
print('g', timeit(g, number=1_000))
f 8.194599456997821
g 49.339132178

It means the loop approach is 6 times slower, even though the str.count() one is iterating over p two times to compute the result.

  • Related