Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Gothmog1065
May 14, 2009
That shouldn't have been that drat difficult to find.

Also, can you set the default path to something other than the default? I keep my small programs on the desktop, and I'd like IDLE to go there first when looking for programs.

edit: another interesting thing: If I run this on the command line (or in the command prompt), even if the word is correct, it won't show it as correct, but it works fine when I run it in IDLE.

Gothmog1065 fucked around with this message at 18:50 on Mar 24, 2011

Adbot
ADBOT LOVES YOU

clearly not a horse
May 8, 2009

undue butt brutality is not a criminal offense
pre:
class Base:
    def __init__(self):
        iam = 0

class Derivedfrom(Base):
    def __init__(self):
        thisis = 1

fish = Derivedfrom()
I am having trouble finding any info on how I can declare a subclass of Bas WITHOUT having to declare every stinking variable from the Base class inside the derived class. ANy tips? It works in C++, but Python is forcing me to write self all the time.

Modern Pragmatist
Aug 20, 2008

clearly not a horse posted:

I am having trouble finding any info on how I can declare a subclass of Bas WITHOUT having to declare every stinking variable from the Base class inside the derived class. ANy tips? It works in C++, but Python is forcing me to write self all the time.

You actually have to call the base class constructor.

code:
class Base:
    def __init__(self):
        iam = 0

class Derivedfrom(Base):
    def __init__(self):
        Base.__init__(self);

fish = Derivedfrom()

Yay
Aug 4, 2007
To provite a slightly different alternative, that uses new-style classes and better supports MRO for multiple inheritance:
code:
class Base(object): # declare as object
    def __init__(self):
        iam = 0 # this won't be available elsewhere on the object instance afterwards.

class DerivedFrom(Base):
    def __init__(self):
        super(DerivedFrom, self).__init__() # use super() to call parent methods.

fish = DerivedFrom()

Haystack
Jan 23, 2005





Alternately, you can use class variables.

code:
class Base(object):
    iam = 0

class Derivedfrom(Base):
    thisis = 1

fish = Derivedfrom()

Note that you should only do this with immutable values; the variable is shared between all instances.

clearly not a horse
May 8, 2009

undue butt brutality is not a criminal offense
Thanks for the replies. I have yet another question, this one regarding file processing. Let's say I have a txt-file which looks like this:

pre:
apple_001
type = apple
weight = 4
value = 2
taste = spiffin

apple_002
type = apple
weight = 5
value = 3
taste = horrible
... And I have a .py file where I have declared a class Fruit.

pre:
class Fruit:
    def __init__(self, fruitid):
        self.type = None
        self.weight = 0
        self.value = 0
        self.taste = None

        self.getfruit(fruitid)

    def getfruit(fruitid):
        #read file, find the corresponding fruitid and assign the corresponding values to the type, weight, value and taste variables in the object.
Example, if I declare a variable Timothy with the value Fruit("apple_002"), the getfruit() function will search the fil for the corresponding entry, and retrieve the values between the id and the next entry. Any ideas?

Found Your Answer
Jul 9, 2004

That's like killing a unicorn!
Can someone briefly indicate to me why Canvas on Tkinter is so slow when doing moving objects/rectangles? I have a while True: loop which sleeps for 30ms (so it should be 33.3 FPS) and then moves ten rectangles around the canvas, bumping off the walls screensaver-style. I don't have any memory/data racking up (like, all I do is clear the canvas, loops through the objects and move their x/y position, then redraw them), so I cannot really comprehend what would cause them to slow down in the canvas over time (after like ten seconds they slow down a ton).

I imagine it's some sort of memory issue that my code should be handling that it isn't, because when I make the same program in Javascript/HTML5 canvas, it never slows down (because the browser is handling something).

tripwire
Nov 19, 2004

        ghost flow
Well first of all, you should never have fixed delays like that in a gui draw loop. You should keep track of the timestamp of the previous frame and only sleep how ever many ms won't put you over schedule for the next draw.
Post your code.

Found Your Answer
Jul 9, 2004

That's like killing a unicorn!

tripwire posted:

Well first of all, you should never have fixed delays like that in a gui draw loop. You should keep track of the timestamp of the previous frame and only sleep how ever many ms won't put you over schedule for the next draw.
Post your code.

