How to convert positive numbers to negative in Python? - 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

If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use:
-abs(n)
Note that integer 0 will remain 0.

-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

I believe the best way would be to multiply each number by -1:
def negativeNumber(x):
neg = x * (-1)
return neg

You are starting with positive numbers, so just use the unary - operator.
arrayLength = 25
array1 = [-random.randint(0, arrayLength) for _ in arrayLength]

This will also go good
import random
array1 = []
arrayLength = 25
for i in range(arrayLength):
array1.append((random.randint(0, arrayLength)*-1))

Related

Creating a list of random numbers shorter than specified 'count' between [0,1) greater than specified 'cutoff'

I am just starting in Python (though have coding experience in other languages) and am working on this assignment for a class in ArcGIS pro. We have been tasked with using the random module to generate a list of random numbers between 0 and 1 with a few different 'cutoffs' (shown here 0.7) and 'counts' shown here 5.
I have tried a few different ways of approaching this problem including using nested loops (shown below, different count and cutoff) but came out with a list too long. I am now trying to approach the problem using only a while loop after some guidance from my professor, yet my list remains... empty? Any help is appreciated.
(https://i.stack.imgur.com/6bNdX.png)
(https://i.stack.imgur.com/QEydA.png)
You have the right idea, just some bugs in your code. The first one, your x is just counting from 0 to count and that's what you are appending to your list of numbers rather than the random.random() output. Also, you didn't assign any value to your random.random() output either.
The second example is much closer to what you're looking for, but you are missing a colon after the if statement and the numbers.append(x) should be indented.
import random
seed = 37
cutoff = 0.4
count = 8
random.seed(seed)
numbers = []
while len(numbers) < count:
x = random.random()
if x > cutoff:
numbers.append(x)
print(numbers)
Consistent with the suggestion by #Tim to use random.uniform(), here is a complete solution that builds on his guidance:
import random
count, cutoff, seed = 10, 0.4, 37
random.seed(seed)
numbers = [
random.uniform(cutoff, 1.0)
for _ in range(count)
]
print(numbers)
Output:
[0.8092027363527867, 0.45496156484773836, 0.7706898093168415, 0.9051519427305738, 0.9007301731456538, 0.7090106354748096, 0.778622779177406, 0.6215379004377511, 0.7168111732115348, 0.46471400998163914]

How do i sum from one to million using min,max,and sum? (in loop)

the question: Make a list of the numbers from one to one million, and then use
min() and max() to make sure your list actually starts at one and ends at one million. Also, use
the sum() function to see how quickly Python can add a million numbers.
So here's my initial code, I do not know how to use min max or sum in this case:
one_million = []
for numbers in range(0,1000000):
counting = numbers+1
one_million.append(counting)
print(one_million)
Do it step by step.
Make a list of the numbers from one to one million
numbers = list(range(1, 1000000 + 1)) # add 1 to upper bound since range is inclusive-exclusive
and then use min() and max() to make sure your list actually starts at one and ends at one million
assert min(numbers) == 1
assert max(numbers) == 1000000
Also, use the sum() function to see how quickly python can add a million numbers
total = sum(numbers)
print(total)
range supports min, max and sum, so you don't need any loop to do this:
numbers = range(1,1000001) #Note that range gives you a number UP TO the last number
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Easy
million = [n for n in range(0, 1000000 + 1)]
million_sum = sum(million)
print(million_sum)
assert min(numbers) == 1
assert max(numbers) == 1000000
I'm assuming you're doing the Python Crash Course book because this is project 4-5. I came across your post while I was looking for documentation on min and max. I thought it was great to see someone else working on the same problem so I thought I would share my code. I came up with this:
million_list = []
for num in range(1,1_000_001):
million_list.append(num)
print(min(million_list))
print(max(million_list))
print(sum(million_list))
JeffUK's answer is nice. Thanks for the info about range not requiring a for loop.
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
#also reading the book!

how to create a range of random decimal numbers between 0 and 1

how do I define decimal range between 0 to 1 in python? Range() function in python returns only int values. I have some variables in my code whose number varies from 0 to 1. I am confused on how do I put that in the code. Thank you
I would add more to my question. There is no step or any increment value that would generate the decimal values. I have to use a variable which could have a value from 0 to 1. It can be any value. But the program should know its boundary that it has a range from 0 to 1. I hope I made myself clear. Thank you
http://docs.python.org/library/random.html
If you are looking for a list of random numbers between 0 and 1, I think you may have a good use of the random module
>>> import random
>>> [random.random() for _ in range(0, 10)]
[0.9445162222544106, 0.17063032908425135, 0.20110591438189673,
0.8392299590767177, 0.2841838551284578, 0.48562600723583027,
0.15468445000916797, 0.4314435745393854, 0.11913358976315869,
0.6793348370697525]
for i in range(100):
i /= 100.0
print i
Also, take a look at decimal.
def float_range(start, end, increment):
int_start = int(start / increment)
int_end = int(end / increment)
for i in range(int_start, int_end):
yield i * increment
This will output decimal number between 0 to 1 with step size 0.1
import numpy as np
mylist = np.arange(0, 1, 0.1)
It seems like list comprehensions would be fairly useful here.
mylist = [x / n for x in range(n)]
Something like that? My Python's rusty.
>>> from decimal import Decimal
>>> [Decimal(x)/10 for x in xrange(11)]
[Decimal("0"), Decimal("0.1"), Decimal("0.2"), Decimal("0.3"), Decimal("0.4"), Decimal("0.5"), Decimal("0.6"), Decimal("0.7"), Decimal("0.8"), Decimal("0.9"), Decimal("1")]
Edit, given comment on Mark Random's answer:
If you really don't want a smoothly incrementing range, but rather a random number between 0 and 1, use random.random().

How to check last digit of number

Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc..
If I use a text variable I can simply put
print number[:-1]
but it works for variables with text(like "hello) but not with numbers. With numbers I get this error:
TypeError: 'int' object is not subscriptable
I am trying to see if there's a better way to deal with numbers this way. I know a solution is to convert to a string and then do the above command but I'm trying to see if there's another way I have missed.
Thanks so much in advance...
Remainder when dividing by 10, as in
numericVariable % 10
This only works for positive numbers. -12%10 yields 8
Use the modulus operator with 10:
num = 11
if num % 10 == 1:
print 'Whee!'
This gives the remainder when dividing by 10, which will always be the last digit (when the number is positive).
So you want to access the digits in a integer like elements in a list; easiest way I can think of is:
n = 56789
lastdigit = int(repr(n)[-1])
# > 9
Convert n into a string, accessing last element then use int constructor to convert back into integer.
For a Floating point number:
n = 179.123
fstr = repr(n)
signif_digits, fract_digits = fstr.split('.')
# > ['179', '123']
signif_lastdigit = int(signif_digits[-1])
# > 9
I can't add a comment yet, but I wanted to iterate and expand on what Jim Garrison said
Remainder when dividing by 10, as in
numericVariable % 10
This only works for positive numbers. -12%10 yields 8
While modulus (%) is working as intended, throw on an absolute value to use the modulus in this situation.
abs(numericVariable) % 10
Lostsoul, this should work:
number = int(10)
#The variable number can also be a float or double, and I think it should still work.
lastDigit = int(repr(number)[-1])
#This gives the last digit of the variable "number."
if lastDigit == 1 :
print("The number ends in 1!")
Instead of the print statement at the end, you can add code to do what you need to with numbers ending in 1.
Hope it helped!
Convert to string first:
oldint = 10101
newint = int(str(oldint)[-1:])
The simplest and most efficient way is to use the reminder :
last_digit = orginal_number % 10
This is a simple yet effective way to do it
if number < 0:
remainder = number % -10
else:
remainder = number % 10
By using iteration and the in built function of 'digit' the number is treated as binary and so it goes from backwards to forwards. Here is an example of a bit of code for you.
for digit in binary:
denary= denary*2 + int(digit)
Try this efficient one-liner code to call the last digit of any integer.
The logic is first to convert the given value to a string and then convert it into the list to call the last digit by calling the -1 index. After that, convert it into an integer to wrap it up.
val is a variable that represents any integer.
int(list(str(val))[-1])
Example:
val = 23442
int(list(str(val))[-1])`
Output: 2

How to generate a random number with a specific amount of digits?

Let's say I need a 3-digit number, so it would be something like:
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
You can use either of random.randint or random.randrange. So to get a random 3-digit number:
from random import randint, randrange
randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop
* Assuming you really meant three digits, rather than "up to three digits".
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.
import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)
Alternatively if you don't want to save the random number as an int you can just do it as a oneliner:
'{:03}'.format(random.randrange(1, 10**3))
python 3.6+ only oneliner:
f'{random.randrange(1, 10**3):03}'
Example outputs of the above are:
'026'
'255'
'512'
Implemented as a function that can support any length of digits not just 3:
import random
def n_len_rand(len_, floor=1):
top = 10**len_
if floor > top:
raise ValueError(f"Floor '{floor}' must be less than requested top '{top}'")
return f'{random.randrange(floor, top):0{len_}}'
Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.
Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)
Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).
You could write yourself a little function to do what you want:
import random
def randomDigits(digits):
lower = 10**(digits-1)
upper = 10**digits - 1
return random.randint(lower, upper)
Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.
import random
fixed_digits = 6
print(random.randrange(111111, 999999, fixed_digits))
out:
271533
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)
import random
first = random.randint(1,9)
first = str(first)
n = 5
nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs)) :
first += str(nrs[i])
print str(first)
From the official documentation, does it not seem that the sample() method is appropriate for this purpose?
import random
def random_digits(n):
num = range(0, 10)
lst = random.sample(num, n)
print str(lst).strip('[]')
Output:
>>>random_digits(5)
2, 5, 1, 0, 4
I know it's an old question, but I see many solutions throughout the years. here is my suggestion for a function that creates an n digits random string with default 6.
from random import randint
def OTP(n=6):
n = 1 if n< 1 else n
return randint(int("1"*n), int("9"*n))
of course you can change "1"*n to whatever you want the start to be.

Categories

Resources