0 Replies - 2101 Views - Last Post: 22 November 2012 - 04:41 PM

#1 DanielKlopp   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 22-November 12

Random Integer Generator.

Posted 22 November 2012 - 04:41 PM

Description: Simply make sure you have imported the module random. Then you can use this like any other iterator. A class that generates an iterator that generates random integers between a specific range
__author__ = 'Daniel Klopp'
__date__= "11/21/2012"

class RandomInt:
    """
        Class that simply generators a specified number of random integers within
        a specific range. Set limit to how many randoms you want, set num_range
        as a tuple containing two integers, first is the lower range, second
        is the upper, all values will be in this range, obviously. Set sort
        to 'even', 'odd' or '/5'(or any int) for only numbers divisble by the int.
        Make sure to import the random module of course..
    """

    def __init__(self, limit, num_range=(0, 9), sort=0):
        self.limit = limit
        self.num_range = num_range
        self.sort = sort

    def __iter__(self):
        if self.sort != 0:
            if '/' in self.sort:
                container_limit = self.limit * 10
            container_limit = self.limit * 5
        self.iter_count = -1
        self.container = [random.randint(self.num_range[0], self.num_range[1]) 
                                                   for i in range(container_limit)]
        self.filter_gen = self.filter()
        return self

    def filter(self):
        for i in self.container:
            yield i

    def __next__(self):
        self.iter_count += 1
        if self.iter_count == self.limit:
            raise StopIteration

        return_value = next(self.filter_gen)

        if self.sort != 0:
            i = 0
            while True:
                i += 1
                if i != 1:
                    return_value = next(self.filter_gen)
                if self.sort == 'even':
                    if return_value % 2 == 0:
                        break
                if self.sort == 'odd':
                    if return_value % 2 != 0:
                        break
                if '/' in self.sort:
                    if return_value % int(self.sort[self.sort.find('/') + 1:]) == 0:
                        break
        return return_value



Is This A Good Question/Topic? 0
  • +

Page 1 of 1