Re: [Tutor] Limit raw_input to hundredth decimal point

2011-07-02 Thread Ryan Kirk
Thanks all! This helps a lot.

On Jul 1, 2011, at 6:13 AM, Steven D'Aprano wrote:

> Ryan Kirk wrote:
>> Is there a way to limit raw_input to the hundredth decimal point?
> 
> No. raw_input is a tool that does one thing: it collects input from the user. 
> It doesn't understand numbers, check for decimal places, check the input for 
> spelling errors, or anything else. It's a hammer, not a combination 
> hammer-screwdriver-wrench-drill-saw-axe :)
> 
> One solution is to build a new tool that checks for decimal places:
> 
> 
> def check(text):
>try:
>x = float(text)
>except ValueError:
>print "please enter a number"
>return None
>y = x*100
>if y - int(y) != 0:
>print "please enter only two decimal places"
>return None
>return x
> 
> 
> def get_number(prompt):
>answer = None
>while answer is None:
>text = raw_input(prompt)
>answer = check(text)
>return answer
> 
> 
> At first, this seems to work well:
> 
> >>> get_number("Please enter a number with two decimal places: ")
> Please enter a number with two decimal places: 77.25
> 77.25
> >>>
> 
> but there's a fundamental problem. The user is entering numbers in decimal 
> (base 10), but Python does calculations in binary (base 2), and something 
> that has two decimal places may not be exact in binary:
> 
> >>> get_number("Please enter a number with two decimal places: ")
> Please enter a number with two decimal places: 77.21
> please enter only two decimal places
> 
> Huh? 77.21 does have two decimal places. But the closest float to 77.21 is in 
> fact 77.204. No computer on Earth can store 77.21 *exactly* as a 
> binary float, no matter how hard you try!
> 
> So, what to do...? You can:
> 
> (1) Give up on forcing the user to only enter two decimal places, and instead 
> use the round() function to round to two places:
> 
> >>> round(77.2123456, 2)
> 77.204
> 
> This is still not two decimal places, but it is the closest possible float to 
> 7.21, so you can't do any better.
> 
> (2) Or give up on using float, and use the decimal module instead. (However 
> decimals are slower and less convenient than floats.)
> 
> >>> from decimal import Decimal
> >>> x = Decimal("77.21")
> >>> x
> Decimal("77.21")
> 
> 
> If you are working with currency, then you should use decimal, and not floats.
> 
> 
> 
> Good luck!
> 
> 
> 
> -- 
> Steven
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] (no subject)

2011-07-02 Thread Marc Tompkins
On Fri, Jul 1, 2011 at 7:11 PM, David Merrick  wrote:

> NameError: global name 'stash' is not defined
>
>
There are a _lot_ of missing pieces here; I think you started writing code
without a plan of how your game would actually run.  The current error is
only the first you're going to run into here...  That being said, we might
as well fix the first one.

You either have several problems here, or just one; I'm going to go for the
"just one" option: I'm going to assume that you actually want "stash" to be
an attribute of a Bet object - I think that it should be an attribute of
each player, not of their individual bets, but that's another issue.

The only time you can refer to a variable without qualifying it is from
within the same block of code.  Otherwise, the interpreter has to guess
which context (also known as "scope") the variable is supposed to belong to,
and the interpreter refuses to guess.  The error you're getting boils down
to "You referred to a variable called 'stash', but since you didn't define
it in the local scope, I assume it's a global variable - but you didn't
define it there either!  What gives?"

In Bet.__init__(), you have

> stash = money
>
This makes "stash" a local variable in the scope of __init__(), and as soon
as __init__() terminates, so does "stash".
What you want is:

> self.stash = money
>
This makes "stash" an attribute of Bet.

To refer to "stash" from inside the Bet object, you need to refer to it as
"self.stash"; from outside, after you've created a Bet object ("bet =
Bet()") you need to refer to it as "bet.stash".

One more thing: you define Bet.__init__() as taking two parameters, "bet"
and "money"; you make "money" optional by defaulting it to 10, but "bet" has
no default, so if your program ever got around to executing "bet = Bet()" it
would blow up because of a missing parameter.

Also, your use of variable names is confusing.  "bet = Bet()" is OK, but
ALSO having "bet" as a parameter to Bet.__init__()?  Python won't be
confused, but I bet you will be - I know I am.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Blackjack 2 - was Re: (no subject)

2011-07-02 Thread Alan Gauld

Please provide a meaningful subject!

"David Merrick"  wrote ># Blackjack


class BJ_Game(object):
   """ A Blackjack Game. """
   def __init__(self, names):
   self.players = []
   for name in names:
   player = BJ_Player(name)
   self.players.append(player)

   self.dealer = BJ_Dealer("Dealer")

   self.deck = BJ_Deck()
   self.deck.populate()
   self.deck.shuffle()

   bet = 0
   bet = Bet()
   bet.betting(stash)




def main():
   print("\t\tWelcome to Blackjack!\n")
   stash = 0
   names = []
   number = games.ask_number("How many players? (1 - 7): ", low = 1, 
high > .


   game = BJ_Game(names)


 File "I:/Python/programs/blackjackBetting.py", line 224, in 


   main()
 File "I:/Python/programs/blackjackBetting.py", line 216, in main
   game = BJ_Game(names)
 File "I:/Python/programs/blackjackBetting.py", line 147, in 
__init__

   bet.betting(stash)
NameError: global name 'stash' is not defined


It says stash is not defined. That means there is no
variable named stash visible to Python inside the
init method of BJ_Game.

The only stash defined is in the main function.
variables defined inside a function (including main()
are *only* visible within that function, nowhere else.

But you have lots of missing names all over.
I suggest you review yuour code before trying
to run it, otherwise you will be seeing a lot of
these error messages.

You will fund information about naming and scope
in the "Whats in a name?" topic of my tutorial.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


[Tutor] Cython question

2011-07-02 Thread Albert-Jan Roskam
Hi,

Some time ago I finished a sav reader for Spss .sav data files (also with the 
help of some of you!):
http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/

It works fine, but it is not fast with big files. I am thinking of implementing 
two of the functions in cython (getValueChar and getValueNum).
As far as I understood it requires the functions to be re-written in a 
Python-like langauge, 'minus the memory manager'. That little piece of code is 
converted to C and subsequently compiled to a .dll or .so file. The original 
program listens and talks to that .dll file. A couple of questions:
-is this a correct representation of things?
-will the speed improvement be worthwhile? (pros)
-are there reasons not to try this? (cons)
-is it 'sane' to mix ctypes and cython for nonintensive and intensive 
operations, respectively?

Thanks in advance!

Cheers!!
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the 
Romans ever done for us?
~~
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cython question

2011-07-02 Thread Stefan Behnel

Albert-Jan Roskam, 02.07.2011 11:49:

Some time ago I finished a sav reader for Spss .sav data files (also with the
help of some of you!):
http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/

It works fine, but it is not fast with big files. I am thinking of implementing
two of the functions in cython (getValueChar and getValueNum).
As far as I understood it requires the functions to be re-written in a
Python-like langauge


"rewritten" only in the sense that you may want to apply optimisations or 
provide type hints. Cython is Python, but with language extensions that 
allow the compiler to apply static optimisations to your code.




, 'minus the memory manager'.


Erm, not sure what you mean here. Cython uses the same memory management as 
CPython.




That little piece of code is
converted to C and subsequently compiled to a .dll or .so file. The original
program listens and talks to that .dll file. A couple of questions:
-is this a correct representation of things?


More or less. Instead of "listens and talks", I'd rather say "uses". What 
you get is just another Python extension module which you can use like any 
other Python module.




-will the speed improvement be worthwhile? (pros)


Depends. If your code is I/O bound, then likely not. If the above two 
functions are true CPU bottlenecks that do some kind of calculation or data 
transformation, it's likely going to be faster in Cython.




-are there reasons not to try this? (cons)


If your performance problem is not CPU related, it may not be worth it.



-is it 'sane' to mix ctypes and cython for nonintensive and intensive
operations, respectively?


Why would you want to use ctypes if you can use Cython?

Stefan

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


Re: [Tutor] Cython question

2011-07-02 Thread Alan Gauld

"Albert-Jan Roskam"  wrote

As far as I understood it requires the functions to be re-written in 
a

Python-like langauge, 'minus the memory manager'.


Thats what I understand too, but I've only read the web docs :-)


converted to C and subsequently compiled to a .dll or .so file.
The original program listens and talks to that .dll file.


I believe it effectively becomes a module that you
import like any other.


-will the speed improvement be worthwhile? (pros)


That depends on the structure of your code.

Profile it first to prove that the functions you are
optimising are in fact the places where the bulk
of the time is spent.

Then check that those functions aren't spending
their time calling C functions already. If all you have
is a loop calling a fubction that is already in C then
cython is unlikely to give huge improvement. But
if you have a lot of python code doing real
processing then yes cython (or similar) should
make a significant difference (ie up to say, 10 times
faster)


-are there reasons not to try this? (cons)


If you optimise the wrong bits you might just waste
your time and it will make future maintenance
more difficult because you have two environments
to support.  Have you tried optimising the Python
code first?


-is it 'sane' to mix ctypes and cython for nonintensive
and intensive operations, respectively?


In the same app yes, in the same function I'd guess
probably not. But I'll let others with more experience
of using both comment.

But bear in mind I've only read the cython docs,
not actually used it...

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Blackjack problem

2011-07-02 Thread Walter Prins
Hi David (and Vincent, as I think you may be interested in this as well),

On 2 July 2011 03:11, David Merrick  wrote:

> # Blackjack
> # From 1 to 7 players compete against a dealer
>

I came accross this book (
http://homepage.mac.com/s_lott/books/oodesign/build-python/html/index.html )
on the internet today, which I submit may be helpful in your journey of
learning.  It specifically covers building object oriented design type
skills (as opposed to learning Python or programming as such) and also has
as subject matter the game of Blackjack (amongst several others.)   The
author also has 2 other books, one specifically for learning the basics of
Python the language and another for learning the basics of programming in
general, which may also be helpful.

Anyway, hope that helps,

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


Re: [Tutor] Cython question

2011-07-02 Thread Albert-Jan Roskam
Hi Stefan, Alan, Matt,

Thanks for your replies. 

I used cProfile to find the bottlenecks, the two Python functions getValueChar 
and getValueNum. These two Python functions simply call two equivalent C 
functions in a .dll (using ctypes). The problem is that these functions are 
called as many times as there are VALUES in a file (e.g. 1000 records * 100 
columns = 10 function calls). So if I understand you correctly, this is not 
Cpu bound and, therefore, alas, Cython won't improve the excution time. Correct?

That .dll contains many more functions, for example to extract certain header 
information (a list of all the spss variables, etc.). Getting this kind of 
information is only done once per spss file. So, to answer your question, 
Stefan, I'd like this part of the code to remain the same, ie. with ctypes. 
Nothing much to win anyway, with just one function call per data file.

Cython might be useful when the program is converting spss date/times (seconds 
since gregorian epoch) to iso-date/times. If I understand it correctly, this is 
certainly cpu bound.

Btw, Matt, I indeed used psyco already, although I never precisely quantified 
the improvement in speed.
 
Cheers!!

Albert-Jan



~~

All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the Romans ever done for us?

~~

--- On Sat, 7/2/11, Stefan Behnel  wrote:

From: Stefan Behnel 
Subject: Re: [Tutor] Cython question
To: tutor@python.org
Date: Saturday, July 2, 2011, 1:29 PM

Albert-Jan Roskam, 02.07.2011 11:49:
> Some time ago I finished a sav reader for Spss .sav data files (also with the
> help of some of you!):
> http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/
> 
> It works fine, but it is not fast with big files. I am thinking of 
> implementing
> two of the functions in cython (getValueChar and getValueNum).
> As far as I understood it requires the functions to be re-written in a
> Python-like langauge

"rewritten" only in the sense that you may want to apply optimisations or 
provide type hints. Cython is Python, but with language extensions that allow 
the compiler to apply static optimisations to your code.


> , 'minus the memory manager'.

Erm, not sure what you mean here. Cython uses the same memory management as 
CPython.


> That little piece of code is
> converted to C and subsequently compiled to a .dll or .so file. The original
> program listens and talks to that .dll file. A couple of questions:
> -is this a correct representation of things?

More or less. Instead of "listens and talks", I'd rather say "uses". What you 
get is just another Python extension module which you can use like any other 
Python module.


> -will the speed improvement be worthwhile? (pros)

Depends. If your code is I/O bound, then likely not. If the above two functions 
are true CPU bottlenecks that do some kind of calculation or data 
transformation, it's likely going to be faster in Cython.


> -are there reasons not to try this? (cons)

If your performance problem is not CPU related, it may not be worth it.


> -is it 'sane' to mix ctypes and cython for nonintensive and intensive
> operations, respectively?

Why would you want to use ctypes if you can use Cython?

Stefan

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


[Tutor] problem with reading dns query

2011-07-02 Thread preetam shivaram
I have got a very simple idea in mind that i want to try out. Say i have a
browser, chrome for instance, and i want to search for the ip of the domain
name, say `www.google.com`. I use windows 7 and i have set the dns lookup
properties to manual and have given the address `127.0.0.1` where my server
(written in Python) is running. I started my server and i could see the dns
query like this:

WAITING FOR CONNECTION.

.recieved from :  ('127.0.0.1', 59339)

"'~\\x17\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03www\\x06google\\x02co\\x02in\\x00\\x00\\x01\\x00\\x01'"

The `waiting for connection` and the `received from` is from my server. How
do i get a breakdown form(a human readable form) of this message??



This is my server code(quiet elementary but still):


Here is the code:

from time import sleep
import socket
host=''
port=53
addr_list=(host,port)
buf_siz=1024
udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp.bind(addr_list)
while True:
print 'WAITING FOR CONNECTION.'
data,addr = udp.recvfrom(buf_siz) print '.recieved from :
',addr
sleep(3)
print repr(data)

is there any better way to get the dns request fro my browser first ,extract
the domain name and then send it to a name server that i wish all in python
? if here is pl explain it without any third party modules i wouldn mind
re-inventing the wheel as long as i can learn all python concepts properly

Thanking you in advance!!!

Yours thankfully,
Preetam
(A python freak)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cython question

2011-07-02 Thread Alan Gauld
"Albert-Jan Roskam"  wrote 

I used cProfile to find the bottlenecks, the two 
Python functions getValueChar and getValueNum. 
These two Python functions simply call two equivalent 
C functions in a .dll (using ctypes). 


In that case cythin will speed up the calling loops 
but it can't do anything to speed up the DLL calls, 
you have effectively already optimised those 
functions by calling the DLL.


The problem is that these functions are called 
as many times as there are VALUES in a file 


It might be worth a try if you have very big data sets
because a C loop is faster than a Python loop. 
But don't expect order of magnitude improvements.


So if I understand you correctly, this is not Cpu 
bound and, therefore, alas, Cython won't improve 
the excution time. Correct?


It may still be CPU bound in that the CPU is doing 
all the work, but if the CPU time is in the DLL 
functions rather than in the loop cython won't 
help much.


CPU bound refers to the type of processing - is 
it lots of logic, math, control flows etc? Or is 
it I/O bound - reading network, disk, or user input?
Or it might be memory bound - creating lots of 
in memory objects (especially if that results in 
paging to disk, when it becomes I/O bound too!)


Knowing what is causing the bottleneck will 
determine how to improve things. Use tools like
TaskManager in Windows or top in *nix to see 
where the time is going and what resources are 
being consumed. Fast code is not always the 
answer.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] problem with reading dns query

2011-07-02 Thread Alan Gauld


"preetam shivaram"  wrote

browser, chrome for instance, and i want to search for 
the ip of the domain name, say `www.google.com`. 


I'm curious why you would want to?
Given the volatility of IP addresses in the modern 
network I'm not sure what good it would do you? 
(as opposed to doing it manually using standard 
networking tools like ping, traceroute etc)


`127.0.0.1` where my server (written in Python) 
is running. 


localhost is not usually a good place to test 
networking tools. Even if you used a local 
LAN IP address allocated via DHCP it would 
be slightly more realistic.


is there any better way to get the dns request 
fro my browser first ,extract  the domain name 
and then send it to a name server that i wish 
all in python


You could set your local DNS settings to your 
local server. But if you want to reroute DNS I 
suspect there are esierways. But I'm still not 
clear about what you really want to do here, 
or why?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Cython question

2011-07-02 Thread Stefan Behnel

Alan Gauld, 02.07.2011 15:28:

"Albert-Jan Roskam" wrote

I used cProfile to find the bottlenecks, the two Python functions
getValueChar and getValueNum. These two Python functions simply call two
equivalent C functions in a .dll (using ctypes).


The code is currently declared as Windows-only and I don't know any good 
C-level profiling code for that platform. Under Linux, once I'm sure I have 
a CPU bound problem below the Python level, I'd use valgrind and 
KCacheGrind to analyse the performance. That will include all C function 
calls (and even CPU instructions, if you want) in the call trace. Makes it 
a bit less obvious to see what Python is doing, but leads to much more 
detailed results at the C level.


It's also worth keeping in mind that all profiling attempts *always* 
interfere with the normal program execution. The results you get during a 
profiling run may not be what you'd get with profiling disabled. So, 
profiling is nice, but it doesn't replace proper benchmarking.




In that case cythin will speed up the calling loops but it can't do
anything to speed up the DLL calls, you have effectively already optimised
those functions by calling the DLL.


The problem is that these functions are called as many times as there are
VALUES in a file


It might be worth a try if you have very big data sets
because a C loop is faster than a Python loop. But don't expect order of
magnitude improvements.


Looking at the code now, it's actually worse than that. The C function call 
does not only go through ctypes, but is additionally wrapped in a method 
call. So the OP is paying the call overhead twice for each field, plus the 
method lookup and some other operations. These things can add up quite easily.


So, iff the conversion code is really a CPU bottleneck, and depending on 
how much work the C functions actually do, the current call overhead, 100 
times per record, may be a substantial part of the game. It's worth seeing 
if it can be dropped at the Python level by removing method lookup and call 
levels (i.e. by inlining the method), but if that's not enough, Cython may 
still be worth it. For one, Cython's call overhead is lower than that of 
ctypes, and if the call is only done once, and the loop is moved into 
Cython (i.e. C) entirely, the overhead will also drop substantially.


It might also be worth running the code in PyPy instead of CPython. PyPy 
will optimise a lot of the overhead away that this code contains.




So if I understand you correctly, this is not Cpu bound


I don't have enough information to comment on that.



It may still be CPU bound in that the CPU is doing all the work, but if
the CPU time is in the DLL functions rather than in the loop cython
won't help much.

CPU bound refers to the type of processing - is it lots of logic, math,
control flows etc? Or is it I/O bound - reading network, disk, or user
input? Or it might be memory bound - creating lots of in memory objects
(especially if that results in paging to disk, when it becomes I/O
bound  too!)

Knowing what is causing the bottleneck will determine how to improve
things. Use tools like TaskManager in Windows or top in *nix to see
where the time is going and what resources are being consumed. Fast code
is not always the answer.


That is very good advice. As a rule of thumb, a process monitor like top 
will tell you how much time is spent in I/O and CPU. If, during a test run 
(with profiling disabled, as that eats time, too!), your CPU usage stays 
close to 100%, your program is CPU bound. If, however, it stays lower, and 
the monitor reports a high I/O waiting time, it's I/O bound. In this case, 
I/O bound is what you want to achieve, because it means that your code is 
running faster than your hard drive can deliver the data.


Stefan

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


[Tutor] Algorithm for sequence matching

2011-07-02 Thread ANKUR AGGARWAL
Hey
I am looking for an algo for the largest sequence search in the two list.

Example : list a accepts some say 'm' numbers. list b accept says 'n'
numbers. I want to look for the largest same sequence between the two list
and then display it. I tried out but failed to do so.
Say A=[11,23,45,21,63,56,78,32]
B=[56,78,11,23,45,21,111,234,56543]

There are two  similar sequence matching over here [11,23] and [23,45,21] i
want to display second sequence because its larger in number. Plz help
Thanks in Advance :)

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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread bob gailer

On 7/2/2011 4:30 PM, ANKUR AGGARWAL wrote:

Hey
I am looking for an algo for the largest sequence search in the two list.

Example : list a accepts some say 'm' numbers. list b accept says 'n' 
numbers. I want to look for the largest same sequence between the two 
list and then display it. I tried out but failed to do so.

Say A=[11,23,45,21,63,56,78,32]
B=[56,78,11,23,45,21,111,234,56543]

There are two  similar sequence matching over here [11,23] and 
[23,45,21] i want to display second sequence because its larger in 
number.


Makes no sense to me!

Pleae explain so a dummy like me can understand.

Also tell us what you tried and how it failed.


--
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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Walter Prins
Hi Ankur,

On 2 July 2011 21:30, ANKUR AGGARWAL  wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
>
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
>
> There are two  similar sequence matching over here [11,23] and [23,45,21] i
> want to display second sequence because its larger in number. Plz help
> Thanks in Advance :)
>

