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
tripwire
Nov 19, 2004

        ghost flow

MeramJert posted:

So even though I posted in this tread about getting into stackless months ago, I got busy and am now trying to get back into it. What I have is a simple program to generate a sine wave in an array and send it through an audio stream to the sound card without the intermediate step of writing a wave file. What I want is a way to play two different waves concurrently.

code:
import math, wave, array, stackless

class Sine:
         
    def __init__(self, seconds, frequency, amplitude, channel, sampleRate=44100):
        cyclesPerSample = float(frequency)/sampleRate
        numberOfSamples = int(seconds*sampleRate)
        maxAmplitude = (amplitude/100.)*32767
        sampleArray = array.array('h')

        for nSamples in xrange(numberOfSamples):
            cycles = nSamples*cyclesPerSample
            cycles -= int(cycles) # makes 0.0<=cycles<1.0
            sampleValue = int(round(maxAmplitude*math.sin(2.0*math.pi*cycles))) # round 
            sampleArray.append(sampleValue)
        self.data = sampleArray        
        stackless.tasklet(self.send_array)(channel)
        
    def send_array(self, channel):
        channel.send(self.data)
code:
import pyaudio, stackless

class OutStream:
    
    def __init__(self, Format=pyaudio.paInt16, Channels=1, sampleRate=44100):
        self.channel = stackless.channel()
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format = Format, channels = Channels, rate = sampleRate, output = True)
        stackless.tasklet(self.listen)()
        
    def listen(self):
        while 1:
            data = self.channel.receive()
            stackless.tasklet(self.play)(data)
        
    def play(self, data):
        self.stream.write(data)
        
    def __del__(self):
        self.stream.close()
        self.p.terminate()
code:
import stackless
from Sine import *
from Output import *

output = OutStream()
output2 = OutStream()

x = Sine(1,650,75,channel=output.channel)
x = Sine(1,450,75,channel=output2.channel)

stackless.run()
I've been playing around with executing the code in different orders, like making the channels a property of Sine instead of Output and generating all the Sine data before sending any of it, but the second wave always plays after the first. There is a little bit of overlap between them, but if I lengthen the first wave the second wave still doesn't play until the first one is just about done, no matter the length. I don't need them to line up at a specific point or anything, but I would like to get them to output concurrently. Is this possible using anything along similar lines to what I've tried so far?
I've done this by feeding numpy arrays through chr and writing to /dev/dsp, but I have some code here that actually uses the python audio modules to do it.

Why are you trying to write two arrays to it? What you want to be doing is adding the two arrays together element-wise and writing the result to audio out.

Check this out, it adds two sine waves to make DTMF tones and outputs it using OSSaudiodev
code:
try:
    import ossaudiodev
except:
    print "ossaudiodev not installed"
    ossaudiodev = None
try:
    from numpy.fft import *
except:
    print "numpy fft not installed"
    ossaudiodev = None
try:
    from numpy import argmax
except:
    print "numpy argmax not installed??"
    ossaudiodev = None
import struct, math, time, threading, copy,sys

def add(s1, s2):
    return minmax([(v1 + v2) for (v1, v2) in zip(s1, s2)])

def minmax(vector):
    return [min(max(v,0),255) for v in vector]

def scale(sample, value):
    return minmax([((s - 128) * value) + 128 for s in sample])

def sine(freqs, seconds, volume = 1.0, sample_rate = 8000.0):
    sample = [128] * int(sample_rate * seconds)
    if type(freqs) == type(0):
        freqs = [freqs]
    for freq in freqs:
        for n in range(len(sample)):
            sample[n] += int(127 * math.sin(n * 2 * math.pi * freq/sample_rate) * volume)
    return minmax(sample)

class SoundThread(threading.Thread):
    def __init__(self, parent, name = "sound thread"):
        threading.Thread.__init__(self, name = name)
        self.parent = parent
        self.event  = threading.Event()
        self.start()
    def run(self):
        while not self.event.isSet():
            self.parent.lock.acquire()
            buffer = copy.copy(self.parent.buffer)
            self.parent.buffer = None
            self.parent.lock.release()
            if buffer != None:
                self.parent.dev.write("".join(map(chr,buffer)))
                self.parent.dev.flush()
            self.event.wait(.001)
    def join(self, timeout=None):
        self.event.set()
        threading.Thread.join(self, timeout)
            
