[Tutor] Is there a better way

2018-11-07 Thread Dave Hill
I have an sqlite database as a source {Asset and Test data from a Megger 
PAT Tester}, which contains a number of tables, and I end up with an 
OpenOffice spreadsheet, with numerous sheets


The data is proceesed in three parts, each using a separate Class.

I extract the useful tables, and store them as '.csv' versions. {Class#1}

I then need to correlate data from various tables, and sort into 
locations, again storing them as '.csv' versions. {Class#2}


Finally, I write all of the locations as separate sheets in an 
OpenOffice spreadsheet. {Class#3}


At this final stage I am converting table index numbers to the relevant 
string.


For example, from the '.csv' file the : TestGroupIndex [1] => Test Group 
['SC2']


'.csv' file for a location

AssetIndex  AssetId Description TestGroupIndex  RetestFrequency
106 43  Router  1   24
164 25  500 Drill   8   24
167 26  110v Ext Lead   11  24
173 37  Router DW625E   1   24
180 47  Vacuum  1   24
181 48  110v Ext11  24

sheet from '.ods' file

Asset   Asset   
TestTestNext
Index   Id  Description Group   FreqTest
106 43  Router  ['SC2'] 24  24/11/19
164 25  500 Drill   ['TO2'] 24  17/12/19
167 26  110v Ext Lead   ['EL3'] 24  24/11/19
173 37  Router DW625E   ['SC2'] 24  12/10/20
180 47  Vacuum  ['SC2'] 24  27/12/19
181 48  110v Ext['EL3'] 24  17/12/19

Test Group '.csv'

TestGroupIndex  Class   Description TestGroupId VoltageOutput
1   2   Class 2 Double insulatedSC2 230
2   1   Standard class 1 earthedSC1 230

The test group table has 30 entries but the index range is 1:31, i.e. 
one test group has been deleted at some point in the past, and the 
numbering is out of my control.


To access the test group I read the testgroup.csv file to a numpy array, 
inside {Class#3}, with two blanks, one for [0], and the other deleted group.


class OdsProcesses:

    def __init__(self, path, filename, noGroups):

        .

        .

    self.group = np.zeros(((self.noGroups + 1), 1), dtype = 
np.dtype('U10'))  # 10-character string


    def extract_TestGroup(self):

    # Open Test Group file for reading
    groupFilename = self.path
    groupFilename += self.filename
    groupFilename += self.TG_suffix
    testGroup = csv.DictReader(open(groupFilename, 'r'))

  # Loop through all Data
    for row in testGroup:
    index = int(row["TestGroupIndex"])
    self.group[index] = row["TestGroupId"]


    def get_TestGroup(self, index):

    groupStr = self.group[index]

    def writeODSData(self, sheet, roomNum):

        .

        .

    groupID = self.get_TestGroup(group)

This works but feels 'clumpy', and I have a feeling that there is a 
better way, but I have run out of ideas.


I am running Python 3.7.0, on a Windows 10 PC

Thank you for any assistance

Dave




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-14 Thread Neil Cerutti
On 2018-08-14, Alan Gauld via Tutor  wrote:
> - Use a list for objects(*) where you might need to
>   change the value of one of the objects

A list is standard practice when you need an ordered collection
of objects of the same type, e.g., a bunch of numbers, a bunch of
chickens, etc.. It is most efficient when the list may grow and
shrink on the end, but becomes suspicious if it usually grows and
shrinks in the middle or at the beginning. Nevertheless, Python
lists are very often used even so, and only require moving to a
different container type when the builtin list start to bog down.

> - Use a tuple for objects where you don't need
>   to change the values (it remains the same during
>   the life of the program).

Yes, a tuple makes an excellent fixed list.

A tuple is typically used to store a fixed-size collection of
objects of different types, when those objects have some logical
connection to one another.

If you had only these two containers to choose from for your
original exercise--a collection of colors and word-lengths--it
might make sense to store the color and wordlength as a tuple,
and to store those tuples in a list, on the assumption that more
colors might be added.

Aside: In Python there's usually no point in storing the length
of a string anywhere, since strings store their own length.

> - Use a set where you want to eliminate duplicates

Sets are great when the most common operations are adding new
items and testing for membership, or when you can take advantage
of set operations, like union or symmetric difference.

If your list of chickens is unordered and has no duplicates,
using a set instead is often a good refinement.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-14 Thread Alan Gauld via Tutor
On 14/08/18 07:56, Rafael Knuth wrote:

> List comprehension is really cool. One thing I like about list
> comprehension is that you can get a dictionary, tuples or lists as a
> result by just changing the type of braces.
> 
> # dictionary
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [{color, len(color)} for color in colors]
> print(colors_len)

Actually, these are sets not dictionaries. A dictionary would
have pairs separated by a colon, a set just has single values
separated by commas. They both use {}.

However List comprehensions are a special subset of a more
general construct called a generator expression and with
those you can build dictionaries:

colors = ["red", "blue", "white", "yellow"]
colors_len = dict( (color, len(color)) for color in colors] )
print(colors_len)

> # tuples
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [(color, len(color)) for color in colors]
> print(colors_len)

This gives a list of tuples, but you can use a gen exp to
create a tuple of tuples:

colors_len = tuple((color, len(color)) for color in colors)

> # lists
> colors = ["red", "blue", "white", "yellow"]
> colors_len = [[color, len(color)] for color in colors]
> print(colors_len)

So many choices :-)

> Can you shed some light on when to use which of the above data structures?
> I assume there is no simple answer to that question, 

Correct, it all depends on the nature of the data and
what you plan on doing with it. But there are some
general guidelines for collections:

- Use a list for objects(*) where you might need to
  change the value of one of the objects

- Use a tuple for objects where you don't need
  to change the values (it remains the same during
  the life of the program).
- Use a tuple if you want to use the collection as
  a key in a dictionary.

- Use a set where you want to eliminate duplicates

- Use a dict where you want direct access to an
  object based on some unique characeristic.

- Use a class where you have objects that
  you need to manipulate in different ways.
  ie. there is functionality associated with the data.

(*) Bearing in mind that an "object" can itself
be a list/tuple/dict etc

So, for your example, the dictionary is probably
the most useful structure since you can access
the length of any string by looking up the string:
eg.
print(color_len['blue'])


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-14 Thread Nitin Madhok
Use List comprehension:

animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
animals_lol = [[animal, len(animal)] for animal in animals]
print(animals_lol)

[['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]

If you want to read more about list comprehension, 
https://www.pythonforbeginners.com/lists/list-comprehensions-in-python/ 
 is a 
good resource!

--

Thanks,
Nitin Madhok
Clemson University

CONFIDENTIALITY NOTICE
This e-mail, and any attachments thereto, is intended only for use by the 
addressee(s) named herein and may contain privileged and/or confidential 
information. If you are not the intended recipient of this e-mail, any 
dissemination, distribution or copying of this e-mail, and any attachments 
thereto, is strictly prohibited. If you have received this e-mail in error, 
please immediately notify the sender by e-mail or telephone and permanently 
delete all copies of this e-mail and any attachments.

> On Aug 13, 2018, at 11:53 AM, Rafael Knuth  wrote:
> 
> I wrote this code below which aims to concatenate strings with their
> respective string length.
> I was wondering if there is a shorter, more elegant way to accomplish this 
> task.
> Thanks!
> 
> animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
> 
> # step one: convert the animal list into a list of lists
> 
> animals_lol = []
> 
> for animal in animals:
>animal_split = animal.split(",")
>animals_lol.append(animal_split)
> 
> # step two: collect the length of each string in a separate list
> 
> animals_len = []
> 
> for animal in animals:
>animals_len.append(len(animal))
> 
> # step three: append the length of each string to the list of lists
> 
> for a, b in enumerate(animals_lol):
>b.append(animals_len[a])
> 
> print(animals_lol)
> 
> [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-14 Thread Rafael Knuth
> I wrote this code below
> I was wondering if there is a shorter, more elegant way to accomplish this 
> task.
> Thanks!

thank you so much everyone!
List comprehension is really cool. One thing I like about list
comprehension is that you can get a dictionary, tuples or lists as a
result by just changing the type of braces.

# dictionary
colors = ["red", "blue", "white", "yellow"]
colors_len = [{color, len(color)} for color in colors]
print(colors_len)

# tuples
colors = ["red", "blue", "white", "yellow"]
colors_len = [(color, len(color)) for color in colors]
print(colors_len)

# lists
colors = ["red", "blue", "white", "yellow"]
colors_len = [[color, len(color)] for color in colors]
print(colors_len)

Can you shed some light on when to use which of the above data structures?
I assume there is no simple answer to that question, I am still trying
to understand the fundamentals of Python (which happens to be my first
programming language). Thanks!

> animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
>
> # step one: convert the animal list into a list of lists
>
> animals_lol = []
>
> for animal in animals:
> animal_split = animal.split(",")
> animals_lol.append(animal_split)
>
> # step two: collect the length of each string in a separate list
>
> animals_len = []
>
> for animal in animals:
> animals_len.append(len(animal))
>
> # step three: append the length of each string to the list of lists
>
> for a, b in enumerate(animals_lol):
> b.append(animals_len[a])
>
> print(animals_lol)
>
> [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-13 Thread Neil Cerutti
On 2018-08-13, Rafael Knuth  wrote:
> I wrote this code below which aims to concatenate strings with their
> respective string length. I was wondering if there is a
> shorter, more elegant way to accomplish this task. Thanks!
>
> animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]

You can perform the whole operation with a single list
comprehension.

animals_lol = [[a, len(a)] for a in animals]

Which is shorthand for the following loop:

animals_lol = []
for a in animals:
animals_lol.append([a, len(a)])

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-13 Thread Mats Wichmann
On 08/13/2018 09:53 AM, Rafael Knuth wrote:
> I wrote this code below which aims to concatenate strings with their
> respective string length.

did you mean concatenate? because you don't do any concatenation...

any time you hear keeping a data element with some information
associated, you should be thinking a dictionary data type, though
there's nothing wrong with having a data element be a list or a tuple
either, and we don't know if you have some specific requirements that
are not showing here.

> I was wondering if there is a shorter, more elegant way to accomplish this 
> task.
> Thanks!
> 
> animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
> 
> # step one: convert the animal list into a list of lists
> 
> animals_lol = []
> 
> for animal in animals:
> animal_split = animal.split(",")
> animals_lol.append(animal_split)
> 
> # step two: collect the length of each string in a separate list
> 
> animals_len = []
> 
> for animal in animals:
> animals_len.append(len(animal))
> 
> # step three: append the length of each string to the list of lists
> 
> for a, b in enumerate(animals_lol):
> b.append(animals_len[a])
> 
> print(animals_lol)
> 
> [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]

If you want a dictionary, you can try this one-liner:

animalinfo = { animal: len(animal) for animal in animals }
print(animalinfo)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to write my code?

2018-08-13 Thread Mark Lawrence

On 13/08/18 16:53, Rafael Knuth wrote:

I wrote this code below which aims to concatenate strings with their
respective string length.
I was wondering if there is a shorter, more elegant way to accomplish this task.
Thanks!

animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]

# step one: convert the animal list into a list of lists

animals_lol = []

for animal in animals:
 animal_split = animal.split(",")
 animals_lol.append(animal_split) >
# step two: collect the length of each string in a separate list

animals_len = []

for animal in animals:
 animals_len.append(len(animal))

# step three: append the length of each string to the list of lists

for a, b in enumerate(animals_lol):
 b.append(animals_len[a])

print(animals_lol)

[['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



For a definition of better:-

animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
animals_lol = []
for animal in animals:
animals_lol.append((animal, len(animal)))
print(animals_lol)

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way to write my code?

2018-08-13 Thread Rafael Knuth
I wrote this code below which aims to concatenate strings with their
respective string length.
I was wondering if there is a shorter, more elegant way to accomplish this task.
Thanks!

animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]

# step one: convert the animal list into a list of lists

animals_lol = []

for animal in animals:
animal_split = animal.split(",")
animals_lol.append(animal_split)

# step two: collect the length of each string in a separate list

animals_len = []

for animal in animals:
animals_len.append(len(animal))

# step three: append the length of each string to the list of lists

for a, b in enumerate(animals_lol):
b.append(animals_len[a])

print(animals_lol)

[['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-10 Thread Chris Roy-Smith

On 10/05/16 07:03, Ondřej Rusek wrote:

Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a):

Hi
Python 3.4 Linux (ubuntu)

This code does what I want.
curs is the result of a mysql query


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
data[row][0]=ddate
data[row][1]=mood
data[row][2]=walk
data[row][3]=lag
data[row][4]=sleep
row +=1


if you want 'lists in list' (like your solution):

data = []
for ddate, mood, walk, lag, sleep in curs:
data += [ [ddate, mood, walk, lag, sleep] ]

or 'tuples in list':

data = []
for ddate, mood, walk, lag, sleep in curs:
  data += [ (ddate, mood, walk, lag, sleep) ]

but for 'tuples in list'... simple:

data = []
for record in curs:
  data += [record]



Thanks,
I hadn't considered having a second list of lists for my calculations,
Your solution is the sort of thing I was looking for.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-10 Thread Chris Roy-Smith

On 10/05/16 12:01, Steven D'Aprano wrote:

On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote:


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
 data[row][0]=ddate
 data[row][1]=mood
 data[row][2]=walk
 data[row][3]=lag
 data[row][4]=sleep
 row +=1

While I don't know a better way to do this, it seems a bit awkward, is
there a better way?

Hmmm, it's hard to be sure because we don't really know what count is.
Do you want a bunch of empty rows at the end? My guess is No.

In your code above, you initialise each row with ten spaces, and only
replace five of them. So assuming you need the extra five spaces:

data = [record + [" "]*5 for record in curs]

provided curs returns lists, rather than tuples. (If not, it's
easy to just convert using `list(record)`.

If you don't need the extra five columns, the code is even simpler:

data = list(curs)

Thank you,
that's much better
I thought I needed the extra columns, but I changed things to use 2 
lists of lists
(one generated with the above line and another to hold my calculated 
results)




What if you do want extra blank rows? Easiest to just add them at the
end:

# initialise data as above, then add blanks
for i in range(how_many_extra_rows):
 data.append([" "]*10)

which can be simplified to:

data.extend([[" "]*10 for i in range(how_many_extra_rows)])





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Steven D'Aprano
On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote:

> data = [[" " for x in range(9)] for y in range(count)]
> for (ddate, mood, walk, lag, sleep) in curs:
> data[row][0]=ddate
> data[row][1]=mood
> data[row][2]=walk
> data[row][3]=lag
> data[row][4]=sleep
> row +=1
> 
> While I don't know a better way to do this, it seems a bit awkward, is 
> there a better way?

Hmmm, it's hard to be sure because we don't really know what count is. 
Do you want a bunch of empty rows at the end? My guess is No. 

In your code above, you initialise each row with ten spaces, and only 
replace five of them. So assuming you need the extra five spaces:

data = [record + [" "]*5 for record in curs]

provided curs returns lists, rather than tuples. (If not, it's 
easy to just convert using `list(record)`.

If you don't need the extra five columns, the code is even simpler:

data = list(curs)


What if you do want extra blank rows? Easiest to just add them at the 
end:

# initialise data as above, then add blanks
for i in range(how_many_extra_rows):
data.append([" "]*10)

which can be simplified to:

data.extend([[" "]*10 for i in range(how_many_extra_rows)])



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Joel Goldstick
On Mon, May 9, 2016 at 6:49 PM, Alan Gauld via Tutor  wrote:
> On 09/05/16 22:03, Ondřej Rusek wrote:
>
>> but for 'tuples in list'... simple:
>>
>> data = []
>> for record in curs:
>>data += [record]
>
> Couldn't that be abbreviated to:
>
> date = list(curs)
>
I thought I nailed it earlier (and others) but this is great.  An
expressive language, python
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Alan Gauld via Tutor
On 09/05/16 22:03, Ondřej Rusek wrote:

> but for 'tuples in list'... simple:
> 
> data = []
> for record in curs:
>data += [record]

Couldn't that be abbreviated to:

date = list(curs)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Ondřej Rusek

Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a):

Hi
Python 3.4 Linux (ubuntu)

This code does what I want.
curs is the result of a mysql query


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
data[row][0]=ddate
data[row][1]=mood
data[row][2]=walk
data[row][3]=lag
data[row][4]=sleep
row +=1


if you want 'lists in list' (like your solution):

data = []
for ddate, mood, walk, lag, sleep in curs:
data += [ [ddate, mood, walk, lag, sleep] ]

or 'tuples in list':

data = []
for ddate, mood, walk, lag, sleep in curs:
  data += [ (ddate, mood, walk, lag, sleep) ]

but for 'tuples in list'... simple:

data = []
for record in curs:
  data += [record]


--
S pozdravem

--
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Ondrej Rusek
GYmnazium BOzeny Nemcove, Hradec Kralove, Czech
ru...@gybon.cz, http://www.gybon.cz/~rusek
ICQ: 150366991
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-


--
Tato zprava byla prohledana na vyskyt viru
a nebezpecneho obsahu antivirovym systemem
MailScanner a zda se byt cista.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Peter Otten
Chris Roy-Smith wrote:

> Hi
> Python 3.4 Linux (ubuntu)
> 
> This code does what I want.
> curs is the result of a mysql query
> 
> 
> data = [[" " for x in range(9)] for y in range(count)]
> for (ddate, mood, walk, lag, sleep) in curs:
>  data[row][0]=ddate
>  data[row][1]=mood
>  data[row][2]=walk
>  data[row][3]=lag
>  data[row][4]=sleep
>  row +=1
> 
> 
> While I don't know a better way to do this, it seems a bit awkward, is
> there a better way?

Does `curs` give `count` records? If so:

data = [
   list(row) + [" "] * 4
   for row in curs
]

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Joel Goldstick
On Mon, May 9, 2016 at 4:13 AM, Chris Roy-Smith
 wrote:
> Hi
> Python 3.4 Linux (ubuntu)
>
> This code does what I want.
> curs is the result of a mysql query
>
>
does this work (untested)?

data = []
for stuff in curs:
   data.append(stuff)
>
> While I don't know a better way to do this, it seems a bit awkward, is there
> a better way?
>
>
> Thank you
> Chris Roy-Smith
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] is there a better way to do this?

2016-05-09 Thread Chris Roy-Smith

Hi
Python 3.4 Linux (ubuntu)

This code does what I want.
curs is the result of a mysql query


data = [[" " for x in range(9)] for y in range(count)]
for (ddate, mood, walk, lag, sleep) in curs:
data[row][0]=ddate
data[row][1]=mood
data[row][2]=walk
data[row][3]=lag
data[row][4]=sleep
row +=1


While I don't know a better way to do this, it seems a bit awkward, is 
there a better way?



Thank you
Chris Roy-Smith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way?

2012-01-11 Thread Marco Casazza

Hello,

I've been slowly teaching myself python, using it for small projects 
when it seems appropriate. In this case, I was handed a list of email 
addresses for a mailing but some of them had been truncated. There are 
only 21 possible email suffixes so I planned to just identify which it 
should be and then replace it. However, when I started writing the code 
I realized that I'd be doing a lot of repeating. Is there a better way 
to fix the suffixes without doing each individually? Here's my working 
code (for 4 colleges):


import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
outlist = []
for line in infile.read().split('\n'):
if line.rstrip().lower().endswith('edu'):
newline = line + '\n'
outlist.append(newline.lower())
elif re.search(@bar, line):
newline = re.sub(@bar.*, @baruch.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@bcc, line):
newline = re.sub(@bcc.*, @bcc.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@bmc, line):
newline = re.sub(@bmc.*, @bmcc.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@leh, line):
newline = re.sub(@leh.*, @lehman.cuny.edu, line)+'\n'
outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
outfile.writelines(outlist)

Thanks,
Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way?

2012-01-11 Thread Joel Goldstick
On Wed, Jan 11, 2012 at 7:34 AM, Marco Casazza marco.vince...@gmail.com wrote:
 Hello,

 I've been slowly teaching myself python, using it for small projects when it
 seems appropriate. In this case, I was handed a list of email addresses for
 a mailing but some of them had been truncated. There are only 21 possible
 email suffixes so I planned to just identify which it should be and then
 replace it. However, when I started writing the code I realized that I'd be
 doing a lot of repeating. Is there a better way to fix the suffixes
 without doing each individually? Here's my working code (for 4 colleges):

 import re
 with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
    outlist = []
    for line in infile.read().split('\n'):
        if line.rstrip().lower().endswith('edu'):
            newline = line + '\n'
            outlist.append(newline.lower())
        elif re.search(@bar, line):
            newline = re.sub(@bar.*, @baruch.cuny.edu, line)+'\n'
            outlist.append(newline.lower())
        elif re.search(@bcc, line):
            newline = re.sub(@bcc.*, @bcc.cuny.edu, line)+'\n'
            outlist.append(newline.lower())
        elif re.search(@bmc, line):
            newline = re.sub(@bmc.*, @bmcc.cuny.edu, line)+'\n'
            outlist.append(newline.lower())
        elif re.search(@leh, line):
            newline = re.sub(@leh.*, @lehman.cuny.edu, line)+'\n'
            outlist.append(newline.lower())

 with file('c:\python27\mvc\output.txt','w') as outfile:
    outfile.writelines(outlist)

 Thanks,
 Marco
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

First, look here about reading files:
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

I like this better:
f = open('filename', 'r')
for line in f:
print line # this will give you one line at a time without
the trailing newline

Second, make a dictionary of with the key being what comes after the @
in your truncated file.  The value will be the complete text you want:
 d = {bcc : bcc.cuny.edu, etc. }

Third, use line.split('@') to split the line into what comes before
and after the @ sign.  It will return a list
address_parts = line.split('@')

address_parts[0] is what you want to keep as is. I'm guessing that the
3 characters after the @ will be enough to identify what the full
address should look like, so
if address_parts[1][0:3] in d:
  result = '@'.join([address_parts[0], d[address_parts[1][0:3]])

write the result to your out file.

Its early in the morning for me, and this is untested, but it might
give you some ideas.

-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way?

2012-01-11 Thread Marco Casazza

On 2012-01-11 07:57, Joel Goldstick wrote:

On Wed, Jan 11, 2012 at 7:34 AM, Marco Casazzamarco.vince...@gmail.com  wrote:

Hello,

I've been slowly teaching myself python, using it for small projects when it
seems appropriate. In this case, I was handed a list of email addresses for
a mailing but some of them had been truncated. There are only 21 possible
email suffixes so I planned to just identify which it should be and then
replace it. However, when I started writing the code I realized that I'd be
doing a lot of repeating. Is there a better way to fix the suffixes
without doing each individually? Here's my working code (for 4 colleges):

import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
outlist = []
for line in infile.read().split('\n'):
if line.rstrip().lower().endswith('edu'):
newline = line + '\n'
outlist.append(newline.lower())
elif re.search(@bar, line):
newline = re.sub(@bar.*, @baruch.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@bcc, line):
newline = re.sub(@bcc.*, @bcc.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@bmc, line):
newline = re.sub(@bmc.*, @bmcc.cuny.edu, line)+'\n'
outlist.append(newline.lower())
elif re.search(@leh, line):
newline = re.sub(@leh.*, @lehman.cuny.edu, line)+'\n'
outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
outfile.writelines(outlist)

Thanks,
Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

First, look here about reading files:
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

I like this better:
 f = open('filename', 'r')
 for line in f:
 print line # this will give you one line at a time without
the trailing newline

Second, make a dictionary of with the key being what comes after the @
in your truncated file.  The value will be the complete text you want:
  d = {bcc : bcc.cuny.edu, etc. }

Third, use line.split('@') to split the line into what comes before
and after the @ sign.  It will return a list
 address_parts = line.split('@')

address_parts[0] is what you want to keep as is. I'm guessing that the
3 characters after the @ will be enough to identify what the full
address should look like, so
if address_parts[1][0:3] in d:
   result = '@'.join([address_parts[0], d[address_parts[1][0:3]])

write the result to your out file.

Its early in the morning for me, and this is untested, but it might
give you some ideas.


Hi Joel,

Thanks. I like the dictionary idea... I hadn't thought of that because I 
was trying to fix one problem and then realized I had more, and then 
yet more, so it just kept growing--a case of not seeing the forest for 
the trees. And, if I split the address at the amphora I wouldn't need to 
worry about where exactly it was truncated, so no regular expressions to 
gather up the remaining characters after the key.


Thanks again,
Marco
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-12-01 Thread Joel Goldstick
On Wed, Nov 30, 2011 at 8:46 PM, Dave Angel d...@davea.name wrote:

 On 11/30/2011 07:49 PM, Steven D'Aprano wrote:

 Norman Khine wrote:

 hello,

 is there a better way to organise this code or optimise it.
 http://pastie.org/2944797


 Is that a question? Because I get a syntax error in my brain when I parse
 it without the question mark. wink

 Sorry to pick on you, but it astonishes me when people don't bother with
 basic English syntax, and yet try writing code where syntax is *much* more
 important. If they can't be bothered with writing correct English, that
 sends all the wrong signals about the quality of their code.

 You should write as if you were coding, otherwise people will assume you
 code like you write.

 Laziness is one of the cardinal virtues of the programmer, but it has to
 be the right sort of laziness. Don't reinvent the wheel, use an existing
 library is good laziness. Leave out required syntax elements and hope
 someone else will fix them is not.

 Before worrying about optimising the code, how about checking whether it
 works?

 (1) What is CSVFile? It appears to be a class, because you inherit from
 it, but it isn't defined anywhere and isn't a builtin. So your code fails
 on the very first line.

 (2) You have a class WorldSchema with no methods, and a top-level
 function get_world that *looks* like a method because it has an argument
 self, but isn't. The indentation is wrong. See what I mean about syntax?
 Syntax is important. So is get_world a wrongly indented method, or a poorly
 written function?

 (3) Since get_world doesn't use self at all, perhaps it should be a
 top-level function of no arguments? Or perhaps a static method of
 WorldSchema?

 (4) You have a class called getCountries, which seems to be a poor name
 for a class. In general, classes should be *things*, not *actions*. Also I
 recommend that you follow PEP 8 for naming conventions. (Google PEP 8 if
 you don't know what I mean, and remember, it isn't compulsory, but it is
 recommended.) A better name might be CountryGetter.

 (5) The use of classes appears on first reading to be a Java-ism. In
 Java, everything must be a class Just Because The Powers Who Be Said So. In
 Python, we are allowed, and encouraged, to mix classes and functions. Use
 the right tool for the job. But without any idea of the broader context, I
 have no idea if classes are appropriate or not.

 (6) getCountries has a method called get_options. Based on the name, a
 reasonable reader would assume it returns some sort of list or dictionary
 of options, right? But according to the documentation, it actually returns
 a JSON ser, whatever that is. Server? Service? Serialization (of what)?
 Something else?

 (7) Other problems:  Enumerate, MSG and iana_root_zone are used but not
 defined anywhere. Documentation is lacking, so I don't understand what the
 code is intended to do. Another class with a poor name, getRegions. There
 may be others, but I stopped reading around this point.


  I stopped looking at his pastie once the background turned black.  I'd
 have had to copy it elsewhere to even read it.


 --

 DaveA


 There is a button in the upper right corner of the paste bin that lets you
switch the hideous black background to something more pleasant. :)

-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-12-01 Thread Norman Khine
hi

On Thu, Dec 1, 2011 at 12:49 AM, Steven D'Aprano st...@pearwood.info wrote:
 Norman Khine wrote:

 hello,

 is there a better way to organise this code or optimise it.
 http://pastie.org/2944797


 Is that a question? Because I get a syntax error in my brain when I parse it
 without the question mark. wink

sorry it was suppose to be a question.


 Sorry to pick on you, but it astonishes me when people don't bother with
 basic English syntax, and yet try writing code where syntax is *much* more
 important. If they can't be bothered with writing correct English, that
 sends all the wrong signals about the quality of their code.

 You should write as if you were coding, otherwise people will assume you
 code like you write.

point taken.


 Laziness is one of the cardinal virtues of the programmer, but it has to be
 the right sort of laziness. Don't reinvent the wheel, use an existing
 library is good laziness. Leave out required syntax elements and hope
 someone else will fix them is not.

 Before worrying about optimising the code, how about checking whether it
 works?

i am using the itools library http://www.hforge.org/itools/docs/csv
and the code does work.


 (1) What is CSVFile? It appears to be a class, because you inherit from it,
 but it isn't defined anywhere and isn't a builtin. So your code fails on the
 very first line.

 (2) You have a class WorldSchema with no methods, and a top-level function
 get_world that *looks* like a method because it has an argument self, but
 isn't. The indentation is wrong. See what I mean about syntax? Syntax is
 important. So is get_world a wrongly indented method, or a poorly written
 function?

 (3) Since get_world doesn't use self at all, perhaps it should be a
 top-level function of no arguments? Or perhaps a static method of
 WorldSchema?

this is where i was uncertain as to how best approach it.


 (4) You have a class called getCountries, which seems to be a poor name
 for a class. In general, classes should be *things*, not *actions*. Also I
 recommend that you follow PEP 8 for naming conventions. (Google PEP 8 if
 you don't know what I mean, and remember, it isn't compulsory, but it is
 recommended.) A better name might be CountryGetter.

ok, will do.


 (5) The use of classes appears on first reading to be a Java-ism. In Java,
 everything must be a class Just Because The Powers Who Be Said So. In
 Python, we are allowed, and encouraged, to mix classes and functions. Use
 the right tool for the job. But without any idea of the broader context, I
 have no idea if classes are appropriate or not.

the broader context is that i would like to reuse CountryGetter,
RegionGetter and CountyGetter within a multi-select widget that will
be called from different forms.


 (6) getCountries has a method called get_options. Based on the name, a
 reasonable reader would assume it returns some sort of list or dictionary of
 options, right? But according to the documentation, it actually returns a
 JSON ser, whatever that is. Server? Service? Serialization (of what)?
 Something else?

yes it is a JSON serialization

 (7) Other problems:  Enumerate, MSG and iana_root_zone are used but not
 defined anywhere. Documentation is lacking, so I don't understand what the
 code is intended to do. Another class with a poor name, getRegions. There
 may be others, but I stopped reading around this point.

again sorry about this, i will try to be more explicit next time.

as mentioned above, i was interested in knowing whether or not i
needed to call the get_world() which loads the CSV file every time
each getCountries, getRegion and getCounty classes are called and if
there was a more efficient way to do this?

thanks




 --
 Steven

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



-- 
% .join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ,adym,*)uzq^zqf ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-12-01 Thread bob gailer

On 11/30/2011 8:46 PM, Dave Angel wrote:

On 11/30/2011 07:49 PM, Steven D'Aprano wrote:

Norman Khine wrote:

hello,

is there a better way to organise this code or optimise it.
http://pastie.org/2944797



I stopped looking at his pastie once the background turned black.  I'd 
have had to copy it elsewhere to even read it.

Check out the drop-down box on the upper right. Choose Clean


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] is there a better way to organise this code

2011-11-30 Thread Norman Khine
hello,

is there a better way to organise this code or optimise it.

http://pastie.org/2944797

thanks

norman
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-11-30 Thread Wayne Werner
On Wed, Nov 30, 2011 at 3:34 PM, Norman Khine nor...@khine.net wrote:

 hello,

 is there a better way to organise this code or optimise it.

 http://pastie.org/2944797


After glancing at it the only change that I would recommend (possibly)
making is lines 58 and 39 - you can wrap the dictionaries (line line 7) and
that will bring all your lines  80 characters. Other than that it looks
perfectly readable. You could add some docstrings for completeness.

As far as anything else - is this code too slow? If not, why bother trying
to optimise it? Obviously if you were doing something horribly inefficient
like a bubble sort (especially considering Python has a built-in sort),
then you would want to get rid of that, but I didn't really notice
anything. Though now that I took a few more seconds, it does look like
you're not using rows, aside from looping over it. If you only care about
the values and not the collection as a whole you could (and should) change
the list comprehension to a generator expression:

 [x for x in (1,2,3)]
[1, 2, 3]
 (x for x in (1,2,3))
generator object genexpr at 0x01BFB6C0

If you're not familiar with a generators, I highly recommend this set of
slides: http://www.dabeaz.com/generators/Generators.pdf

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-11-30 Thread Steven D'Aprano

Norman Khine wrote:

hello,

is there a better way to organise this code or optimise it.
http://pastie.org/2944797


Is that a question? Because I get a syntax error in my brain when I parse it 
without the question mark. wink


Sorry to pick on you, but it astonishes me when people don't bother with basic 
English syntax, and yet try writing code where syntax is *much* more 
important. If they can't be bothered with writing correct English, that sends 
all the wrong signals about the quality of their code.


You should write as if you were coding, otherwise people will assume you code 
like you write.


Laziness is one of the cardinal virtues of the programmer, but it has to be 
the right sort of laziness. Don't reinvent the wheel, use an existing 
library is good laziness. Leave out required syntax elements and hope 
someone else will fix them is not.


Before worrying about optimising the code, how about checking whether it works?

(1) What is CSVFile? It appears to be a class, because you inherit from it, 
but it isn't defined anywhere and isn't a builtin. So your code fails on the 
very first line.


(2) You have a class WorldSchema with no methods, and a top-level function 
get_world that *looks* like a method because it has an argument self, but 
isn't. The indentation is wrong. See what I mean about syntax? Syntax is 
important. So is get_world a wrongly indented method, or a poorly written 
function?


(3) Since get_world doesn't use self at all, perhaps it should be a 
top-level function of no arguments? Or perhaps a static method of WorldSchema?


(4) You have a class called getCountries, which seems to be a poor name for 
a class. In general, classes should be *things*, not *actions*. Also I 
recommend that you follow PEP 8 for naming conventions. (Google PEP 8 if you 
don't know what I mean, and remember, it isn't compulsory, but it is 
recommended.) A better name might be CountryGetter.


(5) The use of classes appears on first reading to be a Java-ism. In Java, 
everything must be a class Just Because The Powers Who Be Said So. In Python, 
we are allowed, and encouraged, to mix classes and functions. Use the right 
tool for the job. But without any idea of the broader context, I have no idea 
if classes are appropriate or not.


(6) getCountries has a method called get_options. Based on the name, a 
reasonable reader would assume it returns some sort of list or dictionary of 
options, right? But according to the documentation, it actually returns a JSON 
ser, whatever that is. Server? Service? Serialization (of what)? Something else?


(7) Other problems:  Enumerate, MSG and iana_root_zone are used but not 
defined anywhere. Documentation is lacking, so I don't understand what the 
code is intended to do. Another class with a poor name, getRegions. There 
may be others, but I stopped reading around this point.





--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there a better way to organise this code

2011-11-30 Thread Dave Angel

On 11/30/2011 07:49 PM, Steven D'Aprano wrote:

Norman Khine wrote:

hello,

is there a better way to organise this code or optimise it.
http://pastie.org/2944797


Is that a question? Because I get a syntax error in my brain when I 
parse it without the question mark. wink


Sorry to pick on you, but it astonishes me when people don't bother 
with basic English syntax, and yet try writing code where syntax is 
*much* more important. If they can't be bothered with writing correct 
English, that sends all the wrong signals about the quality of their 
code.


You should write as if you were coding, otherwise people will assume 
you code like you write.


Laziness is one of the cardinal virtues of the programmer, but it has 
to be the right sort of laziness. Don't reinvent the wheel, use an 
existing library is good laziness. Leave out required syntax 
elements and hope someone else will fix them is not.


Before worrying about optimising the code, how about checking whether 
it works?


(1) What is CSVFile? It appears to be a class, because you inherit 
from it, but it isn't defined anywhere and isn't a builtin. So your 
code fails on the very first line.


(2) You have a class WorldSchema with no methods, and a top-level 
function get_world that *looks* like a method because it has an 
argument self, but isn't. The indentation is wrong. See what I mean 
about syntax? Syntax is important. So is get_world a wrongly indented 
method, or a poorly written function?


(3) Since get_world doesn't use self at all, perhaps it should be a 
top-level function of no arguments? Or perhaps a static method of 
WorldSchema?


(4) You have a class called getCountries, which seems to be a poor 
name for a class. In general, classes should be *things*, not 
*actions*. Also I recommend that you follow PEP 8 for naming 
conventions. (Google PEP 8 if you don't know what I mean, and 
remember, it isn't compulsory, but it is recommended.) A better name 
might be CountryGetter.


(5) The use of classes appears on first reading to be a Java-ism. In 
Java, everything must be a class Just Because The Powers Who Be Said 
So. In Python, we are allowed, and encouraged, to mix classes and 
functions. Use the right tool for the job. But without any idea of the 
broader context, I have no idea if classes are appropriate or not.


(6) getCountries has a method called get_options. Based on the name, a 
reasonable reader would assume it returns some sort of list or 
dictionary of options, right? But according to the documentation, it 
actually returns a JSON ser, whatever that is. Server? Service? 
Serialization (of what)? Something else?


(7) Other problems:  Enumerate, MSG and iana_root_zone are used but 
not defined anywhere. Documentation is lacking, so I don't understand 
what the code is intended to do. Another class with a poor name, 
getRegions. There may be others, but I stopped reading around this 
point.



I stopped looking at his pastie once the background turned black.  I'd 
have had to copy it elsewhere to even read it.



--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way to use scientific notation in an equation?

2010-05-02 Thread David Hutto
In the following code I'm trying to do basic calculations with coulumb's law

#Coulombs Law
'''
F = (9*(10**9)) * (Q1*Q2) / (d**2)
'''
base = 10
Q1mult = raw_input('First enter multiplier of base 10 charge/coloumb(Q1):')
Q1exp = raw_input('Now enter exponent of base 10(Q1):')
Q1 = int(Q1mult)*(10**int(Q1exp))
Q2mult = raw_input('First enter multiplier of base 10 charge/coloumb(Q2):')
Q2exp = raw_input('Now enter exponent of base 10(Q2):')
Q2 = int(Q2mult)*(10**int(Q2exp))
d = raw_input('Enter distance of charges/coulumbs from Q1 to Q2:')



a = (9*(10**9))*((int(Q1))*(int(Q2)))/((int(d))**2)
print a
**

Q1 and Q2 are to be entered as base ten scientific notation.
When I try to input Q1 as raw input, entering in ((2*(10**7)), I get:

ValueError: invalid literal for int() with base 10: '((2)*(10**7))'

Which is why I broke it down into it's sub-components(i.e. what to
multiply the base 10 by[Q1mult] and what exponent to use with the base
10[Q1exp]).

Is there a better way to write this, and what would be the best way to
insert the
scientific notation if not this way. I know there is probably a
module, but this is
for my own practice.

TIA
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to use scientific notation in an equation?

2010-05-02 Thread Steven D'Aprano
On Mon, 3 May 2010 06:44:42 am David Hutto wrote:
 In the following code I'm trying to do basic calculations with
 coulumb's law

 #Coulombs Law
 '''
 F = (9*(10**9)) * (Q1*Q2) / (d**2)
 '''
 base = 10
 Q1mult = raw_input('First enter multiplier of base 10
 charge/coloumb(Q1):') Q1exp = raw_input('Now enter exponent of base
 10(Q1):')
 Q1 = int(Q1mult)*(10**int(Q1exp))
 Q2mult = raw_input('First enter multiplier of base 10
 charge/coloumb(Q2):') Q2exp = raw_input('Now enter exponent of base
 10(Q2):')
 Q2 = int(Q2mult)*(10**int(Q2exp))
 d = raw_input('Enter distance of charges/coulumbs from Q1 to Q2:')



 a = (9*(10**9))*((int(Q1))*(int(Q2)))/((int(d))**2)
 print a
 **

 Q1 and Q2 are to be entered as base ten scientific notation.
 When I try to input Q1 as raw input, entering in ((2*(10**7)), I get:

 ValueError: invalid literal for int() with base 10: '((2)*(10**7))'

((2)*(10**7)) is not an integer, it is a mathematical expression. 
Integers look like:

1
-27
3748105

and similar. Apart from a leading minus sign to make negative numbers, 
only digits are allowed.

The way to enter numbers in scientific notation is to use floats, in 
exponential form, just like scientific calculators:

2e7

and to change your program to use float instead of int. Also, you have a 
lot of unnecessary brackets that don't do anything except make it hard 
to read. This should do it:

a = 9e9*float(Q1)*float(Q2)/float(d)**2



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to use scientific notation in an equation?

2010-05-02 Thread Eike Welk
On Sunday May 2 2010 22:44:42 David Hutto wrote:
 Q1 and Q2 are to be entered as base ten scientific notation.
 When I try to input Q1 as raw input, entering in ((2*(10**7)), I get:
 
 ValueError: invalid literal for int() with base 10: '((2)*(10**7))'
 
 Which is why I broke it down into it's sub-components(i.e. what to
 multiply the base 10 by[Q1mult] and what exponent to use with the base
 10[Q1exp]).
 
 Is there a better way to write this, and what would be the best way to
 insert the
 scientific notation if not this way. 

Maybe this is what you are looking for:

In [1]: 1e9
Out[1]: 10.0

In [2]: float(raw_input())
1e9
Out[2]: 10.0


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Dick Moores

Better than this? http://py77.python.pastebin.com/fc7553a4

I've heard about BeautifulSoup. 
http://www.crummy.com/software/BeautifulSoup/. Is it worth 
learning? Is it crummy? ;-)


So 2 questions.

Thanks,

Dick Moores

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Dick Moores


Here's one opinion, an answer to my second question.
Dick
Date: Fri, 25 Jul 2008 08:54:53 -0500
From: W W [EMAIL PROTECTED]
To: Dick Moores [EMAIL PROTECTED]
Subject: Re: [Tutor] Is there a better way to get a current mid-rate Yen
quote with Python?
Beautiful Soup is really awesome... I've used it a little, and I'd say
it's totally worth learning.
-Wayne
On Fri, Jul 25, 2008 at 7:14 AM, Dick Moores
[EMAIL PROTECTED] wrote:


Better than this?

http://py77.python.pastebin.com/fc7553a4

I've heard about BeautifulSoup.

http://www.crummy.com/software/BeautifulSoup/. Is it worth
learning? Is it crummy? ;-)

So 2 questions.

Thanks,

Dick Moores




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Alan Gauld
Dick Moores [EMAIL PROTECTED] wrote 


Here's one opinion, an answer to my second question.

Dick


And to answer your first: It depends on how you define better.

Certainly Beautiful Soup will not be muh longer and a lot more 
elegant and probably more resilient.


But to extract a single piece of text in a well defined location 
then your approach although somewhat crude will work just fine.


Alan G

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Dick Moores

At 09:47 AM 7/25/2008, Alan Gauld wrote:

Dick Moores [EMAIL PROTECTED] wrote

Here's one opinion, an answer to my second question.
Dick


And to answer your first: It depends on how you define better.

Certainly Beautiful Soup will not be muh longer and a lot more 
elegant and probably more resilient.


Alan, expand a bit, please. Longer? Resilient?


But to extract a single piece of text in a well defined location 
then your approach although somewhat crude will work just fine.


Crude? What's crude about my code? I want to improve, so please tell 
me. http://py77.python.pastebin.com/fc7553a4


Thanks,

Dick
===
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? http://www.rcblue.com/u3/
Get Ulipad 3.9 from http://code.google.com/p/ulipad/downloads/list
svn for the latest revision http://ulipad.googlecode.com/svn/trunk/
Mailing list for Ulipad: http://groups-beta.google.com/group/ulipad

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Alan Gauld
Dick Moores [EMAIL PROTECTED] wrote 

Certainly Beautiful Soup will not be muh longer and a lot more 
elegant and probably more resilient.


Alan, expand a bit, please. Longer? Resilient?


Longer as in lines of code. BS is good for extracting several 
different parts from the soup, but just to pull out one very 
specific item the setup and so on may mean that the 
framework actually works out the same or longer than 
your code.


Resilient as in able to handle unexpected changes in 
the HTML used by the site or slight changes in formatting 
of the results etc.


But to extract a single piece of text in a well defined location 
then your approach although somewhat crude will work just fine.


Crude? What's crude about my code? 


Its just a little bit too hard coded for my liking, all that 
splitting and searching means theres a lot of work going on
to extract a small piece of data. You iterate over the whole 
page to do the first spliot, then you iterate over the whole 
thing again to find the line you want. Consider thios line:


if 'JPY' in x and 'USDJPY=X' in x:

Sincy JPY is in both strings the first check is effectively 
redundant but still requires a string search over the line.
A well crafted regex would probably be faster than the 
double in test and provide better checking by including

allowances for extra spaces or case changes etc.

Then having found the string once with 'in' you them have 
to find it again with split(). You could just have done 
a find the first time and stored the index as a basis for 
the slicing later.


You also use lots of very specific slicing values to extract the 
data - thats where you lose resilience compared to a parser 
approach like BS. Again I suspect a regex might work better 
in extracting the value. And hard coding the url in the function 
also adds to its fragility.


Stylistically all those single character variable names hurts 
readability and maintainability too. 

I want to improve, so please tell 


It will work as is, but it could be tidied up a bit is all.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen quote with Python?

2008-07-25 Thread Dick Moores

At 04:11 PM 7/25/2008, Alan Gauld wrote:

Dick Moores [EMAIL PROTECTED] wrote
Certainly Beautiful Soup will not be muh longer and a lot more 
elegant and probably more resilient.

Alan, expand a bit, please. Longer? Resilient?


Longer as in lines of code. BS is good for extracting several 
different parts from the soup, but just to pull out one very 
specific item the setup and so on may mean that the framework 
actually works out the same or longer than your code.


Resilient as in able to handle unexpected changes in the HTML used 
by the site or slight changes in formatting of the results etc.


But to extract a single piece of text in a well defined location 
then your approach although somewhat crude will work just fine.

Crude? What's crude about my code?


Its just a little bit too hard coded for my liking, all that 
splitting and searching means theres a lot of work going on
to extract a small piece of data. You iterate over the whole page to 
do the first spliot,


Ah. I had the idea that it would be better to split it into its 
natural lines, by line 7.  But I could have just started with the 
first relevant split.


 then you iterate over the whole thing again to find the line you 
want. Consider thios line:


if 'JPY' in x and 'USDJPY=X' in x:

Sincy JPY is in both strings the first check is effectively 
redundant but still requires a string search over the line.
A well crafted regex would probably be faster than the double in 
test and provide better checking by including

allowances for extra spaces or case changes etc.


I'll try to do that.

Then having found the string once with 'in' you then have to find it 
again with split().


Do you mean string x? After c = x (line 10), the next split is on c. 
I'm not finding it again, am I?


 You could just have done a find the first time and stored the 
index as a basis for the slicing later.


You also use lots of very specific slicing values to extract the 
data - thats where you lose resilience compared to a parser approach like BS.


Since I posted I found that I could add some resilience by extending 
the end of the slice and then cutting back with an rstrip().


I haven't the slightest idea what a parser is. But I'll find out 
while learning BS.


 Again I suspect a regex might work better in extracting the value. 
And hard coding the url in the function also adds to its fragility.


I can't imagine what else is possible?

Stylistically all those single character variable names hurts 
readability and maintainability too.


I was at a loss as to what variable names to use, so I figured I'd 
use a, b, c, .. in order, because I thought it was obvious that I was 
narrowing the search for the yen rate. Could you give me an idea of 
what names I could use?



I want to improve, so please tell


It will work as is, but it could be tidied up a bit is all.


Thanks Alan, for your tough look at the code. I appreciate it.

Dick
===
Have you seen Kelie Feng's video introducing the terrific and free
IDE, Ulipad? http://www.rcblue.com/u3/
Get Ulipad 3.9 from http://code.google.com/p/ulipad/downloads/list
svn for the latest revision http://ulipad.googlecode.com/svn/trunk/
Mailing list for Ulipad: http://groups-beta.google.com/group/ulipad

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to get a current mid-rate Yen

2008-07-25 Thread Lie Ryan
 Date: Fri, 25 Jul 2008 05:14:32 -0700
 From: Dick Moores [EMAIL PROTECTED]
 Subject: [Tutor] Is there a better way to get a current mid-rate Yen
 quote with Python?
 To: Python Tutor List tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii; format=flowed
 
 Better than this? http://py77.python.pastebin.com/fc7553a4
 
 I've heard about BeautifulSoup. 
 http://www.crummy.com/software/BeautifulSoup/. Is it worth 
 learning? Is it crummy? ;-)
 
 So 2 questions.
 
 Thanks,
 
 Dick Moores

Slightly better would be to use the re (regular expression) module.
It'd be more flexible than coding and easier than Beautiful Soup (which,
IMHO, is an overkill for simple data extraction like this).

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way to write this function?

2006-06-09 Thread Paul D. Kraus
This is a second... the first one never hit the list. *shrug* should i be using a different interface to post? is this a gateway to newsgroup?I am writing my first python program(at least in a really long time).
Its purpose is to take csv or pipe delimintaed files and convert them
to html pages. Was going to be excel but its just not worth the
headache. Everyone viewing the reports is doing just that viewing
simple tables.
I need to scan through a list that contains headers to my table.If
one of the elements is a tuple and one of the elements of the tuple is
s set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing
everything that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num column','r') ]I
pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented :)
Actual code in my working example used to call function ...report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header):
 list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's':
 self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append(header[cindex][tindex]) header[cindex] = tuple(list)
 self.header = header
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way to do this?

2004-12-22 Thread Ertl, John
I am trying to do the usual thing of asking for an input and then checking
it to see if it is valid.  If the entry is not valid then ask again until
you get the correct answer.

I have come up with this class.  I am trying to make a transition from
procedural programming to object oriented.   Is this a good approach for
such a check?  It seems to me this is more work then needed. (I can put in a
counter also to break out if you try too many times).

Please comment if you have the time. 

class greating:

def __init__(self):
self.OK = False
self.lowValue = 1
self.highValue = 6

def opening(self):
print 
Please choose from the following options.
1) - Normal Unit test with static data.
2) - Normal Unit test with missing data.
3) - Integration test with current DTG.
4) - Integration test with missing data.
5) - Clean directory
6) - Exit

