[Tutor] Baccarat code check.

2011-12-16 Thread col speed
If anyone has the time, please have a look at the attached text file
and let me know any comments on how to improve it.
Thanks a lot
Col
#!usr/bin/env python
# title - baccarat2.py

import random

class Player(object):
"""simple Player object that
   keeps tabs on bets and kitty"""
def __init__(self, name):
self.name = name
self.kitty = 2000
self.hand = []
self.wager = 0
def bet(self, wager):
self.wager = wager
self.kitty -= wager


class PlayerList(list):
"""It didn't seem right to update
a list of players in the 
Player class and I did it this
way rather than using a list
and two functions"""
def win(self):
for i in self:
i.kitty += i.wager*2
def draw(self):
for i in self:
i.kitty += i.wager

class Card(object):
"""Playing cards, self-explanatory"""
def __init__(self, name):
self.name = name
if name in range(2, 10):
self.value = name
elif name in [10, "J", "Q", "K"]:
self.value = 0
elif name == "A":
self.value = 1
else:
print "unrecognised card :{0}".format(name)
import sys
sys.exit()


class Shoe(list):
"""A collection of 8 decks of cards"""
def __init__(self):
for i in range(4):
self.extend([Card(i) for i in range(2, 10)])
self.extend([Card(i) for i in (10, "J", "Q", "K", "A")])
self *= 8
random.shuffle(self)
def deal(self, two_players):
for i in range(2):
for j in two_players:
j.hand.append(self.pop())
def thirdCard(self, player):
player.hand.append(self.pop())


def total(hand):
#In baccarat the tens are discarded
return sum([i.value for i in hand])%10

def bankersThird(last_card, bankers_cards):
#Shows if the bank must stand or draw
if last_card == 0:
return bankers_cards < 4
elif last_card == 9:
if bankers_cards == 3:
return random.choice(True, False)
else:
return bankers_cards < 3
elif last_card == 8:
return bankers_cards < 3
elif last_card in (6,7):
return bankers_cards < 7
elif last_card in (4, 5):
return bankers_cards < 6
elif last_card in (3, 2):
return bankers_cards < 5
elif last_card == 1:
return bankers_cards < 4
elif isinstance(last_card, str):
return bankers_cards < 6

def playersThird(player, shoe):
#A slapped wrist for the print statement, but I was using the all the same statements
#when the total was < 5 or == 5, only the raw_input was different.
shoe.thirdCard(player)
players_cards = total(player.hand)
last_card = player.hand[-1].value
print "You drew a {0}, making a total of {1}".format(last_card, players_cards) 
return players_cards, last_card   

def getPlayers():
players = PlayerList()
while True:
player = raw_input("What is your name? 'f' to finish. ")
if player == "f":
break
players.append(Player(player))
return players

def legalBet(amount, available, kitty):
#Can't bet over the bank limit, or over your own kitty.
return amount.isdigit() and int(amount) <= available and int(amount) <= kitty

def takeOffBets(players):
#Just trying to make main() a bit neater.
for j in players:
if j.wager == 1000:
continue
j.kitty += j.wager
j.wager = 0

def placeBets(players):
bank_amount = 1000
total_bets = 0
bet = ""
for i in players:
while not legalBet(bet, bank_amount-total_bets, i.kitty):
bet = raw_input("How much do you bet {1}? (Must be an integer. Maximum is {0}) ".format(min(bank_amount-total_bets, i.kitty), i.name))
if bet == "banco":
print "{0}'s going all the way!!".format(i.name)
i.bet(1000)
takeOffBets(players)
for j in players:
print j.name, j.wager, j.kitty
return   
else:
i.bet(int(bet))
total_bets += int(bet)
bet = "no"


def main():
shoe = Shoe()
players = getPlayers()
banker = Player("Banker")
while 1:
placeBets(players)
bets = [i.wager for i in players]
the_player = players[bets.index(max(bets))]#Only the player with the maximum bet(nearest the banker's right) plays.
two_players = [banker, the_player]
shoe.deal(two_players)
bankers_cards = total(banker.hand)
players_cards = total(the_player.hand)
print "The banker has a {0} and a {1}, making a total of {2}".format(banker.hand[0].name, banker.hand[1].name,bankers_cards)
print "{0} has a {1} and a {2}, making a total of {