class SoundDevice:
    def __init__(self, device, async = 0, cache = 1):
        self.device = device
        self.async = async
        self.cache = cache
        self.cacheDict = {}
        self.status = "closed"
        self.number_of_channels= 1
        self.sample_rate= 8000
        self.sample_width= 1
        self.minFreq = 20
        self.maxFreq = 3500
        self.debug = 0
        self.buffer = None
        if ossaudiodev != None:
            self.format = ossaudiodev.AFMT_U8
            if self.debug:
                self.setFile("770.txt")
            if self.async:
                self.lock = threading.Lock()
                self.thread = SoundThread(self)

    def initialize(self, mode):
        if ossaudiodev == None: return
        self.dev = ossaudiodev.open("/dev/dsp", mode)
        self.dev.setparameters(self.format,
                              self.number_of_channels,
                              self.sample_rate)
        self.status = mode

    def play(self, sample):
        """
        """
        if ossaudiodev == None: return
        if self.status != "w":
            self.initialize("w")
        if self.async:
            self.lock.acquire()
            self.buffer = sample
            self.lock.release()
        else:
            self.dev.write("".join(map(chr,sample)))
            self.dev.flush()
        
    def playTone(self, freqs, seconds, volume = 1.0):
        """
        freq example: playTone([550,400], .1, volume=.5) # middle C for .1 seconds, half volume
        """
        if ossaudiodev == None: return
        if type(freqs) == type(0):
            freqs = [freqs]
        if self.status != "w":
            self.initialize("w")
        sample = [128] * int(self.sample_rate * seconds)
        for freq in freqs:
            if self.cache and (freq,seconds) in self.cacheDict:
                sample = self.cacheDict[(freq,seconds)]
            else:
                for n in xrange(len(sample)):
                    sample[n] = min(max(sample[n] + int(127 * math.sin(n * 2 * math.pi * freq/self.sample_rate) * volume), 0),255)
                self.cacheDict[(freq,seconds)] = sample
        if self.async:
            self.lock.acquire()
            self.buffer = sample
            self.lock.release()
        else:
            self.dev.write("".join(map(chr,sample)))
            self.dev.flush()

    def read(self, seconds):
        if ossaudiodev == None: return
        if self.status != "r":
            self.initialize("r")
        buffer = self.dev.read(int(self.sample_rate * seconds))
        size = len(buffer)
        return struct.unpack(str(size) + "B", buffer)

    def setFile(self, filename):
        if ossaudiodev == None: return
        self.filename = filename
        self.fp = open(self.filename, "r")

    def readFile(self, seconds):
        if ossaudiodev == None: return
        data = None
        try:
            data = eval(self.fp.readline())
        except:
            self.fp = open(self.filename, "r")
            try:
                data = eval(self.fp.readline())
            except:
                print "Failed reading file '%s'" % self.filename
        time.sleep(seconds)
        return data[:int(seconds * self.sample_rate)]

    def getFreq(self, seconds):
        # change to read from the buffer, rather than block
        if ossaudiodev == None: return
        if self.debug:
            #data = self.readFile(1)
            data = self.read(seconds)
        else:
            data = self.read(seconds)
        transform = fft(data)
        minFreqPos = self.minFreq
        maxFreqPos = self.maxFreq
        freq = argmax(transform[1+minFreqPos:maxFreqPos])
        value = transform[1+minFreqPos:maxFreqPos][freq]
        domFreq = (freq + self.minFreq) / seconds
        if self.debug and abs(value) > 8000 and self.minFreq < domFreq < self.maxFreq:
            print "Frequence:", domFreq, "Value:", value, "Volume:", transform[0]
        return (domFreq, value, transform[0])

    def close(self):
        if ossaudiodev == None: return
        if self.status != "closed":
            self.dev.close()
            self.status = "closed"

def dialnum(num,sd,tones):
    for a in list(num):
        sd.playTone(tones[a], 0.75)
        #time.sleep(0.15)
    return


if __name__ == "__main__":
    sd = SoundDevice("/dev/dsp", async = 0)
    tones = {'1': [697,1209],'2': [697,1336],'3': [697,1477],
             '4': [770,1209],'5': [770,1336],'6': [770,1477],
             '7': [852,1209],'8': [852,1336],'9': [852,1477],
             '*': [941,1209],'0': [941,1336],'#': [941,1477], 'r':[550]}
    dialnum(sys.argv[1],sd,tones)
    
        
## DTMF Tones

##                  1209 Hz 1336 Hz 1477 Hz 1633 Hz

##                           ABC     DEF
##    697 Hz          1       2       3       A

##                   GHI     JKL     MNO
##    770 Hz          4       5       6       B

##                   PRS     TUV     WXY
##    852 Hz          7       8       9       C

##                           oper
##    941 Hz          *       0       #       D

Adbot
ADBOT LOVES YOU

Modern Pragmatist
Aug 20, 2008
I am looking for a Python module that will allow me to generate 3D graphics but that allows a great deal of flexibility (more than visual seems to allow).

Basically what I want to do is be able to display an image or any other data in 3D space and allow the user to interact with it (rotation etc.)

Any suggestions would be appreciated.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Modern Pragmatist posted:

I am looking for a Python module that will allow me to generate 3D graphics but that allows a great deal of flexibility (more than visual seems to allow).

Basically what I want to do is be able to display an image or any other data in 3D space and allow the user to interact with it (rotation etc.)

Any suggestions would be appreciated.

pygame or pyglet, pygame is compiled mostly in C, pyglet is pure python.

Chance
Apr 28, 2002

I'm relatively new to python (and programming in general) and find myself looking for something a tiny bit more complex than IDLE. When I peruse the list of all the editing options out there the features and differences seam daunting.

All I'm looking for is basically IDLE but with tabs for multiple files, and a horizontal scroll bar at the bottom. Any suggestions?

tripwire
Nov 19, 2004

        ghost flow

Modern Pragmatist posted:

I am looking for a Python module that will allow me to generate 3D graphics but that allows a great deal of flexibility (more than visual seems to allow).

Basically what I want to do is be able to display an image or any other data in 3D space and allow the user to interact with it (rotation etc.)

Any suggestions would be appreciated.

Check out the pyopengl module if you know opengl. Pygame and pyglet can interoperate with it fairly easily.

tripwire fucked around with this message at 13:34 on Feb 6, 2009

Benji the Blade
Jun 22, 2004
Plate of shrimp.

MeramJert posted:

code:
import math, wave, array, stackless

class Sine:
         
    def __init__(self, seconds, frequency, amplitude, channel, sampleRate=44100):
        [...]
        self.data = sampleArray        
        stackless.tasklet(self.send_array)(channel)
        
    def send_array(self, channel):
        channel.send(self.data)
code:
import pyaudio, stackless

class OutStream:
    
    def __init__(self, Format=pyaudio.paInt16, Channels=1, sampleRate=44100):
        self.channel = stackless.channel()
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open([...])
        stackless.tasklet(self.listen)()
        
    def listen(self):
        while 1:
            data = self.channel.receive()
            stackless.tasklet(self.play)(data)
        
    def play(self, data):
        self.stream.write(data)
        
    def __del__(self):
        self.stream.close()
        self.p.terminate()
code:
import stackless
from Sine import *
from Output import *

output = OutStream()
output2 = OutStream()

x = Sine(1,650,75,channel=output.channel)
x = Sine(1,450,75,channel=output2.channel)

stackless.run()

Tripwire addressed the correct way to handle this from a sound perspective, but from a Stackless perspective, there's no reason your code should run concurrently. Remember that Stackless is cooperative multitasking, so in order for one tasklet to continue execution, another must give it up, either by sleeping (and letting the scheduler move on to the next tasklet) or else by blocking on a channel.

