2

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Stamend
  • 33
  • 4
  • 2
    Edit the question to explain "does not work". What happens, what should happen? – Michael Butscher Feb 26 '22 at 21:10
  • 1
    For one thing, `.find()` returns the _first_ occurrence of the target string. So in your second example string "1112", `.find()` will return 0 for all three occurrences of "1". – John Gordon Feb 26 '22 at 21:10
  • Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Tomerikoo Feb 26 '22 at 22:47

3 Answers3

5

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)
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
mozway
  • 194,879
  • 13
  • 39
  • 75
1

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
0

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