hughesadam_87 54 Junior Poster

Hmm, that's essentially what I mean, except using the .join() method to handle the "str(i)" part. The snippet of your code:

newstring=''
for i in l:
newstring+=str(i)

Can effectively be replaced by one line using join():

newstring=''.join(mylist)

However, unlike in your code, the join() method won't automatically convert the str without some sort of middle step. This is perhaps not a problem, but I just feel like there should be a method to do this, or even like a **kwarg.

hughesadam_87 54 Junior Poster

Hi,

If I have a list of strings, it's easy to output them using .join(). For example:

mylist=['hi', 'there', 'girls']
myout='\t'.join(mylist)

What I want to know is if there is a builtin python method that acts like join, except it automatically converts ints and floats to strings without giving a Type Error. For example, it would not error with this:

mylist=['hi', 'there', 'girls', 5000]
myout='\t'.join(mylist)
TypeError: sequence item 1: expected string, int found

I understand that I can simply fix mylist in one line with:

my_newlist=[str(entry) for entry in mylist]

However, this is such a common operation that I thought I'd ask around if there's a way to get .join() or a related module to work this way automatically.

hughesadam_87 54 Junior Poster

Check out the "enaml" project from enthought. This is an example of a scripting language (or maybe a psuedo scripting language, I don't have a deep understanding really) that has been developed over python.

What is your motivation for pursuing this end? As the other posters have implied, you may find that basic Python's libaries are adequate to do what you need. Although, this doesn't mean you should not look into the idea; it sure would be a good learning experience if nothing else.

hughesadam_87 54 Junior Poster

I'm an idiot. I went back to the code and python does recognize a single blank space, I must have just made a typo when I first tested this. The following works:

s='hi my name is bill'
print [c for c in s if c != ' ']
hughesadam_87 54 Junior Poster

Thanks PyTony. This is definatley a good solution; however, I need to be able to include nonalphabetic characters like "\" and "-" in the outstring. How can I tell Python to recognize a single whitespace character? I've been looking for this online and can't seem to come across it!

hughesadam_87 54 Junior Poster

Real quick question. If I have a string 'hi my name is bill' and I want to reduce this to a list of letters, with no whitespaces (eg ['h', 'i', 'm', 'y'] as opposed to ['hi', 'i', ' ' , 'm', 'y', ' ', 'n'...]), is there a really quick and tidy way to do this? Or should I say, what is the best way?

If I use:

s='hi my name is bill'
print list(s)

Spaces are not removed.

I've also thought to try:

ls=[letter for letter in s.split() if letter != ' ']  

This doesn't work because first of all, I can't seem to find the whitespace character for python, and also seems like it should have a builtin way.

What do you guys think?

hughesadam_87 54 Junior Poster

Thanks for that ZZucker

hughesadam_87 54 Junior Poster

For 6 and 7, you should look into the module itemgetter() (Do a ctrl+f for getter on this page: http://docs.python.org/library/operator.html)

If you have simple items in a list, for example a list of ints:

mylist=[1,2,5,3,7,8]

Then you can use simply mylist.sort() to sort them. If you have strings, it will sort them alphabetically. But if you have more complex data types like in your case, a person and a score, you can store them in a list of tuples aka:

mylist=[(Bill, 93), (Adam, 100), (Josh,32)]

(Giving myself 100% of course)... then you can use the itemgetter to sort these by the second value in the tuple. This is a handy import because it can be used for even more complex tuples, like a tuple of 3 names and 15 scores.

Once you have the new sorted object, just use obj.reverse() to output it in the opposite order (ascending or descending).

hughesadam_87 54 Junior Poster

Yeah you have to put in an effort, we can't do homework for you.

hughesadam_87 54 Junior Poster
hughesadam_87 54 Junior Poster

Look. I honestly can't make it through all that code but I can say that I used TK to roll my own GUI's and always found eventually the GUI code would end up longer than the source to begin with. I just posted this tutorial on a package that will make your life mega easier for GUI's in python if you don't want to reinvent every wheel ever. You can skip to about 5-10 min in to part 1 and you'll see I make a GUI with an 11 line code that has buttons and everything.

http://www.daniweb.com/software-development/python/threads/419559/application-programming-tutorial-using-enthought-tool-suite

hughesadam_87 54 Junior Poster

You'll want to read up on the "raw input" function in python. You can use it to enter anything (integers, strings, floats) directly from the command line to the program.

hughesadam_87 54 Junior Poster

Also, should mention that for scientists, you should check out chaco (2d parting part 2 halfway through) and mayavi (3d plotting in part 3)

hughesadam_87 54 Junior Poster

Hey everyone,

Last semester my buddy and I made a tutorial on application programming in Python. This video uses the Enthought Tool Suite (ETS), a free powerful Python development toolkit, to build quick, easy and powerful GUI's. I see many posts on this site about Tk, wx, qt but haven't seen much of anything about the ETS. I think that most users will be happily surprised at how easy it is to make graphical interfaces and event handlers using these tools. I would recommend this video to anyone who is not familiar with ETS and especially people who aren't highly fluent in a particular brand of graphical user interface coding in Python. I work almost exclusively in the ETS API now instead of native Python.

My video is in three parts. I'd recommend downloading it locally as it will be better quality, but am posting the hosting links as well. Comments/feedback are appreciated.

(full vid link)
http://www.4shared.com/zip/W5p6c0oT/ETS_Screencast_Files.html

(example .py files from the video)
http://www.4shared.com/zip/JFWCfJ3D/Example_Files.html

(part 1)
http://www.youtube.com/watch?v=ohHoU4qvsNs

(part 2)
http://www.youtube.com/watch?v=Jjs-Zs3X6QY

(part 3)
http://www.youtube.com/watch?v=FDI22rWDnDA

Below is the description that I've also posted to the comments of the videos.

This screencast was adapted from a presentation for the George Washington University physics department. It gives a general overview of application building, and why it is difficult without special tools. It then introduces the Enthought Tool Suite as a way to simplify the application building process in Python. …

hughesadam_87 54 Junior Poster

Post your best try so far and then we can give you help with it.

hughesadam_87 54 Junior Poster

You can shorten this:

for line in responsesfile:
line = line.strip()
parts = [p.strip() for p in line.split(' ')]
responses[parts[1]] = (parts[0], parts[2])
return responses

By doing this:

responses={line.strip()[1] : (line.strip()[0], line.strip()[2]) for line in responses file}

Note this syntax is only valid for python 2.7 or better.

hughesadam_87 54 Junior Poster

PS, is there a list comprehension way to do this in 1-2 lines? I use this so often that I'd like to shorten the syntax.

hughesadam_87 54 Junior Poster

Woooee's method is probably the most common way to do this, so I would keep it in mind for many applications.

hughesadam_87 54 Junior Poster

So basically "is" could be repaced with if id(a) == id(b)?

hughesadam_87 54 Junior Poster

Maybe I am misunderstanding, but you'd simply take the self.textWidget (which seems to be the only class/instance variable in this problem) and make it either a global variable, or pass it to your method as an argument.

hughesadam_87 54 Junior Poster

== it is then, thanks.

hughesadam_87 54 Junior Poster

Hey guys, I've looked over several Google results for basic explanations on

is / '=='

However, I don't think I quite understand enough to know what is the ideal operator for this.

mylist=[1,2,3]

if type(mylist) == list:
   print 'yes'

or do I use

if type(mylise) is list:
   print 'yes'

I understand superficially that == tests value and is test identifier (in the memory?) but not sure I really understand what is the best solution here.

THanks

hughesadam_87 54 Junior Poster

You can use f.readlines() to bring in your entire file into a list. By default, then use some manipulation to split this list at the '\n' characters and write each row into a dictionary. Then you can access rows by a row number keys and columns by a value key.

Do you know what I'm saying or is this unclear?

hughesadam_87 54 Junior Poster

Actually I'm an idiot, I see what you're getting at Sneekula.

hughesadam_87 54 Junior Poster

One simple way to sample a list while skipping elements with with the following syntax.

a=[1,2,3,4,5]
b=a[::2]  #means sample all elements with spacing = 2
print b
>>>[1,3,5]

c=a[2::2]  #means sample all elements with spacing =2 starting from the 3rd element
hughesadam_87 54 Junior Poster

Thanks Gribouillis that was a very helpful answer.

hughesadam_87 54 Junior Poster

I've followed a tutorial where a Person class was used to illustrate the difference between class and instance variables. Something like:

class Person(object):
        population=0
	def __init__(self, name):
		self.name=name
		Person.population += 1
                print 'current population', Person.population

Sally=Person('sally')
Joe=Person('joe')

This example really illustrated the difference between class and instance variables to me; however, it also really confuses me. When I think about it, the Person class is holding the attributes for an individual. The concept of a population; however, is a group of people. Therefore, it seems natural in OOP that a container class, "People" would store the variable population. When you really think about it, "People" is a composition of "Person" objects. And furthermore, the population itself is not really an independent variable. Instead, it is a property of the real variable, which is a list of "Person" objects. Let me show you what I mean:

class Person(object):
	def __init__(self, name):
		self.name=name
                print 'Instantiating person', name

class People(object):
        def __init__(self, persons):
                self.persons=persons

        def add_member(self, person):
                print 'adding a crew member', person.name
                self.persons.append(person)

        def getpop(self):
		print 'my population is now', len(self.persons) 
		return len(self.persons)        
        population=property(getpop)


sally=Person('sally')
joe=Person('joe')
crew=People([sally, joe])
print crew.population, 'is the new population'
bob=Person('bobby')
crew.add_member(bob)
print crew.population, 'is the new population'

I would argue that my People class is a more canonical way of representing a population of people because it holds a list of people and the population is merely a property of this list (i.e. the length of the list).

Let me ask 2 questions. First …

hughesadam_87 54 Junior Poster

This is cool bud. I think if you have enough understanding of OOP to make this chess game, you ought to start learning the Enthough Tool Suite. The Enthought Tool Suite will let you rebuild this program with a total GUI and other things without adding much. I know this isn't very informative, and I'll post some tutorial videos soon, but I think it would make you program easier to use because you can have a fully 3d chessboard using mayavi (a python visualization toolkit wrapper built into the enthough tool suite).

hughesadam_87 54 Junior Poster

Sneekula, I don't really follow what the "5d" means. I think I understand it otherwise...

hughesadam_87 54 Junior Poster

Alright I'll keep that in mind, thx

hughesadam_87 54 Junior Poster

Thanks for both of these good solutions guys.

Also, woooee, why is using "i", 'I' and "O" bad?

hughesadam_87 54 Junior Poster

You can really do anything with Python; however, I'd be interested to know what is "the skill"

hughesadam_87 54 Junior Poster

I think the builtin filter method in python will also do this, but it might not be so straightforward. Vegas's answer will extend to dictionaries if you use:

for item in A.iteritems():
    for item in B.iteritems():

etc...

However if you can't use loops (which is dumb IMO) then you gotta do something else.

hughesadam_87 54 Junior Poster

Hey guys,

In prepping for a job interview, I'm trying to eliminate some bad habits and this trivial problem has me realizing how hard that is :'(.

The problem:

Print a 12 x 12 multiplication table. This is easy....

outstring=''
for i in range(1,13):
	for j in range(1,13):
		outstring +='\t'+str(i*j)  #+= is add new value
	print '\n', outstring
	outstring=''

Resulting in
1 2 3 4 5 6 7 8...
2 4 6 8 10 12 14 16... etc

Ok no biggy, but what I want to do now is to get rid of my sloppy outstring method and use .join(). I also would like to do the iterator in one go. Here's the closet I can get.

outlist=[str(i*j) for i in range(1,13) for j in range(1,13)]
s="".join(outlist)
print s

This works sort of, but now I don't know how to get the nice tab-delimited output. Any ideas of how to modify this so it uses these premises but outputs data like the original method?

Thanks.

hughesadam_87 54 Junior Poster

Hmm, so the way you defined alllists, you did not make a list of lists; rather, you simply made a single list by adding all the items from your smaller lists together. To make a list of lists, you'd use this syntax:

alllists=[classlistA, classlistB, classlistC ]

Then I'd change the following line:

for i in range(classnumber):
       classname = raw_input("Please type the classes you have taken <CODE> <COURSE-NUMBER>: ")
       allLists.remove(classname)

To

for i in range(classnumber):
       classname = raw_input("Please type the classes you have taken <CODE> <COURSE-NUMBER>: ")
       for classlist in alllists:
           if classname in classlist:
               classlist.remove(classname)
hughesadam_87 54 Junior Poster

There are numerous solutions to this problem, but perhaps one that is most straightforward is to just put all your items in a list of lists. Or a tuple of lists, or a dictionary of lists...etc there's many advanced storage options in python.

Here's a list of lists:

def main(): 
    print "This program returns a list of classes you still have to take: "
    classlistA = ["CMSC 201", "CMSC 202", "CMSC 203", "CMSC 304", "CMSC 313",
                 "CMSC 331", "CMSC 341", "CMSC 345", "CMSC 411", "CMSC 421",
                 "CMSC 441"]
    classlistB = ["MATH 151", "MATH 152", "MATH 221"]
    classlistC = ["STAT 334" ,"STAT 451"]

    all_lists=[ classlistA, classlistB, classlistC]

    classname = input ("How many classes have you taken so far?: ")
    
    for i in range(classname):
        classname = raw_input("Please type the classes you have taken <CODE><COURSE-NUMBER>: ")
    for classlists in all_lists:
        try classlists.remove(classname)
    except Exception:
        print 'cannot remove that, not found'
        pass
    
    
    print "part A requirements"
    for x in classlistA:
        print "You still have to take", x


main()

What I did was I just put your 3 classlists in a new list called all_lists. Then I also put in an error exception that will handle the situation when you try to remove an element that is not there.

Again, there are many more elegant solutions.

hughesadam_87 54 Junior Poster

Ahh you're a total genius! Thanks. I didn't even realize this zip feature existed!

hughesadam_87 54 Junior Poster

Hey guys,

I have a simple numpy datatype:

spec_dtype = np.dtype([
	     ('wavelength', float),
   	     ('intensity', float)
			])

I chose to use this in my program because it's very easy to read in 2-column spectral data files using the genfromtxt() method. Therefore, I made a fairly sizable program around this datatype. Now I'm running into a situation wherein I need to pass internal data lists for the "wavelength" and "intensity", rather them importing them externally from a file. This is giving me headaches with manual array creation.

Imagine I have a list of wavelengths and intensity variables pre-stored in my program. For example:

wavelengths=[300.00, 200.00, 100.00]
intensities=[23, 32, 43]

I'd like to simply put these into an array of spec dtype. At first I tried:

myarray=np.array([(wavelengths),(intensities)], dtype=spec_dtype)

This actually doesn't produce the type of array that I'd expect. Instead, I had to iterate through the array and append the items one by one. For example:

myarray=np.empty(,dtype=spec_dtype)
for i in range(len(wavelengths)):
    mydata[i]=((wavelengths[i]), (intensities[i]))

Is there anyway to avoid this and do it all in one fell swoop?

Thanks.

hughesadam_87 54 Junior Poster

Does this functionality have to be incorporated in the function itself? It doesn't seem like something you'd want to use a function for at all. The functions are meant to not be aware of the global operations of the program, so it's not straightforward to have the function be aware of an iterable in the main program. Why exactly to you wan to use a function?

hughesadam_87 54 Junior Poster

At the bottom of the thread there should be a link that says "blah blah is this solved then Mark as Solved" where the "Mark as Solved" is a hyperlink. Just click that. Use ctrl+F to find it quicker in your browser if you don't see it.

hughesadam_87 54 Junior Poster

Thanks for your help. I had forgotten about this thread until I came back to the problem. This fixed my problem! I'm overdeclaring the string space because I can't always anticipate how long the string will be, but this doesn't seem to post any problem except probably just wasting a bit of memory. Thanks again.

hughesadam_87 54 Junior Poster

I have data which has a very particular format that I'm trying to store in a numpy array.

avi_05MSalt00001.txt 2012 Feb 07 20:12:41 50000 (usec) 300 10

I've defined the following numpy datatype:

timefile_dtype=numpy.dtype([
	     ('filename', file),
   	     ('year', int),
	     ('month', str),  #Why don't these work?
	     ('day', int),
 	     ('time', str),
	     ('int_time', int),
	     ('unit', str),
	     ('avg', int),
	     ('boxcar', int),
			])

The output looks like this:'

('avidin_in_water00349.txt', 2012, '', 29, '', 50000, '', 300, 10)

Is it possible for numpy to store these string variables? If so, am I doing something wrong? I like the swiftness of this method rather than making my own list of lists...

Thanks.

hughesadam_87 54 Junior Poster

I'd look into the Enthought Tool Suite and read up on Mayavi. There's no simple solution to your problem.

hughesadam_87 54 Junior Poster

Same with me. Post a sample of the data file so we know how your data is structured then try to explain exactly what you do more clearly and we can suggest a better code.

hughesadam_87 54 Junior Poster

Thanks Gribouillis. I didn't know of this inspect module, which seems to be precisely what I needed.

hughesadam_87 54 Junior Poster

Anyone ever come across this?

hughesadam_87 54 Junior Poster

I feel like this is too complicated for what you want to do. Can you clarify what you want to do and we could suggest a more simple class structure for it.

hughesadam_87 54 Junior Poster

Hey everyone,

I have a set of classes which, when instantiated, take up a lot of memory. I'm trying to write a program which can inspect class attributes and methods given a list of classes, without actually instantiating them. Let's say I wanted to see if the following class had an attribute called "foo"

class Test(object):
   foo=str()
   bar=int()

I know I can do something like:

test=Test()
if test.f is not None:
    print 'found'

However, is it possible to do this without instantiating Test? In reality, I need to do this with 10 objects, all of which are rather large and when instantiated, take up a great deal of memory and slow down my code.


Thanks

hughesadam_87 54 Junior Poster

Sys is standard for most python distributions, so at the top of your code, just put the line:

import sys

and you'll have all the features therein.

hughesadam_87 54 Junior Poster

You define the variable b inside of these private methods, so it doesn't exit outside of the methods. You define it in add, but it is not passed to the other methods. The way you are setting this up, it's suitable for object oriented programming, meaning you should use classes. I'll try to provide an example later.