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
TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

A A 2 3 5 8 K posted:

Some sorts of invalid pages. When you have a database of 400,000 links from all different sources you want to parse, you will find much more that can go wrong with HTML than the authors of any of these packages considered.
HTML5 was designed with rules on how to deal with invalid pages, which are in large part simply documenting existing browser behavior. Assuming the page renders in a browser, it can almost certainly be parsed by an HTML5 parser into a reasonable parse tree, and from there can be processed by BeautifulSoup.

Adbot
ADBOT LOVES YOU

awesomepanda
Dec 26, 2005

The good life, as i concieve it, is a happy life.
hi again guys,

can someone tell me why the following expression is incorrect

listr= [[1,2],[1,3]]

newlistr = [lis.append(3) for lis in listr]

i understand the proper way to build the list im intending on is to use

lis + [3] and not lis.append(3)

but why cant i use the property of an object with a list expression? thanks!

and why do i get [none, none] as a result.

king_kilr
May 25, 2007
See the discussion on immutable and mutable objects. list.append modifies the original object and doesn't return anything (None).

No Safe Word
Feb 26, 2005

CrazyPanda posted:

hi again guys,

can someone tell me why the following expression is incorrect

listr= [[1,2],[1,3]]

newlistr = [lis.append(3) for lis in listr]

i understand the proper way to build the list im intending on is to use

lis + [3] and not lis.append(3)

but why cant i use the property of an object with a list expression? thanks!

and why do i get [none, none] as a result.
Because the result of lis.append is None, always. seq.append is done in-place on that sequence object and returns None.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

CrazyPanda posted:

hi again guys,
You know the correct method to concatenate lists, but want to know why the wrong method gives the wrong result?

What?

Soviet Space Dog
May 7, 2009
Unicum Space Dog
May 6, 2009

NOBODY WILL REALIZE MY POSTS ARE SHIT NOW THAT MY NAME IS PURPLE :smug:
Because MyList.append(x) doesn't return a new list equal to MyList with an x on the end, it returns None and alters MyList by putting an x on the end.

>>> listr= [[1,2],[1,3]]
>>> newlistr = [lis.append(3) for lis in listr]
>>> newlistr
[None, None]
>>> listr
[[1, 2, 3], [1, 3, 3]]

If that doesn't make sense, try to think of it this way:
When you use lis + [3], you are asking the computer to figure out what lis with 3 on the end would be. "+" is a function, with two inputs and an output. You can then save this output value somewhere, by making a new list in memory. In your example (when you use lis + [3]) you are saving this output as elements of newlistr.
When you use lis.append(3), you are telling the computer to change lis by putting a 3 on the end. This returns None, because it is a command to lis to change itself, not a request for a new list. What you are saving to newlistr is the return values of the command, which is None.

duck monster
Dec 15, 2004

A A 2 3 5 8 K posted:

Some sorts of invalid pages. When you have a database of 400,000 links from all different sources you want to parse, you will find much more that can go wrong with HTML than the authors of any of these packages considered.

word. I worked at a company that spidered about 300 sites daily and grabbed details of specials and poo poo , reformetted them, added the markup and published it. The thing ran on a cluster of 5 machines each running a python script with about 400 microthreads (using stackless) and all using beautiful soup , and god drat is there some horrifying HTML out there.

Also a 400 thread spider can rape almost any given site to a smouldering mess in a fraction of a second. Don't do this, but god drat the structure of that thing was fun to write. The actual scrapers however made me hate my life.

tef
May 30, 2004

-> some l-system crap ->

duck monster posted:

The actual scrapers however made me hate my life.

Oh god yes writing scrapers continually is a nightmare.

Zombywuf
Mar 29, 2008

I actually prefer writing web scrapers to working with Webservice XML APIs. The tag soup HTML madness is usually nicer that APIs that are just some websites data backed with "<xml>" stuck at the front and "</xml>" tacked on the end.

But yeah, writing frameworks to write scrapers in is way more fun than the actual scrapers.

Balam
Dec 12, 2006
His royal newbness checking in.
Trying to do an exercise from a book with class.
Basically the program is it draws a card randomly and tells you what number and suit, but I am having some trouble with it. Here is what I have so far, I know it is wrong, but I am not sure what I am doing wrong:

code:
from random import choice as rc

class Cards:
    def __init__(self, rank, suit):
        rank = (1,2,3,4,5,6,7,8,9,10,11,12,13)
        suit = ("Diamonds","Clubs","Hearts","Spades")
        
    def getRank(self):
        self.rank = rc(self.rank)
        return self.rank
    def getSuit(self):
        self.suit = rc(self.suit)
        return self.suit
    
def main():
    rank1 = getRank()
    print rank1
    suit1 = getSuit()
    print suit1



main()
and here is the error I get.

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import cards
File "/Users/Jimmy/Documents/cards.py", line 22, in <module>
main()
File "/Users/Jimmy/Documents/cards.py", line 19, in main
rank1 = getRank()
NameError: global name 'getRank' is not defined

thanks for taking a look.

Edit: Added code tags for clarity! Thanks for the suggestion.

Balam fucked around with this message at 16:44 on Jun 13, 2009

ahobday
Apr 19, 2007

You might want to put that code in [code][/ code] tags so that we can see how it is indented. Are those defs part of the class or separate, for example.

nbv4
Aug 21, 2002

by Duchess Gummybuns

Balam posted:

His royal newbness checking in.

Hint: You're not calling the constructor. No Cards objects are being created. getRank() is a method on the Cards class. It can only be called on a Card object. There is no card object.

duck monster
Dec 15, 2004

Zombywuf posted:

I actually prefer writing web scrapers to working with Webservice XML APIs. The tag soup HTML madness is usually nicer that APIs that are just some websites data backed with "<xml>" stuck at the front and "</xml>" tacked on the end.

But yeah, writing frameworks to write scrapers in is way more fun than the actual scrapers.

All I can say is beautiful soup saved my sanity.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Balam posted:

His royal newbness checking in.
Trying to do an exercise from a book with class.
Basically the program is it draws a card randomly and tells you what number and suit, but I am having some trouble with it. Here is what I have so far, I know it is wrong, but I am not sure what I am doing wrong:

like nbv4 said, you need to instantiate the class to use its methods. Fore main(), try this:

code:
def main():
    c = Cards()
    rank = c.getRank()
    suit = c.getSuit()
    print rank
    print suit
Also, the convention for calling a main() function like that is usually the following:
code:
if __name__ == '__main__':
    main()
The reason for this is that you want your code to be "import safe". If you wanted to import your module into some other module to use the Cards class, as it stands, it would call main whenever you did so. The if statement makes it so that main is only run if you are directly running this module.

hlfrk414
Dec 31, 2008
There is more than one problem with that example. Its a poor example of classes anyways. Why didn't anyone point out that getting rank or suit REPLACES a Card instance's rank or suit with the randomly chosen rank or suit. Or the fact the init does not assign anything to self? Or that init does nothing with the given rank and suit, just replaces them.

This site seems to have a decent introduction to classes in python.

Here would be a better(?) example of a card deck class in python.

code:
import random

class Cards:
	"""Represents a deck of cards.
	
	This class allows you to make a deck
	that can remove cards, shuffle cards,
	and insert cards."""

	def __init__(self, ranks=None, suits=None):
		"""makes one deck of cards, in order"""
		self.ranks = list(range(1,14)) if ranks is None else list(ranks)
		
		self.suits = ["Diamonds","Clubs","Hearts","Spades"] if suits is None else list(suits)
		self.cards = [(suit, rank) for suit in self.suits for rank in self.ranks]

	def shuffle(self):
		"""shuffles remaining cards"""
		random.shuffle(self.cards)

	def remove_card(self):
		"""remove the 'top' card. 'Top' in this case is the last thing
		in the list but only we need to know that. 
		Pops last card from cards"""
		return self.cards.pop()

	def insert_card(self, card, index=0):
		"""place the card at the given index. Defaults to the 'bottom'
		of the deck."""
		self.cards.insert(index, card)
	