Interesting. My CS teacher did say it was a terrible way to do animations (though that was in Java but there's no reason Python would handle it any differently I suppose).

disclaimer: this code is terrible, I only use Python for data-mining/little stuff and I'm learning blah blah

code:
import sys, Tkinter, time, random
from Tkinter import *

class Window(Tk):
	def __init__(self, width, height, background):
		Tk.__init__(self)
		self.canvas = Canvas(self, width = width + 1, height = height + 1)
		self.canvas["bg"] = background
		self.width = width
		self.height = height
		self.background = background
		self.canvas.pack()
		self.update()
		# hack
		if not hasattr(sys, 'ps1'):
			sys.exitfunc = self.mainloop
	def clear(self):
		self.canvas.create_rectangle(0, 0, self.width + 1, self.height + 1, fill=self.background, outline=self.background)
	
	def sleep(self, ms):
		self.update()
		time.sleep(ms / 1000.0)
		self.update()

class Obj():
	def __init__(self, width, height, color):
		self.width = width
		self.height = height
		self.color = color
		self.x = random.randint(0, 600)
		self.y = random.randint(0, 440)
		self.dx = 5
		self.dy = 5
	def move(self):
		self.x += self.dx
		self.y += self.dy
		if self.x > 640 or self.x < 1:
			self.dx = -self.dx
		if self.y > 480 or self.y < 1:
			self.dy = -self.dy
	def draw(self, canvas):
		canvas.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height, fill=self.color)

g = Window(640, 480, "gray")
objs = [0] * 10
for i in range(0, 10):
	objs[i] = Obj(random.randint(10, 20), random.randint(10, 20), "blue")

while True:
	g.sleep(30)
	g.clear()
	for i in range(0, 10):
		objs[i].move()
		objs[i].draw(g.canvas)

Stabby McDamage
Dec 11, 2005

Doctor Rope

clearly not a horse posted:

Thanks for the replies. I have yet another question, this one regarding file processing. Let's say I have a txt-file which looks like this:

pre:
apple_001
type = apple
weight = 4
value = 2
taste = spiffin

apple_002
type = apple
weight = 5
value = 3
taste = horrible
... And I have a .py file where I have declared a class Fruit.

pre:
class Fruit:
    def __init__(self, fruitid):
        self.type = None
        self.weight = 0
        self.value = 0
        self.taste = None

        self.getfruit(fruitid)

    def getfruit(fruitid):
        #read file, find the corresponding fruitid and assign the corresponding values to the type, weight, value and taste variables in the object.
Example, if I declare a variable Timothy with the value Fruit("apple_002"), the getfruit() function will search the fil for the corresponding entry, and retrieve the values between the id and the next entry. Any ideas?

There are several ways to do this, but a line-by-line parser is probably the simplest. File pointers, when used as an iterator, give you lines. So we first can for the right fruit ID, then read & parse line by line to get the details. Regular expressions, as always, are awesome.

code:
import re

class Fruit:
    def __init__(self, fruitid):
        self.fruitid = fruitid
        self.type = None
        self.weight = 0
        self.value = 0
        self.taste = None

        self.getfruit(fruitid)

    def getfruit(self,fruitid):
        with open("fruits.txt") as fp:
            # skip to fruit
            for line in fp:
                if line.strip() == fruitid:
                    break
                    
            # read fruit lines until we hit another ID
            for line in fp:
                m = re.match('(\w+)\s*=\s*(.*)',line)
                if m: # key value pair
                    (key,value) = m.groups()
                    if key in ('type','weight','value','taste'):
                        if re.match('\d+$',value):
                            value = int(value) # recognize integers and save them as such
                        setattr(self,key,value)
                    else:
                        raise TypeError("Unrecognized attribute '%s'" % key)
                        
                elif re.match('\w+$',line):
                    # another fruit id, stop parsing, we're done
                    return
        
f = Fruit('apple_001')
print f.value
print f.taste

clearly not a horse
May 8, 2009

undue butt brutality is not a criminal offense

Stabby McDamage posted:

There are several ways to do this, but a line-by-line parser is probably the simplest. File pointers, when used as an iterator, give you lines. So we first can for the right fruit ID, then read & parse line by line to get the details. Regular expressions, as always, are awesome.

Thanks a lot for show reminding me that I have a pretty long way left - a lot here I need to read up on.

* with X as Y
* match()
* group()
* setattr()

