1 Replies - 1880 Views - Last Post: 26 September 2011 - 10:19 AM

#1 stackoverflow   User is offline

  • D.I.C Addict
  • member icon

Reputation: 166
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Random Class

Posted 19 September 2011 - 11:32 PM

Description: The methods return the values. You need to store them or print them etc. There is no error checking so the class assumes the base and limit are valid.This is a random class for generating random evens, odds within a range-- as well numbers within a range.
import random

class Random:
  def __init__(self, base, limit):
    self.base  = base
    self.limit = limit

  def even(self):
    roll = 1 # can't initialize to 0
    while roll % 2 != 0:
      roll = random.randint(self.base, self.limit)
    return roll

  def odd(self):
    roll = 0 # can't initialize to 1
    while roll % 2 == 0:
      roll = random.randint(self.base, self.limit)
    return roll

  def random(self):
    return random.randint(self.base, self.limit)


Is This A Good Question/Topic? 0
  • +

Replies To: Random Class

#2 stackoverflow   User is offline

  • D.I.C Addict
  • member icon

Reputation: 166
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Re: Random Class

Posted 19 September 2011 - 11:32 PM

Description: The methods return the values. You need to store them or print them etc. There is no error checking so the class assumes the base and limit are valid.This is a random class for generating random evens, odds within a range-- as well numbers within a range.
import random

class Random:
  def __init__(self, base, limit):
    ''' Creates a Random object, the base and limit are inclusive 
    '''
    self.base  = base 
    self.limit = limit  

  def even(self):
    roll = 1 # can't initialize to 0
    while roll % 2 != 0:
      roll = random.randint(self.base, self.limit)
    return roll

  def odd(self):
    roll = 0 # can't initialize to 1
    while roll % 2 == 0:
      roll = random.randint(self.base, self.limit)
    return roll

  def random(self):
    ''' returns a random number between base and limit including the base
        and limit
    '''
    return random.randint(self.base, self.limit)

Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Random Class

Posted 26 September 2011 - 10:19 AM

I would suggest that you make it clear whether or not "base" and "limit" are inclusive or exclusive (for instance, in C#, the lower limit is inclusive, and the upper is exclusive). Also, I'd suggest that you name the first parameter something other than "base", since in the context of numbers, that suggests radix rather than lower bound.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1