[Tutor] Fwd: pickle module error in source code
Hi! My name is Shreya Marwaha. I’m class 12th student in India. I’m using 2.7.5 python version [MSC v.1500 64 bit (AMD64)] on win32 as instructed by CBSE (central board of secondary education). I’ve been having problem in using pickle module. It keeps on showing error in the source code. I’ve attached two files: 1. Prax.py file with error1.txt 2. Video.py file with error.txt Prax.py file is a simple problem, the first program I tried with pickle module. Video.py is my project which I’ll be submitting at the end of my year at school i.e. February 2015. I’ve attached two text documents in which both are showing the error occurring in both the problems. The errors in both the programs are similar. Please help me in this context. -Shreya Marwaha # File name: ...\\Source_XII\Project\Video.py import os from pickle import load, dump import datetime import string MFile = Master.dat File1 = Cassettes.dat File2 = Balance.dat File3 = Customer.dat Cdate = datetime.datetime.now() # Current date and time # Class for date class Cast_Date: def __init__(self): self.dd = Cdate.day self.mm = Cdate.month self.yy = Cdate.year class Master: # Constructor def __init__(self): self.Cast_Code = 0 # cassette/CD code - (Like, 1, 2, 3, etc.) self.Cast_Name = # Title of the cassette/CD self.Cast_Comp = # cassette/CD company self.Cast_Price = 0 # Price per cassette/CD def Check_Code(self, C_Code): MList = list() TRec = list() Flag = False # To check if Cast_Code is in Master.dat or not if os.path.isfile(MFile): Mobj = open(MFile, 'rb') try: while True: MRec = [] # For extracting Master.dat records MRec = load(Mobj) if (C_Code == MRec[0]): TRec = MRec MList.append(MRec[0]) except EOFError: pass for i in range(len(MList)): if (C_Code == MList[i]): Flag = True break Mobj.close() # Flag for Master data entry and TRec for Cassette data entry return Flag, TRec # For Master data entry def Master_Entry(self): TRec = list() # A temporary list to store master record print(Add Master Cassette/CD); ch ='Y' while ch=='Y': while True: self.Cast_Code = int(input(Cassette/CD Code (1/2/3...) # )) Flag, TRec = self.Check_Code(self.Cast_Code) if (Flag == False): while True: self.Cast_Name = input(Cassette/CD Name : ) if (self.Cast_Name == 0 or len(self.Cast_Name) 25): print(Cassette/CD Name should not greater than 25) else: break while True: self.Cast_Comp = input(Company Name : ) if (self.Cast_Comp == 0 or len(self.Cast_Comp) 25): print(Company Name should not greater than 25) else: break while True: self.Cast_Price = float(input(Individual Cassette/CD price : )) if (self.Cast_Price = 0): print(Enter valid price for Cassette/CD) else: break; with open(MFile, 'ab+') as Mobj: if not Mobj: print (MFile, does not created) else: # Appends data into a sequnce object MList = list() MList.append(self.Cast_Code) MList.append(self.Cast_Name) MList.append(self.Cast_Comp) MList.append(self.Cast_Price) # Write data into binary file dump(MList, Mobj) else: print (Code, self.Cast_Code, is already in 'Master.dat' file) ch = input(Add new Cassette/CD code? Y/N: ) ch = ch.upper() if ch=='Y': continue else: break def Master_Display(self): if not os.path.isfile(MFile): print (MFile, file does not exist) else: Mobj = open(MFile, 'rb') print (\nCassette/CD Master Report) print (= * 25) print ({0:7} {1:30} {2:20} {3:8}.format( Code, Cassette/CD Name, Company Name, Price)) print (- * 70)
Re: [Tutor] Tutor Digest, Vol 130, Issue 47
This is regarding the Python drop-down list response. I would like to create a GUI that has a drop down list containing the data and displayed based on the stats of the list contents. I am interested in using Tkinter, wxPython or PyGTK. My data is coming from a csv file. I am using Python 2.79 and have Windows 8 as an operating system Thank you, From: tutor-requ...@python.org Subject: Tutor Digest, Vol 130, Issue 47 To: tutor@python.org Date: Wed, 31 Dec 2014 20:00:28 +0100 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit https://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than Re: Contents of Tutor digest... Today's Topics: 1. Convert string to bytes (shweta kaushik) 2. Help on Python drop-down list options (Tammy Miller) 3. Re: Help on Python drop-down list options (WolfRage) 4. Re: Convert string to bytes (WolfRage) 5. Re: Help on Python drop-down list options (Alan Gauld) 6. Re: Convert string to bytes (Alan Gauld) 7. Re: Convert string to bytes (Alan Gauld) -- Message: 1 Date: Wed, 31 Dec 2014 15:38:05 +0530 From: shweta kaushik coolshw...@gmail.com To: Tutor@python.org Subject: [Tutor] Convert string to bytes Message-ID: CAM--9s6oY=yyfkdqnhsr-+sm5dhdvrpgy-zzhddybj2prjo...@mail.gmail.com Content-Type: text/plain; charset=UTF-8 Hi all, I need help on this problem. I have one message packet in form of string s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02'. I have to send this data to MSP430 microcontroller, but it is not taking data if it is string. If I am passing this as hardcoded value s1 = 0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02 then board is responding. I want to convert s as s1 using python. Please help me out to convert string in normal format for microcontroller to respond. Thanks in advance. Regards, Shweta -- Message: 2 Date: Wed, 31 Dec 2014 08:49:17 -0500 From: Tammy Miller tgmill...@hotmail.com To: tutor@python.org tutor@python.org Subject: [Tutor] Help on Python drop-down list options Message-ID: col125-w488336eb344d6d2f4d6a6bfa...@phx.gbl Content-Type: text/plain; charset=iso-8859-1 Hello All, I need help on the following: I have a created a project from a csv file to calculate the mean and standard deviation. However, I would like to create a drop-down list and display the mean and standard deviation? Is there a module for that? Thank you, Tammy -- Message: 3 Date: Wed, 31 Dec 2014 11:31:14 -0500 From: WolfRage wolfrage8...@gmail.com To: tutor@python.org Subject: Re: [Tutor] Help on Python drop-down list options Message-ID: 54a424d2.20...@gmail.com Content-Type: text/plain; charset=windows-1252; format=flowed What is the user interface that your program is using, currently? IE: QT, GTK, Tkinter, Curses, Kivy, Pygame, Or None? What is the target system on which your program runs? How are you currently viewing the mean and standard deviation results? What version of Python are you using and what is your OS? On 12/31/2014 08:49 AM, Tammy Miller wrote: Hello All, I need help on the following: I have a created a project from a csv file to calculate the mean and standard deviation. However, I would like to create a drop-down list and display the mean and standard deviation? Is there a module for that? Thank you, Tammy ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Message: 4 Date: Wed, 31 Dec 2014 11:34:35 -0500 From: WolfRage wolfrage8...@gmail.com To: tutor@python.org Subject: Re: [Tutor] Convert string to bytes Message-ID: 54a4259b.2000...@gmail.com Content-Type: text/plain; charset=windows-1252; format=flowed I wrote a program to help me break out hex strings awhile ago. It was written to communicate with a Atmega 168. This is written for Python 3. Here is a snippet, see if this helps you. s4 = 28 40 7A 7C 05 00 00 34 hex_array = bytearray.fromhex(s4) print(s4) print(list(hex_array)) print(hex_array) for byte in list(hex_array): print(hex(byte)) print(bytes([byte])) On 12/31/2014 05:08 AM, shweta kaushik wrote: Hi all, I need help on this problem. I have one message packet in form of string
Re: [Tutor] pickle module error in source code
Vedhi Shreya Marwaha wrote: Hi! My name is Shreya Marwaha. I’m class 12th student in India. Welcome! I’m using 2.7.5 python version [MSC v.1500 64 bit (AMD64)] on win32 as instructed by CBSE (central board of secondary education). I’ve been having problem in using pickle module. It keeps on showing error in the source code. I’ve attached two files: 1. Prax.py file with error1.txt 2. Video.py file with error.txt Prax.py file is a simple problem, the first program I tried with pickle module. Video.py is my project which I’ll be submitting at the end of my year at school i.e. February 2015. I’ve attached two text documents in which both are showing the error occurring in both the problems. The errors in both the programs are similar. Please help me in this context. -Shreya Marwaha I'm sorry I am not prepared to read this much code. It is both courteous and helpful to reduce a problem to the smallest amount of code that still shows the bug. Read http://sscce.org/ for the details. On the positive side, thank you for providing version info and tracebacks! Traceback (most recent call last): File C:\Users\Home\Desktop\Project\Video.py, line 678, in module main() File C:\Users\Home\Desktop\Project\Video.py, line 627, in main M.Master_Display() File C:\Users\Home\Desktop\Project\Video.py, line 109, in Master_Display MRec = load(Mobj) File C:\Python27\lib\pickle.py, line 1378, in load return Unpickler(file).load() File C:\Python27\lib\pickle.py, line 858, in load dispatch[key](self) File C:\Python27\lib\pickle.py, line 886, in load_proto raise ValueError, unsupported pickle protocol: %d % proto ValueError: unsupported pickle protocol: 3 This one leads me to believe that you ran some of your code with Python 3 and thus have accidentally created a pickle file that cannot be read by Python 2. Delete your existing pickle files and try again. If it doesn't work out come back with a smaller more focused example. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
On 2014-12-31 16:18, Steven D'Aprano wrote: py grid[1][1] = 99 # Adjust a single cell. py print(grid) [[0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0]] while you expected: [[0, 0, 0, 0, 0], [0, 99, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Am I right? Yes, although perhaps not so much 'expected' as 'hoped.' The problem is that you guessed that list multiplication *copies* the items. It does not. It just repeats them. So: I don't think I understand the distinction between 'copies' and 'repeats'. I think I understand the difference between copy and deep copy and I think that is the issue here but it isn't yet clear. I hope I'm not trying your patience too much: Do I have the correct explanations for these behaviours? (python3 on ubuntu14.04) s_grid = [[0]*5 for i in range(4)] # So for each iteration of the list comprehension, # a brand new, ?immutable? object ( a list of zeros) is created. # Immutable by virtue of the fact that there is no reference to it # and therefore it can't be changed? s_grid [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] s_grid[1][1] = 99 s_grid [[0, 0, 0, 0, 0], [0, 99, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] # :-) l = [0]*5 l [0, 0, 0, 0, 0] grid = [l for i in range(4)] # In this form, the list comprehension is encountering a mutable # object by virtue of the fact that there is a reference to it? grid[1][1] = 99 grid [[0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0]] # ;-( # Is the crux of the matter that l is mutable (because it is a reference,) # while [0]*5 is not (because it is an expression?) my_grid = [[0, 0, 0, 0] for i in range(4)] my_grid [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] my_grid[1][1] = 99 my_grid [[0, 0, 0, 0], [0, 99, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] another_grid = [[0]*5]*4 # The explanations above don't seem to explain things here. another_grid [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] another_grid[1][1] = 99 another_grid [[0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0]] My interpretation is that we appear to be getting a deep copy at the inner level of a multiplication but a not deep copy at the outer level. List comprehension provides us with a deep copy but only if we give it a literal (as opposed to a reference.) Thanks, Steven, for your efforts to help. It's very much appreciated. alex ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Drop-down list [was: Re: Tutor Digest, Vol 130, Issue 47]
On 01/01/15 17:31, Tammy Miller wrote: This is regarding the Python drop-down list response. Thanks, but please do not send the entire digest contents. Delete what is not relevant, then you wouldn't need to tell us, and those who pay by the byte would not have such big bills. Also change the subject to what is relevant. I would like to create a GUI that has a drop down list containing the data and displayed based on the stats of the list contents. I am interested in using Tkinter, wxPython or PyGTK. OK, Since Tkinter is included with python I'll look at that. Actually I recommend looking at Tix which also has a Combo box object, which if you have a lot of data to enter manually might be more useful. There are several Tkinter tutorials on the web, mine is here: http://www.alan-g.me.uk/tutor/tutgui.htm Assuming you read and understand that (if not respond here with more questions) then the next thing to do is look at the documentation for the Listbox object, here: http://effbot.org/tkinterbook/listbox.htm and a more technical but complete specification here: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/listbox.html My data is coming from a csv file. I'll leave extracting the data from the CSV file as an exercise. I assume you have discovered the csv module to help with that? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
On 01/01/2015 11:48 PM, WolfRage wrote: Final Code Using 2d List instead of Doubly Linked List. Please don't top-post. Instead, post your comments inline with the parts of the previous message to which you're responding. Is there a reason you doublespaced the whole thing? And why did you retype it instead of just copy/pasting it? And why lose the indentation, so nobody can actually try it without guessing at your indentation? class GameTile(): def __init__(self, id, **kwargs): # id is (X,Y) self.id = id class GameGrid(): def __init__(self, **kwargs): self.cols = 7 self.rows = 8 These two would more generally have been parameters, and you'd create the grid by specifying the sizes to be used. # grid is 2d array as y, x ie [y][x]. self.grid = [[None] * self.rows for i in range(self.cols)] If you always call make_grid immediately after constructing the grid, then why not combine __init__ with make_grid? It'd be much shorter. def make_grid(self): for row in range(0, self.rows): for col in range(0, self.cols): self.grid[col][row] = GameTile(id=str(row) + ',' + str(col)) def print_by_row(self): for col in range(0, self.cols): for row in range(0, self.rows): print(self.grid[col][row].id) This could be better written as: for col in self.grid: for row in col print row.id def print_by_col(self): for row in range(0, self.rows): for col in range(0, self.cols): print(self.grid[col][row].id) likewise, but it's a bit trickier. def check_bounds(self, x, y): if (0 = x self.rows) and (0 = y self.cols): return True return False This could be simplified to just: return (0 = x self.rows) and (0 = y self.cols) def lookup_node(self, x, y): if not self.check_bounds(x, y): return False return self.grid[y][x] def draw_grid(self): for col in range(0, self.cols): print(end='| ') for row in range(0, self.rows): print(self.grid[col][row].id, end=' | ') print() temp = GameGrid() temp = GameGrid(8, 7) temp.make_grid() temp.draw_grid() -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
Final Code Using 2d List instead of Doubly Linked List. class GameTile(): def __init__(self, id, **kwargs): # id is (X,Y) self.id = id class GameGrid(): def __init__(self, **kwargs): self.cols = 7 self.rows = 8 # grid is 2d array as y, x ie [y][x]. self.grid = [[None] * self.rows for i in range(self.cols)] def make_grid(self): for row in range(0, self.rows): for col in range(0, self.cols): self.grid[col][row] = GameTile(id=str(row) + ',' + str(col)) def print_by_row(self): for col in range(0, self.cols): for row in range(0, self.rows): print(self.grid[col][row].id) def print_by_col(self): for row in range(0, self.rows): for col in range(0, self.cols): print(self.grid[col][row].id) def check_bounds(self, x, y): if (0 = x self.rows) and (0 = y self.cols): return True return False def lookup_node(self, x, y): if not self.check_bounds(x, y): return False return self.grid[y][x] def draw_grid(self): for col in range(0, self.cols): print(end='| ') for row in range(0, self.rows): print(self.grid[col][row].id, end=' | ') print() temp = GameGrid() temp.make_grid() temp.draw_grid() Any feedback for my code is appreciated. Thank you. On 12/31/2014 06:57 PM, Steven D'Aprano wrote: Trust me on this, there is no linked list code you can write in Python that will be faster than using a list of lists. Even in C, traversing a linked list is slower than array access, and Python is not C. OK. I do trust you. Bounds checking is easy: cell [i, j] is in bounds if this is true: (0 = i NUM_ROWS) and (0 = j NUM_COLS) Fast access to any cell is possible: array[i][j] Implemented both. from sys import getsizeof Thanks I forgot about getsizeof. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
On Fri, Jan 02, 2015 at 12:28:38AM -0500, Dave Angel wrote: On 01/01/2015 11:48 PM, WolfRage wrote: Final Code Using 2d List instead of Doubly Linked List. [...] Is there a reason you doublespaced the whole thing? And why did you retype it instead of just copy/pasting it? And why lose the indentation, so nobody can actually try it without guessing at your indentation? I think the reason can be spelled: Bloody Gmail Wolfrage, you will have a lot fewer problems if you can get your Gmail to send plain text rather than rich text, formatted text or whatever they call it these days. (It's actually HTML code, like websites use.) Otherwise your code gets screwed up by Gmail: class GameTile(): def __init__(self, id, **kwargs): # id is (X,Y) self.id = id instead of: class GameTile(): def __init__(self, id, **kwargs): # id is (X,Y) self.id = id -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
On 02/01/15 01:35, Alan Gauld wrote: Repeats replicates the reference to the object but does not create a new object. reference = original # both refer to same object reference = original - True Oops, typo, should be: reference == original - True reference is original - True -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
Fixing the mangled formatting, as best as I am able (and can be bothered). On Thu, Jan 01, 2015 at 11:48:18PM -0500, WolfRage wrote: class GameTile(): def __init__(self, id, **kwargs): # id is (X,Y) self.id = id What is the purpose of the **kwargs? It doesn't get used, it just silently ignores them. Actually, what is the purpose of this GameTile class? It has no methods apart from the constructor. That is a sign of a class that isn't pulling its weight, its not doing anything. All the other code in your program looks inside the GameTile and accesses self.id directly. This is a sure sign of a class that doesn't need to exist. It may be better to give this at least a __str__ method, so if nothing else you can print it without looking inside: class GameTile(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return %d, %d % (self.x, self.y) class GameGrid(): def __init__(self, **kwargs): self.cols = 7 self.rows = 8 # grid is 2d array as y, x ie [y][x]. self.grid = [[None] * self.rows for i in range(self.cols)] Why do you have GameTiles use X,Y but the grid uses the opposite order, Y,X? This is going to cause confusion. I'm already confused! def make_grid(self): for row in range(0, self.rows): for col in range(0, self.cols): self.grid[col][row] = GameTile(id=str(row) + ',' + str(col)) No need to write range(0, Whatever), since range defaults to 0. Better to write range(Whatever). Why does the GameTile record the coordinates as strings? I would prefer something like this: def make_grid(self): for row in range(self.rows): for col in range(self.cols): self.grid[col][row] = GameTile(row, col) although it looks strange due to the backwards ordering of col/row. Your __init__ method should automatically call make_grid. That is: def __init__(self, **kwargs): self.cols = 7 self.rows = 8 # grid is 2d array as y, x ie [y][x]. self.grid = [[None] * self.rows for i in range(self.cols)] self.make_grid() Actually, even better will be to move the self.grid = ... line out of the __init__ method, and make it part of make_grid. Since it is part of making the grid. def print_by_row(self): for col in range(0, self.cols): for row in range(0, self.rows): print(self.grid[col][row].id) This now becomes: def print_by_row(self): for col in range(0, self.cols): for row in range(0, self.rows): print(self.grid[col][row]) since GameTiles now know how to print themselves. Likewise for this: def print_by_col(self): for row in range(0, self.rows): for col in range(0, self.cols): print(self.grid[col][row]) Another simplification here: def check_bounds(self, x, y): return (0 = x self.rows) and (0 = y self.cols) Your lookup_node method returns a GameTile or False on failure: def lookup_node(self, x, y, ): if not self.check_bounds(x, y): return False return self.grid[y][x] I'm not sure about that design. I wonder whether it would be better to return None, or raise an exception. You have a lookup_node method that checks the bounds, but you don't seem to use it anywhere. Why does it exist? def draw_grid(self): for col in range(0, self.cols): print(end='| ') for row in range(0, self.rows): print(self.grid[col][row].id, end=' | ') print() I'm not sure if I have reconstructed the indentation correctly here. A few changes: no need to call range(0, ...). GameTile instances now know how to print themselves, so you can call: print(self.grid[col][row], end=' | ') This could be improved: temp = GameGrid() temp.make_grid() temp.draw_grid() Creating a GameGrid should automatically create the game grid, hence what I said above about having __init__ call make_grid. Then use a more meaningful name, and we have: grid = GameGrid() grid.draw_grid() # Maybe this could be just called draw? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: pickle module error in source code
On 01/01/15 14:06, Vedhi Shreya Marwaha wrote: Hi! My name is Shreya Marwaha. I’m class 12th student in India. I’m using 2.7.5 python version [MSC v.1500 64 bit (AMD64)] on win32 as instructed by CBSE (central board of secondary education). I’ve been having problem in using pickle module. OK, welcome. It keeps on showing error in the source code. I’ve attached two files If the files are short its better to just paste the contents into your mail. Not everyone can (or is allowed to) read attachments. : 1. Prax.py file with error1.txt 2. Video.py file with error.txt Prax.py file is a simple problem, the first program I tried with pickle module. OK, Let's stick with that initially. The error says: Traceback (most recent call last): File C:\Users\Home\Downloads\prax.py, line 25, in module a=pickle.load(f) File C:\Python27\lib\pickle.py, line 1378, in load return Unpickler(file).load() File C:\Python27\lib\pickle.py, line 858, in load dispatch[key](self) File C:\Python27\lib\pickle.py, line 880, in load_eof raise EOFError EOFError The relevant code is: import pickle a=student() f=open(student.log,wb+) In general, don;t use the + modifier with files. It usually creates more confusion. Just open the file for reading after you finish writing. And try very hard not to mix reading and writing to the same file. a.input() pickle.dump(a,f) Here you have written your data to the file. The file 'cursor' is now pointing at the end of the file. a=pickle.load(f) Here you try to read from the file but the cursor is already at the end, so you get an end of file error. To make it work you could rewind the cursor to the beginning of the file using seek(). But it would be much safer to simply close the file after the dump() and then reopen the file for reading. That avoids a whole bunch of potential complexity and bugs just waiting to bite. Also, consider using the 'with' structure for handling files, it is generally safer than open/close: with open('student.log','wb') as f: a.input() pickle.dump(a,f) with open('student.log','rb') as f: a = pickle.load() 'with' ensures the files are closed after use. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making Doubly Linked List with Less Lines of Code.
On 02/01/15 01:03, Alex Kleider wrote: I don't think I understand the distinction between 'copies' and 'repeats'. copy creates a new object with the same attributes as the original original = [1,2,3] copy = original[:] # slicing creates a copy copy == original - True copy is original - False Repeats replicates the reference to the object but does not create a new object. reference = original # both refer to same object reference = original - True reference is original - True I think I understand the difference between copy and deep copy and I think that is the issue here but it isn't yet clear. Deep copy is not an issue here. s_grid = [[0]*5 for i in range(4)] # So for each iteration of the list comprehension, # a brand new, ?immutable? object ( a list of zeros) is created. # Immutable by virtue of the fact that there is no reference to it # and therefore it can't be changed? It's not immutable. Whether a reference to it exists or not has no bearing on whether it has the potential to be changed. In fact each object created has a reference: s_grid[0], s_grid[1], etc... You have 5 objects, each a list of 5 zeros. All 5 lists are mutable and all 5 are equal but not identical (ie. not the same object). s_grid [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] s_grid[1][1] = 99 s_grid [[0, 0, 0, 0, 0], [0, 99, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] # And as expected changing one object has no impact on the others. And by changing it you demonstrate that the objects are not immutable - you just mutated it! l = [0]*5 l [0, 0, 0, 0, 0] You now have one list object containing 5 zeros and a reference to it from 'l' grid = [l for i in range(4)] Now you have 4 more references to the same object 'l' refers to. # In this form, the list comprehension is encountering a mutable # object by virtue of the fact that there is a reference to it? No, the reference is irrelevant. It is mutable by virtue of being a list. grid[1][1] = 99 grid [[0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0]] You modified the object so all references (including the original 'l') will reflect the change # Is the crux of the matter that l is mutable (because it is a reference,) No the objects are mutable in both examples. mutable means you can change them. It has nothing to do with whether there is a reference or not. (Although, if there were truly no references the object would be destyroyed by the garbage collector) # while [0]*5 is not (because it is an expression?) [0]*5 is an expression that yields a list object. The list object is mutable. You proved that by changing one of them. my_grid = [[0, 0, 0, 0] for i in range(4)] my_grid [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] Now you have created another list of 5 objects. Again each object has 4 zeros and they are equal but not identical. They are all mutable. They are all referenced via my_grid. (my_grid[0],...) my_grid[1][1] = 99 my_grid [[0, 0, 0, 0], [0, 99, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] Again you changed(mutated) one of the objects. The others remain untouched. another_grid = [[0]*5]*4 Here you create a list of 4 references to the list produced by [0]*5 One list object, 4 references. # The explanations above don't seem to explain things here. another_grid [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] another_grid[1][1] = 99 another_grid [[0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0], [0, 99, 0, 0, 0]] Again there is only one list object, so when you change it via any of the references all the references reflect that change. My interpretation is that we appear to be getting a deep copy at the inner level of a multiplication but a not deep copy at the outer level. No copying is going on at any point. List comprehension provides us with a deep copy but only if we give it a literal (as opposed to a reference.) No, list comprehensions (and generator expressions in general) return a sequence made up of whatever object the first expression evaluates to. That could be an existing object (like the one referenced by 'l' above) or a newly created (possibly literal) object like [0, 0, 0, 0]. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor