Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 07/08/15 01:15, Ltc Hotspot wrote:

Question1: How type of argument should I use for dict, i.e.,user argument
or list argument.

Read captured traceback:

TypeError
Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_26.py in ()
   1 fname = raw_input("Enter file name: ")
   2 handle = open (fname, 'r')
> 3 count = dict.keys()
   4 for line in handle:
   5 if line.startswith("From: "):



You appear to be making random changes to your code
for no good reason.

I will not make any further suggestions until you
start to explain your thinking.

What do you think the line

count = dict.keys()

will do? Why do you want to do that?
How will it help you solve your problem?

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


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


Re: [Tutor] Fraction Class HELP ME PLEASE!

2015-08-06 Thread Quiles, Stephanie
Hello again Cameron, 

Thank you, your reply is most helpful. Responses and updated code below. 
Thoughts would be appreciated. The assignment has been sent as my deadline was 
11pm EST. But i was able to implement your suggestions and tips right before i 
submitted. responses are below and here is the final code i submitted for 
grading. 


def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

def __str__(self):
if self.den == 1:
return str(self.num)
if self.num == 0:
return str(0)
return str(self.num) + "/" + str(self.den)

def simplify(self):
common = gcd(self.num, self.den)
self.num = self.num // common
self.den = self.den // common

def show(self):
print(self.num, "/", self.den)

def __add__(self, otherfraction):
newnum = self.num * otherfraction.den + self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __iadd__(self, otherfraction):
if isinstance(otherfraction):
return self__iadd__(otherfraction)

def __sub__(self, otherfraction):
newnum = self.num * otherfraction.den - self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __mul__(self, otherfraction):
newnum = self.num * otherfraction.num * self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __imul__(self, otherfraction):
if isinstance(otherfraction):
return self__mul__(otherfraction)

def __div__(self, otherfraction):
newnum = self.num * otherfraction.num / self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __truediv__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __pow__(self, otherfraction):
newnum = self.num * otherfraction.num ** self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __radd__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)




def getNum(self):
return self.num

def getDen(self):
return self.den

def __gt__(self, otherfraction):
return (self.num * self.den) > (otherfraction.num * otherfraction.den)

def __lt__(self, otherfraction):
return (self.num * self.den) < (otherfraction.num * otherfraction.den)

def __eq__(self, otherfraction):
return (self.num * self.den) == (otherfraction.num * otherfraction.den)

def __ne__(self, otherfraction):
return (self.num * self.den) != (otherfraction.num * otherfraction.den)

def __mod__(self, otherfraction):
return (self.num * self.den) % (otherfraction.num * otherfraction.den)

def __rshift__(self, otherfraction):
return (self.num * self.den) >> (otherfraction.num * otherfraction.den)







""" This program will test the following operators, addition, subtraction, 
multiplication,
division, true division, exponentiation, radd, modulo, shifting, ordering (less 
than, greater , equal to, different than,
same as). All using fractions. """
def main():
F1 = Fraction(1,2)
F2 = Fraction(2,3)
print("F1 = ", F1)
print("F2 = ", F2)
print("Add Fractions: F1 + F2=", Fraction.__add__(F1, F2))
print("Subtract Fractions: F1 - F2=", Fraction.__sub__(F1, F2))
print("Multiply Fractions: F1 * F2=", Fraction.__mul__(F1, F2))
print("Division with Fractions: F1 / F2=", Fraction.__div__(F1, F2))
print("True Division with Fractions: F1 / F2=", Fraction.__truediv__(F1, 
F2))
print("Exponentiation with Fractions: F1 ** F2=", Fraction.__pow__(F1, F2))
print("Is F1 Greater than F2?:", Fraction.__gt__(F1, F2))
print("Is F1 less than F2?:", Fraction.__lt__(F1, F2))
print("Is F1 Equal to F2?:", Fraction.__eq__(F1, F2))
print("Is F1 different than F2?:", Fraction.__ne__(F1, F2))
print("Radd:", Fraction.__radd__(F1, F2))
print("Modulo of F1 and F2(this prints the remainder):", 
Fraction.__mod_

Re: [Tutor] Fraction Class HELP ME PLEASE!

2015-08-06 Thread Quiles, Stephanie
thanks Cameron! Here is what i have so far… new question… how do i test the 
iadd, imul, etc. operators? Hopefully this time the indents show up. And yes 
the beginning code came out of our text book I added on some functions myself 
but they give you a big chunk of it. I am hoping that this is what the 
professor was looking for. I want to add some more operators but am unsure how 
to put them in or test them? For example I want to add __ixor__, itruediv, etc. 
Any other suggestions would be great! 

Thanks 


def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n

m = oldn
n = oldm % oldn
return n

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

def __str__(self):
if self.den == 1:
return str(self.num)
elif self.num == 0:
return str(0)
else:
return str(self.num) + "/" + str(self.den)

def simplify(self):
common = gcd(self.num, self.den)

self.num = self.num // common
self.den = self.den // common

def show(self):
print(self.num, "/", self.den)

def __add__(self, otherfraction):
newnum = self.num * otherfraction.den + \
 self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __sub__(self, otherfraction):
newnum = self.num * otherfraction.den - \
 self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __mul__(self, otherfraction):
newnum = self.num * otherfraction.num * \
 self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __imul__(self, otherfraction):
if isinstance(otherfraction):
return self__mul__(otherfraction)

def __iadd__(self, otherfraction):
if isinstance(otherfraction):
return self__iadd__(otherfraction)

def __truediv__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __pow__(self, otherfraction):
newnum = self.num * otherfraction.num ** self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)


def __radd__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def getNum(self):
return self.num

def getDen(self):
return self.den

def __gt__(self, otherfraction):
return (self.num / self.den) > (otherfraction.num / otherfraction.den)

def __lt__(self, otherfraction):
return (self.num / self.den) < (otherfraction.num / otherfraction.den)

def __eq__(self, otherfraction):
return (self.num / self.den) == (otherfraction.num / otherfraction.den)

def __ne__(self, otherfraction):
return (self.num /self.den) != (otherfraction.num /otherfraction.den)

def __is__(self, otherfraction):
return (self.num / self.den) is (otherfraction.num / otherfraction.den)




def main():
F1 = Fraction(1,2)
F2 = Fraction(2,3)
print("F1 = ", F1)
print("F2 = ", F2)
print("Add Fractions: F1 + F2=", Fraction.__add__(F1, F2))
print("Subtract Fractions: F1 - F2=", Fraction.__sub__(F1, F2))
print("Multiply Fractions: F1 * F2=", Fraction.__mul__(F1, F2))
print("True Division with Fractions: F1 / F2=", Fraction.__truediv__(F1, 
F2))
print("Exponentiation with Fractions: F1 // F2=", Fraction.__pow__(F1, F2))
print("Is F1 Greater than F2?:", Fraction.__gt__(F1, F2))
print("Is F1 less than F2?:", Fraction.__lt__(F1, F2))
print("Is F1 Equal to F2?:", Fraction.__eq__(F1, F2))
print("Is F1 different than F2?:", Fraction.__ne__(F1, F2))
print ("Is F1 same as F2?:", Fraction.__is__(F1, F2))
print("Is:", Fraction.__iadd__(F1, F2))

if __name__ == '__main__':
main()

> On Aug 6, 2015, at 5:44 PM, Cameron Simpson  wrote:
> 
> On 06Aug2015 16:55, Quiles, Stephanie  
> wrote:
>> I need to do the following assignment. I need to know how do i hard code an 
>> example for each of the operators I am implementing? What i have so far is 
>> below? He said he does not care if we plug in some numbers or if we have 
>> user input numbers, however I am unsure of how to write a program that tests 
>> each operato

Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Mark,

I'm following the instructor's video exercise, available  at
https://www.youtube.com/watch?v=3cwXN5_3K6Q.

View attached screen shot file, image file shows a copy of the
counter: cou[wrd] =cou.get(wrd,0) +1


Please, explain the differences in counter methods?


Hal

On Thu, Aug 6, 2015 at 4:53 PM, Mark Lawrence 
wrote:

> On 06/08/2015 20:05, Ltc Hotspot wrote:
>
>> On my breath and soul, I did:
>>
>> Counter objects have a dictionary interface except that they return a zero
>> count for missing items instead of raising a KeyError
>> :
>>
>
> That's nice to know.  What do the rest of the methods on the class do?
>
> Please don't top post here, it makes following long threads difficult.
>

> What did you not understand about the above?
>
> You obviously haven't bothered to read the link I gave you about the
>>> Counter class so I give up.
>>>
>>>
> If you'd read the entire write up why are you still wasting time with a
> loop to find a maximum that simply doesn't work, when there is likely a
> solution in the Counter class right in front of your eyes?
>
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Question1: How type of argument should I use for dict, i.e.,user argument
or list argument.

Read captured traceback:

TypeError
Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_26.py in ()
  1 fname = raw_input("Enter file name: ")
  2 handle = open (fname, 'r')
> 3 count = dict.keys()
  4 for line in handle:
  5 if line.startswith("From: "):

TypeError: descriptor 'keys' of 'dict' object needs an argument

In [99]:

Question2: Are all the loop failures resolved in the revised code?

Revised code is available at
https://gist.github.com/ltc-hotspot/00fa77ca9b40c0a77170

Regards,
Hal

On Thu, Aug 6, 2015 at 4:20 PM, Alan Gauld 
wrote:

> On 07/08/15 00:11, Ltc Hotspot wrote:
>
>> Questions(1):Why does print line, prints blank space; and, (2) print
>> address prints a single email address:
>>
>
> See my previous emails.
> You are not storing your addresses so address only holds the last address
> in the file.
> line is at the end of the file so is empty.,
>
> In [72]: print count
>> {'gopal.ramasammyc...@gmail.com ':
>> 1, 'lo...@media.berkeley.edu ': 3,
>> 'cwen@iupui.
>> edu': 5, 'antra...@caret.cam.ac.uk ':
>> 1, 'rjl...@iupui.edu ': 2, 'gsil...@umich.ed
>> u': 3, 'david.horw...@uct.ac.za ': 4, '
>> wagne...@iupui.edu ': 1, 'zq...@umich.edu
>> ':
>>  4, 'stephen.marqu...@uct.ac.za ': 2,
>> 'r...@media.berkeley.edu ': 1}
>>
>> Question(3): why did the elements print count('keys') and print
>> count('items') fail?
>>
>
> Because, as shown above, count is a dictionary.
> So items and keys are methods not strings to be passed
> to a non-existent count() function.
>
> So you need, for example:
>
> print count.keys()
>
> Traceback (most recent call last)
>>  in ()
>> > 1 print count('items')
>>
>> TypeError: 'dict' object is not callable
>>
>>
> Which is what the error is also telling you.
> You cannot call - ie use () - with a dictionary like count.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fraction Class HELP ME PLEASE!

2015-08-06 Thread Cameron Simpson

On 06Aug2015 23:50, Quiles, Stephanie  wrote:

thanks Cameron! Here is what i have so far… new question… how do
i test the iadd, imul, etc. operators?


Like the others, by firing them. You test __add__ by running an add between two 
expressions:


 F1 + F2

You test __iadd__ by running the augmented add operation:

 F1 += F2

and so forth. The "i" probably comes from the word "increment" as the commonest 
one of these you see is incrementing a counter:


 count += 1

They're documented here:

 https://docs.python.org/3/reference/datamodel.html#object.__iadd__

The important thing to note is that they usually modify the source object. So:

 F1 += F2

will modify the internal values of F1, as opposed to __add__ which returns a 
new Fraction object.



Hopefully this time the
indents show up.


Yes, looks good.


And yes the beginning code came out of our text
book I added on some functions myself but they give you a big chunk
of it.


I thought it looked surprisingly complete given your questions. It's good to be 
up front about that kind of thing. Noone will think less of you.



I am hoping that this is what the professor was looking for.
I want to add some more operators but am unsure how to put them in
or test them? For example I want to add __ixor__, itruediv, etc.
Any other suggestions would be great!


Adding them is as simple as adding new methods to the class with the right 
name, eg:


   def __iadd__(self, other):
   ... update self by addition of other ...

If you want to be sure you're running what you think you're running you could 
put print commands at the top of the new methods, eg:


   def __iadd__(self, other):
   print("%s.__iadd__(%s)..." % (self, other))
   ... update self by addition of other ...

Obviously you would remove those prints once you were satisfied that the code 
was working.


Adding __itruediv__ and other arithmetic operators is simple enough, but 
defining __ixor__ is not necessarily meaningful: xor is a binary operation 
which makes sense for integers. It needn't have a natural meaning for 
fractions. When you define operators on an object it is fairly important that 
they have obvious and natural effects becauase you have made it very easy for 
people to use them.  Now, you could _define_ a meaning for xor on fractions, 
but personally that is one I would not make into an operator; I would leave it 
as a normal method because I would want people to think before calling it.


The point here being that it is generally better for a program to fail at this 
line:


 a = b ^ c # XOR(b, c)

because "b" does not implement XOR than for the program to function but quietly 
compute rubbish because the user _thoght_ they were XORing integers (for 
example).


Added points: make your next reply adopt the interleaved style of this message, 
where you reply point by point below the relevant text. It makes discussions 
read like conversations, and is the preferred style in this list (and many 
other techincal lists) because it keeps the response near the source text. Hand 
in hand with that goes trimming irrelevant stuff (stuff not replied to) to keep 
the content shorter and on point.


Other random code comments:

[...snip: unreplied-to text removed here...]

def gcd(m, n):
   while m % n != 0:
   oldm = m
   oldn = n

   m = oldn
   n = oldm % oldn
   return n


It reads oddly to have a blank line in the middle of that loop.


class Fraction:
   def __init__(self, top, bottom):
   self.num = top
   self.den = bottom

   def __str__(self):
   if self.den == 1:
   return str(self.num)
   elif self.num == 0:
   return str(0)
   else:
   return str(self.num) + "/" + str(self.den)


While your __str__ function will work just fine, stylisticly it is a little 
odd: you're mixing "return" and "elif". If you return from a branch of an "if" 
you don't need an "elif"; a plain old "if" will do because the return will 
prevent you reaching the next branch. So that function would normally be 
written in one of two styles:


Using "return":

   def __str__(self):
   if self.den == 1:
   return str(self.num)
   if self.num == 0:
   return str(0)
   return str(self.num) + "/" + str(self.den)

or using "if"/"elif"/...:

   def __str__(self):
   if self.den == 1:
   s = str(self.num)
   elif self.num == 0:
   s = str(0)
   else:
   s = str(self.num) + "/" + str(self.den)
   return s

For simple things like __str__ the former style is fine. For more complex 
functions the latter is usually better because your code does not bail out half 
way through - the return from the function is always at the bottom.



   def simplify(self):
   common = gcd(self.num, self.den)

   self.num = self.num // common
   self.den = self.den // common


Again, I would personally not have a blank line in th middle of this function.


   def show(self):
   print(

Re: [Tutor] Dictionary Issue

2015-08-06 Thread Mark Lawrence

On 06/08/2015 20:05, Ltc Hotspot wrote:

On my breath and soul, I did:

Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a KeyError
:


That's nice to know.  What do the rest of the methods on the class do?


Please don't top post here, it makes following long threads difficult.


What did you not understand about the above?


You obviously haven't bothered to read the link I gave you about the
Counter class so I give up.



If you'd read the entire write up why are you still wasting time with a 
loop to find a maximum that simply doesn't work, when there is likely a 
solution in the Counter class right in front of your eyes?


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

Mark Lawrence

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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 07/08/15 00:11, Ltc Hotspot wrote:
Questions(1):Why does print line, prints blank space; and, (2) print 
address prints a single email address:


See my previous emails.
You are not storing your addresses so address only holds the last 
address in the file.

line is at the end of the file so is empty.,


In [72]: print count
{'gopal.ramasammyc...@gmail.com 
': 1, 'lo...@media.berkeley.edu 
': 3, 'cwen@iupui.
edu': 5, 'antra...@caret.cam.ac.uk ': 
1, 'rjl...@iupui.edu ': 2, 'gsil...@umich.ed
u': 3, 'david.horw...@uct.ac.za ': 4, 
'wagne...@iupui.edu ': 1, 'zq...@umich.edu 
':
 4, 'stephen.marqu...@uct.ac.za ': 
2, 'r...@media.berkeley.edu ': 1}


Question(3): why did the elements print count('keys') and print 
count('items') fail?


Because, as shown above, count is a dictionary.
So items and keys are methods not strings to be passed
to a non-existent count() function.

So you need, for example:

print count.keys()


Traceback (most recent call last)
 in ()
> 1 print count('items')

TypeError: 'dict' object is not callable



Which is what the error is also telling you.
You cannot call - ie use () - with a dictionary like count.

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

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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
On Thu, Aug 6, 2015 at 3:00 PM, Alan Gauld 
wrote:

> On 06/08/15 19:30, Ltc Hotspot wrote:
>
> I moved counter outside the loop and below dict, maxval = None
>> maxkee = None are both positioned outside the loop.
>>
>
> You moved counter but it is still a dict() and you
> don't use it anywhere.
>
> URL link to the revisions are available at http://tinyurl.com/nvzdw8k
>>
>> Question: How do I define Counter
>>
>
> Counter is defined for you in the collections module.
> So to use it you need to import collections and access it as
> collections.Counter.
>
> But did you read how to use it? It is a lot more than
> just a dictionary, it has many extra methods, some of
> which almost solve your problem for you. (Whether your
> teacher will approve of using Counter is another
> issue!)
>
> Revised code reads:
>> fname = raw_input("Enter file name: ")
>> handle = open (fname, 'r')
>>
>> counter = dict ()
>> c = Counter(['address'])
>>
>
> You only need to pass a list if you are adding multiple things.
>
> But by the same token you can add a list of items, such
> as email addresses. So if you had such a list you could
> create a Counter() to hold them and count them for you.
> And return the one with the highest value.
> Sound familiar?
>
> Please (re)read the Counter documentation.
> Then play with one in the >>> prompt.
> Don't expect us to just provide you with code, learn
> how it works for yourself. Experiment.
>
> The >>> prompt is your friend. You will learn more from that in 15 minutes
> than in a bunch of emails showing other peoples
> code.
>
> Alternatively forget about Counter and just go back to
> your dict(). You have written all the code you need already,
> you just need to assemble it in the correct order.
>
> maxval = None
>> maxkee = None
>>
>> for line in handle:
>>  if line.startswith("From: "):
>>  address = line.split()[1]
>>
>
> You are not storing the addresses anywhere.
>
> for maxkee, val in c.items():
>>
>>  maxval = val
>>  maxkee = kee
>>
>
> You are still not testing if its the maximum,
> you just keep overwriting the variables for
> each element.
>
> print maxkee and maxval
>>
>
> You still have an 'and' in there.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>




Hi Alan,

Questions(1):Why does print line, prints blank space; and, (2) print
address prints a single email address:

View print results as follows:

In [70]: %run assignment_9_4_24.py
Enter file name: mbox-short.txt
r...@media.berkeley.edu 1

In [71]: print handle


In [72]: print count
{'gopal.ramasammyc...@gmail.com': 1, 'lo...@media.berkeley.edu': 3,
'cwen@iupui.
edu': 5, 'antra...@caret.cam.ac.uk': 1, 'rjl...@iupui.edu': 2,
'gsil...@umich.ed
u': 3, 'david.horw...@uct.ac.za': 4, 'wagne...@iupui.edu': 1, '
zq...@umich.edu':
 4, 'stephen.marqu...@uct.ac.za': 2, 'r...@media.berkeley.edu': 1}

In [73]: print line


In [74]: print address
c...@iupui.edu


Question(3): why did the elements print count('keys') and print
count('items') fail?

View print commands as follows:


In [75]: dir (count)
Out[75]:
['__class__',
 '__cmp__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'has_key',
 'items',
 'iteritems',
 'iterkeys',
 'itervalues',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values',
 'viewitems',
 'viewkeys',
 'viewvalues']

In [76]:

---
TypeError
Traceback (most recent call last)
 in ()
> 1 print count('items')

TypeError: 'dict' object is not callable

In [77]: print count('keys')
---
TypeError
Traceback (most recent call last)
 in ()
> 1 print count('keys')

TypeError: 'dict' object is not callable

In [78]:


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


Re: [Tutor] About python intrepeters on Android.

2015-08-06 Thread Alan Gauld

On 06/08/15 23:22, Ali Moradi wrote:

Hi, i noticed that the Python intrepeters on Android OS does not have
Tkinter!

Why they couldn't bring Tkinter on Android too?


Two reasons:
1) Tkinter is just a thin wrapper around the Tcl/Tk UI toolkit.
   If Tk isn't on Android then Tkinter will not be.
   And Tk isn't. (It may be at some point but not yet)

2) Tk, and so Tkinter, is based on a windowed environment.
   Android is not. It would be a major task to try to rethink
   how all the widgets in Tk would look and work under Android.

The good news is that there is a UI toolkit for Python
on Android (as well as Windows, Linux, MacOS and iOS)
called Kivy which is apparently quite powerful
and easy to learn. Take a look at kivy.org.

I've never used it but have heard positive reports.

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


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


[Tutor] About python intrepeters on Android.

2015-08-06 Thread Ali Moradi
Hi, i noticed that the Python intrepeters on Android OS does not have
Tkinter!

Why they couldn't bring Tkinter on Android too? It there anyway ti use
tkintr on android too ? Tnx :)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 06/08/15 19:30, Ltc Hotspot wrote:


I moved counter outside the loop and below dict, maxval = None
maxkee = None are both positioned outside the loop.


You moved counter but it is still a dict() and you
don't use it anywhere.


URL link to the revisions are available at http://tinyurl.com/nvzdw8k

Question: How do I define Counter


Counter is defined for you in the collections module.
So to use it you need to import collections and access it as 
collections.Counter.


But did you read how to use it? It is a lot more than
just a dictionary, it has many extra methods, some of
which almost solve your problem for you. (Whether your
teacher will approve of using Counter is another
issue!)


Revised code reads:
fname = raw_input("Enter file name: ")
handle = open (fname, 'r')

counter = dict ()
c = Counter(['address'])


You only need to pass a list if you are adding multiple things.

But by the same token you can add a list of items, such
as email addresses. So if you had such a list you could
create a Counter() to hold them and count them for you.
And return the one with the highest value.
Sound familiar?

Please (re)read the Counter documentation.
Then play with one in the >>> prompt.
Don't expect us to just provide you with code, learn
how it works for yourself. Experiment.

The >>> prompt is your friend. You will learn more from that in 15 
minutes than in a bunch of emails showing other peoples

code.

Alternatively forget about Counter and just go back to
your dict(). You have written all the code you need already,
you just need to assemble it in the correct order.


maxval = None
maxkee = None

for line in handle:
 if line.startswith("From: "):
 address = line.split()[1]


You are not storing the addresses anywhere.


for maxkee, val in c.items():

 maxval = val
 maxkee = kee


You are still not testing if its the maximum,
you just keep overwriting the variables for
each element.


print maxkee and maxval


You still have an 'and' in there.

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


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


Re: [Tutor] Fraction Class HELP ME PLEASE!

2015-08-06 Thread Cameron Simpson

On 06Aug2015 16:55, Quiles, Stephanie  wrote:
I need to do the following assignment. I need to know how do i hard code an 
example for each of the operators I am implementing? What i have so far is 
below? He said he does not care if we plug in some numbers or if we have user 
input numbers, however I am unsure of how to write a program that tests each 
operator? Or can i write one that tests all of them? I don’t know where to 
start with this. Please help!


For someone who doesn't know where to start, you seem to have a lot of decent 
looking code. Is the code below all yours? If so, a good start.


Also, please try to preserve the indentation when pasting in code; indentation 
is critical in Python as you know and incorrect indentation, when not an 
outright syntax error, can be a source of bugs. I'll presume your code was 
originally indented correctly.


Note that in this list we _do_ like code to be pasted inline where it can be 
seen directly and commented on like any other part of the message text. We're 
not big on attachments or links to external things (other than doco citations 
like your reference to the operators Python page).



You may implement as many of these operators as you like (such as isub,
itruediv, etc.) You MUST indicate in your header information which operators
you are implementing, and you MUST hard code an example for each.


"Header information" is usually an opening comment. So perhaps start the 
program with text like this:


 # Here is a Fraction class implementing variaous operators. It currently
 # supports:
 #
 # + (addition)
 # - (subtraction)
 # * (multiplication)
 # / (true division)
 #

and so forth.

Regarding examples and tests, one workable approach to to make your program 
work as a "main program". The idea is that is invoked as a main program it will 
run the examples or tests.


As your code sits now it could be used as a module - someone could place it 
into python's library tree and import it, and use your Fraction class.  
However, you can of course run it directly at the command prompt, eg:


 % python your-fraction-file.py

When you do that, the code is still imported as a module but with the special 
name '__main__'. So what a lot of python modules do is have a "main" function 
which is to be fired only in the command line circumstance, such as:


 def main():
   F1 = Fraction(1, 2) # 1/2
   F2 = Fraction(2, 3) # 2/3
   print("F1 =", F1)
   print("F2 =", F2)
   print("F1 + F2 =", F1 + F2)
   print("F1 - F2 =", F1 - F2)
   print("F1 * F2 =", F1 * F2)

In order to make your program work as both an importable module which defines 
the Fraction class but does not run the main function and also as a main 
program which defines the class and then runs the main function you put this 
piece of boilerplate code on the very bottom of the program:


 if __name__ == '__main__':
   main()

which checks if you're invoking it directly from the command line. If so, run 
the main function.


Hopefully that gives you an idea about hardwiring examples also.

Regarding tests, you might write a simple function like this:

 def check(label, computed, expected):
   ok = computed == expected
   if ok:
 print(label, 'OK', computed, '==', expected)
   else:
 print(label, 'BAD', computed, '!=', expected)
   return ok

Then you might consider modifying your main program to run tests instead of 
bare examples, replacing:


 print("F1 + F2 =", F1 + F2)

with:

 check("F1 + F2", F1 + F2, Fraction(7, 6))

Because check() returns whther the check was ok, you might even count the 
number of failures for some kind of report:


 fail_count = 0
 ...
 if not check("F1 + F2", F1 + F2, Fraction(7, 6)):
   fail_count += 1
 ... more checks ...
 print(fail_count, "failures")

and so forth.

This also gets you test code so that you can test your own program for 
correctness before submitting your assignment.


Feel free to return to this list with updated code and new questions.

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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
On my breath and soul, I did:

Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a KeyError
:
>>>

>>> c = Counter(['eggs', 'ham'])


On Thu, Aug 6, 2015 at 11:59 AM, Mark Lawrence 
wrote:

> On 06/08/2015 18:17, Ltc Hotspot wrote:
>
>> On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence 
>> wrote:
>>
>> On 06/08/2015 05:22, Ltc Hotspot wrote:
>>>
>>> Please don't top post here, it makes following long threads difficult.
>>>
>>> Mark,
>>>

 Replace  count[address]= count.get(address,0) +1 with  c =
 Counter(['address'])?


>>> Try it at the interactive prompt and see what happens.
>>>
>>> How do I define counter,view trace back:
>>>
>>> NameError
>>> Traceback (most recent call last)
>>> C:\Users\vm\Desktop\apps\docs\Python\new.txt in ()
>>>1 fname = raw_input("Enter file name: ")
>>>2 handle = open (fname, 'r')
>>> > 3 c = Counter(['address'])
>>>4
>>>5
>>>
>>> NameError: name 'Counter' is not defined
>>
>>
>> View revised code here:
>>
>> fname = raw_input("Enter file name: ")
>> handle = open (fname, 'r')
>> c = Counter(['address'])
>>
>> count = dict ()
>> maxval = None
>> maxkee = None
>>
>> for kee, val in count.items():
>>  maxval = val
>>  maxkee = kee
>>
>> for line in handle:
>>  if line.startswith("From: "):
>>  address = line.split()[1]
>>  count[address]= count.get(address,0) +1
>> print maxkee and maxval
>>
>>
> You obviously haven't bothered to read the link I gave you about the
> Counter class so I give up.
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe

Thank You, Alan.

This is THE FIRST time, when I've got a pleasure from the opponent.
You're maintain status of a thinking human and, as a humble DAOist, I 
always say THANK YOU, when I talk to such a Man.

'Cause wisdom bring us the beauty.

So, what else I can add.
Just a little bit.

It would be great to work with You.
You know, life is so shot..
And any talks don't make it better, alas.

Just we can do.



Alan Gauld 於 08/06/2015 09:54 PM 寫道:

On 06/08/15 14:28, John Doe wrote:

Well, I think, both of us understands that any reference isn't about any
sort of a language. It's about REGISTER = [ALU, FPU, ...]



