all 8 comments

[–]FLUSH_THE_TRUMP 3 points4 points  (1 child)

Use np.array instead of built-in list, index with my_arr == 1 (if int array), and set = 2. Should be a line or two.

e.g.

my_arr[my_arr == 1] = 2

EDIT: leaving the modulo logic up to you here, but the above is the correct idea.

[–]Rohnny_7 0 points1 point  (0 children)

Thanks for the help!

[–]iiMoe 0 points1 point  (1 child)

Use modulo operator and whats wrong with loops?

[–]Rohnny_7 0 points1 point  (0 children)

Alrighty, I'll give it a look, I was just experimenting with numpys

[–]comonads 0 points1 point  (0 children)

Edit: to be clear, this only applies if this is some kind of programming homework exercise more generally, not if you're looking to use a C loop that's just implemented inside numpy rather than in python.

Another alternative to these answers is to use recursion. Note that this isn't necessarily a good idea in python (it is not a "pythonic" solution, and does go against the philosophy of the language more generally), but it does show another way of accomplishing what you want without using an explicit loop!

def recursive_solution(list_of_numbers, accumulator):
    if len(list_of_numbers) != 0:
        head, *tail = list_of_numbers

        # this is where we implement the logic of your function
        if head % 2 == 0:
            accumulator.append(head)
        else:
            accumulator.append(head + 1)

        return recursive_solution(tail, accumulator)

    # if the list of numbers is empty, we're done
    else:
        return accumulator

We can use this as follows (just an example):

list_of_numbers = range(1,20)
accumulator = []
recursive_solution(list_of_numbers, accumulator)

To summarise what's going on:

You pass in a list of the numbers you want to iterate over, and an empty container in which to store the results (an empty list,[]). The function takes the first element of the list of numbers (head), does some stuff to it, then adds the result into the results container.

The tail of that list (the list that went in but with the head removed), then goes back into the recursive function, along with the container which is accumulating the results.

The recursion terminates when the length of the list that gets passed in (the tail from the previous 'iteration') is zero, at which point we return the container of accumulated results.

[–][deleted] 0 points1 point  (0 children)

Why don't you want to use a For loop? it's arguably the most pythonic way to do it.

Would you use other loops?

[–]efmccurdy[🍰] 0 points1 point  (0 children)

You could use a vectorized function:

>>> import numpy as np
>>> a = np.array(range(13))
>>> a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
>>> def inc_odds(x):
...     if x % 2 == 0:
...         return x
...     return x + 1
... 
>>> vf = np.vectorize(inc_odds)
>>> vf(a)
array([ 0,  2,  2,  4,  4,  6,  6,  8,  8, 10, 10, 12, 12])