def main():
	#get a new deck
	c = Cards()
	print 'This is the starting deck:'
	print c.cards
	c.shuffle()
	print
	print 'shuffled deck:'
	print c.cards

	print

	print 'here is a card from the "top" of the deck:'
	card = c.remove_card()
	print card

	print 'putting card back into deck, now its at the "bottom"'
	c.insert_card(card)
	
	print
	print c.cards

if __name__ == '__main__':
	#called only when run as the starting module
	main()

hlfrk414 fucked around with this message at 00:32 on Jun 14, 2009

Balam
Dec 12, 2006
Thanks for all the help guys. I guess "class" is something that really takes a while to learn so I am going to keep looking over it.
One question for hlfrk414, what does this section of the code do?
code:
if ranks is None else list(ranks)
if suits is None else list(suits)
...and one problem, when I enter your code it gives me this error.
code:
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    cards.main()
  File "/Users/Jimmy/Documents/cards.py", line 31, in main
  File "/Users/Jimmy/Documents/cards.py", line 14, in __init__
    self.suits = ["Diamonds","Clubs","Hearts","Spades"] if suits is None else list(suits)
TypeError: argument of type 'NoneType' is not iterable
Thank you again!

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
That section checks if a custom set of ranks/suites is defined. "Why" would be a better question -- just in case a fifth suite is added later?

His code is a bit bizarre, I would do it like this:

code:
import random

class Card:
	def __init__ (self, suite, rank):
		self.suite = suite
		self.rank = rank
		
class Deck:
	def __init__ (self):
		ranks = range (1, 14) # 1 to 13
		suites = ["Diamonds", "Clovers", "Hearts", "Spades"]
		
		# Two different ways to do build cards. They are equivalent;
		# the first way would be best to use, but I include the second
		# to demonstrate what operations are being performed
		
		# 1. List comprehension
		# http://docs.python.org/tutorial/datastructures.html#list-comprehensions
		self.cards = [Card (suit, rank) for suit in suites for rank in ranks]
		
		# 2. Manual list building
		self.cards = []
		for suite in suites:
			for rank in ranks:
				self.cards.append (Card (suite, rank))
				
	def pick (self):
		return random.choice (self.cards)
		
def main ():
	deck = Deck ()
	card = deck.pick ()
	print "Picked %s of %s" % (card.rank, card.suite)
	
if __name__ == "__main__": main ()

tef
May 30, 2004

-> some l-system crap ->
Aside: http://docs.python.org/dev/py3k/whatsnew/3.1.html

quote:

Enabling a configure option named --with-computed-gotos on compilers that support it (notably: gcc, SunPro, icc), the bytecode evaluation loop is compiled with a new dispatch mechanism which gives speedups of up to 20%, depending on the system, the compiler, and the benchmark.

Anyone know if this is getting backported ? :toot:

hlfrk414
Dec 31, 2008
I considered adding a card class, but since there were no methods to add to it, it seemed unnecessary. Almost java-like to make a class for pure data, and just use it with 'getters'. I took in a possible rank and suit to show how we could use custom decks, but it does complicate it a bit.

My code seems a bit odd because I wanted to represent a deck as something separate from individual cards, where cards could be added, removed, and moved as needed. Custom decks and suits can be used trivially, either to allow different suit names, or more complicated stuff. Randomly choosing a card seems wrong to me, since any game using cards removes the cards, not allowing them to be chosen again, unlike your example. Still, it isn't a very good example a classes, the link I provided goes over classes better than me.

If I remember right, the speedup option will not be back-ported because it changes how the interpreter works, breaking compatibility with older versions.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

hlfrk414 posted:

I considered adding a card class, but since there were no methods to add to it, it seemed unnecessary. Almost java-like to make a class for pure data, and just use it with 'getters'. I took in a possible rank and suit to show how we could use custom decks, but it does complicate it a bit.
There's nothing wrong with a data-only class; it helps document what attributes are expected, and is easier to extend in the future than a tuple. I prefer `namedtuple` as a nice compromise between data-modeling and brevity, but that's only in versions 2.6 and higher; data classes are almost as good.

king_kilr
May 25, 2007

tef posted:

Aside: http://docs.python.org/dev/py3k/whatsnew/3.1.html


Anyone know if this is getting backported ? :toot:

