Tom Musgrove | 1 Jun 2004 01:47
Picon
Favicon

list comprehension question

Hi,

I'm writing some code that takes two meshes, an original, and an altered 
mesh.  Finds the added and deleted edges/vertices.  And then modifiys a list 
of targets that were applied to the original mesh and modifies them to have 
the same behavior on the altered mesh.  (Ie the targets are mesh 
deformations for specified vertices, but the new mesh might have new 
vertices that need to be interpolated, or vertices that have been deleted, 
or moved, etc.)

I have two lists of keys that I have from creating edge dictionaries for the 
altered and original mesh, then using list comprehension to find the unique 
edges. giving, for instance, the following.

ListAUniqueEdges = {(1,5), (2,6), (3,7), (8,9)}
ListBUniqueEdges = {(2,7), (3,5), (1,6), (10,11)}

I need to create two dictionaries from the above, showing how the edges from 
lista relate to those in listb and vice versa, ie the resulting Dict would 
be

DictA = {(1,5): {(1,6), (3,5)}, (2,6): {(2,7), (1,6)}, (3,7): {(3,5), 
(2,7)}, (8,9):{}}

is there some elegant way to do this, I think it should be doable via list 
comprehension, but for some reason I can't think of the solution right now, 
and the power of google isn't helping...

Thanks,

(Continue reading)

Blake Winton | 1 Jun 2004 22:05
Picon
Gravatar

RE: list comprehension question

> I have two lists of keys that I have from creating edge 
> dictionaries for the altered and original mesh, then
> using list comprehension to find the unique edges.
> giving, for instance, the following.
> 
> ListAUniqueEdges = {(1,5), (2,6), (3,7), (8,9)}
> ListBUniqueEdges = {(2,7), (3,5), (1,6), (10,11)}

Just one question, you have those listed as dictionaries, but
I've found it easier to work with if I converted them to lists.
i.e.:
ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)]
ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)]

Was that a typo?

> I need to create two dictionaries from the above, showing
> how the edges from lista relate to those in listb and vice
> versa, ie the resulting Dict would be
> 
> DictA = {(1,5): {(1,6), (3,5)}, (2,6): {(2,7), (1,6)},
> (3,7): {(3,5), (2,7)}, (8,9):{}}
> 
> is there some elegant way to do this, I think it should
> be doable via list comprehension, but for some reason I
> can't think of the solution right now, and the power of
> google isn't helping...

I can do it with a list comprehension, but I'ld like to see
what you came up with first...
(Continue reading)

Martin Hjort Eriksen | 1 Jun 2004 22:48
Picon

Problems with references

Hello

This is a question on how references work with Python.

I have several objects, which use the same class definition. Within this 
class definition, there is an attribute of the type dictionary. During 
the run of the application, this dictionary, will be slowly filled up 
with references to other objects.

I would expect that the dictionary attribute will not be the same 
accross the objects. But everytime i add an object to one dictionary, it 
is also added to all the other dictionary.

When I compare the addresses in the memory for the objects, I can only 
conclude that they are not the same.

Here is an sample of when i put the references into the dictionaries:

    def examineParticipations(self):
        for id, participation in self.Participations.iteritems():
            # lets first figure out what type it is
            connection1ObjectType = 
self.findDiaObject(participation.connection1)
            connection2ObjectType = 
self.findDiaObject(participation.connection2)

            # attr =======================================================
            if connection1ObjectType == "attribute":
                connection1Object = 
self.Attributes[participation.connection1]
(Continue reading)

Lloyd Kvam | 1 Jun 2004 23:29
Favicon

Re: Problems with references

I assume that you made the dictionary a class variable.  Class variables
are common to the class.  When they are immutable such as strings or
numbers, the CHANGED values will be per instance (when assigned to
self).  This is a handy way to provide default values within a class.

(I simply typed this in.  There could be minor typos)
class A:
	foo = 3

	def change_foo(self):
		print self.foo	# 3
		self.foo = 10
		print self.foo	# 10

print A.foo	# 3 unless class variable is explicitly changed

Since the dictionary is mutable, all changes are shared among
instances.  To have separate dictionaries for each instance move the
dictionary creation to the __init__ method and delete the class variable
from the source.