Umm, what about [11,23,45,21]?  That seems to be longer still so should be
the best one to display, or?

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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Walter Prins
Forwarding back to list.

-- Forwarded message --
From: ANKUR AGGARWAL
Date: 2 July 2011 22:23
Subject: Re: [Tutor] Algorithm for sequence matching
To: Walter Prins

ya sorry I forgot to include 11 . i want the answer to be [11,23,45,21]

On Sun, Jul 3, 2011 at 2:46 AM, Walter Prins  wrote:
> Hi Ankur,
>
> Umm, what about [11,23,45,21]?  That seems to be longer still so should be
> the best one to display, or?
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Peter Otten
ANKUR AGGARWAL wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
> 
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
> 
> There are two  similar sequence matching over here [11,23] and [23,45,21]
> i want to display second sequence because its larger in number. Plz help
> Thanks in Advance :)

The following is not particular efficient, but may be good enough if the 
sequences are not too long:

def index(items, value):
"""Generate all occurences of `value` in `items`"""
start = 0
while True:
try:
pos = items.index(value, start)
except ValueError:
break
yield pos
start = pos + 1

def matches(a, b):
for i, x in enumerate(a):
for k in index(b, x):
for p, (s, t) in enumerate(zip(a[i:], b[k:])):
if s != t:
break
yield a[i:i+p]