In your case, you have the Sine class send a single chunk of data over a channel to OutStream.listen, which spawns a tasklet of OutStream.play, which in turn uses a traditional blocking call (if I'm not mistaken) to write to the audio device. Once it's done, OutStream.play completes and only NOW does the Stackless scheduler kick in. And once it comes back around to the OutStream.listen that spawned the play tasklet, it'll block forever on its channel, since the sign only ever writes to that channel once.

Try instead making Sine.send_array send chunks of the data interspersed with calls to stackless.schedule() to make sure other tasklets are getting scheduled.

Basically, remember that control doesn't pass between tasklets unless you TELL it to (again, by blocking on a read to or write from a channel, sleeping, or calling stackless.schedule directly).

wrok
Mar 24, 2006

by angerbotSD

Benji the Blade posted:

Basically, remember that control doesn't pass between tasklets unless you TELL it to (again, by blocking on a read to or write from a channel, sleeping, or calling stackless.schedule directly).

This is the zen of Stackless really. When I started using it I thought I understood this, and knew what I was doing, until I found my program deadlocked (or so I thought). It quickly dawned on me (like a ton of bricks) that there is only explicit yielding and never preemptive yielding (unless you make it so). In that moment I became Stackless enlightened.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

wrok posted:

This is the zen of Stackless really. When I started using it I thought I understood this, and knew what I was doing, until I found my program deadlocked (or so I thought). It quickly dawned on me (like a ton of bricks) that there is only explicit yielding and never preemptive yielding (unless you make it so). In that moment I became Stackless enlightened.

Sort of like me with Twisted earlier this week "oh, you have to schedule deferreds". Still:

Only registered members can see post attachments!

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Whatever happened to freeze.py? I see references to it in the documentation, and it supposedly ships with Python, but it's neither on my Mac or on my CentOS test box. I need to freeze something because I wrote a script that depends on 2.6 but we don't want to install 2.6 on the machine it's going to live on.

I tried bbfeeze and cxfreeze from PyPI but they produce executables that don't have references to sqlite3.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Sock on a Fish posted:

Whatever happened to freeze.py? I see references to it in the documentation, and it supposedly ships with Python, but it's neither on my Mac or on my CentOS test box. I need to freeze something because I wrote a script that depends on 2.6 but we don't want to install 2.6 on the machine it's going to live on.

I tried bbfeeze and cxfreeze from PyPI but they produce executables that don't have references to sqlite3.

I'm not familiar with freeze, but py2app and pyinstaller/etc might work better for you

Sock on a Fish
Jul 17, 2004

What if that thing I said?

m0nk3yz posted:

I'm not familiar with freeze, but py2app and pyinstaller/etc might work better for you

Looks like pyinstaller only works up to 2.4 and py2app makes Mac binaries. I need a Linux binary.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Sock on a Fish posted:

Looks like pyinstaller only works up to 2.4 and py2app makes Mac binaries. I need a Linux binary.

What about http://cx-freeze.sourceforge.net/, freeze isn't installed with python - it's in the python svn repo in the tools directory. http://effbot.org/pyfaq/how-can-i-create-a-stand-alone-binary-from-a-python-script.htm has more information

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

Benji the Blade posted:

Tripwire addressed the correct way to handle this from a sound perspective, but from a Stackless perspective, there's no reason your code should run concurrently. Remember that Stackless is cooperative multitasking, so in order for one tasklet to continue execution, another must give it up, either by sleeping (and letting the scheduler move on to the next tasklet) or else by blocking on a channel.

In your case, you have the Sine class send a single chunk of data over a channel to OutStream.listen, which spawns a tasklet of OutStream.play, which in turn uses a traditional blocking call (if I'm not mistaken) to write to the audio device. Once it's done, OutStream.play completes and only NOW does the Stackless scheduler kick in. And once it comes back around to the OutStream.listen that spawned the play tasklet, it'll block forever on its channel, since the sign only ever writes to that channel once.

Try instead making Sine.send_array send chunks of the data interspersed with calls to stackless.schedule() to make sure other tasklets are getting scheduled.

Basically, remember that control doesn't pass between tasklets unless you TELL it to (again, by blocking on a read to or write from a channel, sleeping, or calling stackless.schedule directly).

Thanks a lot! I've already written something like what Tripwire has, but you guessed right and I was looking to do it from a stackless perspective (since the point of this project is to play around with stackless). I'll play around with this.

Id4ever
Dec 2, 2004

Sock on a Fish posted:

Looks like pyinstaller only works up to 2.4 and py2app makes Mac binaries. I need a Linux binary.

Do a svn checkout of the PyInstaller trunk, I'm pretty sure it supports both Linux and Python 2.6.

RedHasSandles
Mar 24, 2008

Woah dudes!
I am writing a python script for x-chat, and I have come to a problem I can't for the life of me figure out.

code:
__module_name__ = "helloworld" 
__module_version__ = "1.0" 
__module_description__ = "Python module example" 

import xchat
import re 

openfile = open('/Users/myname/Desktop/X-Chat Aqua/Plugins/banwords.txt', 'r')
banwords = []
banwords = openfile.readlines()

def on_join(word, word_eol, userdata):
      triggernick, triggerchannel, triggerhost = word
      destination = xchat.get_context()
      destination.command("msg " + triggernick + " Hello " + triggernick + " this is a test on " + triggerchannel)

def on_message(word, word_eol, userdata):
      i = 0
      j = len(banwords)
      while i < j:
            if re.search(banwords[i], word[1], re.I):
                  xchat.prnt("someone said " + banwords[i])
                  i = j
            else:
                  i = i + 1 

xchat.hook_print('Join', on_join)
xchat.hook_print('Channel Message', on_message)
The on_message part of my script is supposed to search messages for words from a text file. The text file has just one word on each line, but for some reason it only correctly detects the word on the last line of the text file. I have tried replacing banwords[i] with the word it is supposed to find, and it finds it no problem. Only when it gets the word from the text file it fails unless it's the last word.

Example, if the text file is
code:
hat
cat
sat
rat
it will correctly find rat, but none of the others.

ctz
Feb 6, 2003
file.readlines leaves line endings intact. Your last line may not have a line ending on leading to it magically working only on that line.

RedHasSandles
Mar 24, 2008

Woah dudes!
I figured it had something to do with the text's formatting.

How would I make this work then? I only started learning Python today, so I really don't know what I'm doing. It took me 2 hours to write what I have there and another 3 trying to fix this problem.

hey mom its 420
May 12, 2007

Why are you iterating with a while and two counters of some sort? Also, you don't have to initialize banwords to a list because it becomes a generator in the next line either way. I'd do
code:
...
banwords = (banword.strip() for banword in openfile.readlines()) #we strip the words for whitespace, which includes \n
...
def on_message(word, word_eol, userdata):
  for banword in banwords:
    if re.search(banword, word[1], re.I):
      xchat.prnt("someone said %s" % banword)
EDIT: What I used there is a generator expression in the first line. If that confuses you, this might be easier to read:
code:
...
banwords = openfile.readlines()
...
def on_message(word, word_eol, userdata):
  for banword in banwords:
    banword = banword.strip()
    if re.search(banword, word[1], re.I):
      xchat.prnt("someone said %s" % banword)
anyway, strip strips whitespace from the left and right and it's best to iterate over stuff with the for ... in construct.

hey mom its 420 fucked around with this message at 22:37 on Feb 8, 2009

RedHasSandles
Mar 24, 2008

Woah dudes!
Thanks for the help, that worked. Sorry about the messy code, it's been a while since i've scripted in anything.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
A few odd questions starting from OSX and stretching beyond:

* What state is PyCocoa / Cocoa-Python in? I was thinking about a new project, went to XCode and created a Python application. Normally the boilerplate generated by XCode results in a minimal / trivial application that works (if it does nothing), but this errored out immediately with "uncaught exception". I went to the PyCocoa pages, and they're in a state of long neglect, with apologies for no progress. Is there another up-to-date resource for the Cocoa-Python bridge?

* Which leads to another question: PyCocoa obviously calls Cocoa and Foundation libraries from within Python. But I'd like to do that from within a commandline app. (Want to use PDFKit.) Buts there's a dearth of examples. Any pointers?

* Finally, what are people using for code documentation? I've used epydoc for a long time, but Sphinx is popular lately, although it seemed to me to be a documentation tool, more than a code documentation tool.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

outlier posted:

A few odd questions starting from OSX and stretching beyond:

* What state is PyCocoa / Cocoa-Python in? I was thinking about a new project, went to XCode and created a Python application. Normally the boilerplate generated by XCode results in a minimal / trivial application that works (if it does nothing), but this errored out immediately with "uncaught exception". I went to the PyCocoa pages, and they're in a state of long neglect, with apologies for no progress. Is there another up-to-date resource for the Cocoa-Python bridge?

* Which leads to another question: PyCocoa obviously calls Cocoa and Foundation libraries from within Python. But I'd like to do that from within a commandline app. (Want to use PDFKit.) Buts there's a dearth of examples. Any pointers?

* Finally, what are people using for code documentation? I've used epydoc for a long time, but Sphinx is popular lately, although it seemed to me to be a documentation tool, more than a code documentation tool.

re pycocoa, you want to look up pyobjc, which ships with leopard and is actually nice:
http://lethain.com/entry/2008/aug/22/an-epic-introduction-to-pyobjc-and-cocoa/
http://pyobjc.sourceforge.net/NEWS-2.0.html

The website is a wreck.

Also, for API docs, I still use epydoc, sphinx is more for prose and less API

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
Note that the developer tools also ship with PyObjC examples. See /Developer/Examples/Python

wicka
Jun 28, 2007


I'm taking a Python class, and one of our assignments is to turn a list into a dictionary. We didn't think this would be hard, but then we discovered said task is listed absolutely nowhere in the book or in the lecture (but that's beside the point). Anyway, after some hard work, I basically figured it out. But here is the problem: whenever you add a new key-value pair to the dictionary, it overwrites the old one. The dictionary we are making has to assign multiple words to letter, i.e. "a" : ["apple", "air"]. So my code will add apple to the dictionary, which is great, but then overwrite it with with air. So I end up with "a" : ["air"]. Note that we've mostly learned simple poo poo, so while I'm sure there is a straightforward function for this (my brother found some poo poo with setdefault and append, but neither of us have any what is going on his program), I can't really use it. Here is my code (for the purpose of not shattering tables, I've made wlist two lines; it's not that way in the code):

code:
wlist = ["beetle", "beef", "apple", "air", "cat", "dog", "bicycle", "dig", "feet", "five", 
"kite", "goat", "high", "warm", "wolf", "hot", "xylophone", "yuk", "yum", "zoo"]
keys = ("a", "b", "c", "d", "f", "g", "h", "k", "w", "x", "y", "z")
dictionary = {}

for j in range(len(keys)):
    for i in range(len(wlist)):
        if wlist[i][0] == keys[j]:
            dictionary[keys[j]] = wlist[i]
print dictionary
Thanks.

tef
May 30, 2004

-> some l-system crap ->
code:
out = {}
for word in wlist:
    first_letter = word[0]
    if first_letter in out:
        out[first_letter].append(word)
    else
        out[first_letter] = [word]
?

wicka
Jun 28, 2007


tef posted:

code:
out = {}
for word in wlist:
    first_letter = word[0]
    if first_letter in out:
        out[first_letter].append(word)
    else
        out[first_letter] = [word]
?

Hell yes. See, your code is much better because it's not based on some godawful example from a textbook that doesn't even cover the topic. I thank you, fine sir, and I continue to find it hilarious (well, it's funny now, it was infuriating before), that the only way to solve this problem is to use a function (.append) that we were not taught.

Note: I will probably be in here later tonight and tomorrow, because there are two more problems yet to complete and we were taught none of them.

wicka fucked around with this message at 06:39 on Feb 10, 2009

wicka
Jun 28, 2007


OK, gently caress it, here's the next one. We need to take a list of numbers and sort them using an insertion sorting algorithm. I kid you not, she told us to read the Wikipedia article and figure it out. This is the fourth loving week. So, basically, if anyone can write an insertion sorting algorithm in Python, that be fantastic.

yippee cahier
Mar 28, 2005

To help your brother out, here's the dict.setdefault function:
code:
>>> help(dict.setdefault)
Help on method_descriptor:

setdefault(...)
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
so essentially the same thing as that if-else statement can be accomplished in one line.

code:
for word in wlist:
    out.setdefault(word[0],[word]).append(word)
You could also use a collections.defaultdict to have this done automatically for you, but if you're just a beginner just remember in the future that the standard library probably has a solution for whatever problem you're facing.

edit:
If you weren't taught list.append(), maybe you've seen the + operator when used with lists which does the same thing as list.extend():
code:
        out[first_letter] = out[first_letter] + [word]
read the help for these functions or a python tutorial that covers collections

yippee cahier fucked around with this message at 06:57 on Feb 10, 2009

yippee cahier
Mar 28, 2005

wicka posted:

OK, gently caress it, here's the next one. We need to take a list of numbers and sort them using an insertion sorting algorithm. I kid you not, she told us to read the Wikipedia article and figure it out. This is the fourth loving week. So, basically, if anyone can write an insertion sorting algorithm in Python, that be fantastic.

Have you tried reading the wikipedia article? Use their example of sorting a deck of cards. Get a deck of cards and puzzle out the algorithm. Think about what you're iterating over as you sort the cards. Take a look at the .pop(index) and .insert(index, item) functions. Do your own homework.

wicka
Jun 28, 2007


sund posted:

edit:
If you weren't taught list.append(), maybe you've seen the + operator when used with lists which does the same thing as list.extend():
code:
        out[first_letter] = out[first_letter] + [word]
read the help for these functions or a python tutorial that covers collections

I had an inkling I could so something with the + operator, but I tried one way and it didn't work so I tried other routes. Also, the section of my textbook that covers this literally says "if you add a term to a key that already exists, the old term is overwritten," but offers no way to get around this, or even the suggestion that it is possible.

sund posted:

Have you tried reading the wikipedia article? Use their example of sorting a deck of cards. Get a deck of cards and puzzle out the algorithm. Think about what you're iterating over as you sort the cards. Take a look at the .pop(index) and .insert(index, item) functions. Do your own homework.

I'd love to. I did the other three chapters just by figuring it out on my own. The problem is that they've started giving us problems that aren't even remotely covered in the material. I know you are assuming that I just don't want to do my own work, which is understandable, but it's really quite ridiculous the poo poo they are giving us. If you can think of it like a math class you'd understand how frustrated I am; you wouldn't expect your fourth week in a stats class to be covering hypothesis testing.

wicka fucked around with this message at 07:46 on Feb 10, 2009

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

wicka posted:

Hell yes. See, your code is much better because it's not based on some godawful example from a textbook that doesn't even cover the topic. I thank you, fine sir, and I continue to find it hilarious (well, it's funny now, it was infuriating before), that the only way to solve this problem is to use a function (.append) that we were not taught.

Note: I will probably be in here later tonight and tomorrow, because there are two more problems yet to complete and we were taught none of them.

You are the reason I read through a list of resumes looking for the people who taught themselves instead of paying an institution for a piece of paper that certifies, correctly or not, that they are not useless.

wicka
Jun 28, 2007


A A 2 3 5 8 K posted:

You are the reason I read through a list of resumes looking for the people who taught themselves instead of paying an institution for a piece of paper that certifies, correctly or not, that they are not useless.

Thanks, I appreciate your valuable assertion that I should not expect the motherfuckers I pay thousands of dollars to actually teach me anything.

By the way, there were three problems that we weren't taught, I figured out two of them myself. So gently caress you.

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

wicka posted:

Thanks, I appreciate your valuable assertion that I should not expect the motherfuckers I pay thousands of dollars to actually teach me anything.

By the way, there were three problems that we weren't taught, I figured out two of them myself. So gently caress you.

So you believe your role as a student is to know only the material that you've been handheld through, and you're "infuriated" by the notion that you were expected to do a small amount of original research instead of regurgitating only that subset of all knowledge that fits in the first four weeks of your syllabus.

For your own good, you should know it's going to get harder and the problems you'll need to solve will involve increasingly less of what you've been explicitly taught and more research and creativity.

wicka
Jun 28, 2007


A A 2 3 5 8 K posted:

So you believe your role as a student is to know only the material that you've been handheld through, and you're "infuriated" by the notion that you were expected to do a small amount of original research instead of regurgitating only that subset of all knowledge that fits in the first four weeks of your syllabus.

For your own good, you should know it's going to get harder and the problems you'll need to solve will involve increasingly less of what you've been explicitly taught and more research and creativity.

The format of our class is basically: read this chapter -> write these programs. The point is to apply the knowledge you've learned, not spend an hour Googling poo poo you don't understand. If you read a chapter of a history textbook and have the answer the questions at the end, the answers can be gleaned from that chapter. They aren't going to talk about Fort Sumter and then ask you when Sherman began his march to the sea; that would be absurd.

My problem here is not that I was required to do research to finish a program, but rather that I'm not supposed to have to (except for the case of the insertion sorting, obviously). I have no problem with using .append, it's just that I'm going to get my programs graded and it's going say "good job, except where did you learn .append, you are supposed to do it x way." I've done it, but I haven't done it "the right way," because the right way hasn't been taught.

You have to understand, at this stage we aren't just learning how to write a specific program, we're learning how to write a program using what we've learned from the chapter. Early on, when we were learning loops, there were problems that were made much more complicated because you had to use certain kinds of loops. People would search up answers, and while they were much simpler (oh and yaaaay they were creative and did it themselves!) it's still not right because they didn't learn poo poo about loops in the process.

You know what? It's a lot like the professor is giving out assignments from the last professor, but using her own slides, so there is a disconnect between the two.

wicka fucked around with this message at 08:23 on Feb 10, 2009

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?

wicka posted:

The format of our class is basically: read this chapter -> write these programs.

Why do you pay for both the book and the class if you only need the book?

quote:

My problem here is not that I was required to do research to finish a program, but rather that I'm not supposed to have to (except for the case of the insertion sorting, obviously). I have no problem with using .append, it's just that I'm going to get my programs graded and it's going say "good job, except where did you learn .append, you are supposed to do it x way." I've done it, but I haven't done it "the right way," because the right way hasn't been taught.

In the unlikely case you're right and the homework was impossible given the content of the chapter, you're off the hook on that constraint and free to figure it out yourself instead on relying on others. Which is a much greater approximation of software development, or really, any career.

quote:

You know what? It's a lot like the professor is giving out assignments from the last professor, but using her own slides, so there is a disconnect between the two.

What school do you go to and what's the email address of your professor? I'd be interested to hear her side of why independent study is forbidden.

moostaffa
Apr 2, 2008

People always ask me about Toad, It's fantastic. Let me tell you about Toad. I do very well with Toad. I love Toad. No one loves Toad more than me, BELIEVE ME. Toad loves me. I have the best Toad.
I am a complete noob to Python, but I'm about to start learning it.. I thought my first project would be a GeoIP lookup using the MaxMind GeoIP Organization db, but I cannot figure out how to install the module on winxp :(

Could anyone point me in the right direction on how to do this, since the documentation doesn't say anything about how to do it.

wicka
Jun 28, 2007


A A 2 3 5 8 K posted:

Why do you pay for both the book and the class if you only need the book?

:psyduck: Unfortunately when you are signing up for a class there isn't a notice saying "warning: lecture is useless."

A A 2 3 5 8 K posted:

What school do you go to and what's the email address of your professor? I'd be interested to hear her side of why independent study is forbidden.

It's not forbidden, it's just pointless because you're supposed to solve problems based on what you've been given. You're not just learning Python, you're learning a class about Python. I could look up all sorts of other ways to finish my programs, but that's not going to help me at all on the midterm.

Modern Pragmatist
Aug 20, 2008

wicka posted:

It's not forbidden, it's just pointless because you're supposed to solve problems based on what you've been given. You're not just learning Python, you're learning a class about Python. I could look up all sorts of other ways to finish my programs, but that's not going to help me at all on the midterm.

Based on your statements, you are ONLY trying to learn the CLASS about Python. You have to think outside of the box for Python and programming in general. You can look up how to solve your own problems by googling around for hours (that's part of the learning process) and INCORPORATE what you learned in class and not rely solely upon everything that you have been spoon-fed.

If you want to come out with both a good grade in the class and a half-rear end understanding of python, I recommend you grow some balls and learn to figure out the tough problems on your own.

I would be really interested to know:
a) the school you go to
b) what year you are

EDIT: If you look back at the responses you got to your questions. Nothing was "out of the scope" of your class. You just needed to spend more time thinking through it.

Modern Pragmatist fucked around with this message at 16:16 on Feb 10, 2009

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
But us doing your homework will help you on the midterm?

wicka
Jun 28, 2007


Of course I'm trying to learn the class. Learning Python isn't my problem, learning the class is. Like I said, I can easily find lots of ways to write the assigned programs, but that doesn't help me one bit in the class. What I don't think you guys understand is this: we're not trying to write the best program, we're trying to write a program using a specific technique so we understand that technique well. You're not always graded on whether or not you solved the problem, but how you solved the problem. Like that insertion sort algorithm (which I did, by the way); the point of that program is to sort a list. So, I COULD just use the sort function, and it'd be a two line program and the list would be sorted. But I wouldn't get any points because I learned nothing about insertion sorting.

Lord Uffenham posted:

But us doing your homework will help you on the midterm?

Of course it would, because then I would actually know how to do it. I'm not just copying and pasting poo poo here, if someone gives me code I can figure out how it works.

vvv Thank christ.

wicka fucked around with this message at 17:14 on Feb 10, 2009

Adbot
ADBOT LOVES YOU

ahobday
Apr 19, 2007

wicka posted:

Of course I'm trying to learn the class. Learning Python isn't my problem, learning the class is. Like I said, I can easily find lots of ways to write the assigned programs, but that doesn't help me one bit in the class. What I don't think you guys understand is this: we're not trying to write the best program, we're trying to write a program using a specific technique so we understand that technique well. You're not always graded on whether or not you solved the problem, but how you solved the problem. Like that insertion sort algorithm (which I did, by the way); the point of that program is to sort a list. So, I COULD just use the sort function, and it'd be a two line program and the list would be sorted. But I wouldn't get any points because I learned nothing about insertion sorting.


Of course it would, because then I would actually know how to do it. I'm not just copying and pasting poo poo here, if someone gives me code I can figure out how it works.

I understand this pretty well. You're expected to use a method they taught you in class to solve the problem.

  • Locked thread