No, it hasn't. It is in unladen swallow for what it's worth.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


I've done something stupid but for the life of me I can't figure out what.

code:
#!/bin/env python

import sys, re
from os import popen
from optparse import OptionParser

class Process(object):
    def __init__(self, pid, ppid, etime, cmd):
        self.pid = pid
        self.ppid = ppid
        self.etime = etime
        self.cmd = cmd

class JavaProcess(Process):
    def __init__(self, pid, ppid, etime, cmd):
        super(JavaProcess, self).__init__(pid, ppid, etime, cmd)

        for key, string in [('instance','weblogic.Name=(.*?) '), ('jvm','/opt/bea/(.*?)/bin/java'), ('weblogic','wls.home=/opt/bea/(.*?)/server')]:
            temp = re.compile(string).findall(self.cmd)
            if temp:
                setattr(self, key, temp[0])
            else:
                setattr(self, key, '-')


class ProcessList(dict):
    def __init__(self):
        self.refresh()
        print self

    def refresh(self, top=True):
        self = {}

        #do a `ps` and turn output lines into processes
        ps = popen('ps axww -o "pid ppid etime args" | grep java | grep -v grep','r').read()
        ps = ps.split('\n')[:-1]

        for line in ps:
            pid, ppid, etime, cmd = line.split()[:3] + [' '.join(line.split()[3:])]
            self[pid] = JavaProcess(pid, ppid, etime, cmd)

        #get cpu and memory usage data from `top`
        if top:
            top_output = popen('top bn1 | grep java','r').read()
            top_output = top_output.split('\n')[:-1]

            for line in top_output:
                line = line.lstrip().rstrip().split()
                if self.has_key(line[0]):
                    setattr(self[line[0]], 'tcpu', line[8])
                    setattr(self[line[0]], 'tmem', line[9])

        #determine whether or not a pid is a parent process
        #only matters when java threads are shown as individual processes
        def _setParent(pid):
            if self[pid].ppid in self.keys():
                _setParent(self[pid].ppid)
                setattr(self[pid], 'parent', False)
            else:
                setattr(self[pid], 'parent', True)

        for pid in self.keys():
            _setParent(pid)


def main(argv=sys.argv[1:]):
    parser = OptionParser(usage="usage: %prog [options] <list of instances or pids>", version="%prog 2.0")
    parser.add_option('-a', '--all', action='store_true', default=False, dest='all', help='show all pids, displays threads and child processes')
    parser.add_option('-p', '--pipe', action='store_true', default=False, dest='pipe', help='display output in pipe-delimited format')
    options, arguments = parser.parse_args(argv)

    process_list = ProcessList()

    if options.pipe:
        lineout = '%(pid)s|%(etime)s|%(tcpu)s|%(tmem)s|%(instance)s'
    else:
        print 'PID     Uptime       %CPU %MEM Instance                              '
        print '------- ------------ ---- ---- --------------------------------------'
        lineout = '%(pid)-7s %(etime)12s %(tcpu)4s %(tmem)4s %(instance)-38s'

    for p in process_list:
        if options.all:
            print lineout % process_list[p]
        elif p.parent:
            print lineout % process_list[p]


if __name__=='__main__':
    main()
The variable "self" is what it should be in ProcessList.refresh() but after invoking the method, self is an empty dictionary. I did something dumb but I don't know what.

deedee megadoodoo fucked around with this message at 17:12 on Jun 14, 2009

tef
May 30, 2004

-> some l-system crap ->

HatfulOfHollow posted:

code:

class ProcessList(dict):
    def __init__(self):
        self.refresh()
        print self

    def refresh(self, top=True):
        self = {}

I don't think self = {} does what you think it does

code:
>>> foo = {}
>>> def whatdoyouthinkyouaredoing(obj):
...     obj = {}
...     obj['a'] = 'b'
...     print obj
... 
>>> whatdoyouthinkyouaredoing(foo)
{'a': 'b'}
>>> foo
{}
>>> def ithinkyoumeanthis(obj):
...     obj.clear()
...     obj['a'] = 'b'
...     print obj
... 
>>> ithinkyoumeanthis(foo)
{'a': 'b'}
>>> foo
{'a': 'b'}
>>> 

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


