Error while testing the TestAreaCreation in Python using Unittest - python

Question:
Define a class Circle with method init which initializes a cicle with
attribute radius, having follwing restrictions.
radius must be numeric value, if not raise type error with error message "radius must be number".
radius must be between 0 to 1000 inclusive on both sides, if not raise the value error with error message "radius must be between 0 and
1000 inclusive"
Define a class method area and circumference which must return values rounded off to 2 decimals.
Complete the definition of class TestCircleArea which tests the
behaviour of area method as specification below.
Define the test method test_circlearea_with_random_numeric_radius
which creates circle c1 with radius 2.5 and check if its computed area
match the value 19.63
Define the test method test_circlearea_with_min_radius which creates
circle c2 with radius 0 and check if its computed area match the value
0
Define the test method test_circlearea_with_max_radius which creates
circle c3 with radius 1000 and check if its computed area match the
value 3141592.65
Tried solution:
import inspect
import re
import unittest
import math
class Circle:
def __init__(self, radius):
# Define the initialization method below
self.radius=radius
if not isinstance(self.radius,(int,float)):
raise TypeError("radius must be a number")
elif(self.radius>1000 or self.radius<0):
raise ValueError("radius must be between 0 and 1000 inclusive")
else:
pass
def area(self):
# Define the area functionality below
return math.pi*(self.radius**2)
def circumference(self):
return 2*math.pi*self.radius
# Define the circumference functionality below
class TestCircleArea(unittest.TestCase):
def test_circlearea_with_random_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# its area is 19.63.
c1=Circle(2.5)
self.assertEqual(c1.area(), 2.5)
def test_circlearea_with_min_radius(self):
# Define a circle 'c2' with radius 0, and check if
# its area is 0.
c2=Circle(0)
self.assertEqual(c2.area(), 0)
def test_circlearea_with_max_radius(self):
# Define a circle 'c3' with radius 1000.1. and check if
# its area is 3141592.65.
c3=Circle(1000)
self.assertEqual(c3.area(), 3141592.65)
if __name__ == '__main__':
fptr = open('output.txt', 'w')
runner = unittest.TextTestRunner(fptr)
unittest.main(testRunner=runner, exit=False)
fptr.close()
with open('output.txt') as fp:
output_lines = fp.readlines()
pass_count = [ len(re.findall(r'\.', line)) for line in output_lines if line.startswith('.')
and line.endswith('.\n')]
pass_count = pass_count[0]
print(str(pass_count))
doc1 = inspect.getsource(TestCircleArea.test_circlearea_with_random_numeric_radius)
doc2 = inspect.getsource(TestCircleArea.test_circlearea_with_min_radius)
doc3 = inspect.getsource(TestCircleArea.test_circlearea_with_max_radius)
assert1_count = len(re.findall(r'assertEqual', doc1))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc2))
print(str(assert1_count))
assert1_count = len(re.findall(r'assertEqual', doc3))
print(str(assert1_count))
Error:
Traceback (most recent call last):
File "Solution.py", line 61, in <module>
pass_count = pass_count[0]
IndexError: list index out of range
Please assist what's wrong.

I have just modified the init method and it worked for me in hacker rank.
class Circle:
def __init__(self, radius):
# Define the initialization method below
pattern=re.compile("^\\-?[0-9]")
if(pattern.math(str(radius))):
if(radius>=0 and radius<=1000):
self.radius=radius
else:
raise ValueError("radius must be between 0 and 1000 inclusive")
else:
raise TypeError("radius must be a number")
def area(self):
# Define the area functionality below
return math.pi*(self.radius**2)
def circumference(self):
return 2*math.pi*self.radius
# Define the circumference functionality below

you must specify return statements
class TestCircleArea(unittest.TestCase):
def test_circlearea_with_random_numeric_radius(self):
# Define a circle 'c1' with radius 2.5, and check if
# its area is 19.63.
c1=Circle(2.5)
return c1.area
return self.assertEqual(c1.area,19.3)
def test_circlearea_with_min_radius(self):
# Define a circle 'c2' with radius 0, and check if
# its area is 0.
c2=Circle(0)
return c2.area
return self.assertEqual(c2.area,0)
def test_circlearea_with_max_radius(self):
# Define a circle 'c3' with radius 1000.1. and check if
# its area is 3141592.65.
c3=Circle(1000)
return c3.area
return self.assertEqual(c3.area,3141592.65)

Modify the driver code :
Remove/delete the passcount line
Directly assign the value i.e. total number of tests to be performed.(pass_count = 3).

Related

Class function returning 'None'

