HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMinor

Outputting Fractions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
outputtingfractionsstackoverflow

Problem

This program is to return a number one at a time from a given input list of numbers, with a frequency proportional to probability/fraction associated with each number.

I know it could be made a generator function. But if I have to do it inside a class, can you please suggest improvements to this code, particularly with regards to the exception classes I have made below?

from random import random
from bisect import bisect_right

class Invalid_fraction(ValueError): pass
class Negative_fraction(ValueError): pass
class Sum_fraction(ValueError): pass
class NullValues(ValueError): pass

class RandomGen(object):    
    def __init__(self, nums, fractions):
        #Basic error checks
        if ( len(nums)==0 or len(fractions) == 0):
            raise NullValues("Null sample space")

        if ( len(nums) != len(fractions) ):
            raise Invalid_fraction("Invalid fraction list")

        #Data initiallisations
        self._sum  = 0
        self._fractions= []
        self._nums = nums 

    #Allocating a range within 0-1 to each of the input number, along with check for negative fraction.

        for p in fractions:
            if p < 0:
                raise Negative_fraction("negative fraction") 
            self._sum += p
            self._fractions.append(self._sum)

        if self._sum != 1:
            raise Sum_fraction("Sum of fractions is not equal to 1")

    def next_num(self):     
        #Get a random number between 0 and 1 and yield the number of the bucket
        random_number = random()
        index = bisect_right(self._fractions,random_number)
        return self._nums[index]

Solution

Frankly, it seems unnecessary to have any custom exceptions (and if you keep them, they should all have PEP-8-compliant names). All of the custom exceptions could just be ValueErrors ("when a built-in operation or function receives an argument that has the right type but an inappropriate value") with different messages, e.g.:

if not nums or not fractions: # note empty collections evaluate False in a boolean context
    raise ValueError("Null sample space")

Code Snippets

if not nums or not fractions: # note empty collections evaluate False in a boolean context
    raise ValueError("Null sample space")

Context

StackExchange Code Review Q#55786, answer score: 3

Revisions (0)

No revisions yet.