tef posted:

I don't think self = {} does what you think it does

code:
>>> foo = {}
>>> def whatdoyouthinkyouaredoing(obj):
...     obj = {}
...     obj['a'] = 'b'
...     print obj
... 
>>> whatdoyouthinkyouaredoing(foo)
{'a': 'b'}
>>> foo
{}
>>> def ithinkyoumeanthis(obj):
...     obj.clear()
...     obj['a'] = 'b'
...     print obj
... 
>>> ithinkyoumeanthis(foo)
{'a': 'b'}
>>> foo
{'a': 'b'}
>>> 


poo poo. You're right. I was trying to empty the ProcessList dict and hosed myself.

Pie Colony
Dec 8, 2006
I AM SUCH A FUCKUP THAT I CAN'T EVEN POST IN AN E/N THREAD I STARTED
This may be a stupid question but the one thing I don't like about teaching myself a language vs. taking a class is that you never have an opportunity to make sample programs, something that I feel really helps me in reinforcing the education. Is there like a collection or list or something of small programming assignments designed to test your knowledge?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Pie Colony posted:

This may be a stupid question but the one thing I don't like about teaching myself a language vs. taking a class is that you never have an opportunity to make sample programs, something that I feel really helps me in reinforcing the education. Is there like a collection or list or something of small programming assignments designed to test your knowledge?

There are dozens of such lists. Project Euler is one. The contents of any tutorial book is another.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Pie Colony posted:

This may be a stupid question but the one thing I don't like about teaching myself a language vs. taking a class is that you never have an opportunity to make sample programs, something that I feel really helps me in reinforcing the education. Is there like a collection or list or something of small programming assignments designed to test your knowledge?

http://projecteuler.net/
http://codekata.com/
http://forums.somethingawful.com/showthread.php?threadid=2415898

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Pie Colony posted:

This may be a stupid question but the one thing I don't like about teaching myself a language vs. taking a class is that you never have an opportunity to make sample programs, something that I feel really helps me in reinforcing the education. Is there like a collection or list or something of small programming assignments designed to test your knowledge?

Check out the python forums: http://python-forum.org/pythonforum/index.php

My education was just opening up already built programs, trying to understand them, then coding my own additions and seeing if I could get it to work. Its fun, you get to see how other people code, as well as code yourself, and you even get something useful at the end of it.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
An odd problem: I'm writing a quick-and-dirty cgi script in python and I can't import a whole bunch of modules.

In more detail: one or two things in site-packages are being seen. The other 30 or so aren't (as determined by looking at sys.path). I thought maybe it was easyinstall and eggs but an egg is one of things that are being seen. Actually an old version of SQLAlchemy is being picked up while newer versions are being ignored. I'm sure I'm calling the right version of Python. Ideas?

Foiltha
Jun 12, 2008
Any suggestions for a free decent UML tool, aimed at Python in particular? Code generation would be a plus.

duck monster
Dec 15, 2004

Foiltha posted:

Any suggestions for a free decent UML tool, aimed at Python in particular? Code generation would be a plus.

Boa Constructor will generate UML diagrams from code. Dia2Py (or is it Dia2Django) will generate Django models from DIA UML.

Which is to say DIA generates pretty cool UML.

bitprophet
Jul 22, 2004
Taco Defender

outlier posted:

An odd problem: I'm writing a quick-and-dirty cgi script in python and I can't import a whole bunch of modules.

In more detail: one or two things in site-packages are being seen. The other 30 or so aren't (as determined by looking at sys.path). I thought maybe it was easyinstall and eggs but an egg is one of things that are being seen. Actually an old version of SQLAlchemy is being picked up while newer versions are being ignored. I'm sure I'm calling the right version of Python. Ideas?

What OS/version?

Offhand guess: permissions issues? could the ones not being imported not be fully readable by the executing user?

Otherwise, it's pretty much got to be something where you're not ACTUALLY looking at the right site-packages, though iirc sys.path should be showing you full absolute file paths, which would make that pretty unambiguous.

Lord Purple
Mar 7, 2006

