473,810 Members | 3,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic Lists, or...?

I'm trying to figure out a way to create dynamic lists or possibly
antother solution for the following problem. I have multiple lines in a
text file (every line is the same format) that are iterated over and
which need to be compared to previous lines in the file in order to
perform some simple math. Each line contains 3 fileds: a descriptor and
two integers. Here is an example:

rose, 1, 500
lilac, 1, 300
lilly, 1, 400
rose, 0, 100

The idea is that the 0/1 values are there to let the program know
wether to add or subtract the second integer value for a specific
descriptor (flower in this case). So the program comes upon rose, adds
the 500 to an empty list, waits for the next appearance of the rose
descriptor and then (in this case) subtracts 100 from 500 and prints
the value. If the next rose was a 1 then it would have added 100.

I'm uncertain on how to approach doing this though. My idea was to
somehow be able to create lists dynamically upon each new occurence of
a descriptor that currently has no list and then perform the
calculations from there. Unfortunately, the list of descriptors is
potentially infinte, so I'm unable to previously create lists with the
descriptor names. Could anyonw give any suggestions on how to best
approach this problem, hopefully I've been clear enough? Any help would
be very gratly appreciated.

Best regards,
Lorn

Jul 19 '05 #1
4 2328
Lorn wrote:
I'm trying to figure out a way to create dynamic lists or possibly
antother solution for the following problem. I have multiple lines in a
text file (every line is the same format) that are iterated over and
which need to be compared to previous lines in the file in order to
perform some simple math. Each line contains 3 fileds: a descriptor and
two integers. Here is an example:

rose, 1, 500
lilac, 1, 300
lilly, 1, 400
rose, 0, 100


Do you have to maintain a list or just the current value?
Also I did not find it clear why you have to compare with previous line?

Anyway, I think dictionnary may be useful there:

input = """rose, 1, 500 ... lilac, 1, 300
... lilly, 1, 400
... rose, 0, 100"""
entries = [l.split(',') for l in input.split('\n ')]

d = {}
for k, op, n in entries: ... if int(op) == 1:
... d[k] = d.get(k, 0) + int(n)
... else:
... d[k] = d.get(k, 0) - int(n)
... print d {'rose': 400, 'lilly': 400, 'lilac': 300}

That may not be what you want but there may be some things for you to use.
And you can of course keep the full list of operation in d.
Jul 19 '05 #2
# Professional driver on a closed course.
# Don't try this at home.

data = """
rose, 1, 500
lilac, 1, 300
lilly, 1, 400
rose, 0, 100
"""

data = data.replace(', 1, ', ' += ')
data = data.replace(', 0, ', ' -= ')

class DefaultDict(dic t):
def __getitem__(sel f, key):
return self.get(key, 0)

d = DefaultDict()
exec data in {}, d
print d.items()

Jul 19 '05 #3
On Sat, 11 Jun 2005 10:30:53 -0700, Lorn wrote:
I'm trying to figure out a way to create dynamic lists or possibly
antother solution for the following problem. I have multiple lines in a
text file (every line is the same format) that are iterated over and
which need to be compared to previous lines in the file in order to
perform some simple math. Each line contains 3 fileds: a descriptor and
two integers. Here is an example:

rose, 1, 500
lilac, 1, 300
lilly, 1, 400
rose, 0, 100

The idea is that the 0/1 values are there to let the program know
wether to add or subtract the second integer value for a specific
descriptor (flower in this case). So the program comes upon rose, adds
the 500 to an empty list, waits for the next appearance of the rose
descriptor and then (in this case) subtracts 100 from 500 and prints
the value. If the next rose was a 1 then it would have added 100.
Why not just use a leading minus sign for the number if it is to be
subtracted?
I'm uncertain on how to approach doing this though. My idea was to
somehow be able to create lists dynamically upon each new occurence of a
descriptor that currently has no list and then perform the calculations
from there. Unfortunately, the list of descriptors is potentially
infinte, so I'm unable to previously create lists with the descriptor
names. Could anyonw give any suggestions on how to best approach this
problem, hopefully I've been clear enough? Any help would be very gratly
appreciated.