If it isn't too redundant for this thread, I would be glad if someone could clarify the concepts for me.
re.match('(\w+)\s*=\s*(.*)' seems kind of mystic to me, as I can't see where "re" was declared.

devilmouse
Mar 26, 2004

It's just like real life.
I was doing a phone screen today with someone for a decidedly non-technical position, but on both his resume and his cover letter, he mentioned python, so I was curious about his level of aptitude. Now, we're doing the interview over Skype since he was currently traveling and in a hotel in Thailand on some shaky internet. The following conversation took place:

Me: "Can you describe what a list comprehension is and when you'd use one?"
Him: "It's, well, a list of elements and you could use them whenever you had a series of items you'd want to keep track of."
Me: "Pardon? I was asking about list comprehensions. Do you know what they are?"
Him: "Yeah, I comprehend what a list is."

I laughed and we moved back to non-technical topics.

Modern Pragmatist
Aug 20, 2008

quote:

If it isn't too redundant for this thread, I would be glad if someone could clarify the concepts for me.
re.match('(\w+)\s*=\s*(.*)' seems kind of mystic to me, as I can't see where "re" was declared.

re is the Regular Expression module.

Basically this is being used to parse:

variable = value

xtal
Jan 9, 2011

by Fluffdaddy

clearly not a horse posted:

Thanks a lot for show reminding me that I have a pretty long way left - a lot here I need to read up on.

* with X as Y
* match()
* group()
* setattr()

If it isn't too redundant for this thread, I would be glad if someone could clarify the concepts for me.
re.match('(\w+)\s*=\s*(.*)' seems kind of mystic to me, as I can't see where "re" was declared.

re was imported on line 1.

tripwire
Nov 19, 2004

        ghost flow

windwaker posted:

Interesting. My CS teacher did say it was a terrible way to do animations (though that was in Java but there's no reason Python would handle it any differently I suppose).

disclaimer: this code is terrible, I only use Python for data-mining/little stuff and I'm learning blah blah

code:
import sys, Tkinter, time, random
from Tkinter import *

class Window(Tk):
	def __init__(self, width, height, background):
		Tk.__init__(self)
		self.canvas = Canvas(self, width = width + 1, height = height + 1)
		self.canvas["bg"] = background
		self.width = width
		self.height = height
		self.background = background
		self.canvas.pack()
		self.update()
		# hack
		if not hasattr(sys, 'ps1'):
			sys.exitfunc = self.mainloop
	def clear(self):
		self.canvas.create_rectangle(0, 0, self.width + 1, self.height + 1, fill=self.background, outline=self.background)
	
	def sleep(self, ms):
		self.update()
		time.sleep(ms / 1000.0)
		self.update()

class Obj():
	def __init__(self, width, height, color):
		self.width = width
		self.height = height
		self.color = color
		self.x = random.randint(0, 600)
		self.y = random.randint(0, 440)
		self.dx = 5
		self.dy = 5
	def move(self):
		self.x += self.dx
		self.y += self.dy
		if self.x > 640 or self.x < 1:
			self.dx = -self.dx
		if self.y > 480 or self.y < 1:
			self.dy = -self.dy
	def draw(self, canvas):
		canvas.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height, fill=self.color)

g = Window(640, 480, "gray")
objs = [0] * 10
for i in range(0, 10):
	objs[i] = Obj(random.randint(10, 20), random.randint(10, 20), "blue")

while True:
	g.sleep(30)
	g.clear()
	for i in range(0, 10):
		objs[i].move()
		objs[i].draw(g.canvas)
Theres a few problems here, but I'm not familiar enough with TK to help you fully.

I do know that everytime you call the clear method, you are creating a new rectangle. All the previous ones are still there! The call to create_rectangle returns an ID number which you can use with other TK functions, so you only need to call it once and save the result. I think the raise function in canvas might be what you want, but then again theres probably an actual way of clearing the screen that youre supposed to use, I'm just not familiar with tkinter/tk

Heres some fixes i made:

code:
import sys, Tkinter, time, random
from Tkinter import *

class Window(Tk):
    def __init__(self, width, height, background, desired_fps = 30):
        Tk.__init__(self)
        self.canvas = Canvas(self, width = width + 1, height = height + 1)
        self.canvas["bg"] = background
        self.width = width
        self.height = height
        self.background = background
        self.canvas.pack()
        
        #desired time between calls to update, in ms
        self._time_budget = 1000.0 / desired_fps
        
        self.update()
        self._last_update = time.time()
        
        self._empty_rectangle = self.canvas.create_rectangle(
            0,0,self.width + 1,self.height + 1,
            fill=self.background,outline=self.background)
        
        # hack
        if not hasattr(sys, 'ps1'):
            sys.exitfunc = self.mainloop
    def clear(self):
        #...not sure what the syntax for this function is
        self.canvas.raise( self._empty_rectangle ???
        
    
    def tick(self):
        elapsed = time.time() - self._last_update
        duration_to_sleep = self._time_budget - elapsed
        if duration_to_sleep > 0.0:
            time.sleep(duration_to_sleep )
        
        self.update()

class Rectangle():
    def __init__(self, width, height, color):
        self.width = width
        self.height = height
        self.color = color
        self.x = random.randint(0, 600)
        self.y = random.randint(0, 440)
        self.dx = 5
        self.dy = 5
    def move(self):
        self.x += self.dx
        self.y += self.dy
        if self.x > 640 or self.x < 1:
            self.dx = -self.dx
        if self.y > 480 or self.y < 1:
            self.dy = -self.dy
    def draw(self, canvas):
        #Again, you definitely don't want to be making a new
        #rectangle each time you call draw.
        canvas.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height, fill=self.color)

main_window = Window(640, 480, "gray")

ten_to_twenty = lambda : random.randint(10, 20)

rects = [ Rectangle(ten_to_twenty(),
                    ten_to_twenty(),
                    "blue") for _ in xrange(10) ]


while True:
    main_window.tick(30)
    main_window.clear()
    
    for rectangle in rects:
        rectangle.move()
        rectangle.draw(main_window.canvas)
Use descriptive variable names, don't bother with that (for i=0;i<10;i++) style from c/java and just use the standard python for loop on any iterable type.
Wilcard imports will bite you in the rear end!

tripwire fucked around with this message at 07:32 on Mar 25, 2011

Found Your Answer
Jul 9, 2004

That's like killing a unicorn!
Ahhhhhhhhhhh, that is how to properly "tick" an animation loop like this, I see. Very helpful, thank you! I found out that in canvas, you can point to the rectangle objects created by create_rectangle, and later delete them with canvas.delete(id), which removes the need to clear the canvas (which is not how the <canvas> attribute in HTML5 works). You were correct and the slowdown was because those objects kept being created, not sure how I missed that.

Thanks!

tripwire
Nov 19, 2004

        ghost flow
I just realized I forgot to update the value of the Window._last_update in that tick method; don't forget to do that :)

Gothmog1065
May 14, 2009
My last set of questions may have been missed. One, is there a way to get python to change it's default directory (Where it looks for saved files)? Also, this code will not work in the console, but it works fine when run within IDLE. Is there something that would cause that?

Sneftel
Jan 28, 2009
One, what do you mean by "saved files"? You mean, where open() looks? Two, make sure you're actually running the same version of Python both under IDLE and from the command-line; the change in behavior of input() from 2.x to 3.x may be screwing things up.

While I have you here:

1. There's a function called random.shuffle()

2.
code:
true = 1 #Set loop to infinite while the user wants to play
while true:
That's the most terrible thing I've seen since lunchtime. What's wrong with while True?

Sneftel fucked around with this message at 19:10 on Mar 25, 2011

Gothmog1065
May 14, 2009

Sneftel posted:

One, what do you mean by "saved files"? You mean, where open() looks? Two, make sure you're actually running the same version of Python both under IDLE and from the command-line; the change in behavior of input() from 2.x to 3.x may be screwing things up.
Sorry, I mean where the .py files are stored. I'm still working on small stuff as I learn, and all my smaller programs are stored on my desktop in a /python folder. Is there a way to set it so the IDLE client looks there first (instead of having to locate it manually)?

Also, this is a fresh install of windows, and I only installed 3.2. The program works up until it checks to see if it's 'correct'. In IDLE it works just fine, but when running it on the command line, it will never see it as the correct answer.

quote:

While I have you here:

1. There's a function called random.shuffle()

2.
code:
true = 1 #Set loop to infinite while the user wants to play
while true:
That's the most terrible thing I've seen since lunchtime. What's wrong with while True?
I knew that was going to be poo poo, I just didn't realize that the capital 'T' made all the difference. I thought I saw that somewhere else, but it didn't work at first, so I did what I needed to do to make it work.

edit:

With random.shuffle(), simply put the word to be shuffled into the () rather than rebuilding it with the while loop (I'm pretty sure the book is trying to hammer in immutable list modifications)?

Gothmog1065 fucked around with this message at 19:35 on Mar 25, 2011

Dren
Jan 5, 2001

Pillbug

Gothmog1065 posted:

Sorry, I mean where the .py files are stored. I'm still working on small stuff as I learn, and all my smaller programs are stored on my desktop in a /python folder. Is there a way to set it so the IDLE client looks there first (instead of having to locate it manually)?

I'm assuming you are starting your program from the start menu.

Firstly, programs have something called a working directory. If you launch your program from the command line the working directory will be whatever directory you were in when you launched the program. If you launch your program from the start menu the working directory will be whatever it is set to in the shortcut properties. In the case of IDLE, with Python26 (it's what I have installed), the working directory is set to "C:\Python26". Incidentally, it is not called a working directory in the shortcut properties. Instead it is labeled "Start in:".

Anyway, programs generally open to their working directory when you do file->open. You can probably set the working directory to whatever folder your crap is in to get IDLE to default to your folder.

Alternatively, and this is what I would do, you could leave an explorer window open to your crap and right-click edit with IDLE whenever you want to open a file.

Or you could use an IDE with a built-in file explorer.

Gothmog1065 posted:

With random.shuffle(), simply put the word to be shuffled into the () rather than rebuilding it with the while loop (I'm pretty sure the book is trying to hammer in immutable list modifications)?

The random.shuffle doc string:
code:
>>> print random.shuffle.__doc__
x, random=random.random -> shuffle list x in place; return None.

        Optional arg random is a 0-argument function returning a random
        float in [0.0, 1.0); by default, the standard random.random.
Notice that it shuffles the list in place. Your program requires you to shuffle a string. A string is a list in python but a string is immutable whereas a list is not. That is the distinction the book wishes to make clear to you.

Observe
code:
>>> w = 'word'
>>> random.shuffle(w)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\Lib\random.py", line 275, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment
>>> w_list = list(w)
>>> w
'word'
>>> w_list
['w', 'o', 'r', 'd']
>>> random.shuffle(w_list)
>>> w_list
['d', 'w', 'o', 'r']
>>> ''.join(w_list)
'dwor'
Oh, and ಠ_ಠ
code:
true = 1 #Set loop to infinite while the user wants to play
while true:

Gothmog1065
May 14, 2009

Dren posted:

Alternatively, and this is what I would do, you could leave an explorer window open to your crap and right-click edit with IDLE whenever you want to open a file.
I'm lazy so this will probably be what I do, it's really only a few clicks (Click 'desktop' then 'Python'. I think I'm picking the rest up, most of this poo poo is still new, and I know strings, tuples and lists are basically the same thing, but different.

quote:

Oh, and ಠ_ಠ
code:
true = 1 #Set loop to infinite while the user wants to play
while true:

I... I know :eng99:

Sorry if I'm retarding this thread up, but I've always found people to be my best resource for learning.

tripwire
Nov 19, 2004

        ghost flow
To elaborate on the ways strings, tuples and lists are the same: the only commonality is they are all sequence types, they support subscript access and you can iterate through them. You use them for very different reasons.

A tuple is an immutable heterogeneous sequence: you declare it once, you can't assign to elements of it, nor can you append or remove elements. They support subscripting and random access to elements, and they work together with pythons packing/unpacking syntax so you can do things like
code:

resolution = 640,480
width,height = resolution
You can add two tuples together (which makes a new tuple thats the concatenation of the two original tuples) but this is mostly for convenience and you should never be building up a tuple by concatenating it to itself.


A string is also immutable but it is a homogenous sequence- every element has to be a one character string. As with tuples, you should never be building up strings with concatenation, and you are not permitted to assign to elements of a string.

A list IS mutable, and you'll find yourself using them all over. Lists support fast appending, fast length checking, fast popping (from the right) and fast random access (and assignment!). They have a sort method for sorting in place which is very useful.

Stabby McDamage
Dec 11, 2005

Doctor Rope

clearly not a horse posted:

Thanks a lot for show reminding me that I have a pretty long way left - a lot here I need to read up on.

* with X as Y
* match()
* group()
* setattr()

If it isn't too redundant for this thread, I would be glad if someone could clarify the concepts for me.
re.match('(\w+)\s*=\s*(.*)' seems kind of mystic to me, as I can't see where "re" was declared.

with X as Y: Some parts of 'with' get complicated, but here's the short version: for functions that support it, you use it to make Y=X for the body of the 'with' block, and when you leave that block, Y gets cleaned up. Files support the 'with' interface, so I used it so work with that file without worrying about closing it -- that lets me simply return instead of breaking out of the loop and hitting a close() at the end. Just some brevity.

match() and group(): part of the regular expression system. Basically, regular expressions are a language to let you match parts of strings, which makes for easy parsing. See the 're' documentation for details. Here's a good quick reference PDF (it's for Perl, but the syntax is the same). Regular expressions are amazingly stupendously powerful tools -- you should definitely learn them.

setattr(): just a global function in python that lets you set object attributes by string instead of by identifier. So thing.speed = 5 is the same as setattr(thing,'speed',5). Why use the latter? Because you can specify the attribute as a string, i.e. the name of the attribute can itself be in a variable. This was a shortcut I took because your text file field names were the same as your attribute names. I could just as easily have done:
code:
if key=='name':  self.name  = value
if key=='taste': self.taste = value
# etc...

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

tripwire posted:

A tuple is an immutable heterogeneous sequence: you declare it once, you can't assign to elements of it, nor can you append or remove elements.

You do have to be careful though when using mutable types inside of a tuple, i've seen more then one person think that tuple means that the data inside the tuple cannot change ever.

code:
>>> my_tuple = (1, [], 'test')
>>> my_tuple
(1, [], 'test')
>>> my_tuple[1].append('what')
>>> my_tuple
(1, ['what'], 'test')

king_kilr
May 25, 2007
Fun times:

code:
>>> a = ([], 2)

>>> a[0] += ["boy oh boy"]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/alex/<ipython console> in <module>()

TypeError: 'tuple' object does not support item assignment

>>> a
[3] (['boy oh boy'], 2)

Hughmoris
Apr 21, 2007
Let's go to the abyss!
Quick question. First, I'm a novice programmer, doing this as a hobby and sucking at it.

With python, how do you stop people from looking at your code? I want to write a small simple program that will encrypt a text file, and then decrypt it when the user wants to. Is there way to stop people from looking at my script's code?

*A quick google search says no. Any differing opinions?

Hughmoris fucked around with this message at 06:00 on Mar 28, 2011

FoiledAgain
May 6, 2007

I'm trying to pull some numbers out of a bunch of files and then use them to print some figures. But I'm getting this error
IOError: [Errno 13] Permission denied: 'C:\\Python27\\Figures'


code:
import pylab
import os

path = 'C:\\Python27\\Figures\\'
listing = os.listdir(path)
y = dict() #floats representing error of a particular node 
x = dict() #integers representing time

pylab.xlabel('Error')
pylab.ylabel('Time')

for infile in listing:
    with open(''.join([path,infile]),'r') as f:
        y[infile] = [line.rstrip('\n') for line in f]
        x[infile] = [num for num in range(len(y[infile]))]

    for num in y[infile]:
        num = float(num) #need floats for pylab.plot
        
    #plot in a pretty blue line
    pylab.plot(x[infile],y[infile],'b')

    #save the file
    filename=''.join([path,'Figures\\error_node_',str(listing.index(infile)),'.png'])
    pylab.savefig(filename)

edit: drat, it's that windows 7 thing where you can't turn off the "read-only" property of a folder
double edit: just learned that pylab.plot does not do quite what I thought it did

FoiledAgain fucked around with this message at 08:12 on Mar 28, 2011

Opinion Haver
Apr 9, 2007

Hughmoris posted:

Quick question. First, I'm a novice programmer, doing this as a hobby and sucking at it.

With python, how do you stop people from looking at your code? I want to write a small simple program that will encrypt a text file, and then decrypt it when the user wants to. Is there way to stop people from looking at my script's code?

*A quick google search says no. Any differing opinions?

You can obfuscate your code to make it hard to read, and I'm pretty sure there are tools that will bundle the interpreter and your script up into one executable (which will be hard to read as well) but ultimately any encryption method that depends on nobody being able to read your code is a Bad Idea.

king_kilr
May 25, 2007

yaoi prophet posted:

You can obfuscate your code to make it hard to read, and I'm pretty sure there are tools that will bundle the interpreter and your script up into one executable (which will be hard to read as well) but ultimately any encryption method that depends on nobody being able to read your code is a Bad Idea.

Even the bundling isn't particularly secure against anyone who knows what to look for.

FISHMANPET
Mar 3, 2007

Sweet 'N Sour
Can't
Melt
Steel Beams
I pretty much us Python as a scripting language to replace bash/csh, so quite often I want to run a command, maybe get what it printed to stdout, and maybe get the return value.

The subprocess module does all that, but just seems really complicated. Apparently everything is deprecated in 3.x though, so am I stuck with subprocess? Is there another easier way to run unix commands from within Python?

Lurchington
Jan 2, 2003

Forums Dragoon
at the bottom of the subprocess's 2.7 documentation, there's:
http://docs.python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module
which is helpful for this kind of thing, maybe a few extra characters compared to the old stuff, but not terrible.

but honestly, if you're on 2.7 (or I assume 3.x), then check_output does basically everything I'd ever want.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Hughmoris posted:

Quick question. First, I'm a novice programmer, doing this as a hobby and sucking at it.

With python, how do you stop people from looking at your code? I want to write a small simple program that will encrypt a text file, and then decrypt it when the user wants to. Is there way to stop people from looking at my script's code?

*A quick google search says no. Any differing opinions?

Make it a web service. People upload the text file and you send it back.

That's pretty much the only way.

Dren
Jan 5, 2001

Pillbug

Hughmoris posted:

Quick question. First, I'm a novice programmer, doing this as a hobby and sucking at it.

With python, how do you stop people from looking at your code? I want to write a small simple program that will encrypt a text file, and then decrypt it when the user wants to. Is there way to stop people from looking at my script's code?

*A quick google search says no. Any differing opinions?

Your problem isn't hiding what your code is doing. Your problem is the method of encryption you have chosen.

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.
How do I check if an int is less than the length of 2 separate list lengths? Here is what I have now, but it dosnt seem to work.

code:
if counter >= len(list1) or len(list2):
It works if I do something clumsy like
code:
if counter >= len(list1):
[TAB]if counter >= len(list2):
But I *know* that there must be a way to do it on one line that I'm not quite getting.

spankweasel
Jan 4, 2006

zarg posted:

How do I check if an int is less than the length of 2 separate list lengths? Here is what I have now, but it dosnt seem to work.

code:
if counter >= len(list1) or len(list2):
It works if I do something clumsy like
code:
if counter >= len(list1):
[TAB]if counter >= len(list2):
But I *know* that there must be a way to do it on one line that I'm not quite getting.

You need to check the variable against both lengths.

code:
 if counter >= len(list1) or counter >= len(list2)

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

zarg posted:

How do I check if an int is less than the length of 2 separate list lengths? Here is what I have now, but it dosnt seem to work.

code:
if counter >= len(list1) or len(list2):
It works if I do something clumsy like
code:
if counter >= len(list1):
[TAB]if counter >= len(list2):
But I *know* that there must be a way to do it on one line that I'm not quite getting.

You're checking if counter is greater than, not less than.

brosmike
Jun 26, 2009
In python as in most other languages, the "or" operator just operates on two boolean expressions. Let's take a look at your original if statement with some clarifying parentheses to make it clear why this matters to you. When you tell python

code:
if counter >= len(list1) or len(list2):
...it sees...

code:
if (counter >= len(list1)) or (len(list2)):
To do what you want, you have a few options (including the sort of clunky one you mentioned already). You could do:

code:
if counter >= len(list1) or counter >= len(list2):
or you could do

code:
if counter >= min(len(list1), len(list2)):
Edit: beaten like gently caress, and also yes this is checking greater than

Lurchington
Jan 2, 2003

Forums Dragoon
Dunno if you've ever used the 'all' or 'any' built-ins, but they're convenient for this:

code:
list1 = [0, 2, 4, 5, 6]
list2 = [0, 2, 4, 5]
print all(4 < len(_list) for _list in (list1, list2)) # false
print all(3 < len(_list) for _list in (list1, list2)) # true
http://docs.python.org/library/functions.html#any
http://docs.python.org/library/functions.html#all

Lurchington fucked around with this message at 21:27 on Mar 28, 2011

Adbot
ADBOT LOVES YOU

Scaevolus
Apr 16, 2007

king_kilr posted:

Fun times:
code:
>>> a = ([], 2)
>>> a[0] += ["boy oh boy"]
TypeError: 'tuple' object does not support item assignment
>>> a
[3] (['boy oh boy'], 2)
Is this a (known?) bug?

  • Locked thread