No thats about the implementation.
The language and implemewntation are completely searate.
There can be many different implementations of a single
language and they all have to follow the semantics defined
by the language but are free to build those semantics
any way they like. (And indeed the different versions
of Python do just that!)


While You're talking about Python - You're talking ONLY about
interpreter for a BYTEcode
Alas, CPU don't speak BYTEcode but BITcode.


Some do. Some speak higher level things. For example
some CPUs speak Forth. And still others don't use binary
at all but use tri-state values. There werte even some
in the early days that used 4-state values. But these
are all implementation details that the programmer
doesn't need to care about.


So, Python can't allocate memory for CPU only for interpreter, which
will ask allocation through underlying-C-language.


Not necessarily. The interpreter could get C to allocate
a huge pool of memory at startup and then use that for
its own allocation/deallocation purposes.


CPU have compiler for Python?


Not yet but it is theoretically possible.
And python would not change if someone built one.


As well as multithreading, for instance, in Python goes to a single
interpreter, but in C - to multiple cores of CPU.


That depends on the implementation. I have a C compiler
that does not do multi-core/thread working. It's an
implementation detail and the C language does not
specify that it must. It all depends on the code that
the compiler generates.


 So Python doesn't have
REAL multithreading, but C - does.


Python does. But not all of its implementations do.
The emulate it instead.  But so far as the programmer is
concerned his code is using threading/concurrency.
He may need to be aware that the implementation is not
honoring his request fully but that doesn't change his
code.


And in my case by means of C-rules Python allocates FOR-loop's list as a
reference.


No, the C implementation might do that. Python as a language
does not. High level languages exist to stop us thinking about
the low level details. The implementation may change, that's not our
problem. Python specifies how the Python execution model works
not how the CPU or the assembler, or the compiler or the
implementer interprets that.

Even C has many different implementations. Some are more efficient
than others. Should we be worrying about which C compiler was used
to build our interpreter? Should we care about whether the CPU
implements multiplication in hardware or in microcode? Or whether it
caches local variables on on-chip cache or uses main memory?

And what about the I/O routines. Do we need to worry about
whether our chosen C compiler is using it's own I/O library,
or calling the BIOS directly?  or using the OS system calls?
These are all implementation details that regular
programmers can, and should, ignore.


And that mistake wastes each iteration of FOR-loop in
unnecessary RE-evaluation of initial-list IN LOGIC STATEMENT, which must
be created only once. Any INITIATIONS make once. 'Cause it sucks
CPU-memory-allocation-cycle.


In the modern world of fast CPUs and memory and where the vast majority
of applications run in virtual machines(JVM, .Net) and the vast majority
of servers run inside virtualized environments (VMWare etc)
none of that is of the slightest concern to me.

If I was writing code for an embedded system it might be more worrisome,
but then I'd probably not be using Python for that.


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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Mark,

Visit the following URL link to view a captured copy of the latest code
revision, available at http://tinyurl.com/nvzdw8k

Regards,
Hal

On Thu, Aug 6, 2015 at 10:17 AM, Ltc Hotspot  wrote:

>
>
> On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence 
> wrote:
>
>> On 06/08/2015 05:22, Ltc Hotspot wrote:
>>
>> Please don't top post here, it makes following long threads difficult.
>>
>> Mark,
>>>
>>> Replace  count[address]= count.get(address,0) +1 with  c =
>>> Counter(['address'])?
>>>
>>
>> Try it at the interactive prompt and see what happens.
>>
>> How do I define counter,view trace back:
>>
>> NameError
>> Traceback (most recent call last)
>> C:\Users\vm\Desktop\apps\docs\Python\new.txt in ()
>>   1 fname = raw_input("Enter file name: ")
>>   2 handle = open (fname, 'r')
>> > 3 c = Counter(['address'])
>>   4
>>   5
>>
> NameError: name 'Counter' is not defined
>
>
> View revised code here:
>
> fname = raw_input("Enter file name: ")
> handle = open (fname, 'r')
> c = Counter(['address'])
>
> count = dict ()
> maxval = None
> maxkee = None
>
> for kee, val in count.items():
> maxval = val
> maxkee = kee
>
> for line in handle:
> if line.startswith("From: "):
> address = line.split()[1]
> count[address]= count.get(address,0) +1
> print maxkee and maxval
>
>
> In [20]:
> Hal
>
>>
>>>
>>>
>>>
 ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Hi Alan,

I moved counter outside the loop and below dict, maxval = None
maxkee = None are both positioned outside the loop.

URL link to the revisions are available at http://tinyurl.com/nvzdw8k

Question: How do I define Counter

Revised code reads:
fname = raw_input("Enter file name: ")
handle = open (fname, 'r')

counter = dict ()
c = Counter(['address'])

maxval = None
maxkee = None

for line in handle:
if line.startswith("From: "):
address = line.split()[1]

for maxkee, val in c.items():

maxval = val
maxkee = kee

print maxkee and maxval


Traceback message reads:
NameError
Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_16.py in ()
  3
  4 counter = dict ()
> 5 c = Counter(['address'])
  6
  7 maxval = None

NameError: name 'Counter' is not defined


Regards,
Hal

On Thu, Aug 6, 2015 at 2:47 AM, Alan Gauld 
wrote:

> On 06/08/15 03:27, Ltc Hotspot wrote:
>
>> The output as reported by the latest code revision: c...@iupui.edu
>>  1← Mismatch
>>
>> Looks like python continues to print the wrong data set:
>>
>
> Python will print what you ask it to. Don't blame the tool!  :-)
>
> > for line in handle:
> >  if line.startswith("From: "):
> >  address = line.split()[1]
> >  count[address]= count.get(address,0) +1
> >
> > maxval = None
> > maxkee = None
> > for kee, val in count.items():
> >
> > maxval = val
> > maxkee = kee
> >
> > print address, val
>
> Look at the loops.
>
> In the second loop you are no longer setting the values to
> those of the max item but are setting them every time.
> So at the end of the loop val holds the val of
> the last item (and so does maxval so even if you used
> that it would be the same result).
>
> Similarly with the code for address. You are setting that
> for each 'From ' line in your file so at the end of the loop
> address is the last address in the file.
>
> Now, dictionaries do not store data in the order that you
> insert it, so there is no guarantee that the last item in
> the dictionary loop is the same as the last address
> you read.
>
> You need to reinstate the test for max val in the second
> loop and then print the kee that corresponds with that
> (maxkee) as the address. ie. print maxkee and maxval.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 06/08/15 18:17, Ltc Hotspot wrote:


Replace  count[address]= count.get(address,0) +1 with  c =
Counter(['address'])?


You didn't do what Mark suggested.
Did you read the documentation about Counter?


NameError
Traceback (most recent call last)
   2 handle = open (fname, 'r')
> 3 c = Counter(['address'])


NameError: name 'Counter' is not defined


So where do you define Counter? Do you import the module?
Do you import Counter from the module?
It's not shown in your code.


View revised code here:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
c = Counter(['address'])

count = dict ()
maxval = None
maxkee = None

for kee, val in count.items():
 maxval = val
 maxkee = kee

for line in handle:
 if line.startswith("From: "):
 address = line.split()[1]
 count[address]= count.get(address,0) +1
print maxkee and maxval


You have introduced an 'and' here which makes no sense.
It will try to print the logical AND of the two values.
That's not what you want.

