[Tutor] List and dictionary comprehensions

2014-09-29 Thread Armindo Rodrigues
Hi everyone,

This is my first post so I don't know if I am asking the correct way so let
me know if I messed anything up.

***Please note. My code contains a list of quotes that has many lines. I
have noted the beginning and end of the quotes list so you can easily skip
and go straight to the code section. ***


This is technically NOT a homework assignment. I am the teaching assistant
for the Python course at my school. The teacher doesn't give me the
homework ahead of time so I typically try the homework myself so I can help
anyone else out that may be confused. The assignment has come and gone but
I want to challenge myself with making this thing more efficient and learn
comprehensions along the way.

The assignment was as follows:
The teacher provided the class with a list of quotes called data_list. We
were to implement a very simple search algorithm that took in a user's
query and we searched based on those words. If the user entered an OR then
we searched for quotes that contained either of the words. Any other
combination of AND OR will be an AND search.

Once we completed the search algorithm, the assignment called for
pre-processing that would make the search more efficient and faster. I
created a dictionary based on each word in the quotes list as the key and
then searched against those words. I greatly increased the search time.

MY QUESTION:
Can anyone look at this and explain how I could create a list comprehension
and a dictionary comprehension if possible? Also any suggestions with
making the search faster would be appreciated.


import re
from datetime import datetime
import time


###  DATA LIST STARTS HERE