Remove your eyes...
I am trying to write a python program to manage music and I am thinking about creating a "music library" type mini-database inside of the program. Does anybody know of a good python library that handles this kind of thing or a good approach to this?

No Safe Word
Feb 26, 2005

scrabbleship posted:

I am trying to write a python program to manage music and I am thinking about creating a "music library" type mini-database inside of the program. Does anybody know of a good python library that handles this kind of thing or a good approach to this?

Absolutely

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

bitprophet posted:

What OS/version?

Offhand guess: permissions issues? could the ones not being imported not be fully readable by the executing user?

Otherwise, it's pretty much got to be something where you're not ACTUALLY looking at the right site-packages, though iirc sys.path should be showing you full absolute file paths, which would make that pretty unambiguous.

OSX10.5, Python 2.5.2.

I've got a working solution, although the root problem is still unclear. I pointed the cgi script directly at the python interpreter in question (i.e. using the full path) and that means most of the other modules are being picked up. (Note: most. And I was certainly calling the same interpreter. Hmmm,)

Haven't found the common link as yet to the non-loading ones, although I have discovered that (logically) modules installed with "setup.py develop" don't load.

Balam
Dec 12, 2006
This is a little program I wrote to emulate n number games of Craps and tells you how many times you win or lose. If I emulate just one game there is no problem but anything more and it seems like it is looping infinitely, I can't seem to resolve this.
code:
from random import randrange

def main():
    n = input("How many games would you like to simulate? ")
    for i in range(n):
        die1 = randrange(1, 7)
        die2 = randrange(1, 7)
        value1 = die1 + die2
        wins = loses = 0
        if value1 == 7 or value1 == 11:
            wins = wins + 1
        elif value1 == 2 or value1 == 3 or value1 == 12:
            loses = loses + 1
        else:
            value2 = 0
            while value2 != value1 or value2 != 7:
                die1 = randrange(1, 7)
                die2 = randrange(1, 7)
                value2 = die1 + die2
            if value2 == value1:
                wins = wins + 1
            elif value2 == 7:
                loses = loses + 1

    print wins, loses
The problem seems to be the while section, but I can't figure it out.

spankweasel
Jan 4, 2006

Balam posted:

This is a little program I wrote to emulate n number games of Craps and tells you how many times you win or lose. If I emulate just one game there is no problem but anything more and it seems like it is looping infinitely, I can't seem to resolve this.
code:
from random import randrange

def main():
    n = input("How many games would you like to simulate? ")
    for i in range(n):
        die1 = randrange(1, 7)
        die2 = randrange(1, 7)
        value1 = die1 + die2
        wins = loses = 0
        if value1 == 7 or value1 == 11:
            wins = wins + 1
        elif value1 == 2 or value1 == 3 or value1 == 12:
            loses = loses + 1
        else:
            value2 = 0
            while value2 != value1 or value2 != 7:
                die1 = randrange(1, 7)
                die2 = randrange(1, 7)
                value2 = die1 + die2
            if value2 == value1:
                wins = wins + 1
            elif value2 == 7:
                loses = loses + 1

    print wins, loses
The problem seems to be the while section, but I can't figure it out.

If value2 comes up 7, you'll still continue through the while loop since you have an "or" statement there.

Try changing the while statement to:

code:
while value2 != value1:
and stick a break in the elif:

code:
elif value2 == 7:
    loses += 1
    break

Balam
Dec 12, 2006
ok, I fixed it spankweasel and it works well. I did find another problem too. Wins and Loses never got above one, no matter how many games played because I was defining them both as 0 within in the loop so each time it would go around and reset their values to zero.

edit: spellcheck.

duck monster
Dec 15, 2004

I still draw up little truth tables as soon as a logical operation looks like its going to have more than 3 or 4 terms

Adbot
ADBOT LOVES YOU

pankus
Jul 30, 2003
Does anyone have some experience with numpy? I'm trying to copy a 2-dimensional array into a third dimension. I was wondering if there was a more efficient way to do what I am currently doing:
code:
calCCzExp = np.dstack( np.array( self.vinCount*[calCCz] ))
calCCz has dimensions [6,5]; calCCzExp has dimensions [6,5,25].

  • Locked thread