Please try to work through this manually and see
how it works (or doesn't). There is no point in folks
making suggestions for improvements until you
understand how it should work yourself.b You have
all the components needed to build the solution,
now its up to you to fit them together such that
they work. We can make suggestions but you need
to solve the problem, we can't, and won't do it
for you.

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


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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Mark Lawrence

On 06/08/2015 18:17, Ltc Hotspot wrote:

On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence 
wrote:


On 06/08/2015 05:22, Ltc Hotspot wrote:

Please don't top post here, it makes following long threads difficult.

Mark,


Replace  count[address]= count.get(address,0) +1 with  c =
Counter(['address'])?



Try it at the interactive prompt and see what happens.

How do I define counter,view trace back:

NameError
Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\new.txt in ()
   1 fname = raw_input("Enter file name: ")
   2 handle = open (fname, 'r')
> 3 c = Counter(['address'])
   4
   5


NameError: name 'Counter' is not defined


View revised code here:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
c = Counter(['address'])

count = dict ()
maxval = None
maxkee = None

for kee, val in count.items():
 maxval = val
 maxkee = kee

for line in handle:
 if line.startswith("From: "):
 address = line.split()[1]
 count[address]= count.get(address,0) +1
print maxkee and maxval



You obviously haven't bothered to read the link I gave you about the 
Counter class so I give up.


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

Mark Lawrence

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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread Alan Gauld

On 06/08/15 14:28, John Doe wrote:

Well, I think, both of us understands that any reference isn't about any
sort of a language. It's about REGISTER = [ALU, FPU, ...]



No thats about the implementation.
The language and implemewntation are completely separate.
There can be many different implementations of a single
language and they all have to follow the semantics defined
by the language but are free to build those semantics
any way they like. (And indeed the different versions
of Python do just that!)


While You're talking about Python - You're talking ONLY about
interpreter for a BYTEcode
Alas, CPU don't speak BYTEcode but BITcode.


Some do. Some speak higher level things. For example
some CPUs speak Forth. And still others don't use binary
at all but use tri-state values. There werte even some
in the early days that used 4-state values. But these
are all implementation details that the programmer
doesn't need to care about.


So, Python can't allocate memory for CPU only for interpreter, which
will ask allocation through underlying-C-language.


Not necessarily. The interpreter could get C to allocate
a huge pool of memory at startup and then use that for
its own allocation/deallocation purposes.


CPU have compiler for Python?


Not yet but it is theoretically possible.
And python would not change if someone built one.


As well as multithreading, for instance, in Python goes to a single
interpreter, but in C - to multiple cores of CPU.


That depends on the implementation. I have a C compiler
that does not do multi-core/thread working. It's an
implementation detail and the C language does not
specify that it must. It all depends on the code that
the compiler generates.


 So Python doesn't have
REAL multithreading, but C - does.


Python does. But not all of its implementations do.
The emulate it instead.  But so far as the programmer is
concerned his code is using threading/concurrency.
He may need to be aware that the implementation is not
honoring his request fully but that doesn't change his
code.


And in my case by means of C-rules Python allocates FOR-loop's list as a
reference.


No, the C implementation might do that. Python as a language
does not. High level languages exist to stop us thinking about
the low level details. The implementation may change, that's not our 
problem. Python specifies how the Python execution model works

not how the CPU or the assembler, or the compiler or the
implementer interprets that.

Even C has many different implementations. Some are more efficient
than others. Should we be worrying about which C compiler was used
to build our interpreter? Should we care about whether the CPU 
implements multiplication in hardware or in microcode? Or whether it 
caches local variables on on-chip cache or uses main memory?


And what about the I/O routines. Do we need to worry about
whether our chosen C compiler is using it's own I/O library,
or calling the BIOS directly?  or using the OS system calls?
These are all implementation details that regular
programmers can, and should, ignore.


And that mistake wastes each iteration of FOR-loop in
unnecessary RE-evaluation of initial-list IN LOGIC STATEMENT, which must
be created only once. Any INITIATIONS make once. 'Cause it sucks
CPU-memory-allocation-cycle.


In the modern world of fast CPUs and memory and where the vast majority 
of applications run in virtual machines(JVM, .Net) and the vast majority 
of servers run inside virtualized environments (VMWare etc)

none of that is of the slightest concern to me.

If I was writing code for an embedded system it might be more worrisome, 
but then I'd probably not be using Python for that.


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


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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 06/08/15 18:17, Ltc Hotspot wrote:


View revised code here:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
c = Counter(['address'])

count = dict ()
maxval = None
maxkee = None

for kee, val in count.items():
 maxval = val
 maxkee = kee

for line in handle:
 if line.startswith("From: "):
 address = line.split()[1]
 count[address]= count.get(address,0) +1
print maxkee and maxval


Let's hold up here a second. You do understand that
Python executes your code from top to bottom, yes?

So reading your code from the top you have a loop that
sets maxval and maxkee before you even put anything
into count. How do you think that would ever work?

You have a lot of people spending time trying to
help you here, but you do need to exercise a little
bit of insight yourself. That code can never work
and it has nothing to do with Pyhon it is your
logic that is faulty.

Try working through it with a pencil and paper.
Write down what each variable contains at each
stage of the program. (or just print it to see).

You have been very close to a solution but you
seem to be getting farther away rather than closer
which suggests you are trying stuff without
understanding why.

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


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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe



Well...
Try this look. But I'm just a human and can make mistakes.:))

Passing value - allocates stack and creates NEW memory position.
Passing reference - makes stack pointer pointing to any position.
Dereference - makes stack pointer pointing to any position AND TAKES VALUE.

So, You can count how much in every case does CPU make steps.
And now add to this BIG ARRAY as input for calculation.

Always must keep in mind, that the NAME of variable exists for SCOPE of
You code, but VALUE - for CPU.

So, reference will be always, unless CPU have reached quantum-mechanics



Steven D'Aprano 於 08/06/2015 05:21 PM 寫道:

On Thu, Aug 06, 2015 at 08:57:34AM -0400, Joel Goldstick wrote:

On Thu, Aug 6, 2015 at 4:34 AM, John Doe  wrote:

Can You, please, elaborate this "..Passing in Python is different than in C
or other languages..."


I hesitate, because this question is usually the fuel of flaming wars.


Very wise :-)

But since I'm not so wise, here are some more comments.



So in short:

C can pass a value or a reference to a value (the address of the place
in memory where the value is stored)


You are correct that C can pass a reference to a value, namely a
pointer. But from the perspective of the C compiler, that pointer *is*
the value, not the thing being pointed at. So passing a pointer as
argument is no different from passing an int or a float or a bool, it's
just a value, and the C compiler will use pass by value on the pointer
itself.

In C, one can use pointers to *simulate* pass by reference. But this is
not the same thing as actual pass by reference. In pass by reference,
you don't pass (a pointer to the variable you want), you pass (the
variable you want), and the compiler does all the magic needed to make
it work.




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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe

Thank You, Steven.

I've already written to Your colleague, so You will can see about.

And when I'm saying 'ALLOCATION' I keep in mind the REGISTER, not a 
glossary or thesaurus. Language is created for us, not for CPU.

Do You agree?

Passing VALUE is a time-expensive procedure. Python can't reach 
processor, so any Python's memory allocations don't have sense.


Language always was, is and will be the ONE - compiled bitcode.
Others - just syntax + specially-sphere-applied variations for Your 
pleasure.


Isn't it?

Steven D'Aprano 於 08/06/2015 04:45 PM 寫道:

On Thu, Aug 06, 2015 at 11:34:51AM +0300, John Doe wrote:


Can You, please, elaborate this "..Passing in Python is different than
in C or other languages..."


Argument passing in Python is:

- different to Perl, C, Scala, Algol and Pascal;

- the same as Ruby, Lua, Applescript and Javascript;

- the same as Java boxed values (object);

- different to Java unboxed values (machine types).


In C, all values are passed by value. When you pass an argument to a
function, the C compiler makes a copy of that value and passes the
value.

In Pascal, values can be passed by value (like C), or by reference.

The simplest demonstration of pass-by-reference is to write a "swap"
procedure. In Python terms:


# This does not actually work in Python.
def swap(a, b):
 tmp = a
 a = b
 b = tmp

x = 23
y = 42
swap(x, y)
print x, y  # prints 42 23

z = 19
swap(x, z)
print x, z  # prints 19 42


You *cannot* write a swap procedure like this in Python. The closest you
can do is write a function that returns the two values, then assign
them:

def swap(a, b):
 return b, a

x, y = swap(x, y)  # this works

but that is not pass by reference.

In Pascal, you can write such a swap procedure.

Scala and Algol use pass by name, and pass by value. This page explains
pass by name in Scala, and how it differs from pass by value:

http://alvinalexander.com/source-code/scala/simple-scala-call-name-example

In Java, unboxed values (not objects, low-level machine ints and floats)
are passed by value, like C.

Python, Ruby, Javascript, Lua, Java boxed values (objects), and many
other languages, all use the same passing style. This has a number of
names:

- pass by object;
- pass by sharing;
- pass by object sharing;

Some people (especially Ruby programmers) call it "pass by reference"
but that is wrong. Others (especially Java programmers) call it "call by
value, where the value is a reference" which is technically correct but
too long. Another name is "call by value/pass by reference", which is
just confusing.

See also:

https://en.wikipedia.org/wiki/Evaluation_strategy

In pass by object sharing, the argument is evaluated but *not* copied.
Since the argument is not copied, it is not pass-by-value. Inside the
function, you can modify the object, and since it is not a copy, the
original sees the changes. But *assignment* to the local variable inside
the function does not affect the caller's variable, so it is not
pass-by-reference.

To summarise:

Pass by value:
- Argument is copied? YES
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? NO

Pass by reference:
- Argument is copied? NO
- Assignment inside function affects original? YES
- Mutation of argument inside function affects original? YES

Pass by object sharing:
- Argument is copied? NO
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? YES




'Cause as far as I know - default major Python's implementation CPython
is written in C.


That is irrelevent. The argument passing strategy of a language is part
of the language itself, not the implementation language.

C does not allow variables to change type. But Python does. You cannot
do this in C:

x = 23  # x is an integer
x = "foo"  # and now it is a string

so clearly the behaviour of a programming language is not always the
same as that of the implementation language.




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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence 
wrote:

> On 06/08/2015 05:22, Ltc Hotspot wrote:
>
> Please don't top post here, it makes following long threads difficult.
>
> Mark,
>>
>> Replace  count[address]= count.get(address,0) +1 with  c =
>> Counter(['address'])?
>>
>
> Try it at the interactive prompt and see what happens.
>
> How do I define counter,view trace back:
>
> NameError
> Traceback (most recent call last)
> C:\Users\vm\Desktop\apps\docs\Python\new.txt in ()
>   1 fname = raw_input("Enter file name: ")
>   2 handle = open (fname, 'r')
> > 3 c = Counter(['address'])
>   4
>   5
>
NameError: name 'Counter' is not defined


View revised code here:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
c = Counter(['address'])

count = dict ()
maxval = None
maxkee = None

for kee, val in count.items():
maxval = val
maxkee = kee

for line in handle:
if line.startswith("From: "):
address = line.split()[1]
count[address]= count.get(address,0) +1
print maxkee and maxval


In [20]:
Hal

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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe
Well, I think, both of us understands that any reference isn't about any 
sort of a language. It's about REGISTER = [ALU, FPU, ...]


That's why reference inevitable.

While You're talking about Python - You're talking ONLY about 
interpreter for a BYTEcode

Alas, CPU don't speak BYTEcode but BITcode.

So, Python can't allocate memory for CPU only for interpreter, which 
will ask allocation through underlying-C-language.


Do I wrong?
CPU have compiler for Python?
As well as multithreading, for instance, in Python goes to a single 
interpreter, but in C - to multiple cores of CPU. So Python doesn't have 
REAL multithreading, but C - does.