if __name__ == "__main__":
a = [11, 23, 45, 21, 63, 56, 78, 32]
b = [56, 78, 11, 23, 45, 21, 111, 234, 56543]

print(max(matches(a, b), key=len))
print(sorted(matches(a, b)))


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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Walter Prins
Hi Ankur,

On 2 July 2011 21:30, ANKUR AGGARWAL  wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
>
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
>
> There are two  similar sequence matching over here [11,23] and
> [11,23,45,21] i want to display second sequence because its larger in
> number. Plz help
>
>
OK, so what if A = [1,4,2,7,4,6] and B = [4,9,10,11,12,14,17,4]?  Would you
consider [4,4] a valid answer to your question?  It is a common subsequence,
albeit not of concescutive elements?

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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Walter Prins
Just to clarify further:

On 2 July 2011 23:46, Walter Prins  wrote:

> On 2 July 2011 21:30, ANKUR AGGARWAL  wrote:
>
>> Example : list a accepts some say 'm' numbers. list b accept says 'n'
>> numbers. I want to look for the largest same sequence between the two list
>> and then display it. I tried out but failed to do so.
>> Say A=[11,23,45,21,63,56,78,32]
>> B=[56,78,11,23,45,21,111,234,56543]
>>
>> There are two  similar sequence matching over here [11,23] and
>> [11,23,45,21] i want to display second sequence because its larger in
>> number. Plz help
>>
>
> OK, so what if A = [1,4,2,7,4,6] and B = [4,9,10,11,12,14,17,4]?  Would you
> consider [4,4] a valid answer to your question?  It is a common subsequence,
> albeit not of concescutive elements?
>

