'How to convert positive numbers to negative in Python?
I know that abs() can be used to convert numbers to positive, but is there somthing that does the opposite?
I have an array full of numbers which I need to convert to negative:
array1 = []
arrayLength = 25
for i in arrayLength:
array1.append(random.randint(0, arrayLength)
I thought perhaps I could convert the numbers as they're being added, not after the array is finished. Anyone knows the code for that?
Many thanks in advance
Solution 1:[1]
-abs(n) is a really good answer by Tom Karzes earlier because it works whether you know the number is negative or not.
If you know the number is a positive one though you can avoid the overhead of a function call by just taking the negative of the variable:
-n
This may not matter much at all, but if this code is in a hot loop like a gameloop then the overhead of the function call will add add up.
>>> timeit.timeit("x = -abs(y)", setup="y = 42", number=5000)
0.0005687898956239223
>>> timeit.timeit("x = -y", setup="y = 42", number=5000)
0.0002599889412522316
Solution 2:[2]
I believe the best way would be to multiply each number by -1:
def negativeNumber(x):
neg = x * (-1)
return neg
Solution 3:[3]
You are starting with positive numbers, so just use the unary - operator.
arrayLength = 25
array1 = [-random.randint(0, arrayLength) for _ in arrayLength]
Solution 4:[4]
This will also go good
import random
array1 = []
arrayLength = 25
for i in range(arrayLength):
array1.append((random.randint(0, arrayLength)*-1))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | zgebac26 |
| Solution 3 | chepner |
| Solution 4 | Divyessh |