And in my case by means of C-rules Python allocates FOR-loop's list as a 
reference. And that mistake wastes each iteration of FOR-loop in 
unnecessary RE-evaluation of initial-list IN LOGIC STATEMENT, which must 
be created only once. Any INITIATIONS make once. 'Cause it sucks 
CPU-memory-allocation-cycle.


Does this point make sense for You?

Joel Goldstick 於 08/06/2015 03:57 PM 寫道:

On Thu, Aug 6, 2015 at 4:34 AM, John Doe  wrote:

Can You, please, elaborate this "..Passing in Python is different than in C
or other languages..."


I hesitate, because this question is usually the fuel of flaming wars.
So in short:

C can pass a value or a reference to a value (the address of the place
in memory where the value is stored)
Python passes an object -- everything in python is an object.  If the
object is mutable, and the function mutates it, those results will be
seen outside the function.  If the object is immutable, and the
function tries to change its value, a new object is created with the
new value.  Its name is the name given in the parameter list -- not
the name that the function was called with.  When the function
completes, that object is lost since the outer scoped named object
wasn't changed.


'Cause as far as I know - default major Python's implementation CPython is
written in C.


What language is used for its implementation has nothing to do with
its own specification.


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


[Tutor] Fraction Class HELP ME PLEASE!

2015-08-06 Thread Quiles, Stephanie
Hello All,

I need to do the following assignment. I need to know how do i hard code an 
example for each of the operators I am implementing? What i have so far is 
below? He said he does not care if we plug in some numbers or if we have user 
input numbers, however I am unsure of how to write a program that tests each 
operator? Or can i write one that tests all of them? I don’t know where to 
start with this. Please help!


We discussed implementing different operators in our Fraction class. Here is a 
link to some operators in Python (look at Section 10.3.1). 
https://docs.python.org/3/library/operator.html

You may implement as many of these operators as you like (such as isub, 
itruediv, etc.) You MUST indicate in your header information which operators 
you are implementing, and you MUST hard code an example for each.

def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n

m = oldn
n = oldm % oldn
return n


class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

def __str__(self):
if self.den == 1:
return str(self.num)
elif self.num == 0:
return str(0)
else:
return str(self.num) + "/" + str(self.den)

def simplify(self):
common = gcd(self.num, self.den)

self.num = self.num // common
self.den = self.den // common`

def show(self):
print(self.num, "/", self.den)

def __add__(self, otherfraction):
newnum = self.num * otherfraction.den + \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __sub__(self, otherfraction):
newnum = self.num * otherfraction.den - \
self.den * otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __mul__(self, otherfraction):
newnum = self.num * otherfraction.num * \
self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __imul__(self, otherfraction):
if isinstance(otherfraction):
return self__mul__(otherfraction)

def __iadd__(self, otherfraction):
if isinstance(otherfraction):
return self__iadd__(otherfraction)

def __truediv__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def __radd__(self, otherfraction):
newnum = self.num * otherfraction.num // self.den * otherfraction.den
newden = self.den * otherfraction.den
common = gcd(newnum, newden)
return Fraction(newnum // common, newden // common)

def getNum(self):
return self.num

def getDen(self):
return self.den

def __gt__(self, otherfraction):
return (self.num / self.den) > (otherfraction.num / otherfraction.den)

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


[Tutor] Problem with battleship game

2015-08-06 Thread asets...@gmail.com
Hello. I'm writing battleship game. I have one class for bot 
field:https://bpaste.net/show/b3ddcd7724f4 and one class for player 
field:https://bpaste.net/show/6a7981fb4634 I made class for player field 
from bot field class. For some reason I can't place ship properly for 
player.


Full text of program:https://bpaste.net/show/8b8f37bd3cca

What may be the problem?

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


Re: [Tutor] how to define constant width errorbars on log-log plot

2015-08-06 Thread Laura Creighton
In a message of Thu, 06 Aug 2015 12:41:22 -0300, Colin Ross writes:
>Does anyone have an example code that shows how to plot errorbars with a 
>constant line width for a dataset on a log log plot? Thank you.


Assuming you want to use matplotlib (there are other python programs
that do this) see:
http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html

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


Re: [Tutor] how to define constant width errorbars on log-log plot

2015-08-06 Thread Mark Lawrence

On 06/08/2015 16:41, Colin Ross wrote:

Does anyone have an example code that shows how to plot errorbars with a 
constant line width for a dataset on a log log plot? Thank you.


Directly no, but is there anything from one or more of the examples here 
http://matplotlib.org/gallery.html that you could use?


I believe this is getting beyond the remit of this list as we're talking 
third party code.  So if you don't get answers please go to 
https://lists.sourceforge.net/lists/listinfo/matplotlib-users which is 
also available as gmane.comp.python.matplotlib.general


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

Mark Lawrence

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


[Tutor] how to define constant width errorbars on log-log plot

2015-08-06 Thread Colin Ross
Does anyone have an example code that shows how to plot errorbars with a 
constant line width for a dataset on a log log plot? Thank you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Mark Lawrence

On 06/08/2015 05:22, Ltc Hotspot wrote:

Please don't top post here, it makes following long threads difficult.


Mark,

Replace  count[address]= count.get(address,0) +1 with  c =
Counter(['address'])?


Try it at the interactive prompt and see what happens.



Regards,
Hal

On Wed, Aug 5, 2015 at 9:03 PM, Mark Lawrence 
wrote:


On 05/08/2015 23:58, Ltc Hotspot wrote:


Hi Mark,

Address identifies the email address with the maximum  number of sends:
c...@iupui.edu.

Secondly, we are missing a count on the number of messages sent by
c...@iupui.edu, i.e., 5.

Thirdly, maxval 'none' is not defined on line # 24

Questions: How do we define the value of none for the key maxval and
retrieve a number count on the number of messages sent by c...@iupui.edu.


NameError:

Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in ()
   22 ## find the greatest number of mail messages.
   23
---> 24 maxval = none
   25 maxkee = none
   26 for kee, val in count.items():

NameError: name 'none' is not defined

In [52]: print address
c...@iupui.edu

Revised data:


## The program looks for 'From ' lines and takes the second
## word of those lines as the person who sent the mail.

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
for line in handle:
  if line.startswith("From: "):
  address = line.split()[1]


## The program creates a Python dictionary that maps
## the sender's mail address to a count of the number
## of times they appear in the file.

  count = dict()
  for wrd in address:
  count[wrd]= count.get(wrd,0) +1

## After the dictionary is produced, the program reads
## through the dictionary using a maximum loop to
## find the greatest number of mail messages.

maxval = none
maxkee = none
for kee, val in count.items():
  if maxval == none or maxval 
You can greatly simplify all of the above code if you use a Counter from
the collections module
https://docs.python.org/3/library/collections.html#collections.Counter

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

Mark Lawrence



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

Mark Lawrence

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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread Steven D'Aprano
On Thu, Aug 06, 2015 at 08:57:34AM -0400, Joel Goldstick wrote:
> On Thu, Aug 6, 2015 at 4:34 AM, John Doe  wrote:
> > Can You, please, elaborate this "..Passing in Python is different than in C
> > or other languages..."
> >
> I hesitate, because this question is usually the fuel of flaming wars.

Very wise :-)

But since I'm not so wise, here are some more comments.


> So in short:
> 
> C can pass a value or a reference to a value (the address of the place
> in memory where the value is stored)

You are correct that C can pass a reference to a value, namely a 
pointer. But from the perspective of the C compiler, that pointer *is* 
the value, not the thing being pointed at. So passing a pointer as 
argument is no different from passing an int or a float or a bool, it's 
just a value, and the C compiler will use pass by value on the pointer 
itself.

In C, one can use pointers to *simulate* pass by reference. But this is 
not the same thing as actual pass by reference. In pass by reference, 
you don't pass (a pointer to the variable you want), you pass (the 
variable you want), and the compiler does all the magic needed to make 
it work.

Pascal is a good example of pass by reference because it also has 
pointers, so we can demonstrate both the real thing and the simulation. 
Here is a small Pascal program that uses pass by value, a pointer 
simulating pass by reference, and actual pass by reference:


=== cut ===

program demo (input, output);

type
  intptr = ^integer;
var
  x, y, z: integer;
  w: intptr;

function sum(a: integer; b: intptr; var c: integer): integer;
  var
total: integer;
  begin
total := 0;
total := total + a;
total := total + b^;
total := total + c;
a := -1;
b^ := -1;
c := -1;
sum := total;  {set the return value}
end;

begin
  x := 100;
  y := 100;
  z := 100;
  w := @y;   { address-of operator @ is non-standard Pascal }
  writeln(x, ' ', y, ' ', z);
  writeln(sum(x, w, z));
  writeln(x, ' ', y, ' ', z);
end.


=== cut ===

The output is:

100 100 100
300
100 -1 -1


Note that except for the declaration, inside the body of the function 
you treat c as an ordinary variable just like a, while with b you have 
to manually dereference the pointer whenever you want to access the int 
value. Since C lacks real pass by reference (var c), you have to use the 
pointer work-around (b) technique.

Also, assigning to a inside the function has no visible effect since it 
is a purely local variable; assignment to b also would have no effect, 
since b itself is a local variable, but assignment to what b points to 
(b^) is visible outside the function; and of course assignment to c is 
visible outside the function.

Pascal "var" parameters are sometimes called output parameters, since 
they can be used to pass values back out to the caller.


> Python passes an object -- everything in python is an object.  If the
> object is mutable, and the function mutates it, those results will be
> seen outside the function.  If the object is immutable, and the
> function tries to change its value, a new object is created with the
> new value.  Its name is the name given in the parameter list -- not
> the name that the function was called with.  When the function
> completes, that object is lost since the outer scoped named object
> wasn't changed.

I agree with this paragraph.


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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread Steven D'Aprano
On Thu, Aug 06, 2015 at 11:34:51AM +0300, John Doe wrote:

> Can You, please, elaborate this "..Passing in Python is different than 
> in C or other languages..."

Argument passing in Python is:

- different to Perl, C, Scala, Algol and Pascal;

- the same as Ruby, Lua, Applescript and Javascript;

- the same as Java boxed values (object);

- different to Java unboxed values (machine types).


In C, all values are passed by value. When you pass an argument to a 
function, the C compiler makes a copy of that value and passes the 
value.

In Pascal, values can be passed by value (like C), or by reference. 

The simplest demonstration of pass-by-reference is to write a "swap" 
procedure. In Python terms:


# This does not actually work in Python.
def swap(a, b):
tmp = a
a = b
b = tmp

x = 23
y = 42
swap(x, y)
print x, y  # prints 42 23

z = 19
swap(x, z)
print x, z  # prints 19 42


You *cannot* write a swap procedure like this in Python. The closest you 
can do is write a function that returns the two values, then assign 
them:

def swap(a, b):
return b, a

x, y = swap(x, y)  # this works

but that is not pass by reference.

In Pascal, you can write such a swap procedure.

Scala and Algol use pass by name, and pass by value. This page explains 
pass by name in Scala, and how it differs from pass by value:

http://alvinalexander.com/source-code/scala/simple-scala-call-name-example

In Java, unboxed values (not objects, low-level machine ints and floats) 
are passed by value, like C.

Python, Ruby, Javascript, Lua, Java boxed values (objects), and many 
other languages, all use the same passing style. This has a number of 
names: 

- pass by object;
- pass by sharing;
- pass by object sharing;

Some people (especially Ruby programmers) call it "pass by reference" 
but that is wrong. Others (especially Java programmers) call it "call by 
value, where the value is a reference" which is technically correct but 
too long. Another name is "call by value/pass by reference", which is 
just confusing.

See also:

https://en.wikipedia.org/wiki/Evaluation_strategy

In pass by object sharing, the argument is evaluated but *not* copied. 
Since the argument is not copied, it is not pass-by-value. Inside the 
function, you can modify the object, and since it is not a copy, the 
original sees the changes. But *assignment* to the local variable inside 
the function does not affect the caller's variable, so it is not 
pass-by-reference.

To summarise:

Pass by value:
- Argument is copied? YES
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? NO

Pass by reference:
- Argument is copied? NO
- Assignment inside function affects original? YES
- Mutation of argument inside function affects original? YES

Pass by object sharing:
- Argument is copied? NO
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? YES



> 'Cause as far as I know - default major Python's implementation CPython 
> is written in C.

That is irrelevent. The argument passing strategy of a language is part 
of the language itself, not the implementation language.

C does not allow variables to change type. But Python does. You cannot 
do this in C:

x = 23  # x is an integer
x = "foo"  # and now it is a string

so clearly the behaviour of a programming language is not always the 
same as that of the implementation language.



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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread Joel Goldstick
On Thu, Aug 6, 2015 at 4:34 AM, John Doe  wrote:
> Can You, please, elaborate this "..Passing in Python is different than in C
> or other languages..."
>
I hesitate, because this question is usually the fuel of flaming wars.
So in short:

C can pass a value or a reference to a value (the address of the place
in memory where the value is stored)
Python passes an object -- everything in python is an object.  If the
object is mutable, and the function mutates it, those results will be
seen outside the function.  If the object is immutable, and the
function tries to change its value, a new object is created with the
new value.  Its name is the name given in the parameter list -- not
the name that the function was called with.  When the function
completes, that object is lost since the outer scoped named object
wasn't changed.

> 'Cause as far as I know - default major Python's implementation CPython is
> written in C.

What language is used for its implementation has nothing to do with
its own specification.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can this code be made even better ?

2015-08-06 Thread Laura Creighton
In a message of Thu, 06 Aug 2015 11:24:21 +0545, Aadesh Shrestha writes:
>import re
>
>text = input('Enter your text with phone number using xx-xxx format \n')
>contact = re.compile(r'\d\d-\d\d\d\d\d\d\d')
>
>for i in range(len(text)):
>chunk = text[i:i+10]
>mo = contact.search(chunk)
>if mo:
>print('Phone Number Found:'+mo.group())
>
>
>Thanks
>
>
>Aadesh Shrestha

One of the things we know about human beings is that most people can
handle information in chunks of 7 plus or minus 2.  This means that 5
is the max for a lot of people.

see: https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two

This means that when you ask human beings to type in a 7 digit phone number
is xxx you have already exceeded the cognitive capacity of many of them.
They will have a hard time producing 7 digits in a row without error.
If they are typing in their own phone numbers, they are more likely to
get it correct than if they are typing in somebody else's number, unless
it is a number they call frequently -- and this is changing.  Cell phones
have meant that we don't give out our numbers to our friends as often
as we used to -- we just send them an sms and the number miraculously
arrives as the destination.  And we phone our friends by tapping on their
names, and maybe a picture of them as well, and so do not get to know our
friends phone numbers.

Verifying a number is harder than producing it in the first place.  Looking
at a string of digits and checking that the digits there are the ones you
meant to type in the first place is fairly hard for most people in the
case of 7 digits.

Thus most people will be much happier if you let them type in phone numbers
as xx-xxx  -- and since they will make fewer errors, it has that to
recommend it as well.  And some people will have their own way of remembering
numbers:

21-55 66 314

may be the way that somebody who has such a number remembers it, because
55 66  (something) is easier to remember than 556 6(something)

This is important for telephone numbers, but even more important if you
ever have to take credit card numbers in your application.  There is a
reason that credit card companies print their card numbers in groups of 4.

Which means, to improve your app, suggest to you users that they type
things in as xx-xxx  but be very lenient and let them type in as
many spaces as they like.  Read the string in, strip out the spaces
and then feed it to your regexp to see that it is well formatted.

If you need to present the user with what they typed -- say they typed
xx-  (that was 8 x's after the dash, and see how that was harder
to read than xx- ) stick spaces in before you resent it to them,
with whatever error message you want to give them.

Note:

x x x x x x x x

doesn't work either.  Adding more spaces does not make it better.  Indeed
most people try to read x x x x x x x x exactly as xxx -- one chunk.

Also, are you certain that all phone numbers will be in the form xx-xxx  ?
In Sweden phone numbers are variable length, but I am told we are unusual
in that respect.

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


Re: [Tutor] output formatting question

2015-08-06 Thread Alan Gauld

On 06/08/15 05:08, tom arnall wrote:

i have read --  with what i think is a reasonable amount of attention
-- all of the doc' i can find about string formatting in python. for
the life of me, i cannot see how any of the other methods do more than
you can do with,

... percent style formatting...

Mostly you are correct, there is not a huge difference in their 
capability and there is little to encourage you to adopt the new style 
other than the fact that it is "preferred" for new code.


However, there are a few things it can do that percent formatting
can't (or at least only with some difficulty). But I'm not the best 
person to list those since I still tend to use % if I'm honest - just 
because its shorter and I'm a C kind of guy so it looks clearer

to me!

You can do some clever stuff with items in a collection.
The docs give this example:

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

Now for a simple two element example you could do

'X: %d; Y: %d' %(coord[0],coord[1])

But I can see that there might be dynamic cases with
more elements where the new style might be easier

I'm sure there are other similar cases, and others
will supply examples.


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


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


Re: [Tutor] How can this code be made even better ?

2015-08-06 Thread Alan Gauld

On 06/08/15 06:39, Aadesh Shrestha wrote:

import re

text = input('Enter your text with phone number using xx-xxx format \n')
contact = re.compile(r'\d\d-\d\d\d\d\d\d\d')

for i in range(len(text)):
 chunk = text[i:i+10]
 mo = contact.search(chunk)
 if mo:
 print('Phone Number Found:'+mo.group())


Remove the loop?
re.search can find the pattern in the whole of text
without a loop. That's basically the point of it.

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


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


Re: [Tutor] Pep 8, about indentation

2015-08-06 Thread Alan Gauld

On 06/08/15 04:40, Steven D'Aprano wrote:


Um, the oldest standard for TABs is *eight* spaces, not 3 or 4,


Yes, but that comes from the days of mechanical typewriters not any 
study of code comprehension. I was referring to the recommended spacing 
for comprehending code. There were a lot of studies done on this back in 
the 70's and 80's. The only one I can find a reference to right now is 
an Article from 1983, "Program Indentation and Comprehensibility" by 
Miaria et al. It showed a 20-30% improved comprehension based
on 2-4 tabs.  0-1 space tabs and larger tabs decreased the 
comprehensibility of the code.



For interest, here's a survey done by Perl programmers in 2002:

http://www.perlmonks.org/?node_id=158886


Yes, but that's a survey of what developers prefer to use. It's not a 
study of whose code is most reliably read and understood!

(Which in the case of Perl might not be very high for any style!!)
Developers are notoriously bad at choosing the most readable
standard, they tend to go by what they think looks pretty.

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


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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Alan Gauld

On 06/08/15 03:27, Ltc Hotspot wrote:
The output as reported by the latest code revision: c...@iupui.edu 
 1← Mismatch


Looks like python continues to print the wrong data set:


Python will print what you ask it to. Don't blame the tool!  :-)

> for line in handle:
>  if line.startswith("From: "):
>  address = line.split()[1]
>  count[address]= count.get(address,0) +1
>
> maxval = None
> maxkee = None
> for kee, val in count.items():
>
> maxval = val
> maxkee = kee
>
> print address, val

Look at the loops.

In the second loop you are no longer setting the values to
those of the max item but are setting them every time.
So at the end of the loop val holds the val of
the last item (and so does maxval so even if you used
that it would be the same result).