There is a difference between a sub*sequence* and a sub*string*.  Strictly
speaking, a *subsquence* is a sequence that can be derived from another
sequence by deleting some of the elements from the other sequence.  The
result thus retains the ordering from the original but the elements need not
have been consecutive elements.  A *substring* on the other hand implies
consecutive elements.  I'm trying to make sure I understand your question,
and whether you're really after the longest common subsequence (LCS) or
longest common substring.  My question above thus are trying to establish
which of the two cases you're really after. Obviously the answer will be
different depending on what you really want.

Regards

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


[Tutor] Blackjack Betting

2011-07-02 Thread David Merrick
Each player needs to be able to bet

# Blackjack
# From 1 to 7 players compete against a dealer

import cards, games

class BJ_Card(cards.Card):
""" A Blackjack Card. """
ACE_VALUE = 1

@property
def value(self):
if self.is_face_up:
v = BJ_Card.RANKS.index(self.rank) + 1
if v > 10:
v = 10
else:
v = None
return v

class BJ_Deck(cards.Deck):
""" A Blackjack Deck. """
def populate(self):
for suit in BJ_Card.SUITS:
for rank in BJ_Card.RANKS:
self.cards.append(BJ_Card(rank, suit))


class BJ_Hand(cards.Hand):
""" A Blackjack Hand. """
def __init__(self, name):
super(BJ_Hand, self).__init__()
self.name = name