I am trying to learn class inheritance for OOP in python. The following code does what I want it to so far, but returns None after printing the pipe data when the function in the parent class is called. At first I didn't have the function returning the print statement, so I added in the return keyword, but that didn't get rid of the issue. I know it must be a return issue that I am overlooking. Any help would be appreciated.
import numpy as np
class piping:
def __init__(self, diameter, length):
self.d = diameter
self.len = length
def getPipeData(self):
return print('The pipe length is %.1fm, and the diameter is %.1fm.' % (self.len, self.d))
class hydrodynamics(piping):
def __init__(self, diameter, length, fluid, density):
super().__init__(diameter, length)
self.fluid = fluid
self.density = density
self.volume = self.getVolume()
def getVolume(self):
return np.pi*self.d**2/4
sec1 = hydrodynamics(1, 10, 'water', 1000)
sec2 = hydrodynamics(0.5, 30, 'water', 1000)
print(sec1.getPipeData())
print(sec2.getPipeData())
print(sec1.volume)
print(sec2.volume)
This is what is being returned...(as I said, everything works fine so far, except that I am having issues with the return None)
The pipe length is 10.0m, and the diameter is 1.0m.
None
The pipe length is 30.0m, and the diameter is 0.5m.
None
0.7853981633974483
0.19634954084936207
The output I was expecting is:
The pipe length is 10.0m, and the diameter is 1.0m.
The pipe length is 30.0m, and the diameter is 0.5m.
0.7853981633974483
0.19634954084936207
If that really is what you want from your program then you could change your calling code to this:
sec1.getPipeData()
sec2.getPipeData()
print(sec1.volume)
print(sec2.volume)
However, better is to not print anything inside member functions. If you change your class to the following, you can keep your driving code as is.
class piping:
def __init__(self, diameter, length):
self.d = diameter
self.len = length
def getPipeData(self):
return 'The pipe length is %.1fm, and the diameter is %.1fm.' % (self.len, self.d)
You should leave out the print statement in your definition of getPipeData and only return the string.
OR:
Call sec1.getPipeData() without the print, since the print will be executed when you call sec1.getPipeData()

Python: Name not defined error even though function is clearly defined before call [duplicate]