Similarly with the code for address. You are setting that
for each 'From ' line in your file so at the end of the loop
address is the last address in the file.

Now, dictionaries do not store data in the order that you
insert it, so there is no guarantee that the last item in
the dictionary loop is the same as the last address
you read.

You need to reinstate the test for max val in the second
loop and then print the kee that corresponds with that
(maxkee) as the address. ie. print maxkee and maxval.

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

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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe
Can You, please, elaborate this "..Passing in Python is different than 
in C or other languages..."


'Cause as far as I know - default major Python's implementation CPython 
is written in C.





Joel Goldstick 於 08/05/2015 03:44 PM 寫道:

On Wed, Aug 5, 2015 at 3:53 AM, John Doe  wrote:

To pass by reference or by copy of - that is the question from hamlet.
("hamlet" - a community of people smaller than a village
python3.4-linux64)

xlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 0
for x in xlist:
 print(xlist)
 print("\txlist[%d] = %d" % (i, x))
 if x%2 == 0 :
 xlist.remove(x)
 print(xlist, "\n\n")
 i = i + 1

So, catch the output and help, PLEASE, me improve the answer:
Does it appropriate ALWAYS reevaluate the terms of the list on each
iteration?
But if I want to pass a copy to FOR instead of a reference (as seen
from an
output) and reduce unreasonable reevaluation, what I must to do for
that?


You aren't passing anything.  the for statement is in the same
namespace as the rest of the code.  Passing in python is different
than in C or other languages.

A couple of comments:

setting i = 0, then incrementing at the end of the loop would more
pythonically be done with the enumerate function.
Its generally a bad idea to remove items from and iterable while
interating over it.  I'm guessing that this is what is confusing you.
One way to remove items from a list is to create a new list, and
append items you want to it, skipping the ones you don't.  You don't
really need the index at all since python interation protocol will
walk through the list for you without worrying about index values


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


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Mark,

Replace  count[address]= count.get(address,0) +1 with  c =
Counter(['address'])?

Regards,
Hal

On Wed, Aug 5, 2015 at 9:03 PM, Mark Lawrence 
wrote:

> On 05/08/2015 23:58, Ltc Hotspot wrote:
>
>> Hi Mark,
>>
>> Address identifies the email address with the maximum  number of sends:
>> c...@iupui.edu.
>>
>> Secondly, we are missing a count on the number of messages sent by
>> c...@iupui.edu, i.e., 5.
>>
>> Thirdly, maxval 'none' is not defined on line # 24
>>
>> Questions: How do we define the value of none for the key maxval and
>> retrieve a number count on the number of messages sent by c...@iupui.edu.
>>
>>
>> NameError:
>>
>> Traceback (most recent call last)
>> C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in ()
>>   22 ## find the greatest number of mail messages.
>>   23
>> ---> 24 maxval = none
>>   25 maxkee = none
>>   26 for kee, val in count.items():
>>
>> NameError: name 'none' is not defined
>>
>> In [52]: print address
>> c...@iupui.edu
>>
>> Revised data:
>>
>>
>> ## The program looks for 'From ' lines and takes the second
>> ## word of those lines as the person who sent the mail.
>>
>> fname = raw_input("Enter file name: ")
>> handle = open (fname, 'r')
>> for line in handle:
>>  if line.startswith("From: "):
>>  address = line.split()[1]
>>
>>
>> ## The program creates a Python dictionary that maps
>> ## the sender's mail address to a count of the number
>> ## of times they appear in the file.
>>
>>  count = dict()
>>  for wrd in address:
>>  count[wrd]= count.get(wrd,0) +1
>>
>> ## After the dictionary is produced, the program reads
>> ## through the dictionary using a maximum loop to
>> ## find the greatest number of mail messages.
>>
>> maxval = none
>> maxkee = none
>> for kee, val in count.items():
>>  if maxval == none or maxval >  maxval = val
>>  maxkee = kee
>>
>>
> You can greatly simplify all of the above code if you use a Counter from
> the collections module
> https://docs.python.org/3/library/collections.html#collections.Counter
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
Hi Alan


The output as reported by the latest code revision: c...@iupui.edu 1 ←
Mismatch

Looks like python continues to print the wrong data set:

In [11]: print val
1 In [12]: print kee r...@media.berkeley.edu In [13]: print address
c...@iupui.edu
In order to complete the assignment, using data from the source  file,
 python must print the email address of the maximum sender and the number
of sends, i.e.,  c...@iupui.edu 5

I think the problem is in the placement of the counter?

Question: What is the source of the dictionary keys and values:
maxval = None
maxkee = None

Here is the latest revised code as follows:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
count = dict ()
for line in handle:
if line.startswith("From: "):
address = line.split()[1]
count[address]= count.get(address,0) +1

maxval = None
maxkee = None
for kee, val in count.items():

maxval = val
maxkee = kee

print address, val





Hal




On Wed, Aug 5, 2015 at 6:21 PM, Alan Gauld 
wrote:

> On 05/08/15 23:58, Ltc Hotspot wrote:
>
> fname = raw_input("Enter file name: ")
>> handle = open (fname, 'r')
>> for line in handle:
>>  if line.startswith("From: "):
>>  address = line.split()[1]
>>
>>
> So far so good.
>
>
>> ## The program creates a Python dictionary that maps
>> ## the sender's mail address to a count of the number
>> ## of times they appear in the file.
>>
>>  count = dict()
>>
>
> But here you create a brand new dictionary.
> Every time you go round the loop.
> And it wipes out the old one.
> You need to move that out of the loop.
>
>  for wrd in address:
>>
>
> address is a string. So wrd will be set to every
> character in the string. I don;t think that's what
> you want?
>
>  count[wrd]= count.get(wrd,0) +1
>>
>> ## After the dictionary is produced, the program reads
>> ## through the dictionary using a maximum loop to
>> ## find the greatest number of mail messages.
>>
>> maxval = none
>> maxkee = none
>>
>
> See my previous email. none should be None.
> Case matters in Python.
>
> for kee, val in count.items():
>>  if maxval == none or maxval >  maxval = val
>>  maxkee = kee
>>
>>
>> #items are printed
>>
>> print address
>>
>
> Notice that address gets reset every time the loop reads
> a new line so this will only print the last address.
> But maybe that's what you wanted?
>
> --> Did I resolve the reset  in the revised code?

>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] output formatting question

2015-08-06 Thread tom arnall
i have read --  with what i think is a reasonable amount of attention
-- all of the doc' i can find about string formatting in python. for
the life of me, i cannot see how any of the other methods do more than
you can do with, to use a concrete example:

print "Here %s a number: %3d" % ("is",  1)

#OR:

s =   "Here %s a number: %3d" % ("is", 1)
print s

what am i not getting?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Issue

2015-08-06 Thread Ltc Hotspot
The revised output reads:

In [3]: %run assignment_9_4_9.py
Enter file name: mbox-short.txt
c...@iupui.edu 14

The desired output: c...@iupui.edu 5


Question: How do I trace the source of the count?

Revised data code reads:

fname = raw_input("Enter file name: ")
handle = open (fname, 'r')
count = dict ()
for line in handle:
if line.startswith("From: "):
address = line.split()[1]

for wrd in address:
count[wrd]= count.get(wrd,0) +1

maxval = None
maxkee = None
for kee, val in count.items():

maxval = val
maxkee = kee

print address, val





On Wed, Aug 5, 2015 at 4:11 PM, Alan Gauld 
wrote:

> On 05/08/15 15:15, Ltc Hotspot wrote:
>
> Raw data code reads:
>>
>
> Being picky here but data and code are very different
> things (in most languages at least) and what you have
> below is definitely code not data.
>
> Meanwhile there are lots of issues in this code...
>
> fname = raw_input("Enter file name: ")
>> handle = open (fname, 'r')
>> text = handle.read()
>>
>> ## The program looks for 'From ' lines and takes the second
>> ## word of those lines as the person who sent the mail.
>>
>> addresses = set()
>> for addr in [ text.split()[2]('From  ')
>>  if fromline
>>
>
> The above looks like its supposed to be a list
> comprehension embedded in a for loop. Putting too much
> code in one line is usually a bad idea especially before
> you have it working.
>
> Try separating out the formation of your list from the
> for loop. Once you get the comprehension working correctly
> then you can consider embedding it.
>
> As for the expression
>
> text.split()[2]('From  ')
>
> Can you explain how you think that works?
> Try it at the >>> prompt with text set to
> a sample line of data.
>
>
--> What command did you type to get the triple chevrons ?

--> My python interpreter:  iPython (py.2.7)


> Try
>
> >>> text = .. # whatever your data looks like
> >>> text.split()
>
> >>> text.split[2]
>
> >>> text.split()[2]('From  ')
>

-->  address data, review the latest revised code?


>
> The >>> prompt is one of your most powerful tools while
> writing code, you should always have one ready to try
> stuff out. You can answer a lot of questions that way.
>
> ## The program creates a Python dictionary that maps
>> ## the sender's mail address to a count of the number
>> ## of times they appear in the file.
>>
>>  count = dict()
>>  for wrd in word:
>>
>
> What is word? You don't define it anywhere?
>
>  count[wrd]= count.get(wrd,0) +1
>>
>> ## After the dictionary is produced, the program reads
>> ## through the dictionary using a maximum loop to
>>
>
>> --> imported address data, review revised code?


>
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How can this code be made even better ?

2015-08-06 Thread Aadesh Shrestha
import re

text = input('Enter your text with phone number using xx-xxx format \n')
contact = re.compile(r'\d\d-\d\d\d\d\d\d\d')

for i in range(len(text)):
chunk = text[i:i+10]
mo = contact.search(chunk)
if mo:
print('Phone Number Found:'+mo.group())


Thanks


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