Re: [Tutor] timeit() help

2011-12-16 Thread Steven D'Aprano

Robert Sjoblom wrote:

So, it turns out that my ISP blocked Project Euler, so instead of
working on my next problem, I polished Problem 4 a bit:


Your ISP blocked Project Euler

More likely the site is just temporarily down, but if you're right, what on 
earth would they block Project Euler for???





My biggest problem now is that I don't know how to measure any changes
in efficiency. I know that the functions are working perfectly fine
as-is, and I shouldn't really optimize without a need to, but I'm
mostly curious as to whether the check_value() function is worth it or
not. To this I thought I'd use timeit(), but I can't for the life of
me work out how it works.


It would help if you show us what you have tried, and the result you get, 
rather than just give us a vague "it doesn't work".


But for what it's worth, here's some examples of using timeit.


Is the built-in sum() function faster than one I write myself? I want to test 
this at the interactive interpreter, so I use the Timer class from the timeit 
module.


Normally you will give Timer two arguments: the first is the code to be timed, 
the second is the setup code. The setup code gets run once per test; the code 
to be timed can be run as many times as you like.



>>> def my_sum(numbers):
... total = 0
... for x in numbers:
... total += x
... return x
...
>>> from timeit import Timer
>>> t1 = Timer('sum(mylist)', 'mylist = [2*i + 5 for i in range(100)]')
>>> t2 = Timer('my_sum(mylist)',
... 'from __main__ import my_sum; mylist = [2*i + 5 for i in range(100)]')

Notice that Timer takes strings to represent the code you want to time. That 
sometimes requires a little indirect dance to get your functions for testing. 
In the interactive interpreter you can use the "from __main__ import WHATEVER" 
trick to have that work.


Now that we have two Timers, t1 and t2, we can run the tests to compare. The 
absolute minimum necessary is this:


>>> t1.timeit()
2.916867971420288
>>> t2.timeit()
11.48215913772583

This calls the setup code once, then calls the timed code one million times 
and returns the time used. Three seconds to sum 100 numbers one million times 
isn't too bad.


On my computer, the built-in sum seems to be about 4 times faster than my 
custom-made one. However, there is a catch: on modern computers, there are 
always other programs running, all the time, even when you can't see them: 
virus checkers, programs looking for updates, background scanners, all sorts 
of things. Maybe one of those programs just happened to start working while 
my_sum was being tested, and slowed the computer down enough to give a false 
result.


Not very likely, not with such a big difference. But when timing two code 
snippets where the difference is only a matter of a few percent, it is very 
common to see differences from one test to another. Sometimes the slower one 
will seem speedier than the faster one, just because a virus scanner or cron 
job fired off at the wrong millisecond.


We can help allow for this by doing more tests. Here I will increase the 
number of cycles from one million to two million, and pick the best out of five:


>>> min( t1.repeat(number=200, repeat=5) )
4.8857738971710205
>>> min( t2.repeat(number=200, repeat=5) )
22.03256916999817


I think that's pretty clear: my hand-written sum function is about four and a 
half times slower than the built-in one.


If a test seems to be going for ever, you can interrupt it with Ctrl-C.


Here's another way to use timeit: from the command line. If you have Windows, 
you should use command.com or cmd.exe (or is it the other way around?). I'm 
using Linux, but the method is more or less identical.


This time, I want to see what is the overhead of the "pass" statement. So I 
compare two code snippets, identical except one has "pass" after it:


steve@runes:~$ python -m timeit -s "x = 42" "x += 1"
1000 loops, best of 3: 0.0681 usec per loop
steve@runes:~$ python -m timeit -s "x = 42" "x += 1; pass"
1000 loops, best of 3: 0.0739 usec per loop


"steve@runes:~$" is my prompt; you don't type that. You type everything 
starting from python to the end of the line.


Notice that when called from the command line, timeit tries to be smart: it 
starts looping, doing the test over and over again until it has enough loops 
that the time taken is reasonable. Then it does it two more times, and prints 
the best of three.


In this case, the overhead of a pass statement is about 0.006 microseconds on 
my computer.



--
Steven

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


Re: [Tutor] modify values for object derived from datetime.datetime

2011-12-16 Thread Steven D'Aprano

rail shafigulin wrote:

i writing some code to do device testing at my work. testing is related to
date and time, so naturally i decided to create a class that inherits from
datetime.datetime. main reason is that i need to add, subtract and compare
datetime objects and datetime.datetime allows me to do that. here is the
code:

class LTime(datetime.datetime):
  TOLERANCE = 10

  def __new__(self, year, month, day, *args):
if year == 0:
  year = 2000
return super().__new__(self, year, month, day, *args)



By convention, the first argument of __new__ is normally spelled as "cls", 
short for class, because the instance hasn't been created yet.




  def modify(self):
self = self.replace(2012, 12, 12)
print(self)


The replace method creates a new datetime object. Just because you assign it 
to the name "self" doesn't mean you can change the existing datetime object. 
That is simply impossible: datetime objects are immutable, like ints.


You might not quite understand why modifying immutable objects would be bad 
(which is why Python doesn't allow it). I can simulate the effect with this 
simple wrapper class:


>>> class Mutable:
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return str(self.value)
... __repr__ = __str__
... def add(self, value):
... self.value += value
...
>>> one = Mutable(1)  # Pretend this is the int 1
>>> print(one)
1
>>> x = one
>>> x.set(1)  # pretend this was x += 1
>>> one  # the int 1 has been modified in place
2

So if ints (and datetime objects) could be changed in place, you could never 
be sure what value a literal like 1 would have.


Obviously this is useful in some situations, which is why we have mutable 
objects like lists. But datetime objects are not mutable, a design choice made 
by the creator of the module, so you cannot change it.


So you have to change your design. Instead of writing code like this:


today = LTime(2011, 12, 16)
# ...
# ... do stuff with today
# ...
today.modify(day=17)  # fast forward in time to tomorrow
# ...
# ... do stuff with today, which is actually tomorrow
# ...

you need to change your code to be more like this:


today = LTime(2011, 12, 16)
# ...
# ... do stuff with today
# ...
tomorrow = today.modify(day=17)
# ...
# ... do stuff with tomorrow
# ...




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


Re: [Tutor] Tutor Digest, Vol 94, Issue 58

2011-12-16 Thread Calle

Message: 1
Date: Thu, 15 Dec 2011 23:37:49 +0100
From: "Calle" 
To: "Robert Sjoblom" 
Cc: tutor@python.org
Subject: Re: [Tutor] [TUTOR]Code Deciphering
Message-ID: 
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
reply-type=original

-Ursprungligt meddelande- 
From: Robert Sjoblom

Sent: Thursday, December 15, 2011 10:34 PM
To: Calle
Cc: tutor@python.org
Subject: Re: [Tutor] [TUTOR]Code Deciphering


I was wondering, how do you use Python to decipher codes? It feels like it
should be pretty simple, but I haven't found any tutorials about it yet.


What kind of codes? Or do you mean ciphers? Generally speaking, a code
represent letters or numbers in transmitting a message. In other
words, a code deals with phrases and sentences or whole words. Example
"steal the cabbage at dawn" could mean "kill the king on wednesday".

A cipher deals with letters. It is a message written in letters in a
predetermined code. This means that a cipher is a system of
communication that uses letters instead of phrases. Examples being the
standard Caesar cipher where "APPLE" might be written "BQQMB" (ie,
shifted one letter to the right).
--
best regards,
Robert S.


--
Hi!

Sorry, I meant ciphers. How would a basic script for solving
move-one-step-to-the-right ciphers look like?

Have a nice day
//
Calle



--
--

Message: 3
Date: Fri, 16 Dec 2011 00:53:35 +0100
From: Robert Sjoblom 
To: Calle 
Cc: tutor@python.org
Subject: Re: [Tutor] [TUTOR]Code Deciphering
Message-ID:

Content-Type: text/plain; charset=ISO-8859-1

On 15 December 2011 23:37, Calle  wrote:

-Ursprungligt meddelande- From: Robert Sjoblom
Sent: Thursday, December 15, 2011 10:34 PM
To: Calle
Cc: tutor@python.org
Subject: Re: [Tutor] [TUTOR]Code Deciphering



I was wondering, how do you use Python to decipher codes? It feels like
it
should be pretty simple, but I haven't found any tutorials about it yet.



What kind of codes? Or do you mean ciphers? Generally speaking, a code
represent letters or numbers in transmitting a message. In other
words, a code deals with phrases and sentences or whole words. Example
"steal the cabbage at dawn" could mean "kill the king on wednesday".

A cipher deals with letters. It is a message written in letters in a
predetermined code. This means that a cipher is a system of
communication that uses letters instead of phrases. Examples being the
standard Caesar cipher where "APPLE" might be written "BQQMB" (ie,
shifted one letter to the right).



Sorry, I meant ciphers. How would a basic script for solving
move-one-step-to-the-right ciphers look like?


Wll... There are different ways to solve that, but show us what
you've come up with so far and we might be able to point you in the
right direction. You won't learn anything by getting the answer posted
and just copy-paste it for whatever (nefarious) use you need it;
you'll learn a lot more if you work toward the solution yourself. I'll
just point you in the direction of ASCII values for now.

--
best regards,
Robert S.


Well, I don't really know where to begin. I tried looking at other peoples
code and write something based on that, but it ended up being too similair
to the original code... I could show you what I came up with using
pseudo-code.

Get the cipher from user.
Use ord() to convert into numbers.
Add number to a new string while at the same time making it into a letter 
using chr().

Repeat 25 times and print the results.

Am I on the right track with this or should I re-think?

//
Calle 


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


Re: [Tutor] modify values for object derived from datetime.datetime

2011-12-16 Thread rail shafigulin
On Fri, Dec 16, 2011 at 5:26 AM, Steven D'Aprano wrote:

> rail shafigulin wrote:
>
>> i writing some code to do device testing at my work. testing is related to
>> date and time, so naturally i decided to create a class that inherits from
>> datetime.datetime. main reason is that i need to add, subtract and compare
>> datetime objects and datetime.datetime allows me to do that. here is the
>> code:
>>
>> class LTime(datetime.datetime):
>>  TOLERANCE = 10
>>
>>  def __new__(self, year, month, day, *args):
>>if year == 0:
>>  year = 2000
>>return super().__new__(self, year, month, day, *args)
>>
>
>
> By convention, the first argument of __new__ is normally spelled as "cls",
> short for class, because the instance hasn't been created yet.
>
>
>
>   def modify(self):
>>self = self.replace(2012, 12, 12)
>>print(self)
>>
>
> The replace method creates a new datetime object. Just because you assign
> it to the name "self" doesn't mean you can change the existing datetime
> object. That is simply impossible: datetime objects are immutable, like
> ints.
>
> You might not quite understand why modifying immutable objects would be
> bad (which is why Python doesn't allow it). I can simulate the effect with
> this simple wrapper class:
>
> >>> class Mutable:
> ... def __init__(self, value):
> ... self.value = value
> ... def __str__(self):
> ... return str(self.value)
> ... __repr__ = __str__
> ... def add(self, value):
> ... self.value += value
> ...
> >>> one = Mutable(1)  # Pretend this is the int 1
> >>> print(one)
> 1
> >>> x = one
> >>> x.set(1)  # pretend this was x += 1
> >>> one  # the int 1 has been modified in place
> 2
>
> So if ints (and datetime objects) could be changed in place, you could
> never be sure what value a literal like 1 would have.
>
> Obviously this is useful in some situations, which is why we have mutable
> objects like lists. But datetime objects are not mutable, a design choice
> made by the creator of the module, so you cannot change it.
>
> So you have to change your design. Instead of writing code like this:
>
>
> today = LTime(2011, 12, 16)
> # ...
> # ... do stuff with today
> # ...
> today.modify(day=17)  # fast forward in time to tomorrow
> # ...
> # ... do stuff with today, which is actually tomorrow
> # ...
>
> you need to change your code to be more like this:
>
>
> today = LTime(2011, 12, 16)
> # ...
> # ... do stuff with today
> # ...
> tomorrow = today.modify(day=17)
> # ...
> # ... do stuff with tomorrow
> # ...
>
>
>
>
> --
> Steven
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>

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


Re: [Tutor] Tutor Digest, Vol 94, Issue 58

2011-12-16 Thread Steven D'Aprano

Calle wrote:

Message: 1
Date: Thu, 15 Dec 2011 23:37:49 +0100
From: "Calle" 

[...]


I'm sorry, it is too hard for me to work out which parts are your comments, 
and which are quotations from older emails in the Digest.


Please do not reply to multiple messages in a digest at once: each reply to a 
message should be in a separate email. Also, please edit the subject line to 
something more useful that "Re Tutor Digest".


I recommend you change your mail settings and turn of Digest and go onto 
individual emails. It is MUCH easier to carry on a discussion that way.


One last thing: "--" on a line on its own is the marker for "End Of Email", 
with only the user's signature below the line. When you comment below the End 
Of Email line, many common email programs will grey the text out and make it 
difficult or impossible to reply to your comment.



Thank you.



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


Re: [Tutor] Baccarat code check.

2011-12-16 Thread Prasad, Ramit
> If anyone has the time, please have a look at the attached text file and let 
> me know any comments on how to improve it.

Not everyone on this list gets attachments. You are usually better off 
including short code in the email or a pastebin link.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


-Original Message-
From: tutor-bounces+ramit.prasad=jpmorgan@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmorgan@python.org] On Behalf Of col 
speed
Sent: Friday, December 16, 2011 2:30 AM
To: Python Tutors
Subject: [Tutor] Baccarat code check.

Thanks a lot
Col
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sqlite3: turning on foreign key support thru python

2011-12-16 Thread Monte Milanuk
I'm setting up an sqlite3 database to use as a base for some programming stuff I
want to work on.  Currently using python 2.7, which appears to have a new enough
version of sqlite (just barely) to support foreign keys.

As I understand things, sqlite by default has foreign keys turned off, unless
specifically compiled otherwise or until you turn on foreign keys using 'pragma
foreign_keys=ON'.  And it needs to be turned on for each connection too.

So... just putzing around using the python interactive shell...


import sqlite3
sqlite3.sqlite_version
'3.6.21'
conn = sqlite3.connect('contacts.db')
conn.execute('pragma foreign_keys=ON')

conn.execute('pragma foreign_keys')



It appears I am able to successfully import sqlite3, its of a recent enough
version to support foreign keys (> 3.6.19), I connected it to an existing
database 'contacts.db', and when I execute the pragma statement to turn on
foreign key support it returns a cursor object.  Similarly, when I send a pragma
statement to query the status of foreign key support, it returns a cursor 
object.

Now for the stupid question(s):  

How do I tell if it succeeded (short of trying an operation that should be
blocked by foreign keys)?  How do I use that cursor object returned by the
pragma query to tell if its a '1' (on) or a '0' (off) and verify the state?

TIA,

Monte

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


Re: [Tutor] sqlite3: turning on foreign key support thru python

2011-12-16 Thread Modulok
>> How do I tell if it succeeded (short of trying an operation that should be
>> blocked by foreign keys)?  How do I use that cursor object returned by the
>> pragma query to tell if its a '1' (on) or a '0' (off) and verify the state?


The cursor object contains the result set. It's a python generator object. (Or
at least a generator interface.) You have to iterate over it in order to see
the resulting rows which are stored as a tuple. Not all operations return a
result row. (For example, conn.execute('pragma foreign_keys=ON' will return a
cursor object, but it won't generate any result rows, as there were
none returned by the database.)

To see the result of your second command, do something like this::

rows = conn.execute('pragma foreign_keys')
for r in rows:
print r


You'll then see something like this when foreign keys are turned on::

(1,)

Or this when they're turned off::

(0,)

Hope that helps.
-Modulok-

On 12/16/11, Monte Milanuk  wrote:
> I'm setting up an sqlite3 database to use as a base for some programming
> stuff I
> want to work on.  Currently using python 2.7, which appears to have a new
> enough
> version of sqlite (just barely) to support foreign keys.
>
> As I understand things, sqlite by default has foreign keys turned off,
> unless
> specifically compiled otherwise or until you turn on foreign keys using
> 'pragma
> foreign_keys=ON'.  And it needs to be turned on for each connection too.
>
> So... just putzing around using the python interactive shell...
>
>
> import sqlite3
> sqlite3.sqlite_version
> '3.6.21'
> conn = sqlite3.connect('contacts.db')
> conn.execute('pragma foreign_keys=ON')
> 
> conn.execute('pragma foreign_keys')
> 
>
>
> It appears I am able to successfully import sqlite3, its of a recent enough
> version to support foreign keys (> 3.6.19), I connected it to an existing
> database 'contacts.db', and when I execute the pragma statement to turn on
> foreign key support it returns a cursor object.  Similarly, when I send a
> pragma
> statement to query the status of foreign key support, it returns a cursor
> object.
>
> Now for the stupid question(s):
>
> How do I tell if it succeeded (short of trying an operation that should be
> blocked by foreign keys)?  How do I use that cursor object returned by the
> pragma query to tell if its a '1' (on) or a '0' (off) and verify the state?
>
> TIA,
>
> Monte
>
> ___
> 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] sqlite3: turning on foreign key support thru python

