Question

In this code, I'm trying to divide variable self.damage by 20:

self.damage = map(lambda x: x/20, self.damage)
...
...
print("\nPICKAPOO's DAMAGE RATING WAS DECREASED BY 20%")
print("PICKAPOO's DAMAGE RATING IS NOW {}".format(str(self.damage)))
...
return self.damage

When I run it, I get this weird bug:

PICKAPOO's DAMAGE RATING WAS DECREASED BY 20%
PICKAPOO's DAMAGE RATING IS NOW <map object at 0x0000000002CB1128>

If I try any other code than the one I've got, it returns the same TypeError: unsupported operand type(s) error.

Any thoughts, opinions, and advice for the future would be highly appreciated.

Was it helpful?

Solution

In Python 3.x, map() returns an iterable, not a list. If you want a list, use list(map(...)).

The normal use case is just to iterate over it, which you can do just as you would if it was a list.

Arguably a better solution here is a list comprehension:

[x / 20 for x in self.damage]

As a note, dividing by 20 is not a 20% reduction (it's a 95% reduction) - to do that, you want:

[x * 0.8 for x in self.damage]

OTHER TIPS

You don't want to use map for this. map applies a function to every element in a list, while you're just trying to do simple division. Just use

self.damage = self.damage / 20

However, based on your text you are trying to reduce it by 20%, which is a different formula altogether:

self.damage = self.damage * (1 - 20 / 100)

EDIT:

It helps to know that self.damage is a tuple representing the damage range. Here's a function that can reduce that by x%:

self.damage = tuple(damageValue * (1 - x/100) for damageValue in self.damage)

If you don't care about keeping it as a tuple, you can use a list comprehension:

self.damage = [damageValue * (1 - x/100) for damageValue in self.damage]

Lists and tuples are very similar to work with, so it probably does not matter which one you use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top