self.choice = raw_input(Choice(1-6) )

def check(self):
try:
self.choice = int(self.choice)
except ValueError:
print Please enter a number from ,self.lowValue, to
,self.highValue
pass

if self.choice  self.highValue or self.choice  self.lowValue:
print You have entered an invalid entry. Please try again
else:
self.OK = True


a = greating()

while a.OK != True:
a.opening()
a.check()

print a.choice


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a better way to do this?

2004-12-22 Thread Kent Johnson
John,
In this case I think using a class is overkill. You can write a simple 
procedural version like this:
def getOption():
while True:
print 
Please choose from the following options.
1) - Normal Unit test with static data.
2) - Normal Unit test with missing data.
3) - Integration test with current DTG.
4) - Integration test with missing data.
5) - Clean directory
6) - Exit

choice = raw_input(Choice(1-6) )
try:
choice = int(choice)
except ValueError:
print Please enter a number from 1 to 6
if 1 = choice = 6:
return choice
print You have entered an invalid entry. Please try again
option = getOption()
print You chose, option
If you have multiple clients you could parameterize it so it becomes
def getOption(prompt, low, high)
I try to do the simplest thing that could possibly work. Sometimes that is just straight line code, 
with maybe a few functions mixed in. Sometimes a procedural approach works fine. Sometimes classes 
and objects are the right way to go, but I don't introduce classes until I need them.

Don't get me wrong, I am a huge fan of OOP, but sometimes it is a bigger hammer 
than you need.
Kent
Ertl, John wrote:
I am trying to do the usual thing of asking for an input and then checking
it to see if it is valid.  If the entry is not valid then ask again until
you get the correct answer.
I have come up with this class.  I am trying to make a transition from
procedural programming to object oriented.   Is this a good approach for
such a check?  It seems to me this is more work then needed. (I can put in a
counter also to break out if you try too many times).
Please comment if you have the time. 

class greating:
def __init__(self):
self.OK = False
self.lowValue = 1
self.highValue = 6
def opening(self):
print 
Please choose from the following options.
1) - Normal Unit test with static data.
2) - Normal Unit test with missing data.
3) - Integration test with current DTG.
4) - Integration test with missing data.
5) - Clean directory
6) - Exit

self.choice = raw_input(Choice(1-6) )
def check(self):
try:
self.choice = int(self.choice)
except ValueError:
print Please enter a number from ,self.lowValue, to
,self.highValue
pass

if self.choice  self.highValue or self.choice  self.lowValue:
print You have entered an invalid entry. Please try again
else:
self.OK = True

a = greating()
while a.OK != True:
a.opening()
a.check()
print a.choice
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor