Stamend
Stamend

Reputation: 33

Add 1 to every second number

How do I add 1 to every second number?
Example:

2323 -> 2424
1112 -> 1213
3912 -> 31013

That is what I have now:

def plus_to_every_second(integer):
    integer = str(integer)
    integer_new = ''
    for i in integer:
        if integer.find(i) % 2 != 0:
            integer_new += str(int(i) + 1)
        else:
            integer_new += i

    return integer_new

For some reason, it does not work. But what is the actual solution?

Upvotes: 2

Views: 284

Answers (3)

mozway
mozway

Reputation: 261000

Don't use find, that only finds the first occurrence, rather iterate the digits together with the position using enumerate:

IIUC, you could do:

def add1(n):
    return int(''.join(str(int(d)+i%2) for i,d in enumerate(str(n))))

add1(2323)
# 2424

add1(1112)
# 1213

add1(3912)
# 31013
using a classical loop
def add1(n):
    s = str(n)
    out = ''
    for i,d in enumerate(s):
        out += str(int(d)+i%2)
    return int(out)

Upvotes: 5

Aniketh Malyala
Aniketh Malyala

Reputation: 2660

This modified function should work:

def plus_to_every_second(integer):
    integer = str(integer)
    integer_new = ''
    for i in range(len(integer)):
      if i % 2 == 1:
        integer_new += str(int(integer[i]) + 1)
      else:
        integer_new += integer[i]
    return integer_new

First, as you did, we convert integer to a str and create a new variable, integer_new which holds an empty String.

However, in our for loop, we should iterate through integer so that we have access to the index.

If the index is odd (every second number), we then convert the character at that index to a number, add 1 to it, convert it back to a string, and then add it into integer_new.

If it's not at an odd index, then we just add the character into integer_new.

Upvotes: 1

Alistair Celik
Alistair Celik

Reputation: 1

You won't have the best performance, but you can do the following for a quick solution:

>>> number = 3912
>>> digit_lst = list(str(number))
>>> digit_lst
['3', '9', '1', '2']
>>> new_digit_lst = [n if i % 2 == 0 else str(int(n)+1) for i, n in enumerate(digit_lst)]
>>> new_digit_lst
['3', '10', '1', '3']
>>> new_number = int(''.join(new_digit_lst))
>>> new_number
31013

Upvotes: 0

Related Questions