If the dictionary is NOT a class variable, please let us know.  Then it
will take further investigation.

On Tue, 2004-06-01 at 16:48, Martin Hjort Eriksen wrote:
> Hello
> 
> This is a question on how references work with Python.
> 
> I have several objects, which use the same class definition. Within this 
(Continue reading)

Danny Yoo | 2 Jun 2004 00:32
Picon

Re: Problems with references


On Tue, 1 Jun 2004, Martin Hjort Eriksen wrote:

> This is a question on how references work with Python.
>
> I have several objects, which use the same class definition. Within this
> class definition, there is an attribute of the type dictionary. During
> the run of the application, this dictionary, will be slowly filled up
> with references to other objects.

Hi Martin,

Let's look at two possible implementations of a class with an attribute:

###
class FirstExample:
    names = []
    def __init__(self):
        pass
    def add(self, name):
        self.names.append(name)
    def report(self):
        for n in names:
            print n

class SecondExample:
    def __init__(self):
        self.names = []
    def add(self, name):
        self.names.append(name)
(Continue reading)

Tom Musgrove | 2 Jun 2004 00:43
Picon
Favicon

RE: list comprehension question

>Was that a typo?

Hi Blake, it was indeed a typo, new to the whole python thing...

Here is the solution I came up with

>>>ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)]
>>>ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)]
>>>NewDict = {}
>>>for k,v in ListAUniqueEdges:
>>>	listTemp = []
>>>	for m,n in ListBUniqueEdges:
>>>		if((k==m)or(k==n)or(v==m)or(v==n)): #seems there should be a better 
>>>method here
>>>			if (listTemp == []) :
>>>				listTemp = [(m,n)]
>>>			else:
>>>				listTemp.extend([(m,n)])
>>>	NewDict[(k,v)] = listTemp
>>>
>>>NewDict
{(3,7): [(2,7), (3,5)], (2,6): [(2,7), (1,6)], (8,9): [], (1,5):[(3,5), 
(1,6)]}
>>>

So, it seems to work ok

I'd be interested if there is a 'better' or more elegant way.  Especially
the

(Continue reading)

Blake Winton | 2 Jun 2004 02:58
Picon
Gravatar

Re: list comprehension question

On Tue, Jun 01, 2004 at 10:43:45PM +0000, Tom Musgrove wrote:
> >Was that a typo?
> Hi Blake, it was indeed a typo, new to the whole python thing...

No worries, just checking.

> Here is the solution I came up with
> >>>ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)]
> >>>ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)]
> >>>NewDict = {}
> >>>for k,v in ListAUniqueEdges:
> >>>    listTemp = []
> >>>    for m,n in ListBUniqueEdges:
> >>>        if((k==m)or(k==n)or(v==m)or(v==n)):
> >>>            if (listTemp == []) :
> >>>                listTemp = [(m,n)]
> >>>            else:
> >>>                listTemp.extend([(m,n)])
> >>>    NewDict[(k,v)] = listTemp
> >>>
> >>>NewDict
> {(3,7): [(2,7), (3,5)], (2,6): [(2,7), (1,6)], (8,9): [], (1,5):[(3,5), 
> (1,6)]}
> >>>
> So, it seems to work ok
> 
> I'd be interested if there is a 'better' or more elegant way.  Especially
> the
> if((k==m)or(k==n)or(v==m)or(v==n))
> (I tried (k or v) == (m or n) but didn't give the result I'd hoped for...)
(Continue reading)

Dragonfirebane | 2 Jun 2004 03:46
Picon
Favicon

(no subject)

Hello all,
 
I'm a high school student that recently became interested in Python.  I've attached the beginnings of a program called BankSim whose hopeful future abilities are documented in the .txt file.  I put 'CHECK' next to items already accomplished and 'IN PROGRESS' for sections under construction in the .txt file.  The majority of the items on this list are currently not being worked on pending resolution of the problems with the 'IN PROGRESS' item.
 
I'm having some trouble understanding the use of the re module in searches, etc.  What I am trying to do in the attached code is get the user's first and last name with a maximum of 6 characters each (I don't know how to get only the first six characters of each name (first, last). I'll probably divide that into one for each name to make it easier) and find the number of vowels in it.  I am utterly confused regarding how to do this . . . any help would be appreciated.
 