This question already has answers here:
function name is undefined in python class [duplicate]
(2 answers)
Closed 5 years ago.
I'm new to python and having a weird issue with function definitions. I have checked around the forums and made sure to define my function before calling it, however that has not helped the issue. I keep getting a name not defined error when I try to call literally function in this one particular method.
from eight_puzzle import Puzzle
import math
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
class Node:
"""
A class representing a node.
- 'state' holds the state of the node.
- 'parent' points to the node's parent.
- 'action' is the action taken by the parent to produce this node.
- 'path_cost' is the cost of the path from the root to this node.
"""
def __init__(self, state, parent, action, path_cost):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
def gen_child(self, problem, action):
"""
Returns the child node resulting from applying 'action' to this node.
"""
return Node(state=problem.transitions(self.state, action),
parent=self,
action=action,
path_cost=self.path_cost + problem.step_cost(self.state, action))
#property
def state_hashed(self):
"""
Produces a hashed representation of the node's state for easy
lookup in a python 'set'.
"""
return hash(str(self.state))
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def retrieve_solution(node,num_explored,num_generated):
"""
Returns the list of actions and the list of states on the
path to the given goal_state node. Also returns the number
of nodes explored and generated.
"""
actions = []
states = []
while node.parent is not None:
actions += [node.action]
states += [node.state]
node = node.parent
states += [node.state]
return actions[::-1], states[::-1], num_explored, num_generated
################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def print_solution(solution):
"""
Prints out the path from the initial state to the goal given
a tuple of (actions,states) corresponding to the solution.
"""
actions, states, num_explored, num_generated = solution
print('Start')
for step in range(len(actions)):
print(puzzle.board_str(states[step]))
print()
print(actions[step])
print()
print('Goal')
print(puzzle.board_str(states[-1]))
print()
print('Number of steps: {:d}'.format(len(actions)))
print('Nodes explored: {:d}'.format(num_explored))
print('Nodes generated: {:d}'.format(num_generated))
################################################################
### Skeleton code for your Astar implementation. Fill in here.
################################################################
class Astar:
"""
A* search.
- 'problem' is a Puzzle instance.
"""
def __init__(self, problem):
self.problem = problem
self.init_state = problem.init_state
self.num_explored = 0
self.num_generated = 1
def selectState(self, listOfStates):
'''
Selects the loweset cost node for expansion based on f(n) = g(n) + h(n)
'''
lowestCostPath = listOfStates[0].path_cost
index = int(1)
lowestNodeIndex = int(0)
while index != len(listOfStates):
scannedPathCost = listOfStates[index].path_cost
if index < scannedPathCost:
lowestCostPath = scannedPathCost
lowestNodeIndex = index
index += 1
return listOfStates[lowestNodeIndex]
def f(self,node, method):
'''
Returns a lower bound estimate on the cost from root through node
to the goal.
'''
return node.path_cost + self.h(node, method)
def getManhattanDistance(self, node):
'''
Evaluates the manhattan distance for a given state
'''
iterator = int(0)
misplacedCount = int(0)
totalDistance = int(0)
while iterator != len(node.state):
if iterator != node.state[iterator] and node.state[iterator] != 0:
misplacedCount = misplacedCount + 1
xCurrent = int(node.state[iterator]/3)
yCurrent = int(node.state[iterator]%3)
xDesired = int(iterator/3)
yDesired = int(iterator%3)
totalDistance = totalDistance + int(abs(xCurrent - xDesired)) + int(abs(yCurrent - yDesired))
iterator = iterator + 1
return totalDistance + misplacedCount
def h(self,node, method='man'):
'''
Returns a lower bound estimate on the cost from node to the goal
using the different heuristics.
'''
################################################################
### Your code here.
################################################################
if method == 'man':
self.getManhattanDistance(node)
return -1
elif method == 'rowcol':
return -1 # compute rowcol heuristic
elif method == 'misplaced':
return -1 # compute misplaced tiles the number of tiles out of place
elif method == 'null':
return -1 # compute null heuristic
else:
return 0
def method_stats(self, board, trials=100, method='man'):
'''
Returns an mean and standard deviation of the number of nodes expanded
'''
# write code here to randomly generate puzzles and
# compute the mean and standard deviation of the number
# nodes expanded. You can use np.mean() and np.std()
expanded_mean = 0.
expanded_std = 0.
for t in range(trials):
puzzle = Puzzle(board).shuffle()
solver = Astar(puzzle)
actions, states, num_explored, num_generated = solver.solve(method=method)
############################################################
### Compute upper bound for branching factor and update b_hi
### Your code here.
############################################################
return expanded_mean, expanded_std
def anotherFunction(self, node, method):
return 1
def generateStatesFor(self, node, method, listOfStates):
'''
Decides how to select an action from a list of available actions
'''
def solve(self, method='man'):
node = Node(state = self.init_state,
parent = None,
action = None,
path_cost = 0)
num_explored = int(0)
num_generated = int(0)
listOfStates = []
listOfStates.append(node)
print(listOfStates[0].state)
anotherFunction(self, node, method)
return retrieve_solution(node, num_explored=num_explored, num_generated=num_generated)
if __name__ == '__main__':
# Simple puzzle test
## board = [[3,1,2],
## [4,0,5],
## [6,7,8]]
board = [[7,2,4],
[5,0,6],
[8,3,1]]
puzzle = Puzzle(board)
solver = Astar(puzzle)
solution = solver.solve()
##print_solution(solution)
# Harder puzzle test
board = [[7,2,4],
[5,0,6],
[8,3,1]]
puzzle = Puzzle(board)
solver = Astar(puzzle)
##solution = solver.solve()
##print(len(solution[0]))
# branching factor test
method='man'
emean, estd = solver.method_stats(board, trials=100, method=method)
##print('mean and standard deviation: {0:.2f}, {1:.2f} using heuristic: {2}'.format(emean, estd, method))
The Error code:
Traceback (most recent call last): File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 214, in <module>
solution = solver.solve() File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 200, in solve
anotherFunction(self, node, method) NameError: name 'anotherFunction' is not defined [Finished in 0.1s with exit code 1]
As you can see, the function calling it is on line 200 and the function is defined at line 185. Any idea what the issue could be? I am also able to call the exact same "anotherFunction" method from other methods which aren't solve. Any tips would be appreciated.
When you define a function with "self" as an argument, you need to call that function from the class in which it is defined. For example, if you have an instance of the class myClass where anotherFunction is defined, the syntax would be myClass.anotherFunction(node, method). The "self" argument in the definition indicates anotherFunction is a member function of whatever class it is defined in - I would need to see more of your code to know what class that is.

builtins.TypeError: __init__() missing 2 required positional arguments: 'height' and 'radius'