Use a dictionary:

def update_dict(D, key, sign, value):
"""Update dictionary D item with key by adding
or subtracting value."""
if not sign:
value = -value
x = D.get(key, 0)
D[key] = x + value

def split_line(s):
"""Split a string s into a tuple (key, sign, value),
ignoring whitespace."""
L = s.split(",")
return L[0].strip(), L[1].strip(), L[2].strip()
# WARNING: insufficient error checking for real world use.

Then call them like this:

D = {}
for line in sourcetext:
key, sign, value = split_line(line )
update_dict(D, key, sign, value)
Oh, by the way... just in case this is homework, which I'm sure it isn't
<wink>, I've deliberately left a teeny tiny bug in the code. You'll find
the bug pretty much the first time you run it, and the fix is very simple.
--
Steven.

Jul 19 '05 #4
On 13 Jun 2005 01:04:53 -0700, rumours say that "Raymond Hettinger"
<py****@rcn.com > might have written:
# Professional driver on a closed course.
# Don't try this at home.

data = """
rose, 1, 500
lilac, 1, 300
lilly, 1, 400
rose, 0, 100
"""

data = data.replace(', 1, ', ' += ')
data = data.replace(', 0, ', ' -= ')

class DefaultDict(dic t):
def __getitem__(sel f, key):
return self.get(key, 0)

d = DefaultDict()
exec data in {}, d
print d.items()


For kids trying this at home, note that it only works if the descriptor
is a valid Python identifier.
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1852
by: JZ | last post by:
I use Webware and FormKit. I have a problem with dynamic added field to the form. The following code creates one input field and two submit buttons. I would like to add more (up to 4) input fields after pressing "more" button. It does not work and I have no idea how to solve it. import re from WebKit.Page import Page from FormKit import Form, Fields, Validators from FormKit.FormKitMixIn import FormKitMixIn
5
4940
by: Charlie | last post by:
Hi, The description of Python always mentions "very high level dynamic data types". Now, I can't seem to find any examples of these (nothing described with this term anyway). Is this simply refering to built-in dynamic data structures such as lists and dictionaries, with a great deal of operators defined on? Or is there something else meant by "dynamic data types" in Python? Regards,
0
1469
by: Prem Soman | last post by:
--0-416482240-1060749044=:93966 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Content-Id: Content-Disposition: inline Note: forwarded message attached. ________________________________________________________________________ Want to chat instantly with your online friends? Get the FREE Yahoo!
13
2901
by: mr_burns | last post by:
hi, is it possible to change the contents of a combo box when the contents of another are changed. for example, if i had a combo box called garments containing shirts, trousers and hats, when the user selects shirts another combo box called 'size' would contain sizes in relation to shirts (ie. chest/neck size). the same would occur for trousers and hats. when the user selects an option in the garment combo box, the options available...
0
3520
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list boxes do not necessarily need to have a selection made to be used in the dynamic query. In essence the form can have selections made in all or none of its list boxes to form the dynamic query I am looking to get some feedback in reference to...
8
3691
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
2
1985
by: taras.di | last post by:
Hi everyone, I've been reading up on how to create a drop down box who's context is dynamically produced based on the value of a previous select box. I've read a lot about some of the browsers not properly readjusting the width of a dynamically produced drop down box, and some browsers having problems adjusting the height and widths (most notably NN). Most solutions involve manually refreshing the browser window and/or padding the...
3
1437
by: simon | last post by:
hello, i have a form where there are multiple dropdown lists that will all be populated from the same initial data query. i have a vb class defined to make the stored proc call and that returns a dataset. in my codebehind, i have in an "If Not Page.IsPostBack" block with statements that populate each of the dropdown lists. there could be up to 10 dropdowns lists used, which means the current way i'm doing it i'd have 10 sets of the same...
28
6068
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a C-professional, just a hobby-programmer trying to teach it myself. I found C rather difficult without those lists (and corresponding string-functions). Slowly getting into C-strings, I thought, what if I take a C-string and
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10393
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.