-7

I'm writing some code to find patterns in pseudo-random numbers. I would like to print these numbers as they are added to a list. How do I get the last generated 'random' int? I would use this value to print it to the console. I've looked through the documentation, but can't find that in the documentation.

Here is some code:

pseudo_random_list += str(random.randrange(0, 9))
# [Snippet to print last integer generated]

(pseudo_random_list is a string.)

I would also not like to creat temp variables. (Memory isn't unlimited)

SnakeException
  • 1,148
  • 1
  • 8
  • 26

4 Answers4

2

Just assign the integer to a variable:

num = random.randint(1,5)

print(num)  # First time

print(num)  # Print again, to verify it doesn't change

And it stays the same:

4
4

Example of using this in a loop:

while True:
    num = random.randint(1,5)

    print(num)

    # Do whatever here
Aero Blue
  • 518
  • 2
  • 14
1

You could do it by writing your own function that remembers the last digit it returned. Since it only stores the last one, it won't consume more and more memory every time it's called.

import random

def random_digit():
    random_digit.last = random.randrange(0, 9)
    return random_digit.last

pseudo_random_list = ''

for _ in range(7):
    pseudo_random_list += str(random_digit())

# Sample usage.
print(repr(pseudo_random_list)) # -> '5538304'
print(random_digit.last) # -> 4

Note: I think you may want to use random.randint() instead of random.randrange() because random.randrange(0, 9) will only generate numbers in the range 0..8, whereas random.randint(0, 9) would generate numbers in the range 0..9.

martineau
  • 119,623
  • 25
  • 170
  • 301
0

I think I figured it out myself.

I can simply add a value to my list and then print the value using print(pseudo_random_list[-1])

SnakeException
  • 1,148
  • 1
  • 8
  • 26
  • This will give you the last _character_ that was added to the list, not the last `int` generated (although there's a relationship between the two, obviously). – martineau Jun 05 '19 at 01:26
  • @martineau Practically, it is, because I added the last int to the end of the list. – SnakeException Jun 05 '19 at 02:30
-1

Just have a temp variable that they get passed through. That will have the last value.

Jacob
  • 887
  • 1
  • 8
  • 17
  • Generating a bunch of numbers and then comparing two slices (as I'm doing) is very memory-intensive already, and I would not like to add creating temp variables to the mix. – SnakeException Jun 04 '19 at 23:59
  • 3
    @Divergence Then please add your code to your question – C.Nivs Jun 05 '19 at 00:01
  • Not sure why this got downvoted. Using: `temp = random.randrange(0, 9);` `pseudo_random_list += str(temp)` This would only have 1 temp variable the gets overwrote with the last random number. (Almost no increase on memory) – Jacob Jun 05 '19 at 01:16