Brian
Brian

Reputation: 148

python map vs list comprehsnion

I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

This code does not work for the following example:

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214

However, a similar function crafted as:

def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))

Returns the correct answer

print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214

Shouldn't

map(int, numbers)

be the same as

[int(number) for number in numbers]

Why do the two functions not return the same values?

Upvotes: 2

Views: 87

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

No, it shouldn't because you don't assign the result of map anywhere so min and max use numbers from numbers.split(' '). That is, you're using string comparisons.

The list comprehension is saved to nn and that is the name that is used in min and max.

Despite that, even if you did save numbers as the result of map:

numbers = map(int, numbers)

you'd still get an error since max will first consume the iterable (until it's exhausted) and then min will complain because it'll receive an empty iterable.

You'd probably need to use something like itertools.tee, supply both min and max with map(int, numbers) or use a list-comprehension as you've already done.

Upvotes: 4

keepAlive
keepAlive

Reputation: 6665

Why do the two functions not return the same values?

Because the function you involve in map does not work in place.

when you write

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)    ## DOES NOT WORK IN PLACE
    ## So ADD THE LINE BELOW
    numbers = map(int, numbers)    
    return str(max(numbers)) + ' ' + str(min(numbers))

you must somewhere reassign numbers like so

numbers = map(int, numbers) 

Upvotes: 1

Wondercricket
Wondercricket

Reputation: 7882

In your high_and_low method, map(int, numbers) is not being assigned to a value.

def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

Also, map returns an iterator in Python 3.x. Your min(numbers) will error because max will exhaust the iterator and throw a ValueError due to an empty sequence. So you need to convert it to a list

def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = list(map(int, numbers))
    return str(max(numbers)) + ' ' + str(min(numbers))

Upvotes: 4

Related Questions