import math
EMPTY = '-'
def is_between(value, min_value, max_value):
""" (number, number, number) -> bool
Precondition: min_value <= max_value
Return True if and only if value is between min_value and max_value,
or equal to one or both of them.
>>> is_between(1.0, 0.0, 2)
True
>>> is_between(0, 1, 2)
False
"""
return value >= min_value and value <= max_value
# Students are to complete the body of this function, and then put their
# solutions for the other required functions below this function.
def game_board_full(cells):
""" (str) -> bool
Return True if no EMPTY in cells and else False
>>> game_board_full ("xxox")
True
>>> game_board_full ("xx-o")
False
"""
return "-" not in cells
def get_board_size (cells):
""" (str) -> int
Return the square root of the length of the cells
>>>get_board_size ("xxox")
2
>>>get_board_size ("xoxoxoxox")
3
"""
sqrt_cell= len(cells) ** 0.5
return int(sqrt_cell)
def make_empty_board (size):
""" (int) -> str
Precondition: size>=1 and size<=9
Return a string for storing information with the size
>>>make_empty_board (2)
"----"
>>>make_empty_board (3)
"---------"
"""
return "-" *size ** 2
def get_position (row_index,col_index,size):
""" (int,int,int) -> int
Precondition:size >=col_index and size >= row_index
Return the str_index of the cell with row_index,col_index and size
>>>get_position (2,2,4)
5
>>>get_position (3,4,5)
13
"""
str_index = (row_index - 1) * size + col_index - 1
return str_index
def make_move( symbol,row_index,col_index,game_board):
"""(str,int,int,str) -> str
Return the resultant game board with symbol,row_index,col_index and game_board
>>>make_move("o",1,1,"----")
"o---"
>>>make_move("x"2,3,"---------")
"-----x---"
"""
length=len(game_board)
size=len(cells) ** 0.5
str_index = (row_index - 1) * size + col_index - 1
return "-"*(str_index-1)+symbol+"-"*(length-str_index)
def extract_line (cells,direction,cells_num):
""" (str,str,int) -> str
Return the characters of a specified row with cells, direction and cells_num
>>>extract_line ("xoxoxoxox","across",2)
"oxo"
>>>extract_line ("xoxo","up_diagonal","-")
"xo"
"""
num=cells_num
s=cells
size= get_board_size (cells)
if direction=="across":
return s[(num-1)* size : num*size]
elif direction=="down":
return s[num-1:size **2:size]
elif direction=="up_diagonal":
return s[(size-1)*size:size-2:1-size]
elif direction=="down_diagonal":
return s[0:size*2:size+1]
NameError: name 'cells' is not defined
I don't know how to define cells because it is a parameter.
You have NO cells parameter in
def make_move( symbol,row_index,col_index,game_board):
Next time read the error message carefully so you know in which code line you have a problem.
I find that you have referred to the variable cells in your make_move function without declaration, maybe you should define it in the arguments list.
By the way, you MUST put up all your traceback or it's difficult for all of us to find out the problem.
Related
class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
def RecursiveBinarySearchAlgo(List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return Algorithms.SearchAlgorithm.RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return Algorithms.SearchAlgorithm.RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(Result):
print("Target found: ", Result)
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = RecursiveBinarySearchAlgo(Numbers, 12)
Verify(Result)
# Test Case 2
Result = RecursiveBinarySearchAlgo(Numbers, 5)
Verify(Result)
I am getting a name error that the class is not defined name 'Algorithms' is not defined.
I tried entering init function with each class with self. But I am still getting the same error
the program should result in:
Target found : True
target found: False
I don't know why within inner class we cannot call method directly, but as #juanpa.arrivillaga suggested moving to one level up and using an instance of inner class works in addition to self keyword on methods:
class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
def RecursiveBinarySearchAlgo(self, List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return self.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return self.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(self, Result):
print("Target found: ", Result)
rbs = RecursiveBinarySearch()
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = rbs.RecursiveBinarySearchAlgo(Numbers, 12)
rbs.Verify(Result)
# Test Case 2
Result = rbs.RecursiveBinarySearchAlgo(Numbers, 5)
rbs.Verify(Result)
If you don't want to create an instance in that case you can use #classmethod annotation as well:
class Algorithms:
class SearchAlgorithms:
class RecursiveBinarySearch:
#classmethod
def RecursiveBinarySearchAlgo(cls, List, Target):
'''
Return true value if it exists and a false if it doesn't
'''
# If the length of the List is equal to 0 : return False
if len(List) == 0:
return False
# Else if the list is not empty
else:
Midpoint = (len(List))//2
# IF the Midpoint value within the list is equal to Target value: return true
if List[Midpoint] == Target:
return True
else:
if List[Midpoint] < Target:
return cls.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
else:
return cls.RecursiveBinarySearchAlgo(List[:Midpoint], Target)
def Verify(Result):
print("Target found: ", Result)
Numbers = [1,2,3,4,5,6,7,8]
# Test Cases 1
Result = RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 12)
RecursiveBinarySearch.Verify(Result)
# Test Case 2
Result = RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 5)
RecursiveBinarySearch.Verify(Result)
For school i have to make an assignment -->
"The city of Amsterdam wants to store the maximum values of the past few years for research
purposes. It is important that the current maximum measured value can be accessed very quickly.
One idea to fulfill this requirement is to use a priority queue. Your job is to implement a priority
queue with a maximum heap and return again a tuple of the current maximal measurement and
its corresponding date when the maximum occurred. Output: date,covid level"
The program takes as input:
(string)’yyyy-mm-dd’, (int)sensor id, (int)covid level.
The expected output is: yyyy-mm-dd,covid level.
Input: 2022−09−08, 23, 371; 2022−09−08, 2, 3171; 2022−09−08, 12, 43; 2021−03−21, 4, 129
Output: 2022 −09 −08, 3171
I have provided my code below. When creating a max heap, the max element should be the first element (root). A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node, though when inserting the tuples the nodes do not get sorted. My output is very strange, i do not understand where it comes from. When putting in the above input, this is my output:
1.1.1977, 9223372036854775807
could somebody help me? what piece of code am i missing, i have gone over it so many times.
import sys
class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = ('1.1.1977', sys.maxsize)
self.FRONT = 1
# Function to return the position of
# parent for the node currently
# at pos
def parent(self, pos):
return pos // 2
# Function to return the position of
# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos
# Function to return the position of
# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
if pos >= (self.size // 2) and pos <= self.size:
return True
return False
# Function to swap two nodes of the heap
def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],
self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap
def insert(self, element):
if self.size >= self.maxsize:
return
self.size += 1
self.Heap[self.size] = element
current = self.size
while (self.Heap[current] >
self.Heap[self.parent(current)]):
self.swap(current, self.parent(current))
current = self.parent(current)
# Function to print the contents of the heap
def Print(self):
for i in range(1, (self.size // 2) + 1):
print(i)
print("PARENT : " + str(self.Heap[i]) +
"LEFT CHILD : " + str(self.Heap[2 * i]) +
"RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
# Function to remove and return the maximum
# element from the heap
def extractMax(self):
extraction = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.maxHeapify(self.FRONT)
return extraction
# Driver Code
if __name__ == "__main__":
input = input()
input = input.split(";")
dates = []
values = []
for d in input:
date = d.split(',', 2)
dates.append(date[0])
values.append(date[2])
values = [int(x) for x in values]
tuples = list(zip(dates, values))
heap = MaxHeap(len(tuples) + 1)
# print(tuples)
for t in tuples:
heap.insert(t)
print(t)
print(heap.extractMax())
I am trying to design a spreadsheet app. I have been able to come up with a class for my Index which is typically the point consisting of row, col. I want to be able to assign a value to the point. The challenge is I am unable to update the value for that cell.
This is what I tried so far
models.py
class Index(NamedTuple):
row: int
"""The row (y-coordinate)"""
col: int
"""The column (x-coordinate)"""
val: str = None
#property
def column_label(self):
nreps = (self.col // 26) + 1
char = chr(ord("A") + self.col % 26)
return nreps * char
#property
def row_label(self):
return str(self.row + 1)
def __str__(self):
if self.val:
return f"{self.val}"
return f"{self.column_label}{self.row_label}"
app.py
class App:
def set(self, index, raw):
"""index (Index): the cell to update
raw (str): the raw string
"""
index._replace(val=raw)
Tried the above, but the value for that cell even after assigning it in the set() is still None. What is the best approach to assign a value for that index ?
I might be missing something but cant you just do
index.val = raw
instead of
index._replace(val=raw)
Again, I am not sure if I understand correctly but is a working example with just your index class:
class Index():
row: int
"""The row (y-coordinate)"""
col: int
"""The column (x-coordinate)"""
val: str = None
#property
def column_label(self):
nreps = (self.col // 26) + 1
char = chr(ord("A") + self.col % 26)
return nreps * char
#property
def row_label(self):
return str(self.row + 1)
def __str__(self):
if self.val:
return f"{self.val}"
return f"{self.column_label}{self.row_label}"
d = Index()
d.val = 2
print(d.val)
d.val = 100
print(d.val)
output
2
100
I'm playing around with some interval calculations in Python. This is an excerpt of what I've written. I want to include degenerate intervals i.e. the interval for the real number 1 is [1,1].
So when I type Interval(1), I want [1,1] returned. But I've defined my interval class in terms of two parameters.
I can't make a subclass - it would still expect two parameters. Can anyone point me in the right direction please? Could I extend the __contains__ in some sense?
TLDR: How can I get an [x,x] output from an x input?
from numpy import *
import numpy as np
from pylab import *
class Interval:
def __init__(self, LeftEndpoint, RightEndpoint):
self.min = LeftEndpoint
self.max = RightEndpoint
if LeftEndpoint > RightEndpoint:
raise ValueError('LeftEndpoint must not be greater than RightEndpoint')
def __repr__(self): #TASK 3
return '[{},{}]'.format(self.min,self.max)
def __contains__(self, num):
if num < self.min:
raise Exception('The number is not in the given interval')
if num > self.max:
raise Exception('The number is not in the given interval')
p = Interval(1,2)
print(p) #returns [1,2]
Just give RightEndpoint a default value, like None; if it is still None in the function, you know no value was assigned to it and thus can be set to the same value as LeftEndpoint:
def __init__(self, LeftEndpoint, RightEndpoint=None):
if RightEndpoint is None:
RightEndpoint = LeftEndpoint
Note: if you follow the Python styleguide, PEP 8, parameter and local variable names should be all lowercase_with_underscores. And the __contains__ method should really return True or False, not raise an exception:
class Interval:
def __init__(self, left, right=None):
if right is None:
right = left
if left > right:
raise ValueError(
'left must not be greater than right')
self.left = left
self.right = right
def __repr__(self):
return f'[{self.left}, {self.right}]'
def __contains__(self, num):
return self.left <= num <= self.right
Note that the __contains__ method can now be expressed as a single test; either num is in the (inclusive) range of left to right, or it is not.
Demo:
>>> Interval(1, 2)
[1, 2]
>>> Interval(1)
[1, 1]
>>> 11 in Interval(42, 81)
False
>>> 55 in Interval(42, 81)
True
You can use *args to pass in a variable number of arguments, then just assign RightEndpoint dynamically:
def __init__(self, *args):
self.min = args[0]
if len(args) < 2:
RightEndpoint = args[0]
elif len(args) == 2:
RightEndpoint = args[1]
else:
# decide what to do with more than 2 inputs
self.max = RightEndpoint
#...
p = Interval(1,2)
print(p) #returns [1,2]
p1 = Interval(1)
print(p1) #returns [1,1]
(Alternately you can use **kwargs if you want to use keyword arguments instead.)
I'm working on the MIT open courseware for CS-600 and I can't figure out why the last print statement isn't printing anything. Here's the code I wrote:
#!/usr/bin/env python
# encoding: utf-8
# 6.00 Problem Set 9
#
# Name:
# Collaborators:
# Time:
from string import *
class Shape(object):
def area(self):
raise AttributeException("Subclasses should override this method.")
class Square(Shape):
def __init__(self, h):
"""
h: length of side of the square
"""
self.side = float(h)
def area(self):
"""
Returns area of the square
"""
return self.side**2
def __str__(self):
return 'Square with side ' + str(self.side)
def __eq__(self, other):
"""
Two squares are equal if they have the same dimension.
other: object to check for equality
"""
return type(other) == Square and self.side == other.side
class Circle(Shape):
def __init__(self, radius):
"""
radius: radius of the circle
"""
self.radius = float(radius)
def area(self):
"""
Returns approximate area of the circle
"""
return 3.14159*(self.radius**2)
def __str__(self):
return 'Circle with radius ' + str(self.radius)
def __eq__(self, other):
"""
Two circles are equal if they have the same radius.
other: object to check for equality
"""
return type(other) == Circle and self.radius == other.radius
#
# Problem 1: Create the Triangle class
#
## TO DO: Implement the `Triangle` class, which also extends `Shape`.
class Triangle(Shape):
def __init__(self, base, height):
self.base = float(base)
self.height = float(height)
def area(self):
return self.base*self.height/2
def __str__(self):
return 'Triangle with base ' + str(self.base) + 'and height ' + str(self.height)
def __eq__(self, other):
return type(other) == Triangle and self.base == other.base and self.height == other.height
#
# Problem 2: Create the ShapeSet class
#
## TO DO: Fill in the following code skeleton according to the
## specifications.
class ShapeSet(object):
def __init__(self):
"""
Initialize any needed variables
"""
self.allCircles = []
self.allSquares = []
self.allTriangles = []
self.allShapes = self.allCircles + self.allSquares + self.allTriangles
self.place = None
def addShape(self, sh):
"""
Add shape sh to the set; no two shapes in the set may be
identical
sh: shape to be added
"""
if not isinstance(sh, Shape): raise TypeError('not a shape')
if isinstance(sh, Square):
for sq in self.allSquares:
if sh == sq:
raise ValueError('shape already in the set')
self.allSquares.append(sh)
if isinstance(sh, Triangle):
for tri in self.allTriangles:
if sh == tri:
raise ValueError('shape already in the set')
self.allTriangles.append(sh)
if isinstance(sh, Circle):
for circ in self.allCircles:
if sh == circ:
raise ValueError('shape already in the set')
self.allCircles.append(sh)
def __iter__(self):
"""
Return an iterator that allows you to iterate over the set of
shapes, one shape at a time
"""
self.place = 0
return self
def next(self):
if self.place >= len(self.allShapes):
raise StopIteration
self.place += 1
return self.allShapes[self.place - 1]
def __str__(self):
"""
Return the string representation for a set, which consists of
the string representation of each shape, categorized by type
(circles, then squares, then triangles)
"""
shapeList = ""
for item in self.allShapes:
shapeList += item.get__str__ + "br/"
return shapeList
#
# Problem 3: Find the largest shapes in a ShapeSet
#
def findLargest(shapes):
"""
Returns a tuple containing the elements of ShapeSet with the
largest area.
shapes: ShapeSet
"""
## TO DO
#
# Problem 4: Read shapes from a file into a ShapeSet
#
def readShapesFromFile(filename):
"""
Retrieves shape information from the given file.
Creates and returns a ShapeSet with the shapes found.
filename: string
"""
## TO DO
def main():
sq1 = Square(4.0)
sq2 = Square(5.0)
sq3 = Square(3.0)
circ1 = Circle(3.0)
circ2 = Circle(3.2)
tri1 = Triangle(3.0, 4.0)
tri2 = Triangle(4.0, 3.0)
tri3 = Triangle(1.0, 1.0)
thisSet = ShapeSet()
thisSet.addShape(sq1)
thisSet.addShape(sq2)
thisSet.addShape(sq3)
thisSet.addShape(circ1)
thisSet.addShape(circ2)
thisSet.addShape(tri1)
thisSet.addShape(tri2)
thisSet.addShape(tri3)
print thisSet
if __name__ == '__main__':
main()
This line:
self.allShapes = self.allCircles + self.allSquares + self.allTriangles
doesn't do what you think it does. It sets allShapes to an empty list, and then as you add shapes later, nothing updates allShapes.
Then your __str__ function just loops over allShapes, which is still empty, so your __str__ returns an empty string.
This line makes allShapes an empty list:
self.allShapes = self.allCircles + self.allSquares + self.allTriangles
If you modify allCircles, that doesn't affect allShapes. I would personally eliminate allShapes, and in the str method, add them at the last possible second:
for item in self.allCircles + self.allSquares + self.allTriangles:
The problem is here:
self.allShapes = self.allCircles + self.allSquares + self.allTriangles
When you concatenate lists like this, the result is a copy of the component lists. So when those lists are changed later, the concatenated list isn't changed. In this case, self.allCircles, etc. are all empty. So self.allShapes is an empty list too; the for loop in ShapeSet.__str__ doesn't append anything to ShapeList, and so the result is an empty string.
One simple way to fix this would be to make allShapes a method that you call, and that returns a new concatenation of self.allCircles... etc. each time it's called. That way, allShapes is always up-to-date.
If this is your actual code, then it must be because of
item.get__str__
which should raise an exception.
Edit: as others have noted, this isn't the actual problem, but I leave this here as a hint for further progress. Mind you, it's considered bad style ("unpythonic") to call x.__str__() directly, as you probably intended. Call str(x) instead, even in the implementation of __str__.
You assign allShapes to be the value of self.allCircles + self.allSquares + self.allTriangles at the start in your init method (when the other lists are empty).
It's value is then never changed, so it remains empty.
You need this in addShape:
self.allShapes.append(sh)