Python Forum
How to convert every even number in a list to odd?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to convert every even number in a list to odd?
#1
Hey all, one of my revision questions was to create a func that takes a list of integer values as a list, and convert every even number into an odd number.

Expected Output:
integer_list = [1, 2, 3 , 4, 5, 6, 7]
Before: [1, 2, 3, 4, 5, 6, 7]
After: [1, 3, 3, 5, 5, 7, 7]

integer_list = [1, -2, 3 , -4, 8, 16, 21, -17]
Before: [1, -2, 3, -4, 8, 16, 21, -17]
After: [1, -3, 3, -5, 9, 17, 21, -17]

Code thus far:
def make_all_odd(integer_list):
    for number in integer_list:
        if (number % 2) == 0:
            number += 1
            integer_list.append(number)
So far, I've only figured out that I need to iterate through every element in the list and check if it is even using a for loop, but I'm not sure how to modify the original string to change the identified even numbers into odd. I know my code just adds the recently converted even to odd numbers to the end of the list, but in my case I have to replace, not add.
Reply
#2
First of all I want to quote:

"If fact, in any programming language for most part if you mutate something while you iterating over it you living in state of sin and you deserve whatever happens to you" -- Raymond Hettinger, Python core-developer, Transforming Code into Beautiful, Idiomatic Python

Is in-place mutation of list required? Following assumes that not.

You are almost there. Just de-intent last row to same level as if and return newly constructed list (and yes, we do test our code especially then sample inputs and outputs are given):

def oddify(nums):
    odd = []
    for num in nums:
        if num % 2 == 0:
            num += 1
        odd.append(num)
    return odd

assert oddify([1, 2, 3, 4, 5, 6, 7]) == [1, 3, 3, 5, 5, 7, 7]
assert oddify([1, -2, 3, -4, 8, 16, 21, -17]) == [1, -3, 3, -5, 9, 17, 21, -17]
We have encountered assertion error. Why? Because -2 + 1 = -1 but -3 is expected. We can mitigate this problem using conditional expression to determine whether we need add 1 or -1:

def oddify(nums):
    odd = []
    for num in nums:
        if num % 2 == 0:
            num += 1 if 0 < num else -1
        odd.append(num)
    return odd

assert oddify([1, 2, 3, 4, 5, 6, 7]) == [1, 3, 3, 5, 5, 7, 7]
assert oddify([1, -2, 3, -4, 8, 16, 21, -17]) == [1, -3, 3, -5, 9, 17, 21, -17]
No assertion error anymore. But... if there is value of 0 in input list then we will (probably) have wrong answer. Why probably? 0 is considered even number but it's unclear whether 0 should be converted to -1 or 1 (or should it kept unchanged). As this is homework you should figure it out yourself and adjust conditional expression accordingly if needed :-)
Bruizeh likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Hi,

In order to cope with the negative numbers,
an even shorter alternative could be to divide num by abs(num).
That gives 1 or -1 as needed.

Paul
Bruizeh likes this post
Reply
#4
@DPaul, good point.

def oddify_int(iterable):
    """
    Generator to oddify integers from iterable.
    
    If the even value is positive, 1 is added
    If the even value is negative, 1 is subtracted
    0 is not affected.
    """
    for value in iterable:
        
        # optional type checking to prevent the use
        # of floats or other types like Decimal, Fraction etc...
        if not isinstance(value, int):
            raise ValueError(f"'{value}' is not an int.")
                
        if value % 2 == 0 and value != 0:
            sign = abs(value) // value
            value += sign
            # (x + -1) == (x - 1)
        yield value
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
def oddify(arr):
    for n, i in enumerate(arr):
        if i%2 == 0:
            if i >= 0: arr[n] += 1
            else: arr[n] -= 1
    return arr
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list digit into number Voldyy 2 1,496 Jul-10-2022, 06:13 PM
Last Post: deanhystad
  Displaying list correspond to the column number danlopek14q 9 3,898 Aug-27-2021, 04:32 AM
Last Post: naughtyCat
  Get the biggest number from a two dimensional list rs74 13 3,944 Aug-09-2020, 04:02 PM
Last Post: deanhystad
  How can I print the number of unique elements in a list? AnOddGirl 5 3,196 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  Convert a list of integers to strings? Cornelis 3 2,222 Nov-15-2019, 12:13 PM
Last Post: perfringo
  how to convert list into string Shevach 3 2,589 May-14-2019, 09:51 AM
Last Post: perfringo
  Convert string to a specific number of bytes artblinked 1 2,399 Mar-28-2019, 08:43 PM
Last Post: Larz60+
  Convert number to a different base and make calculations frequency 12 5,536 Dec-17-2018, 05:21 PM
Last Post: frequency
  Multiplying number in a list in an order pythoneer 12 6,480 Mar-23-2018, 08:21 PM
Last Post: buran
  adding a number to the list atux_null 4 3,798 Nov-06-2017, 07:01 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020