2011-12-16 Thread Monte Milanuk
That helped immensely... I was trying some different things trying to get
at the results, but it never occurred to me to try iterating over it.  The
bit about some objects being iterable and some not is good to know!

Thanks,

Monte

On Fri, Dec 16, 2011 at 11:43 AM, Modulok  wrote:

> >> How do I tell if it succeeded (short of trying an operation that should
> be
> >> blocked by foreign keys)?  How do I use that cursor object returned by
> the
> >> pragma query to tell if its a '1' (on) or a '0' (off) and verify the
> state?
>
>
> The cursor object contains the result set. It's a python generator object.
> (Or
> at least a generator interface.) You have to iterate over it in order to
> see
> the resulting rows which are stored as a tuple. Not all operations return a
> result row. (For example, conn.execute('pragma foreign_keys=ON' will
> return a
> cursor object, but it won't generate any result rows, as there were
> none returned by the database.)
>
> To see the result of your second command, do something like this::
>
>rows = conn.execute('pragma foreign_keys')
>for r in rows:
>print r
>
>
> You'll then see something like this when foreign keys are turned on::
>
>(1,)
>
> Or this when they're turned off::
>
>(0,)
>
> Hope that helps.
> -Modulok-
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [TUTOR]Code Deciphering(Re-sent)

2011-12-16 Thread Calle

On 15 December 2011 23:37, Calle  wrote:
I was wondering, how do you use Python to decipher codes? It feels like 
it should be pretty simple, but I haven't found any tutorials about it 
yet.




What kind of codes? Or do you mean ciphers? Generally speaking, a code
represent letters or numbers in transmitting a message. In other
words, a code deals with phrases and sentences or whole words. Example
"steal the cabbage at dawn" could mean "kill the king on wednesday".

A cipher deals with letters. It is a message written in letters in a
predetermined code. This means that a cipher is a system of
communication that uses letters instead of phrases. Examples being the
standard Caesar cipher where "APPLE" might be written "BQQMB" (ie,
shifted one letter to the right).

--
best regards,
Robert S.




>Sorry, I meant ciphers. How would a basic script for solving

move-one-step-to-the-right ciphers look like?




Wll... There are different ways to solve that, but show us what
you've come up with so far and we might be able to point you in the
right direction. You won't learn anything by getting the answer posted
and just copy-paste it for whatever (nefarious) use you need it;
you'll learn a lot more if you work toward the solution yourself. I'll
just point you in the direction of ASCII values for now.

--
best regards,
Robert S.



Well, I don't really know where to begin. I tried looking at other peoples
code and write something based on that, but it ended up being too similair
to the original code... I could show you what I came up with using
pseudo-code.

Get the cipher from user.
Use ord() to convert into numbers.
Add number to a new string while at the same time making it into a letter
using chr().
Repeat 25 times and print the results.

Am I on the right track with this or should I re-think?

//
Calle 


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


[Tutor] reset password program

2011-12-16 Thread ADRIAN KELLY

Hi guys,
i created a program that allows users to login using a password that i set at 
the top of the program.  
Among other things users are given the option to change their password.  My 
questions is;
 
Is it possible for me to make this new password stick, in other words when they 
shut down and 
log in again i am back to the original password.the new password only works 
while the programming 
is running.  I know why this is happening, what i don't know is what to do 
about it.
 
I am new to python and programming so if you have any ideas... 
 
please keep them simple.
 
thanks all,
adrian___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reset password program

2011-12-16 Thread Dave Angel

On 12/16/2011 05:02 PM, ADRIAN KELLY wrote:

Hi guys,
i created a program that allows users to login using a password that i set at 
the top of the program.
Among other things users are given the option to change their password.  My 
questions is;

Is it possible for me to make this new password stick, in other words when they 
shut down and
log in again i am back to the original password.the new password only works 
while the programming
is running.  I know why this is happening, what i don't know is what to do 
about it.

I am new to python and programming so if you have any ideas...

please keep them simple.

thanks all,
adrian  

Nothing in Python objects is persistent.  If you want something to 
survive till the next run, you have to write it to something external, 
such as a file.


If this is a serious program, with important passwords, you'll want to 
encrypt the file.  If it's just casual, encode the file in some obscure 
way.  But if it's a class assignment, then save it in a text file, in a 
directory you'll be able to find next time.


That last point is important.  The program directory may be read-only to 
that user.  So you might not be able to store it there.  One approach is 
to save it in the user's home directory,so for me, it might be   
/home/daveaConvention is to start it with a leading period, so that 
the ls command won't show it by default.  Another question is whether 
you want a different password per user, and if you might have more than 
one user logged into your machine at the same time.


Hope this helped,







--

DaveA

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


Re: [Tutor] reset password program

2011-12-16 Thread ADRIAN KELLY

thanks dave,
just tried writing to file for the first time

def main():
 outfile.write('Hello this is a test')
 outfile.close()
main()

error, globalname outfile is not defined, do i need to import function to get 
this working?

   

> Date: Fri, 16 Dec 2011 17:13:04 -0500
> From: d...@davea.name
> To: kellyadr...@hotmail.com
> CC: tutor@python.org
> Subject: Re: [Tutor] reset password program
> 
> On 12/16/2011 05:02 PM, ADRIAN KELLY wrote:
> > Hi guys,
> > i created a program that allows users to login using a password that i set 
> > at the top of the program.
> > Among other things users are given the option to change their password. My 
> > questions is;
> >
> > Is it possible for me to make this new password stick, in other words when 
> > they shut down and
> > log in again i am back to the original password.the new password only 
> > works while the programming
> > is running. I know why this is happening, what i don't know is what to do 
> > about it.
> >
> > I am new to python and programming so if you have any ideas...
> >
> > please keep them simple.
> >
> > thanks all,
> > adrian 
> >
> Nothing in Python objects is persistent. If you want something to 
> survive till the next run, you have to write it to something external, 
> such as a file.
> 
> If this is a serious program, with important passwords, you'll want to 
> encrypt the file. If it's just casual, encode the file in some obscure 
> way. But if it's a class assignment, then save it in a text file, in a 
> directory you'll be able to find next time.
> 
> That last point is important. The program directory may be read-only to 
> that user. So you might not be able to store it there. One approach is 
> to save it in the user's home directory, so for me, it might be 
> /home/davea Convention is to start it with a leading period, so that 
> the ls command won't show it by default. Another question is whether 
> you want a different password per user, and if you might have more than 
> one user logged into your machine at the same time.
> 
> Hope this helped,
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> DaveA
> 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reset password program

2011-12-16 Thread Emile van Sebille

On 12/16/2011 2:49 PM ADRIAN KELLY said...

thanks dave,
just tried writing to file for the first time

def main():
outfile.write('Hello this is a test')
outfile.close()
main()

*error, globalname outfile is not defined, do i need to import function
to get this working?*


No, but you do need to initialize outfile appropriately.  The error 
(next time post the entire traceback please -- it provides the specifics 
you'll need to fix the bug) tells you that 'outfile is not defined'


If you set outfile to a writable file object you'll get it going.  Look 
at the 'open' documentation.


HTH,

Emile


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


Re: [Tutor] reset password program

2011-12-16 Thread Sarma Tangirala
> thanks dave,
> just tried writing to file for the first time
>
> def main():
>  outfile.write('Hello this is a test')
>  outfile.close()
> main()
>
> error, globalname outfile is not defined, do i need to import function to
get this working?
>
>

Fyi, you should check the python docs. They have a good introduction if
this is the first time. Also its a good idea to use a try block incase the
file does not exist and you have to do a bit of error handling.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reset password program

2011-12-16 Thread Steven D'Aprano

ADRIAN KELLY wrote:

Hi guys,
i created a program that allows users to login using a password that i set at the top of the program.  
Among other things users are given the option to change their password.  My questions is;
 
Is it possible for me to make this new password stick, in other words when they shut down and 
log in again i am back to the original password.the new password only works while the programming 
is running.  I know why this is happening, what i don't know is what to do about it.



This will be *very* low security and so shouldn't be used for real passwords.


# Read the user's password
# 
try:
password_file = open("my secret password.txt", "r")
except (IOError, OSError):
# password file doesn't exist, or is unreadable
password = ''
else:
# password file does exist
password = password_file.read()
password_file.close()


# Write the user's password
# -
password_file = open("my secret password.txt", "w")
password_file.write(password)
password_file.close()




Some improvements to think about, in order of least secure (easiest) to most 
secure (hardest).


(1) "my secret password.txt" is a crappy name. Is there a better name?

(2) Can you make the file hidden so users won't accidentally delete it? Hint: 
on Linux and Mac, you can hide a file by starting the name with a dot. How 
about Windows?


(3) Can you make sure that the password file is only readable by the user? 
Hint: os.chmod function. You will need to investigate how it works.


(4) Anyone who opens the password with a text editor will see the password in 
plain ordinary text. Can you obfuscate the password so it is harder to read?


(5) Do you really need to store the *actual* password? It may be better to 
just store a hash of the password, and then compare hashes instead of actual 
passwords. Research "md5" and "sha" hashes and the hashlib library.


(6) Even with hashes, breaking passwords is not difficult. Investigate the 
importance of "salting" the password so as to increase security.




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


Re: [Tutor] reset password program

2011-12-16 Thread Hugo Arts
On Fri, Dec 16, 2011 at 11:49 PM, ADRIAN KELLY  wrote:
> thanks dave,
> just tried writing to file for the first time
>
> def main():
>  outfile.write('Hello this is a test')
>  outfile.close()
> main()
>
> error, globalname outfile is not defined, do i need to import function to
> get this working?
>

A lot of stuff is missing here. let's get back to basics. What is
outfile? It's a variable. So, where does it come from? well, right
now, you just sort of magically conjure it up out of nowhere, which is
why python is complaining ("not defined" is the python telling you
"you never told me what this thing is"). So, we want the variable
outfile to point to a file object. Making a file object is very
simple, just call the open() function. You don't have to import
open(), it's a builtin, which means it's always available to you:

outfile = open('file_name.txt', 'w')

open takes two arguments. The first one is the filename, the second is
the mode in which the file is to be opened. Basically, 'r' is for
reading, 'w' for writing (this mode will delete existing data in the
file, if any), and 'a' is appending. You can add a 'b' for opening in
binary mode, and a '+' for opening the file for updating.

Now we have a file object, and we can use the write() method on it as
you have done above (make sure not to forget close(), it's good
practice). That should get you started. There's a good bit of theory
behind saving passwords securely (you don't usually want everyone to
be able to open the file and read the passwords, basically), but I
won't get into that right now. If you're ready for that, you might
want to check out hashlib
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reset password program

2011-12-16 Thread Robert Sjoblom
> Some improvements to think about, in order of least secure (easiest) to most
> secure (hardest).
>
> (1) "my secret password.txt" is a crappy name. Is there a better name?

I'm going to go with "EULA.txt"; the reasons should be obvious.

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