def __str__(self):
rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
if self.total:
rep += "(" + str(self.total) + ")"
return rep

@property
def total(self):
# if a card in the hand has value of None, then total is None
for card in self.cards:
if not card.value:
return None

# add up card values, treat each Ace as 1
t = 0
for card in self.cards:
  t += card.value

# determine if hand contains an Ace
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains_ace = True

# if hand contains Ace and total is low enough, treat Ace as 11
if contains_ace and t <= 11:
# add only 10 since we've already added 1 for the Ace
t += 10

return t

def is_busted(self):
return self.total > 21


class BJ_Player(BJ_Hand):
""" A Blackjack Player. """

def betting(stash):
try:
if stash > 0:
wager = int(input("\nHow much do you want to wager?: "))
if wager > bet.stash:
int(input("\n You can only wager what you have. How
much?: "))
elif wager < 0:
int(input("\n You can only wager what you have. How
much?: "))
except ValueError:
int(input("\n That's not valid! Choose a number: "))

def is_hitting(self):
response = games.ask_yes_no("\n" + self.name + ", do you want a hit?
(Y/N): ")
return response == "y"

def bust(self):
print(self.name, "busts.")
self.lose()

def lose(self):
print(self.name, "loses.")

def win(self):
print(self.name, "wins.")

def push(self):
print(self.name, "pushes.")


class BJ_Dealer(BJ_Hand):
""" A Blackjack Dealer. """
def is_hitting(self):
return self.total < 17

def bust(self):
print(self.name, "busts.")

def flip_first_card(self):
first_card = self.cards[0]
first_card.flip()


class BJ_Game(object):
""" A Blackjack Game. """
def __init__(self, names):
self.players = []
for name in names:
player = BJ_Player(name)
bet = BJ_Player(name).betting(stash = 10)
self.players.append(player)

self.dealer = BJ_Dealer("Dealer")

self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()

@property
def still_playing(self):
sp = []
for player in self.players:
if not player.is_busted():
sp.append(player)
return sp

def __additional_cards(self, player):
while not player.is_busted() and player.is_hitting():
self.deck.deal([player])
print(player)
if player.is_busted():
player.bust()

def play(self):
# deal initial 2 cards to everyone
self.deck.deal(self.players + [self.dealer], per_hand = 2)
self.dealer.flip_first_card()# hide dealer's first card
for player in self.players:
print(player)
print(self.dealer)

# deal additional cards to players
for player in self.players:
self.__additional_cards(player)

self.dealer.flip_first_card()# reveal dealer's first

if not self.still_playing:
# since all players have busted, just show the dealer's hand
print(self.dealer)
else:
# deal additional cards to dealer
print(self.dealer)
self.__additional_cards(self.dealer)

if self.dealer.is_busted():
# everyone still playing wins
for player in self.still_playing:
player.win()
else:
# compare each player still playing to dealer
for player in self.still_playing:
if player.total > self.dealer.total:
player.win()
elif player.total < self.dealer.total:
player.lose()

Re: [Tutor] problem reading script

2011-07-02 Thread R. Alan Monroe

> Suggestions for "a programmers font" gratefully received.

DejaVu Sans Mono

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


Re: [Tutor] Algorithm for sequence matching

2011-07-02 Thread Steven D'Aprano

ANKUR AGGARWAL wrote:

Hey
I am looking for an algo for the largest sequence search in the two list.

Example : list a accepts some say 'm' numbers. list b accept says 'n'
numbers. I want to look for the largest same sequence between the two list
and then display it. I tried out but failed to do so.


Google is your friend. Please search for "longest common subsequence" 
and "longest common substring". You can add "algorithm" and "python" if 
you like. Wikipedia, for example, gives good algorithms for both 
problems, which can be adapted to Python.


You might also like to look at the difflib module in the standard 
library, particularly the SequenceMatcher class.



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


Re: [Tutor] Blackjack Betting

2011-07-02 Thread Marc Tompkins
On Sat, Jul 2, 2011 at 4:47 PM, David Merrick  wrote:

> Each player needs to be able to bet
>

Traceback (most recent call last):
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 204, in 
> main()
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 196, in main
> game = BJ_Game(names)
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 120, in __init__
> bet = BJ_Player(name).betting(stash = 10)
> TypeError: betting() got multiple values for keyword argument 'stash'
> >>>
>
>

The "(stash = 10)" syntax is only used in the function (or method, in this
case) definition.  It means that "stash" is optional: if no value is
supplied for "stash", then it will be assigned a default value of 10.

So you have choices: all of the following will invoke "betting" with "stash"
having an initial value of 10.
By value:

> bet = BJ_Player(name).betting(10)
>
By passing a variable:

> pari = 10
>
bet = BJ_Player(name).betting(pari)
>
By default:

> bet = BJ_Player(name).betting()
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with reading dns query

2011-07-02 Thread Steven D'Aprano

preetam shivaram wrote:

I have got a very simple idea in mind that i want to try out. Say i have a
browser, chrome for instance, and i want to search for the ip of the domain
name, say `www.google.com`. I use windows 7 and i have set the dns lookup
properties to manual and have given the address `127.0.0.1` where my server
(written in Python) is running. I started my server and i could see the dns
query like this:



It seems to me that you want to learn how to write your own DNS caching 
server. To do that, you have to understand the DNS protocol. Start with 
the Wikipedia article:


http://en.wikipedia.org/wiki/Domain_Name_System

We probably can't help you here, this is a list for learning Python, not 
DNS. You might have more luck on the main Python list, 
 or news group  But generally, 
I would expect they'll give you the same advice I am giving: google is 
your friend.


Search for "python DNS server" and you will find information that may be 
useful to you.



More comments below:



WAITING FOR CONNECTION.

.recieved from :  ('127.0.0.1', 59339)

"'~\\x17\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03www\\x06google\\x02co\\x02in\\x00\\x00\\x01\\x00\\x01'"

The `waiting for connection` and the `received from` is from my server. How
do i get a breakdown form(a human readable form) of this message??


Define "human readable form".

The data you get includes binary bytes, that is, you are getting:

tilde
hex byte 17
hex byte 01
null byte
null byte
hex byte 01

etc.

How would you like the string to be displayed, if not with escaped hex 
codes?


If you just print the string, the binary bytes will probably disappear 
because your terminal doesn't show them. You can convert to human 
readable form with escaped binary bytes using repr() like this:



>>> print s  # non-printable characters don't print
~wwwgooglecoin
>>> print repr(s)
'~\x17\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x02co\x02in\x00\x00\x01\x00\x01'


You could also try a hex dump, there are many recipes on the Internet. 
Here's the first one I tried:


http://code.activestate.com/recipes/142812-hex-dumper/

>>> print(dump(s))
   7E 17 01 00 00 01 00 00~...
0008   00 00 00 00 03 77 77 77.www
0010   06 67 6F 6F 67 6C 65 02.google.
0018   63 6F 02 69 6E 00 00 01co.in...
0020   00 01  ..



--
Steven

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