I am getting an error that says I am missing 2 required positional arguments: 'height' and 'radius.' I feel like I have tried everything but I know I am missing something small. Any help?
Thanks
# import math
import math
class SodaCan :
# Constructs sodaCan with a given height and radius
# #param height = given height and radius = given radius
def __init__(self, height, radius):
self._height = height
self._radius = radius
# Constructs the volume with the given height and radius
def volume(self):
self._volume = (pi * (self._radius ** 2) * self._height)
# Constructs the Surface Area with the given height and radius
def surfaceArea(self):
self._surfaceArea = (2 * pi * self._radius * self._height) + (2 * pi * (self._radius)**2)
# Return the volume
def getVolume(self):
return self._volume
# Return the Surface Area
def getSurfaceArea(self):
return self._surfaceArea
I am not sure what I am doing wrong here. Below there is the test program for my code.
##
# This program test the sodaCan.py
##
# import math so the program can read pi
import math
# from the file folder, ipmort the code from program 'sodaCan'
from sodaCan import SodaCan
mySodaCan = SodaCan()
mySodaCan.height(10)
mySodaCan.radius(4)
print(mySodaCan.getVolume())
print(mySodaCan.getSurfaceArea())
You need the pass the height and radius when you initialize the class. Arguments in the init class mean that they have to be passed when you initialize the class. Something like this would work:
height = 40
radius = 10
a = SodaCan(height, radius)
When you define the initializer like this:
class SodaCan:
def __init__(self, height, radius):
...
You are saying that height and radius are required. They must be specified in order to create a soda can instance.
mySodaCan = SodaCan(height=10, radius=4)
If you want them to be optional, you may specify default values for those arguments when you define the __init__ method. Then when you create an instance, the arguments will take the default values if omitted when creating an instance.

Python iteration over non-sequence in an array with one value

I am writing a code to return the coordinates of a point in a list of points. The list of points class is defined as follows:
class Streamline:
## Constructor
# #param ID Streamline ID
# #param Points list of points in a streamline
def __init__ ( self, ID, points):
self.__ID = ID
self.__points = points
## Get all Point coordinates
# #return Matrix of Point coordinates
def get_point_coordinates ( self ):
return np.array([point.get_coordinate() for point in self.__points])
With
class Point:
## Constructor
# #param ID Streamline ID
# #param cor List of Coordinates
# #param vel List of velocity vectors (2D)
def __init__ ( self, ID, coord, veloc):
self.__ID = ID
self.set_coordinate( coord )
self.set_velocity( veloc )
The thing is that I start my code by defining a Streamline with one Point in the point list. A little down the road I call the function get_point_coordinates and the iteration over the list of points raises the following error:
return np.array([point.get_coordinate() for point in self.__points])
TypeError: iteration over non-sequence
I need to find a way to bypass this error and neatly return just a 1x2 matrix with the point coordinates.
I've had a look at this question but it wasn't very helpful.
Either call the Streamline-constructor with a sequence instead of a single point: sl = Streamline(ID, [first_point])
Or ensure the constructor makes the single point to be iterable:
class Streamline:
def __init__ ( self, ID, first_point):
self.__ID = ID
self.__points = [first_point]
It is a bad idea to write the constructor to accept a single point (Streamline(ID, point1)) and a sequence of points (Streamline(ID, [point1, point2, ...])). If you want so, you can do
from collections import Iterable
class Streamline:
def __init__ ( self, ID, first_point):
self.__ID = ID
self.__points = points if isinstance(points, Iterable) else [points]
Better than 3. would be to unpack the points given in arguments via * to enable Streamline(ID, point1) and Streamline(ID, point1, point2, ...).
class Streamline:
def __init__ ( self, ID, *points):
self.__ID = ID
self.__points = points

simple CLASS in python

from math import pi
class sphere(object):
def __init__(self,radius):
self.radius = radius
def get_radius(self):
return radius
def surfaceArea(self):
return 4*pi*radius**2
def volume(self):
return (4//3)*pi*radius**3
radius = input("Please enter your radius:")
print sphere.get_radius()
print sphere.surfaceArea()
print sphere.volume()
i need to write the program that prompts the user for a radius then uses your sphere class to output the surface area and volume of a sphere. and I get a type error unbound method get_Radius() must be called with sphere instance as first argument(got nothing instead). Any way to solve this problemo?
You have never created an object from class sphere. Instead of calling sphere.get_radius(), you need to first initiate an object from that class, then call the method on that object.
a = sphere(radius) # initiate an object of class sphere called a
a.get_radius() # call method on the object a.
you need to create a new object and assign redius variable
You need also to use self.redius inside the class.
Check the code below for the above mentioned-comments
from math import pi
class sphere(object):
def __init__(self,radius):
self.radius = radius
def get_radius(self):
return self.radius
def surfaceArea(self):
return 4*pi*self.radius**2
def volume(self):
return (4//3)*pi*self.radius**3
radius = input("Please enter your radius:")
s= sphere(radius)
print s.get_radius()
print s.surfaceArea()
print s.volume()

Categories