data_list=["And now here is my secret, a very simple secret: It is only
with the heart that one can see rightly; what is essential is invisible to
the eye.",
"All grown-ups were once children... but only few of them remember it.",
"People have forgotten this truth,\" the fox said. \"But you mustn?t forget
it. You become responsible forever for what you?ve tamed. You?re
responsible for your rose.",
"It is the time you have wasted for your rose that makes your rose so
important.",
"The most beautiful things in the world cannot be seen or touched, they are
felt with the heart.",
"What makes the desert beautiful,' said the little prince, 'is that
somewhere it hides a well...",
"You - you alone will have the stars as no one else has them...In one of
the stars I shall be living. In one of them I shall be laughing. And so it
will be as if all the stars were laughing, when you look at the sky at
night...You - only you - will have stars that can laugh.",
"Well, I must endure the presence of a few caterpillars if I wish to become
acquainted with the butterflies.",
"You see, one loves the sunset when one is so sad.",
"You're beautiful, but you're empty...One couldn't die for you. Of course,
an ordinary passerby would think my rose looked just like you. But my rose,
all on her own, is more important than all of you together, since she's the
one I've watered. Since she's the one I put under glass, since she's the
one I sheltered behind the screen. Since she's the one for whom I killed
the caterpillars (except the two or three butterflies). Since she's the one
I listened to when she complained, or when she boasted, or even sometimes
when she said nothing at all. Since she's my rose.",
"If you love a flower that lives on a star, it is sweet to look at the sky
at night. All the stars are a-bloom with flowers...",
"And when your sorrow is comforted (time soothes all sorrows) you will be
content that you have known me. You will always be my friend. You will want
to laugh with me. And you will sometimes open your window, so, for that
pleasure . . . And your friends will be properly astonished to see you
laughing as you look up at the sky! Then you will say to them, 'Yes, the
stars always make me laugh!' And they will think you are crazy. It will be
a very shabby trick that I shall have played on you...",
"You become responsible, forever, for what you have tamed.",
"Of course I?ll hurt you. Of course you?ll hurt me. Of course we will hurt
each other. But this is the very condition of existence. To become spring,
means accepting the risk of winter. To become presence, means accepting the
risk of absence.",
"Where are the people?\" resumed the little prince at last. \"It?s a little
lonely in the desert\" \"It is lonely when you?re among people, too,\" said
the snake.",
"All men have stars, but they are not the same things for different people.
For some, who are travelers, the stars are guides. For others they are no
more than little lights in the sky. For others, who are scholars, they are
problems... But all these stars are silent. You-You alone will have stars
as no one else has them... In one of the stars I shall be living. In one of
them I shall be laughing. And so it will be as if all the stars will be
laughing when you look at the sky at night..You, only you, will have stars
that can

[Tutor] I've been trying to make this program work so i can transfer it to final user. please do have a look and see if the code can be corrected in anyway.

2014-09-29 Thread Brave Heart





Perrsonal Monney Assistance(PMA
===
1. ADD Record
2. MODIFY Record
3. DELETE Record
4. SHOW All
5. SHOW Summary
6. Exit
Please enter your Choise (1-6): 1
ADD Record
==
(Key in '-e' to back to main menu)

Key in new record .. 
Date : 09-09-2013
For : sh
Total : EU 10
Traceback (most recent call last):
  File "C:/Python34/cash.py", line 602, in 
main_menu()
  File "C:/Python34/cash.py", line 45, in main_menu
resp_process(resp)
  File "C:/Python34/cash.py", line 52, in resp_process
add_rec()
  File "C:/Python34/cash.py", line 115, in add_rec
add_func(date, desc, amt)
  File "C:/Python34/cash.py", line 339, in add_func
os.chdir(sqlite3_path)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 
'C:/sqlite3/'





















This is my code:

#***
#   Program Name : cash.py (Personal Finance Assistance)
#   Version  : 1.8
#   Desciption   : This program is menu-based program which can connect to 
database
#  and then performming addition, updating, deletion and showing
#  the summary. It use to record personal daily expenses.
#   Working in   : Null
#   Future   : Add "search" function,
#  Add some "Analysis Tools"  
#   Ext. Module  : sqlite3
#***


#imported library files
import sqlite3
import re
import os
import time
import sys

#global variables
sqlite3_path = ("C:/sqlite3/")
database = "cash.db"

# format = DD-MM-
date_format = r'^([0-3][\d])([-])([0-1][\d])([-])([\d]{4})$'


def main_menu():
'''Display main menu (LO)'''
os.system("cls")
print ("Perrsonal Monney Assistance(PMA")
print ("===")
print ("1. ADD Record")
print ("2. MODIFY Record")
print ("3. DELETE Record")
print ("4. SHOW All")
print ("5. SHOW Summary")
print ("6. Exit")
resp = input("Please enter your Choise (1-6): ")
resp_process(resp)


def resp_process(r):
'''Process the response from user input (L1)'''
if str(r).isdigit() == 1 and int(r) >= 0 and int(r) <= 5:
if r == '1':
add_rec()
elif r == '2':
edit_rec()
elif r == '3':
del_rec()
elif r == '4':
show_all()
elif r == '5':
show_summ()
else:
exit()

else:
print ("You have enter an invalid input\n")
time.sleep(2)
# return to main menu
main_menu()  


def add_rec():
'''Add data to db from user input (L1)'''
# get current date
currDate = time.strftime("%d-%m-%Y", time.localtime(time.time()))
cont = 1

os.system("cls")

#print function header
print ("ADD Record")
print ("==")
print ("(Key in '-e' to back to main menu)")

while cont == 1:
print ("\nKey in new record .. ")
# get input for date
date = input("Date : ")
back_main_menu(date)

if date == "":
date = currDate
else:
while date_check(date) == 0:
print ("Error! It's not a date.\n")
date = raw_input("Date : ")
back_main_menu(date)
if date == "":
date = currDate

# get input for description
desc = input("For : ")
back_main_menu(desc)

# get input for amount
amt = input("Total : EU ")
back_main_menu(amt)

while amt_check(amt) == 0:
print ("Error! It's not a money.\n")
amt = raw_input("Total : EU")
back_main_menu(amt)
amt = "%.2f" % float(amt)

# insert to sqlite
add_func(date, desc, amt)

resp = raw_input("Continue ? ")
resp = resp.upper()
if resp == 'N':
cont = 0
# return to main menu
main_menu()


def edit_rec():
''' Edit / Modify record in db(L1)'''
os.system("cls")

#print function header
print ("MODIFY Record")
print ("=")
print ("(Key in '-e' to back to main menu)")

s_date = raw_input("Enter the DATE of record you want to modify: ")
back_main_menu(s_date)

col = "date"
result = search_func(col, s_date)

# print search result
if len(result) > 0:
for i in range (len(result)):
dt = result[i][0]
ds = result[i][1]
at = result[i][2]
at = ("%.2f") % float(at)
print (i+1), ")",  ("%s%s%s%s%s%s%s%s%s") % ((" " * (2 - (i + 
len(")", "Date: ", dt, (" " * (20 - len(dt))), "Desc: ", ds, (" " * (25 - 
len(ds))), "Amount: RM", at)

row = raw_input("Enter the number of row you want to modify: ")
back_main_menu(row)

if row.isdigit() == 1:
  

[Tutor] Trouble with making a chart

2014-09-29 Thread Martin Skåreby
Hello!So i'm having trouble with a task i got from my teacher in a book. I'm 
supposed to create a chart which shows the converted numbers between Celsius 
and Fahrenheit. They want the Celsius to range from 40 to -40. I also get to 
know that Fahrenheit  = 32+celsius*9/5. Now I managed to write the number 40 to 
-40 from top to bottom. But i'm having trouble converting celsius to fahrenheit 
and printing it at the same time on the side of celsius. The chart should look 
something like this:Fahrenheit to Celsius=Celsius   
Fahrenheit40  10439  102,238  100,437   
   98,6etc.etc.My current code is: print("Fahrenheit to 
Celsius")print("===")print("Celsius\tFahrenheit")for f 
in range(40,-41,-1):print(f)for c in range(104,-41,-1):print(32 + c * 9 
/ 5)Now this makes the numbers for Fahrenheit to just add below celsius. How do 
I make them go to the other side  under the text Fahrenheit? I'm doing this in 
iPython Notebook.



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


Re: [Tutor] Python advice about API, JSON

2014-09-29 Thread Patrick Thunstrom
On Mon, Sep 22, 2014 at 4:01 PM, Juan Christian
 wrote:
> I'm trying to make my script the more pythonic possible. How would a good
> approach regarding external API and json be?

I don't think dealing with a specific API is actually appropriate for
this list. I'll try to answer the general elements.

> I'm calling this API (http://docs.themoviedb.apiary.io/) using 'requests'.
> The thing is that I need to do a bunch of different calls to the API:
>
> - http://api.themoviedb.org/3/person << Receive ID and return person info
> - http://api.themoviedb.org/3/tv << Receive ID and return serie info
> - http://api.themoviedb.org/3/movie << Receive ID and return movie info
> - http://api.themoviedb.org/3/search << Receive "Name of person or serie or
> movie" and return ID
>
> I have the following structures:
>
> - {query}/{type}?api_key={key}&query={person or tv or movie}
> - {query}/{id}?api_key={key}
> - {query}/{id}/credits?api_key={key}
> - {query}/{id}/season/{season_numer}?api_key={key}
> - {query}/{id}/season/{season_numer}/episode/{episode_number}?api_key={key}
> -
> {query}/{id}/season/{season_numer}/episode/{episode_number}/credits?api_key={key}
>
>
> I'm thinking about creating a class 'API' and have all these URLs and
> structures there. The thing is that I need to pass my API_KEY and this key
> will be used for everything, so I just need to pass it once, how can I do
> that? Yes, I know about class attributes, but the thing is that I will call
> this class 'API' from different classes and I'll need to instantiate a API
> obj in each of them, is it a good approach? Inside this 'API' class I would
> have a __init__ that would receive an API_KEY and different methods, each
> for a type of query (person, tv, movie, search, credits).

First question: Why do you need multiple versions of this theoretical
class floating around? Perhaps if you wrote a single module api that
handles interactions with the API, you can then import that module
into any other module that will use the API, and you only have to
write all of this once.

> Maybe my explanation is a bit confusing but I hope you guys understood,
> anyway, you can ask for more information if needed!
>
> And another thing, What's better, a single module with multiple classes
> (total lines: ~110) or multiple modules with 1-3 classes (correlated, like
> class serie, season and episode in the same module, and class person and
> character in the same module) each?

I personally prefer multiple modules, though it absolutely depends on
the demands of the project.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with pythonw.exe

2014-09-29 Thread Gregory Karakeussian
Hi there,

 

My antivirus has uninstalled pythonw.exe by mistake and now I can`t fix it,
deinstall it, reinstall it, I'm stuck.. is there a solution?

 

thanks

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


[Tutor] Python Serial Communication

2014-09-29 Thread m.v gautam
Hi,
I am trying out serial communication between raspberry pi and atmega 32 using 
pyserial module . I have tried serial communication between two atmega and it 
is working.
But when I try it rpi and atmega I get blank lines as output. My python code is 

import serial
ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10)
while True:
print "try"
val = ser.read(10)
print val
Output:
try

try.
There is a blank line being printed every time in place of val. The logic level 
conversion between atmega and rpi has been done perfectly.Can you tell me why 
'val' is being printed as blank value.
Thanks in advance.

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


[Tutor] python code error

2014-09-29 Thread Madeleine Austen
Hi

Here is my code:


from datetime import datetime
timeStart = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
numberPlates = 0
print("There has been {0} number plates since {1}".format (numberPlates,
timeStart))

speedLimit = 25
distance = 1

class NumberPlates:
  """A class that holds information from sensor for ANPR system"""
  distance = 1
def __init__(self, name, enter, exit):
self.number = name
self.enter = enter
self.exit = exit
def speed(self):
distance = 1
time = exit - enter
speed = distance/time
print(speed)


one = NumberPlates("lemon", 1030, 1050)


one.speed()




It says there are no arguements


Thanks
Madeleine
-- 
*Madeleine Austen*
*11L*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] code help

2014-09-29 Thread itsthewendigo1111 .
I'm taking an online intro to programing class unfortunately the teacher
has not be very helpful.   well this is the assignment
http://burtondsc.pbworks.com/w/file/fetch/84469141/Assignment03.pdf and
here is my code so far

from tkinter import*
master = Tk();

canvas = Canvas(master, width = simpledialog.askinteger("Canvas size",
"Enter width of canvas"))
canvas = Canvas(master, height = simpledialog.askinteger("Canvas size",
"Enter height of canvas"))
canvas = Canvas(master, background = simpledialog.askstring("Canvas color",
"Enter color for canvas"))
canvas.pack()

s1 = canvas.create_rectangle(150,300,450,150, width =
simpledialog.askinteger('Square size', "Enter side length of square"))
s1 = simpledialog.askstring("Square color","Enter color for the square")


I'm having trouble with the "width = simpledialog.askinteger".  width
almost makes like a border and not resize the square.   I have tried using
size,length, len, scale, but nothing seems to work.  I'm also having
trouble with getting the square to change color.  If u guys could offer any
help I would really appreciate it
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Back from vacation

2014-09-29 Thread Alan Gauld
I'm just home from vacation and have flushed the moderation queue so 
there might be some out of date or repeat messages appearing out of 
sequence.


Apologies, but normal service should now be resumed.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] List and dictionary comprehensions

2014-09-29 Thread Alan Gauld

On 28/09/14 03:36, Armindo Rodrigues wrote:


have noted the beginning and end of the quotes list so you can easily skip
and go straight to the code section. ***


It would probably have been better to just delete all but a nfew of the 
quotes. We don't need all of them to evaluate your code.



import re
from datetime import datetime
import time


###  DATA LIST STARTS HERE

data_list=["And now here is my secret, a very simple secret: It is only
with the heart that one can see rightly; what is essential is invisible to
the eye.",
"All grown-ups were once children... but only few of them remember it.",

...

"If you love a flower that lives on a star, then it's good at night, to
look up at the sky. All the stars are blossoming."]


## CODE STARTS HERE

#Create a list of words taken from each individual word in the datalist
word_list = []
for item in data_list:
 for word in item.split(" "):
 word = re.sub('^[^a-zA-z]*|[^a-zA-Z]*$','', word)


word.strip() would be better here. You can specify a string of chars to 
be stripped if its not only whitespace. Consider regular expressions as 
a weapon of last resort.



 word_list.append(word)
word_list = sorted(list(set(word_list))) #Remove repeated words


You don't need to convert the set into a list. sorted() works
with sets too.


quotesDict = {}
for word in word_list:
 quotesDict.setdefault(word,[]) #Create a dictionary with keys based on
each word in the word list


By putting the words in the dictionary you lose the sorting you did 
above. So the sorting was a waste of time.



for key, value in quotesDict.items():
 indexofquote = 0
 for quote in data_list:


You should use enumerate for this. It will automatically give you the 
index and quote and be less error prone than maintaining the index yourself.



 if key in quote:
 quotesDict[key].append(indexofquote) #Append the index of the
found quotes to the dictionary key
 indexofquote+=1

query=input("query: ")
query = query.strip(" ").split(" ")
query = list(set(query))



I don;t think you need the conversion to list here either.
You can just use the set.


start_time = time.time()

FoundQuotes = []

# Right now the OR search just prints out the index of the found quotes.
if ("or" in query) and ("and" not in query):


The logic here can be simplified by testing for 'and' first

if 'and' in query
   remove 'or'
   process and
elif 'or' in query
   process 'or'
else process simple query




 query.remove("or")
 print("Performing OR search for: ", query)
 for item in query:
 if (item in quotesDict):
 print("FOUND ",len(quotesDict[item]),  " ", item, "QUOTES: ",
quotesDict.get(item))
 print("\n--- Execution ---\n", (time.time() - start_time) * 1000,
"microseconds\n")

else:
 if "and" in query:
 query.remove("and")
 if "or" in query:
 query.remove("or")
 print("Performing AND search for: ", query)


This looks wrong. What about the case where neither and/or are in the query?


 for item in query:
 if (item in quotesDict):
 FoundQuotes = FoundQuotes + (quotesDict.get(item))
 FoundQuotes = list(set([x for x in FoundQuotes if FoundQuotes.count(x)

1]))


This doesn't look right either.
Foundquotes is a list of indexes. The comprehension builds a list of all 
the indexes that appear more than once - what about a quote that was 
only found once?


It then eliminates all the duplicates(set()) and returns it back to a 
list(why not leave it as a set?)


I'd have expected a simple conversion of FoundQuotes to a set would be 
what you wanted.



 for x in FoundQuotes:
 print(data_list[x])
 print("\n--- Execution ---\n", (time.time() - start_time) * 1000,
"microseconds\n")


The other problem is that you are serching the dictionary
several times, thus losing some of the speed advantage of
using a dictionary.

You would get more benefit from the dictionary if you adopt a try/except 
approach and just access the key directly. So, instead of:


>  for item in query:
>  if (item in quotesDict):
>  FoundQuotes = FoundQuotes + (quotesDict.get(item))

for item in query:
  try: FoundQuotes = FoundQuotes + quotesDict[item]
  except KeyError: pass

Or better still use the default value of get:

for item in query:
FoundQuotes = FoundQuotes + quotesDict.get(item,[])

There are a few other things that could be tidied up but that should 
give you something to get started with.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Problem with pythonw.exe

2014-09-29 Thread Alan Gauld

On 27/09/14 20:32, Gregory Karakeussian wrote:


My antivirus has uninstalled pythonw.exe by mistake and now I can`t fix it,
deinstall it, reinstall it, I'm stuck.. is there a solution?


What happens when you try to reinstall?

Turn off the antivirus before doing so of course.

Maybe get a new antivirus program too?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Python Serial Communication

2014-09-29 Thread Alan Gauld

On 28/09/14 10:32, m.v gautam wrote:


import serial
ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10)
while True:
 print "try"
 val = ser.read(10)
 print val



There is a blank line being printed every time in place of val.


How do you know that val is not a blank line?
Remember that a blank line is not necessarily empty, it might be full of 
unprintable characters.


Try this instead:

while True:
 print "try"
 val = ser.read(10)
 print 'len: ', len(val)
 for char in val:
print ord(char)

That will tell you ow many characters you actually
read and what character values are being read.
You might find you have and end of file in there or similar.


The logic level conversion between atmega and rpi has been done perfectly.


That's a very bold claim. Very little is ever perfect in programming.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] I've been trying to make this program work so i can transfer it to final user. please do have a look and see if the code can be corrected in anyway.

2014-09-29 Thread Alan Gauld

On 26/09/14 12:58, Brave Heart wrote:


   File "C:/Python34/cash.py", line 339, in add_func
 os.chdir(sqlite3_path)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 
'C:/sqlite3/'


I assume you have checked that the folder exists? and
that you (ie. the user running the program) have permission
to go there?



def add_func(dt, ds, at):
 '''Insert data into db(L2)'''
 sql_insert = """
 INSERT INTO expenses (date, desc, amount)
 VALUES ('%s', '%s', '%s')
 """ % (dt, ds, at)

 os.chdir(sqlite3_path)

 # open connection to database
 try:
 cx = sqlite.connect(database)
 except sqlite.Error(errmsg):
 print ("Can not open ") +str(errmsg)

 # insert data into table
 try:
 cu = cx.cursor()
 cu.execute(sql_insert)
 cx.commit()
 except sqlite.Error(errmsg):
 print ("Can not execute: ") +str(errmsg)

 # close connection
 cx.close()


BTW Its probably better to set the database to the full path rather than 
change into the folder for every access of the database.

In fact I usually just open the database once at the start
of my program. The data functions then only need to create
a cursor (in fact I often keep the cursor open too!).

That reduces the work in each function and the duplication of code
although you could put the open and cursor code into a function
called by the other data functions - that would help with
maintenance in future.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Trouble with making a chart

2014-09-29 Thread Alan Gauld

On 24/09/14 07:07, Martin Skåreby wrote:

Hello!So i'm having trouble with a task i got from my teacher in a book. I'm supposed to create a chart which 
shows the converted numbers between Celsius and Fahrenheit. They want the Celsius to range from 40 to -40. I 
also get to know that Fahrenheit  = 32+celsius*9/5. Now I managed to write the number 40 to -40 from top to 
bottom. But i'm having trouble converting celsius to fahrenheit and printing it at the same time on the side 
of celsius. The chart should look something like this:Fahrenheit to Celsius=Celsius   
Fahrenheit40  10439  102,238  100,437  98,6etc.
etc.My current code is: print("Fahrenheit to 
Celsius")print("===")print("Celsius\tFahrenheit")for f in 
range(40,-41,-1):print(f)for c in range(104,-41,-1):print(32 + c * 9 / 5)Now this makes the numbers 
for Fahrenheit to just add below celsius. How do I make them go to the other side  under the text Fahrenheit? 
I'm

doing this in iPython Notebook.

Please send emails in plain text. Yours has come out as one long line...

I'll try to reformat as best I can...

> same time on the side of celsius. The chart should look something
> like this:
> Fahrenheit to Celsius
> =
> Celsius   Fahrenheit
> 40  104
> 39  102

> current code is:
> print("Fahrenheit to Celsius")
> print("===")
> print("Celsius\tFahrenheit")
> for f in range(40,-41,-1):
>print(f)
> for c in range(104,-41,-1):
>print(32 + c * 9 / 5)

> Now this makes the numbers for Fahrenheit to just add
> below celsius. How do I make them go to the other side

The normal way to do this is store the results before
trying to print them.
Then you can use string formatting to print both
figures in a single line.

Something like this pseudocode:

results = []
for c in range(-41,40):
f = (32+c*9/5)
results.append( (c,f) )

print headers
for result in results:
print("{}\t{}".format(result))


The notebook of IPython can do much cleverer things with
data but I'll ignore that for now and stick with
simple text tables.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] code help

2014-09-29 Thread Alan Gauld

On 22/09/14 16:16, itsthewendigo . wrote:


from tkinter import*
master = Tk();

canvas = Canvas(master, width = simpledialog.askinteger("Canvas size",
"Enter width of canvas"))


Its generally a bad idea to mix interactivity with widget creation. 
Better(and much easier to debug) to query the width first then create 
the widget:


w = simpledialog.askinteger("Canvas size", "Enter width of canvas")
canvas = Canvas(master, width = w)

Then you can print out the value of w or inspect it in a debugging tool.

Also you create several canvases but store only the last one in your 
canvas widget. Is that really what you want? Or do you really want to 
configure several attributes of the same canvas? Inwhich case use the 
configure method of the widget:

eg:
h = simpledialog
col = simpledialog
canvas.configure(height=h, color=col)  #etc...



s1 = canvas.create_rectangle(150,300,450,150, width =
simpledialog.askinteger('Square size', "Enter side length of square"))
s1 = simpledialog.askstring("Square color","Enter color for the square")


Here you have overwritten your square widget variable with
the string value. Is that really what you want?



I'm having trouble with the "width = simpledialog.askinteger".  width
almost makes like a border and not resize the square.


I'm assuming you are referring to the width in the rectangle widget
not the width in the canvas. Have you checked the documentation
of the square to see what the width parameter does?

The size of the rectangle is set by the two points you give it

s1 = canvas.create_rectangle(150,300,450,150,...

So it starts at (150,300) and ends at (450,150) So its size
in pixels is:

150-450 = 300
300-150 = 150


trouble with getting the square to change color.


You need to look at the fill attribute I suspect.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Python Serial Communication

2014-09-29 Thread Steven D'Aprano
On Mon, Sep 29, 2014 at 12:58:09PM +0100, Alan Gauld wrote:
[...]
> How do you know that val is not a blank line?
> Remember that a blank line is not necessarily empty, it might be full of 
> unprintable characters.
> 
> Try this instead:
> 
> while True:
>  print "try"
>  val = ser.read(10)
>  print 'len: ', len(val)
>  for char in val:
> print ord(char)

Another way to see invisible control characters is:

print repr(val)



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


Re: [Tutor] Python Serial Communication

2014-09-29 Thread Steven D'Aprano
On Sun, Sep 28, 2014 at 05:32:26PM +0800, m.v gautam wrote:
> Hi,
> I am trying out serial communication between raspberry pi and atmega 32 using 
> pyserial module . I have tried serial communication between two atmega and it 
> is working.
> But when I try it rpi and atmega I get blank lines as output. My python code 
> is 
> 
> import serial
> ser = serial.Serial('/dev/ttyAMA0',38400,timeout = 10)
> while True:
> print "try"
> val = ser.read(10)
> print val

According to this Stackoverflow question, you need to use keyword 
arguments. Try this:

val = ser.read(size=10)

http://stackoverflow.com/questions/19143360/python-writing-to-and-reading-from-serial-port


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


Re: [Tutor] List and dictionary comprehensions

2014-09-29 Thread Peter Otten
Armindo Rodrigues wrote:

> Hi everyone,
> 
> This is my first post so I don't know if I am asking the correct way so
> let me know if I messed anything up.
> 
> ***Please note. My code contains a list of quotes that has many lines. I
> have noted the beginning and end of the quotes list so you can easily skip
> and go straight to the code section. ***
> 
> 
> This is technically NOT a homework assignment. I am the teaching assistant
> for the Python course at my school. The teacher doesn't give me the
> homework ahead of time so I typically try the homework myself so I can
> help anyone else out that may be confused. The assignment has come and
> gone but I want to challenge myself with making this thing more efficient
> and learn comprehensions along the way.
> 
> The assignment was as follows:
> The teacher provided the class with a list of quotes called data_list. We
> were to implement a very simple search algorithm that took in a user's
> query and we searched based on those words. If the user entered an OR then
> we searched for quotes that contained either of the words. Any other
> combination of AND OR will be an AND search.
> 
> Once we completed the search algorithm, the assignment called for
> pre-processing that would make the search more efficient and faster. I
> created a dictionary based on each word in the quotes list as the key and
> then searched against those words. I greatly increased the search time.

That is very unlikely. Note that you include the print() calls into your 
measurement. These will dominate the time you measure, i. e. searches with 
more matching text will appear to take longer and searches with little or no 
text will appear to be fast.

> MY QUESTION:
> Can anyone look at this and explain how I could create a list
> comprehension and a dictionary comprehension if possible? 

I tried to solve the problem myself below -- and did not find a place where 
list comprehensions would fit in naturally.

> Also any
> suggestions with making the search faster would be appreciated.

As hinted above, your code does not have speed issues; you can simplify and 
clean it a bit (I stopped halfway), put every separate step into a function 
with an informative name, avoid global variables, follow the naming 
conventions of PEP 8  -- and that's 
it.

My most significant modifications:

- Use the strings directly instead of indices into the list
- Build the word-to-quote lookup directly without the intermediate list of
  all words.

#!/usr/bin/env python3
import re
import time
from itertools import zip_longest
from sys import exit

data_list = [...] # won't repeat your data

RED = "\033[31m"
BLUE = "\033[34m"

EMPTY = frozenset()


def colored(s, color):
# if the coloring attempt messes up your screen
# change this to
# return s
return "%s%s\033[0m" % (color, s)


def find(term):
return quotes_dict.get(term.lower(), EMPTY)


def mark_terms(phrase, terms):
def mark(m):
return colored(m.group(), RED)

expr = r"\b(%s)\b" % "|".join(terms)
return re.compile(expr).sub(mark, phrase)


def clean(word):
return re.sub('^[^a-zA-z]*|[^a-zA-Z]*$', '', word)


quotes_dict = {}
for item in data_list:
for word in item.split():
quotes_dict.setdefault(clean(word), set()).add(item)

query = input("query: ")

start_time = time.time()

query = query.split()
if not query:
exit("no search term")

terms = query[::2]
found_quotes = find(query[0])
for operator, term in zip_longest(query[1::2], query[2::2]):
if term is None:
exit("dangling operator " + operator)
operator = operator.lower()
if operator == "or":
found_quotes |= find(term)
elif operator == "and":
found_quotes &= find(term)
else:
print("unknown operator", operator)
exit(1)

print(
"\n--- Execution ---\n",
(time.time() - start_time) * 1000, "microseconds\n")

for index, quote in enumerate(found_quotes):
print(colored("{} >>>".format(index), BLUE), mark_terms(quote, terms))

Note that my handling of the operators does not follow your teacher's spec. 
It simply `or`s or `and`s the next match to what is in the current set of 
matches.

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


Re: [Tutor] python code error

2014-09-29 Thread Dave Angel
Madeleine Austen  Wrote in message:
>
> 
 It says there are no arguements

I don't see any print functions with such text, so presumably
 you're paraphrasing an exception traceback.  Please quote the
 entire traceback,  as there is usually lots of information there.
 And use copy/paste,  don't attempt to retype it.

If I had to guess, I'd say your indentation is the problem. The
 methods of a class must be indented inside the class. As written,
  you have defined no methods.

Please use text mode in your messages,  not html.  Frequently
 indentation is messed up by buggy html.

Also, please specify at least the version numbers for Python, 
 your os, and anything else relevant. 

-- 
DaveA

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


Re: [Tutor] python code error

2014-09-29 Thread Danny Yoo
On Sun, Sep 28, 2014 at 8:26 AM, Madeleine Austen
 wrote:
> Hi
>
> Here is my code:
>
>
> from datetime import datetime
> timeStart = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
> numberPlates = 0
> print("There has been {0} number plates since {1}".format (numberPlates,
> timeStart))
>
> speedLimit = 25
> distance = 1
>
> class NumberPlates:
>   """A class that holds information from sensor for ANPR system"""
>   distance = 1
> def __init__(self, name, enter, exit):
> self.number = name
> self.enter = enter
> self.exit = exit
> def speed(self):
> distance = 1
> time = exit - enter
> speed = distance/time
> print(speed)
>
>
> one = NumberPlates("lemon", 1030, 1050)
>
>
> one.speed()
>
>
>
>
> It says there are no arguements

Hi Madeleine,


Unlike English class, you're not penalized for copying-and-pasting
errors for diagnostic, bug tracking purposes.  I can tell that you've
paraphrased the error in some way because what you report has a
spelling mistake that's not present anywhere in the Python source
tree.

What you've done is somewhat akin to what happened to the poor Ecce
Homo painting:

http://en.wikipedia.org/wiki/Ecce_Homo_(El%C3%ADas_Garc%C3%ADa_Mart%C3%ADnez)

in paraphrasing a perfectly good error message.  :P


Please include the exact error message.  When you do so,
copy-and-paste is your friend.  When you see the error message, please
copy and paste the exact error text.  It helps to copy the entire
error context if it's not too large.  Show the program run.


Provide more precise information, and that will help folks here give
you good help.  Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor