Re: [Tutor] =Linked List Using Map
Thank You Steven for your great help You really helped me to understand my assignment more as well as what maps and linked lists are. I used your guidance and came up with my full code. May you take a look and let me know what needs to be changed? Thank you in advance. class Node: def __init__( self, key, value, next = None ) : self.key = key self.value = value self.next = next def getItem( self ) : return self.key def getNext( self ) : return self.next def setItem( self, item ) : self.next = next def setNext( self, next ) : self.next = next class Map: def __init__( self, contents = []) : self.first = None self.last = self.first self.numItems = 0 # traverse the linked list node = self.first while node is not None: print(key = %s, value = %s % (node.key, node.value)) node = node.next # Add new node to the end node = self.first if node is None: self.first = Node(the key, some value) else: while node.next is not None: node = node.next node.next = Node(the key, some value) def length( self ) : if node.next == Node(the key, some value): self.numItems = self.numItems + 1 else: self.numItems = self.numItems - 1 return self.numItems def contains() : node = self.first while node is not None: if node.key == key: return True else: return False def setitem( self, key, value ) : node = self.first while node is not None: if key in self.key : pos = self.key.index(key) node.value[pos] = value return else: node = node.next def getitem( self, key ) : node = self.first while node is not None: assert key in self.key keypos = self.key.index(key) return node.value[keypos] # Clears or empties the map by removing all key/value pairs def clear( self ): return self.first == None # Returns a list containing the keys stored in the map. def keys( self ): return self.key # Returns a list contain the values stored in the map. def values( self ): return self.value # Returns a string representation of the map in the following format:{k1:v1, k2:v2, ..., kN:vN} def __repr__( self ): return {%s} % (, .join([%s:%s % (k,v) for k, v in zip(self._key, self._value)])) # Returns the minimum key in the map. The map cannot be empty. def min(self, key ): node = self.first while node is not None and self.first == None: pass # Returns the maxiumum key in the map. The map cannot be empty. def max( self, key ): node = self.first while node is not None and self.first == None: pass # Create a new linked list that contains the same entries as the origninal def copy( self ): if self.next is None: return self.value else: return self.value, self.next.copy() Sent from Windows Mail From: Steven D'Aprano Sent: Saturday, April 18, 2015 11:02 PM To: tutor@python.org Cc: Ni'Yana Morgan Hello Ni'Yana, and welcome! On Fri, Apr 17, 2015 at 06:11:00PM +, niyanax...@gmail.com wrote: Hello I need guidance trying to solve my assignment. I am completely lost when using maps with linked lists. I understand linked lists though. May someone work with me? We will not do your homework, but perhaps we can guide you. Thank you for showing your code. It looks like you have already made a lot of progress. Unfortunately, the one thing you did not tell us is what part of the assignment you are having problems with! It looks like you have done most of the work correctly so far, so what part is giving you trouble? A few comments on your code below: class Node: def __init__( self, item, next = None ) : self.item = item self.next = next def getItem( self ) : return self.item def getNext( self ) : return self.next def setItem( self, item ) : self.item = item def setNext( self, next ) : self.next = next Your Node class looks straightforward, but it doesn't match the requirements. The requirement for the Map is that it must have key:value pairs. But your Node doesn't have two data fields, it only has one! So you cannot give the Node both a key and a value. Your Node class needs to start like this: class Node: def __init__(self, key, value, next=None):
[Tutor] =Linked List Using Map
Sent from Windows Mail From: Ni'Yana Morgan Sent: Friday, April 17, 2015 2:06 PM To: tut...@python.org Hello I need guidance trying to solve my assignment. I am completely lost when using maps with linked lists. I understand linked lists though. May someone work with me? implement the Map ADT using a singly linked list: • Map(): Creates a new empty map. • length(): Returns the number of key/value pairs in the map. • contains(key): Returns a Boolean indicating if the given key is in the map. • setitem(key, value): Adds a new key/value pair to the map if the key is not in the map. If the key is in the map, the new value replaces the original value associated with the key. • getitem(key): Returns the value associated with the given key, which must exist. • clear(): Clears or empties the map by removing all key/value pairs. • keys(): Returns a list containing the keys stored in the map. • values(): Returns a list containing the values stored in the map. • toString(): Returns a string representation of the map in the following format: {k1:v1, k2:v2, ..., kN:vN} • min(): Returns the minimum key in the map. The map can not be empty. • max(): Returns the maximum key in the map. The map can not be empty. • copy(): Creates and returns a new map that is a duplicate copy of this map. My Code (so far): class Node: def __init__( self, item, next = None ) : self.item = item self.next = next def getItem( self ) : return self.item def getNext( self ) : return self.next def setItem( self, item ) : self.item = item def setNext( self, next ) : self.next = next class Map: def __init__( self, contents = []) : self.first = LinkedList.Node(None, None) self.last = self.first self.numItems = 0 for e in contents: self.append(e) def __len__( self ) : count = 0 while self != None: count +=1 self = self.next return count def contains() : pass def __setitem__( self, index, value ) : if index = 0 and index self.numItems: cursor = self.first.getNext() for i in range( index ): cursor = cursor.getNext() return cursor.getItem() def __getitem__( self, index, value ) : if index = 0 and index self.numItems: cursor = self.first.getNext() for i in range( index ): cursor = cursor.getNext() cursor.setItem( value ) return ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reversi Game Logic
Thank you Danny Yoo for replying. I figured out what to do for the isLegalMove but I ran into another problem. I now get a traceback error every chip is black. This is the traceback: Traceback (most recent call last): File C:\Python34\lib\tkinter\__init__.py, line 1487, in __call__ return self.func(*args) File u:\code\reversiguiapp.py, line 83, in _cbMouseClick TypeError: makeMove() takes 2 positional arguments but 3 were given Exception in Tkinter callback Here is my code again just in case: from ezarrays import Array2D # Values representing the color of the chips on the board. EMPTY = 0 BLACK = 1 WHITE = 2 class ReversiGameLogic : # Creates an instance of Reversi game logic with the board correctly # initialized and the current player set to black. def __init__(self) : # Use a 2-D array to represent the board. self._gameBoard = Array2D(8, 8) self._gameBoard.clear(EMPTY) # Set the initial configuration of the board. self._gameBoard[4,3] = BLACK self._gameBoard[3,4] = BLACK self._gameBoard[3,3] = WHITE self._gameBoard[4,4] = WHITE # Maintain the number of the current player. self._currentPlayer = BLACK # Keep track of the number of each players chips. self._numBlackChips = 2 self._numWhiteChips = 2 # A flag that is set when the game is over. That is, when there are # no empty squares on the board or neither player can make a move. self._gameOver = False # Returns a boolean indicating whether the game is over. def isOver(self) : isOver = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] != 0 : isOver = isOver + 1 if isOver == 64 : self._gameOver = True return True else: return False # Returns the player number of the current player. def whoseTurn(self) : if self._currentPlayer == 1: return 1 else: self._curentPlayer == 2 return 2 # Returns the number of chips on the board for the given player. def numChips(self, player) : chipCounter = 0 if player == 1 : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : chipCounter = chipCounter + 1 else : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == WHITE : chipCounter = chipCounter + 1 return chipCounter # Returns the number of open squares on the board. def numOpenSquares(self) : numOpenSquares = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == EMPTY : numOpenSquares = numOpenSquares + 1 return numOpenSquares # Returns the player number of the winner or 0 if it's a draw. def getWinner( self ): player1 = 0 player2 = 0 if self._gameOver is True : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : player1 = player1 + 1 else : player2 = player2 + 1 if player1 player2 : return 1 if player2 player1 : return 2 else: return 0 # Returns the Return a Boolean indicating if the current player can place # their chip in the square at position (row, col). Both row and col must be # valid indices def isLegalMove( self, row, col ): if row 0 or row = 8 or col 0 or col = 8: return False if self._gameBoard[row,col] == EMPTY: return True else: return False # Returns the player number whose chip occupies the given square. def occupiedBy(self, row, col): if self._gameBoard[row, col] == BLACK : return 1 if self._gameBoard[row, col] == WHITE : return 2 else: return 0 # Performs an actual move in the game. That is the current player places # one of his chips in the square at position (row, col). def makeMove( row, col ): if isALineOfAttack(row, col, 1, 1) is True : if self._currentPlayer == 1 : self._gameBoard[row, col] = BLACK else : self._gameBoard[row, col] = WHITE # Helper method that returns a Boolean indicating if there is a line of # attack from cell (row, col) in the direction offset given by rowInc # and colInc. The direction offsets should be, 0, 1, or -1. def _isALineOfAttack(self, row, col, rowInc, colInc) : row += rowInc col += colInc # The next cell in the line must contain the opponents chip. if self.occupiedBy(row, col) == self._currentPlayer : return False # Traverse along the line and determine if it's a line of attack. while row = 0 and col = 0 and row 8 and col 8 : if self.occupiedBy(row, col) == self._currentPlayer : return True elif self.occupiedBy(row, col) == EMPTY : return False else :
Re: [Tutor] Reversi Game Logic
I am very new to Comp Science and am still learning. I have attached the programs needed for testing to show that I am testing my code as well as the instructions provided for my project. Please help me out! Sent from Windows Mail From: Ni'Yana Morgan Sent: Friday, March 20, 2015 11:16 AM To: Mark Lawrence I am very new to Comp Science and am still learning. I have attached the programs needed for testing to show that I am testing my code as well as the instructions provided for my project. Please help me out! Sent from Windows Mail From: Mark Lawrence Sent: Friday, March 20, 2015 11:11 AM To: Ni'Yana Morgan please use reply all so everybody can benefit Kindest regards. Mark Lawrence. On Friday, 20 March 2015, 15:04, niyanax...@gmail.com niyanax...@gmail.com wrote: Thank you Mark for replying. I fixed the note you provided on the isLegalMove. However the lineOfAttack function is a function my Professor did so students are not allowed to touch it. For the isOver function, are you able to guide me on that? I am very new to Comp Science and am still learning. I have attached the programs needed for testing to show that I am testing my code as well as the instructions provided for my project. Please help me out! from ezarrays import Array2D # Values representing the color of the chips on the board. EMPTY = 0 BLACK = 1 WHITE = 2 class ReversiGameLogic : # Creates an instance of Reversi game logic with the board correctly # initialized and the current player set to black. def __init__(self) : # Use a 2-D array to represent the board. self._gameBoard = Array2D(8, 8) self._gameBoard.clear(EMPTY) # Set the initial configuration of the board. self._gameBoard[4,3] = BLACK self._gameBoard[3,4] = BLACK self._gameBoard[3,3] = WHITE self._gameBoard[4,4] = WHITE # Maintain the number of the current player. self._currentPlayer = BLACK # Keep track of the number of each players chips. self._numBlackChips = 2 self._numWhiteChips = 2 # A flag that is set when the game is over. That is, when there are # no empty squares on the board or neither player can make a move. self._gameOver = False # Returns a boolean indicating whether the game is over. def isOver(self) : isOver = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] != 0 : isOver + 1 if isOver == 64 : self._gameOver = True return True else: return False # Returns the player number of the current player. def whoseTurn(self) : if self._currentPlayer == 1: return 1 else: self._curentPlayer == 2 return 2 # Returns the number of chips on the board for the given player. def numChips(self, player) : chipCounter = 0 if player == 1 : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : chipCounter = chipCounter + 1 else : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == WHITE : chipCounter = chipCounter + 1 return chipCounter # Returns the number of open squares on the board. def numOpenSquares(self) : numOpenSquares = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == EMPTY : numOpenSquares = numOpenSquares + 1 return numOpenSquares # Returns the player number of the winner or 0 if it's a draw. def getWinner( self ): player1 = 0 player2 = 0 if self._gameOver is True : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : player1 = player1 + 1 else : player2 = player2 + 1 if player1 player2 : return 1 if player2 player1 : return 2 else: return 0 # Returns the def isLegalMove( self, row, col): if row 8 col: if self._gameBoard[row,col] != EMPTY: return True else: return False # Returns the player number whose chip occupies the given square. def occupiedBy(self, row, col): if self._gameBoard[row, col] == BLACK : return 1 if self._gameBoard[row, col] == WHITE : return 2 else: return 0 # Performs an actual move in the game. That is the current player places # one of his chips in the square at position (row, col). def makeMove( row, col ): if isALineOfAttack(row, col, 1, 1) is True : if self._currentPlayer == 1 : self._gameBoard[row, col] = BLACK else : self._gameBoard[row, col] = WHITE # Helper method that returns a Boolean indicating if there is a line of # attack from cell (row, col) in the direction offset
[Tutor] Reversi Game Logic
I am having trouble with a function in my reversi logic code. The function is the isLegalMove I am asked to Return a Boolean indicating if the current player can place their chip in the square at position (row, col). Both row and col must be valid indices. So I came up with my code below, however a move I make in the game says Error: not a legal move. Please help! Code: from ezarrays import Array2D # Values representing the color of the chips on the board. EMPTY = 0 BLACK = 1 WHITE = 2 class ReversiGameLogic : # Creates an instance of Reversi game logic with the board correctly # initialized and the current player set to black. def __init__(self) : # Use a 2-D array to represent the board. self._gameBoard = Array2D(8, 8) self._gameBoard.clear(EMPTY) # Set the initial configuration of the board. self._gameBoard[4,3] = BLACK self._gameBoard[3,4] = BLACK self._gameBoard[3,3] = WHITE self._gameBoard[4,4] = WHITE # Maintain the number of the current player. self._currentPlayer = BLACK # Keep track of the number of each players chips. self._numBlackChips = 2 self._numWhiteChips = 2 # A flag that is set when the game is over. That is, when there are # no empty squares on the board or neither player can make a move. self._gameOver = False # Returns a boolean indicating whether the game is over. def isOver(self) : isOver = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] != 0 : isOver + 1 if isOver == 64 : self._gameOver = True return True else: return False # Returns the player number of the current player. def whoseTurn(self) : if self._currentPlayer == 1: return 1 else: self._curentPlayer == 2 return 2 # Returns the number of chips on the board for the given player. def numChips(self, player) : chipCounter = 0 if player == 1 : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : chipCounter = chipCounter + 1 else : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == WHITE : chipCounter = chipCounter + 1 return chipCounter # Returns the number of open squares on the board. def numOpenSquares(self) : numOpenSquares = 0 for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == EMPTY : numOpenSquares = numOpenSquares + 1 return numOpenSquares # Returns the player number of the winner or 0 if it's a draw. def getWinner( self ): player1 = 0 player2 = 0 if self._gameOver is True : for i in range(8) : for j in range(8) : if self._gameBoard[i, j] == BLACK : player1 = player1 + 1 else : player2 = player2 + 1 if player1 player2 : return 1 if player2 player1 : return 2 else: return 0 # Returns the def isLegalMove( self, row, col): if row 8 and col 8: if self._gameBoard[row,col] != EMPTY: return True else: return False # Returns the player number whose chip occupies the given square. def occupiedBy(self, row, col): if self._gameBoard[row, col] == BLACK : return 1 if self._gameBoard[row, col] == WHITE : return 2 else: return 0 # Performs an actual move in the game. That is the current player places # one of his chips in the square at position (row, col). def makeMove( row, col ): if isALineOfAttack(row, col, 1, 1) is True : if self._currentPlayer == 1 : self._gameBoard[row, col] = BLACK else : self._gameBoard[row, col] = WHITE # Helper method that returns a Boolean indicating if there is a line of # attack from cell (row, col) in the direction offset given by rowInc # and colInc. The direction offsets should be, 0, 1, or -1. def _isALineOfAttack(self, row, col, rowInc, colInc) : row += rowInc col += colInc # The next cell in the line must contain the opponents chip. if self.occupiedBy(row, col) == self._currentPlayer : return False # Traverse along the line and determine if it's a line of attack. while row = 0 and col = 0 and row 8 and col 8 : if self.occupiedBy(row, col) == self._currentPlayer : return True elif self.occupiedBy(row, col) == EMPTY : return False else : row += rowInc col += colInc if row 0 or row 7 or col 0 or col 7 : return False return False ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fixed Vector Array
Need help trying to implement insert, remove, indexof, and reverse functions. I tried to do them but am not sure if it is correct. I am struggling with arrays. This is python and using ezarrays. Assignment: A fixed vector is very similar to the vector in that it is a sequence container that can grow and shrink as needed and include many useful operations. But the fixed vector has a maximum capacity beyond which it can not expand. • FixedVector(maxSize): Creates an empty fixed vector with the given maximum capacity. • length(): Returns the number of elements contained in the vector. • isFull(): Returns a Boolean indicating if the vector is full. • getitem(index): Returns the element stored in the vector at position index. The value of index must be within the valid range. • setitem(index, item): Sets the element at position index to contain the given item. The value of index must be within the valid range, which includes one position beyond the end of the vector. In the latter case, the item is simply appended onto the end. • contains(item): Determines if the given item is contained in the vector. • toString(): Returns a string representation of the vector. • append(item): Adds the given item to the end of the vector. An item can not be appended to a full vector. • clear(): Removes all elements from the vector. • insert(index, item): Inserts the given item into the vector at position index. The elements at and following the given position are shifted down to make room for the new item. The index must be within the valid range and the vector can not be full. If index is one position beyond the end of the vector, the item is appended onto the vector. • remove(index): Removes the element at position index from the vector. The removed element is returned. The index must be within the valid range. • indexOf(item): Returns the index of the element containing the given item. The item must be in the list. • reverse(): Performs a list reversal by reversing the order of the elements within the vector. My Code: from ezarrays import Array class FixedVector : # Creates a new empty fixed vector with the given maximum capacity. def __init__(self, maxSize) : self._theItems = Array(maxSize) self._numItems = 0 # Returns the number of elements contained in the vector. def __len__(self) : return self._numItems # Returns a Boolean indicating if the vector is full. def isFull(self) : return self._numItems == len(self._theItems) # Returns the element stored in the vector at position index. # The value of index must be within the valid range. def __getitem__(self, index) : assert index = 0 and index self._numItems, Index out of Range. return self._theItems[index] # Sets the element at position index to contain the given item. The # value of index must be within the valid range, which includes one # position beyond the end of the vector. In the latter case, the item # is simply appended onto the end. def __setitem__(self, index, item) : assert index = 0 and index = self._numItems, Index out of range. if index == self._numItems : self.append(item) else : self._theItems[index] = item # Determines if the given item is contained in the vector. def __contains__(self, item) : i = 0 while i self._numItems : if self._theItems[i] == item : return True i = i + 1 return False # Returns a string representation of the vector. def __repr__(self) : if self._numItems == 0 : return [] vectStr = [ + str(self._theItems[0]) for i in range(1, self._numItems) : vectStr = vectStr + , + str(self._theItems[i]) vectStr = vectStr + ] return vectStr # Adds the given item to the end of the vector. An item can not be # appended to a full vector. def append(self, item) : assert self._numItems len(self._theItems), \ Can not add to a full vector. self._theItems[self._numItems] = item self._numItems = self._numItems + 1 # Removes all elements from the vector. def clear(self) : self._theItems.clear(None) # Inserts the given item into the vector at position index. The elements # at and following the given position are shifted down to make room # for the new item. The index must be within the valid range and the # vector can not be full. If index is one position beyond the end of # the vector, the item is appended. def insert(self, index, item) : i = numItems while i index : self._theItem[i] = self._theItem[i-1] i = i-1 self._theItems[i] = item self._numItems = self._numItems + 1 # Removes the element at position index from the vector. The removed # element is returned. The index must be within the valid range. def remove(self, index) : removed =
[Tutor] Sets Python
I am not understanding how I am supposed to do the highlighted things on the problem statement. If someone could please direct me on the steps to go about doing what is highlighted. Have do I read each command, by making the program read each line?? How do I add the invalid commands into a set? When printing the command is invalid, do I simply do as I did with the valid commands print? Problem Statement: We are going to write a program that reads an input file of commands (Commands.txt) to Arnold the Robot. The four valid command are: Up Down Left Right After you read each command, make sure it is valid (included in the set of valid commands). If the command is valid, print “Valid command entered, the command was:” and the command. If the command is invalid, print “Invalid command entered, the command was:” and the command. If the command is invalid, add it to a set of invalid commands. Keep a count of: The total number of commands read The total number of valid commands read The total number of invalid commands read After all of the commands have been read: Print the total number of commands read Print the total number of valid commands read Print the total number of invalid commands read Print the number of unique invalid commands read Print the set of invalid commands. The format of the input files is: Each line in the file contains a command, not all command are valid My Code So Far: def main() : # Define main variables leftCount = 0 rightCount = 0 upCount = 0 downCount = 0 commandCount = 0 invalidCommands = 0 command = (left, right, up, down) numUnique = 0 numInvalid = 0 invalidCommands = set() filename = input(Enter filename (default: Commands.txt): ) if len(filename) == 0 : filename = Commands.txt inputFile = open(filename, r) command = input(Please enter a command for Arnold: ) if command in command : commandCount = commandCount + 1 print(The total amount of commands: , commandCount) if command == up : upCount = upCount + 1 print(Valid command entered, the command was: up) elif command == down : downCount = downCount + 1 print(Valid command entered, the command was: down) elif command == left : leftCount = leftCount + 1 print(Valid command entered, the command was: left) elif command == right : rightCount = rightCount + 1 print(Valid command entered, the command was: right) else : print(Invalid command entered, the command entered was: , command) numInvalid = numInvalid + 1 if not command in invalidCommands : numUnique = numUnique + 1 invalidCommands.add(command) for line in inputFile : theWords = line.split() for word in theWords : cleaned = clean(word) if cleaned != : numUnique.append(cleaned) print(The file contains, len(numUnique), unique words.) # Cleans a string by making letters lowercase and removing characters that are not letters # @param string the string to be cleaned # @return the cleaned string def clean(string) : result = for char in string : if char.isalpha() : result = result + char return result.lower() # Start the program. main() What Happens When Ran: 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] Python Type help, copyright, credits or license for more information. [evaluate CommandsDraft.py] Enter filename (default: Commands.txt): Commands.txt Please enter a command for Arnold: dawn The total amount of commands: 1 Invalid Traceback (most recent call last): File C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py, line 70, in module File C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py, line 52, in main builtins.AttributeError: 'int' object has no attribute 'append'___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Empty GraphicsWindow
I need help figuring why my GraphicsWindow empty, I cannot figure out why it is empty. Here is my code : # Import graphics from module from graphics import GraphicsWindow tileSize = 0 def main() : # Define global variables tilesInRow = 0 tilesInCol = 0 gapX = 0 gapY = 0 # Input room width roomWidth = getNumber(100, 500, Enter a room width between 100 and 500: , ) roomLength = getNumber(100, 450, Enter a room length between 100 and 450: , ) tileSize = getNumber(20, 50, Enter a tile size between 20 and 50: , ) numCols = tilesForSize(roomWidth, tileSize) print(The total number of Columns:, numCols) numRows = tilesForSize(roomLength, tileSize) print(The total number of Rows:, numRows) # Print the total number of tiles print(The total number or Tiles: %d %(numCols * numRows)) # Calculate the gap # the gap = (the total width - the number of tiles * tile width / 2 gapX = calculateGap(roomWidth, numCols) gapY = calculateGap(roomLength, numRows) # Print the gaps print(The gap at each end of a row is: %.1f % (gapX)) print(The gap at each end of a column is: %.1f % (gapY)) # Draw graphics window win = GraphicsWindow(roomWidth, roomLength) canvas = win.canvas() # Draw the checkered surface for row in range(numRows) : # If the row is even if row % 2 == 0 : # If the column is even set color to black, if odd yellow drawRow(canvas, row, gapX, numCols, gapY, black, yellow) # If the row is odd else: # If the column is even set color to yellow, if odd black drawRow(canvas, row, gapX, numCols, gapY, yellow, black) win.wait() def getNumber(minBound, maxBound, msg, err_msg) : num = minBound - 1 while num minBound or num maxBound : if(msg == ) : num = float(input(Enter a number between %f and %f: % (minBound, maxBound))) else : num = float(input(msg)) if num minBound or num maxBound : if err_msg == : print(Invalid input.) else: print(err_msg) return num def tilesForSize(size, tileSize) : pairs = int(size - tileSize) // int(2 * tileSize) num = int(1 + (2 * pairs)) return num def calculateGap(size, num) : return (size - num * tileSize) / 2 def drawRow(canvas, row, gapX, numCols, gapY, color1, color2) : for col in range(numCols) : if col % 2 == 0 : canvas.setColor(black) else: canvas.setColor(yellow) # Draw the actual rectangle canvas.drawRect(row * tileSize + gapX, col * tileSize + gapY, tileSize, tileSize) main () Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Input Files
How do I know write the loop code for the table for both inputfiles, Table1.txt and Table2.txt and make a third table from the elements multiplied in table1.txt and table2.txt. I'm trying to Check the size of the two tables to make sure they both have the same number of rows and columns o If the tables are not the same size print an error message Once you have read the data from each file create a third table The elements in the third table are the result of multiplying each element in the first table by the corresponding element in the second table: thirdTable [i] [j] = firstTable[i] [j] * secondTable[i] [j Here is my code so far: def main(): print(Table One) (row1, column1, table1) = readInput(Table 1.txt) print(Table Two) (row2, column2, table2) = readInput(Table 2.txt) return() def readInput(filename): table = [] inputFile = open(filename, r) # Read the first line containing the number of rows and columns line = inputFile.readline() # split the line into two strings (row, column) = line.split() # convert the strings into integers row = int(row) column = int(column) # loop on the file container, reading each line for line in inputFile : line = line.rstrip() #strip off the newline dataList = line.split() # split the string into a list table.append(dataList) # Loop through the table and convert each element to an integer for i in range(row): for j in range (column): table[i] [j] = int(table[i] [j]) # convert the string to an integer print( %3d % (table[i] [j]), end = ) print() inputFile.close() # close the file return(row, column, table) # return the number of rows and columns main() Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fw: Traceback
I get this message: Traceback (most recent call last): File C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py, line 87, in module File C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py, line 20, in main File C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py, line 70, in tilesForSize builtins.TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' Sent from Windows Mail From: Ni'Yana Morgan Sent: Tuesday, November 18, 2014 4:42 PM To: tu...@phython.org Trying to figure out why I get a traceback on line 20, 70, and 87. Please Help Problem Statement: 1. The first and last tile in the first row shall be black. 2. The first and last tile in the first column shall be black. 3. The tiles will alternate between black and lemon The task is to write a function to compute and print: the number of tiles needed in the first row (the number of columns) the number of tiles needed in the first column (the number of rows) the total number of tiles needed to cover the floor the gap at the end of each row the gap at the end of each column And then print (using a function): 1. The colored tile pattern to a graphics window a. The pattern should be printed centered in the graphics window, with equal gaps at the end of each row, and equal gaps at the end of each column Use functions to: 1. Read and validate the input values a. Width b. Length c. Tile Size 2. Compute the number of rows, columns, total tiles required, and the size of the gaps at the end of each row and column 3. Print the tile pattern My Code: # Import graphics from module from graphics import GraphicsWindow tileSize = 0 def main() : # Define global variables tilesInRow = 0 tilesInCol = 0 gapX = 0 gapY = 0 # Input room width roomWidth = getNumber(100, 500, Enter a room width between 100 and 500: , ) roomLength = getNumber(100, 450, Enter a room length between 100 and 450: , ) tileSize = getNumber(20, 50, Enter a tile size between 20 and 50: , ) numCols = tilesForSize(roomWidth) print(The total number of Columns:, numCols) numRows = tilesForSize(roomLength) print(The total number of Rows:, numRows) # Print the total number of tiles print(The total number or Tiles: %d %(numCols * numRows)) # Calculate the gap # the gap = (the total width - the number of tiles * tile width / 2 gapX = calculateGap(roomWidth, numCols) gapY = calculateGap(roomLength, numRows) # Print the gaps print(The gap at each end of a row is: %.1f % (gapX)) print(The gap at each end of a column is: %.1f % (gapY)) # Draw graphics window win = GraphicsWindow(roomWidth, roomLength) canvas = win.canvas() # Draw the checkered surface for row in range(numRows) : # If the row is even if row % 2 == 0 : # If the column is even set color to black, if odd yellow drawRow(canvas, row, gapX, numCols, gapY, black, yellow) # If the row is odd else: # If the column is even set color to yellow, if odd black drawRow(canvas, row, gapX, numCols, gapY, yellow, black) win.wait() def getNumber(minBound, maxBound, msg, err_msg) : num = minBound - 1 while num minBound or num maxBound : if(msg == ) : num = float(input(Enter a number between %f and %f: % (minBound, maxBound))) else : num = float(input(msg)) if num minBound or num maxBound : if err_msg == : print(Invalid input.) else: print(err_msg) def tilesForSize(size) : pairs = int((size - tileSize) // int(2 * tileSize)) num = int(1 + (2 * pairs)) return num def calculateGap(size, num) : return (size - num * tileSize) / 2 def drawRow(canvas, row, gapX, numCols, gapY, color1, color2) : for col in range(numCols) : if col % 2 == 0 : canvas.setColor(color1) else: canvas.setColor(color2) # Draw the actual rectangle canvas.drawRect(row * tileSize + gapX, col * tileSize + gapY, tileSize, tileSize) return main()___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tile Code
Statement: 1. The first and last tile in the first row shall be black. 2. The first and last tile in the first column shall be black. 3. The tiles will alternate between black and lemon The task is to write a function to compute and print: the number of tiles needed in the first row (the number of columns) the number of tiles needed in the first column (the number of rows) the total number of tiles needed to cover the floor the gap at the end of each row the gap at the end of each column And then print (using a function): 1. The colored tile pattern to a graphics window a. The pattern should be printed centered in the graphics window, with equal gaps at the end of each row, and equal gaps at the end of each column Use functions to: 1. Read and validate the input values a. Width b. Length c. Tile Size 2. Compute the number of rows, columns, total tiles required, and the size of the gaps at the end of each row and column 3. Print the tile pattern This is my outline but some things I do not know how to do. from graphics import GraphicsWindow x = 10 y = 10 def main() : -- // do stuff -- width = getNumber(Choose a width: , Invalid value., 1, 1000) -- height = getNumber(Choose a height: , Invalid value., 1, 1000) -- win = GraphicsWindow(width, height) -- canvas = win.canvas() -- drawCheckerboard(canvas, x, y, width, height) main() According to the constraints he wants you to use convenient functions. Those would likely be, getNumber() and drawCheckerboard() You want a number between A and B so we have # Prompt user with msg to return a number between min and max otherwise output err_msg def getNumber(msg, err_msg, min, max): -- num = min - 1 -- while num min or num max -- -- num = input(msg) -- -- if num min or num max -- -- -- print(err_msg) // print invalid msg # Draws checkerboard def drawCheckerboard(canvas, x, y, width, height) : -- // more stuff let me know when you get to this part Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating Lists
Create a list of 20 unique (no number appears twice) random integers with values between 1 and 45. Print the list of random numbers with the header “Random list of 20 numbers”. Find the largest number in the list. Remove the largest number from the list. Find the smallest number in the list. Remove the smallest number from the list. Print the length of the list with the header “The length of the list is: ” Print the list with the header “The list with the largest and smallest number removed: ” Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating Table
Create a table based on two user inputs. Have the user enter two integers between 2 and 6. Validate the user inputs are in the proper range as they are entered. The first integer represents the number of rows in the table. The second integer represents the number of columns. Create the table by storing the value (i **j) in each cell in the table. Print the Power table with a column header separated from the table by a line of underscores (“_”) and a row header that lists the row number, a “|” and the row of data. This is what I have. I am very confused on what to do. i = 6 j = 6 row = int(input(Row: )) column = int(input(Column: )) if row == 7 : print(Invalid entry.) elif row = 2 or row 6 : print(Invalid entry. The row has a range of 2 to 6. Try again.) if column == 7 : print(Invalid entry.) elif column = 2 or column 6: print(Invalid entry. The column has a range of 2 to 6. Try again.) for n in range(row) : print(%10d % n, end=) print() for n in range(1, row + 1) : print(%10s % x , end=) print(\n, , - * 35) for i in range(row): for j in range (column): table[i] [j] = int(table[i] [j]) # convert the string to an integer print( %3d % (table[i] [j]), end = ) print() Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tile Code Program
This is the prompt: Write an algorithm / pseudocode that: • Reads in a two integers; the width and length of a room. i. The valid range for the width (x-axis) of the room is between 100 and 1000 pixels. ii. The valid range for the length (y-axis) of the room is between 100 and 900 pixels. • Validate the inputs, prompting the user to try again if they enter an invalid integer. • Compute the number of tiles in each row (the number of columns) • Compute the number of tiles in each column (the number of rows) • Print the number of columns • Print the number of rows • Print the total number of tiles needed • Print the gap at the end of each row • Print the gap at the end of each column • Print the pattern of tiles centered in a graphics window My Code: #This is a program to compute tiles # Constants # from graphics import GraphicsWindow TILESIZE = 20 roomWidth = 100.0 roomLength = 90.0 while roomWidth 100 or roomWidth 1000: roomWidth = float(input(Please enter a room width between 100 and 1000: )) if roomWidth = 100 or roomWidth = 1000: print(Invalid entry) while roomLength 100 or roomLength 900: roomLength = float(input(Please enter a room length between 100 and 900: )) if roomLength = 100 or roomLength = 900: print(Invalid entry.) win = GraphicsWindow(roomWidth, roomLength) canvas = win.canvas() #Calculate the number of pairs of tiles # the number of pairs = interger part of (total width - tile width) / (2 * tile width) numberOfPairsWidth = int((roomWidth - TILESIZE) // (2 * TILESIZE)) numberOfPairsLength = int((roomLength - TILESIZE) // (2 * TILESIZE)) #Calculate the number of columns and rows numberOfCol = int(1 + (2 * numberOfPairsWidth)) numberOfRow = int(1 + (2 * numberOfPairsLength)) #Calculate the gap # the gap = (the total width - the number of tiles * tile width / 2 gapCol = (roomWidth - numberOfCol * TILESIZE) / 2 gapRow = (roomLength - numberOfRow * TILESIZE) / 2 # Draw Tiles for i in range(numberOfCol) : if i % 2 == 0 : for j in range(numberOfRow) : if j % 2 == 0 : canvas.setColor(black) else : canvas.setColor(yellow) canvas.drawRect(gapCol + i * TILESIZE, gapRow + j * TILESIZE, TILESIZE, TILESIZE) else : for j in range(numberOfRow) : if j % 2 == 0 : canvas.setColor(yellow) else : canvas.setColor(black) canvas.drawRect(gapCol + i * TILESIZE, gapRow + j * TILESIZE, TILESIZE, TILESIZE) # Print results print(The number of columns is: , numberOfCol) print(The number of rows is: , numberOfRow) print(The total number of tiles needed is: , numberOfCol * numberOfRow) print(The gap at the end of each rows is: , gapRow) print(The gap at the end of each column is: , gapCol) The output: Please enter a room length between 100 and 900: 200 Invalid entry. The number of columns is: 5 The number of rows is: 9 The total number of tiles needed is: 45 The gap at the end of each rows is: 10.0 The gap at the end of each column is: 0.0 Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor