Home > OS >  How can I assign positives and negatives to a string?
How can I assign positives and negatives to a string?

Time:10-21

I'm trying to create this code so that when variable J is present, it is a positive number, but if H is present, it is a negative number. Here is my code.

record = ['1J2H']
def robot_location(record: str):
    if J in record:
        sum()
    if H in record:
        ** I dont know how to subtract them** 
print(robot_location(record)

So if record = [1J2H] then the output should be (( 1) (-2)) = -1 should be the output... how can I do that?? Somebody pls help explain this.

CodePudding user response:

You need to iterate over string inside list, check char by char and asume thats always length of string will be odd

record = ['1J2H']
def robot_location(record: str):
    total = 0
    aux_n = 0
    for a in record:
        if a.isnumeric():
            aux_n = int(a)
        else:
            if a == 'H':
                total = total   aux_n*-1
            else:
                total = total   aux_n
            aux_n = 0
    return total

print(robot_location(record[0]))

CodePudding user response:

Here is a concise way to do this via a list comprehension:

record = '1J2H'
nums = re.findall(r'\d [JH]', record)  # ['1J', '2H']
output = sum([int(x[:-1]) if x[-1] == 'J' else -1*int(x[:-1]) for x in nums])
print(output)  # -1

CodePudding user response:

One way to do that is by using iter and converting the string into an iterable, that allows to use next which moves the iteration to the next item meaning that if one simply iterates over it it will get moved to the next item and then if one uses next it will return the current value where the "pointer"? is and move it to the next value so the next iteration with a for loop (list comprehension in this case) will get the next value, meaning that the loop will return only the numbers while next will return only the letters:

lst = ['1J2H']


def robot_location(record: str):
    record = iter(record)
    numbers = [int(i) if next(record) == 'J' else -int(i) for i in record]
    return sum(numbers)


print(robot_location(lst[0]))

CodePudding user response:

You could modify a string like s = '1J2H' to '1 2*-1 0' and let Python evaluate it:

result = eval(s.replace('J', ' ').replace('H', '*-1 ')   '0')
  • Related