Thanks
1.	Allow creation of accounts with unique id's (based on birthday [ddmmyyyy] times pi times 1000 times
'time.time()' % 100000000)	CHECK
2.	Allow these accounts to be manipulated (deposits, withdrawals, transfers to existing accounts, and
transfers to new accounts)
3.	Allow account info (including account id, balance, date of opening, date of last use, a log of
transactions, time since opening, and time since last use (but NOT the password)) to be saved.
4.	Allow retrieval of this saved information only when the CORRECT password for the account id is entered.
5.	Allow a directory of stored account id's to be visible without a password (but NOT their balances).
6.	Allow compound interest to take effect compounded quarterly at 3 percent.
7.	Allow the bank to charge a .5% commission on all transactions.
8.	*optional* Allow the bank to hold a certain amount of money (expressly from aforementioned fees) to be
used in loans at 25% interest compounded semi-annually, with payments to be made once a month.
9.	Allow each user to be assigned a certain amount of money to begin with, based on the number of vowels in
their name times  'time.time()' to the power of pi split into at most 6 digits. IN PROGRESS
def newuser():
    new = raw_input("Are you a new user [y/n]? ")
    while new not in 'yYnN':
        new = raw_input("""
        Please enter 'y' for yes or 'n' for no.
        Are you a new user? """)
    if new in 'yY':
        startmon = raw_input("Please enter your first and last name [------ ------]. ")
        vowsearch = re.compile('[aeiou]*', re.IGNORECASE)
        print re.search(vowsearch, startmon).group()
def newacc():
    newac = raw_input("Would you like to create a new account [y/n]? ")
    while newac not in 'yYnN':
        newac = raw_input("""
        Please enter 'y' for yes or 'n' for no.
        Would you like to create a new acount? """)
    if newac in 'yY':
        newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. "))
        newacid = 3141.5962 * newacid
        newacid = newacid * time.time()
        newacid = newacid % 100000000
        initbal = int(raw_input("How much money would you like to put in your account? "))
        print "Account number %d created with $%d in it." % (newacid, initbal)      
        return newacid
import time
import re
newuser()
newacc()
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor
Glen Wheeler | 2 Jun 2004 04:18
Picon
Favicon

Re: (no subject)


  Hi Dragonfirebane,

> I'm having some trouble understanding the use of the re module in
searches, etc.
> What I am trying to do in the attached code is get the user's first and
last name
> with a maximum of 6 characters each (I don't know how to get only the
first six
> characters of each name (first, last). I'll probably divide that into one
for each
> name to make it easier) and find the number of vowels in it.  I am utterly
confused
> regarding how to do this . . . any help would be appreciated.

  Well, for such a simple task I would not use the re module.  Regular
expressions can be hard to understand, and especially for someone who is
relatively new to programming.  More intuitive is to roll your own!

  The standard string object has plenty of builtin functionality.  If you
want to only get names of maximum 6 characters, then use a while loop with
len(name) as a check.  For example:

name = raw_input("Please enter your name > ")
while len(name) > 6:
    print "Six characters maximum.  Please try again."
    name = raw_input("Please enter your name > ")

  Or if you want to get the first six characters of the input string, use a
slice.  For example:

>>> name = "Jimbiusmongius"
>>> shortname = name[:6]
>>> shortname
'Jimbiu'

  To find the number of vowels in a name, try something like :

>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> name = "Alista"
>>> for letter in name:
..  if letter.lower() in vowels:
..   vowelcount = vowelcount + 1
>>> vowelcount
3

  The reason .lower() is required is to ensure that the name contains no
uppercase letters, which are not present in our vowels list, since uppercase
and lowercase are not the same according to python.

  HTH,
  Glen

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor

Tom Musgrove | 2 Jun 2004 04:25
Picon
Favicon

Re: list comprehension question

Thanks,

I think I'll stick with my code, but replace the k,v with vertA and vertB, 
and m,n with edge for a slight readability improvement.

I can't believe I forgot about the in thing - duh!  I guess I'm just not 
used to seeing it in a programming context.

Tom M.

_________________________________________________________________
Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! 
http://join.msn.click-url.com/go/onm00200362ave/direct/01/

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
http://mail.python.org/mailman/listinfo/tutor


Gmane