Re: [Tutor] using a for loop in another method

2016-04-22 Thread Michael Selik
On Fri, Apr 22, 2016 at 1:57 PM Rene.Castillo  wrote:

> expected output-
> reverse_words("This is an example!") # returns  "sihT si na !elpmaxe"
>
> def reverse_words(strng):
>   strng = strng[::-1].split(' ')
>   strng.reverse()
>   return ' '.join(strng)
>

Let's walk through each step that you wrote. First, I'd rather use the
variable name ``s`` than ``strng``. It's just as readable in small snippets
of code like this.

``s`` gets passed in. We'll go ahead and assume it's a str, or something
str-like. There's no need to check the type. That's for more paranoid
languages.

s = s[::-1].split()

This reverses the string via slicing, then splits on whitespace, assigning
the resulting list back over the variable ``s``. If ``s`` (or previously,
``strng``) suggests that the variable refers to a str, we now have some
confusion as it's referring to a list, not a str.

s.reverse()

In-place reversal of a list. When I see this line without paying attention,
I think it's a bug. The str type does not have a reverse method! But of
course, I was misled by the variable name and the code indeed works.

' '.join(s)

Again, this looks like a bug, but since ``s`` is a list, it works just fine.


Now let's look at your friend's code, which actually has a little bug in it.

' '.join( ... )
We already know what that does, joins a list of strings on a ' ' separator.

s[::-1] for s in str.split(' ')
Looking at the first bit, there's a ``s[::-1]`` so that must reverse a
string. Then there's ``for s in ...`` and that looks like a regular
for-loop, assigning to a variable ``s`` for each iteration. And finally,
``str.split(' ')`` is where we find the bug. They probably meant
``strng.split()`` and intended to keep the parameter named ``strng``.
There's no need to pass any input to the split method, as it splits on
whitespace by default.

Tim Golden already mentioned that this technique is a comprehension. It is
equivalent to writing like this:

def reverse_words(sentence):
reversals = []
for word in sentence.split():
reversals.append(word[::-1])
return ' '.join(reversals)

Note how using more meaningful variable names avoids confusion. Instead of
using names like "intgr" or "strng" you should probably name things after
their meanings instead of their data types.



> def reverse_words(s)
> return ' '.join(s[::-1] for s in str.split(' '))
>
>
>
> how can a for loop be called within another method like that- and possibly
> what situations does this benefit
> i don't even know how to google this sort of thing
> any words are appreciated-
>
>
>
> R
> ___
> 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] The game of nim in python

2016-04-22 Thread Michael Selik
What's the problem you're trying to solve? Did you get an error?

Here's a quick revision. There's probably a more elegant way, but this
seems to work.

#/usr/bin/env python

from __future__ import print_function
import random

try:
input = raw_input
except NameError:
pass # already using Python 3


player = input('Enter your name: ')

straws = random.randint(10, 20)
if straws % 4 == 1:
straws += 1

while straws:
print("It's the Computer's turn. {} straws left.".format(straws))
n = random.randint(1, min(3, straws))
straws -= n
print("The Computer removes {} straws.".format(n))

if not straws:
print("The Computer won!")
break

print("It's your turn, {}. There are {} straws
left.".format(player, straws))
n = None
while not n:
print("You can remove between 1 and {} straws.".format(min(3,
straws)))
try:
n = int(input('How many straws do you want to remove? '))
if n < 1 or n > min(3, straws):
n = None
except ValueError:
pass
straws -= n
print("You removed {} straws.".format(n))

if not straws:
print("You won!")
break


On Fri, Apr 22, 2016 at 1:58 PM Henderson, Kevin (GE Aviation, US) <
kevinm.hender...@ge.com> wrote:

> Python to Jython.
>
> Can you help me with a Jython code for the Nim game?
>
> Removing 1-4 sticks out of 13, last player who picks up the last stick wins
>
> Player 1 vs player2(Computer)
>
> player1=str(input("Enter your name. "))
> player2="Computer"
> howMany=0
> gameover=False
> strawsNumber=random.randint(10,20)
>
> if (strawsNumber%4)==1:
> strawsNumber+=1
>
> def removingStrawsComputer():
> removedNumber=random.randint(1,3)
> global strawsNumber
> while removedNumber>strawsNumber:
> removedNumber=random.randint(1,3)
> strawsNumber-=removedNumber
> return strawsNumber
>
> def removingStrawsHuman():
> global strawsNumber
> strawsNumber-=howMany
> return strawsNumber
>
> def humanLegalMove():
> global howMany
> legalMove=False
> while not legalMove:
> print("It's your turn, ",player1)
> howMany=int(input("How many straws do you want to remove?(from 1
> to 3) "))
> if  howMany>3 or howMany<1:
> print("Enter a number between 1 and 3.")
> else:
> legalMove=True
> while howMany>strawsNumber:
> print("The entered number is greater than a number of straws
> remained.")
> howMany=int(input("How many straws do you want to remove?"))
> return howMany
>
> def checkWinner(player):
> if strawsNumber==0:
> print(player," wins.")
> global gameover
>gameover=True
> return gameover
>
> def resetGameover():
> global gameover
> gameover=False
> return gameover
>
> def game():
> while gameover==False:
> print("It's ",player2,"turn. The number of straws left:
> ",removingStrawsComputer())
> checkWinner(player1)
> if gameover==True:
> break
> humanLegalMove()
> print("The number of straws left: ",removingStrawsHuman())
> checkWinner(player2)
> game()
>
>
>
>
> ___
> 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] Extracting bits from an array

2016-04-29 Thread Michael Selik


> On Apr 29, 2016, at 1:15 PM, Colin Ross  wrote:
> 
> Hello,
> 
> I have an array that takes on the following form:
> 
> x = [1000,1001,1011,]
> 
> The array elements are meant to be binary representation of integers.
> 
> Goal: Access array elements and extract the first two bits.
> 
> e.g. Final result would look something like this:
> 
> x_new = [10,10,10,11]
> 
> What I have tried:
> 
> data_indices = range(4)  #  Set up array of values to loop over
> 
> for idx in data_indices:
> f = x[idx]  # Index into array of x values

Instead of looping over a range of indices, you should loop over the data 
itself.

for number in x:
s = bin(number)
print s

> f_idx = f[:2]  # Extract first two elements

You couldn't slice an integer. First convert to the binary representation in 
string form. You can strip off the prefix if you just want the digits.

s = bin(number).lstrip('0b')

Then you can slice off the first two digits if you want. Remember, it's a str 
of digits, not a number.

> print f_idx
> 
> I then receive the following error:
> 
> IndexError: invalid index to scalar variable.
> 
> Any help with accomplishing my outline dgoal would be greatly appreciated.
> 
> Thank you.
> 
> Colin
> ___
> 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 Question

2016-05-03 Thread Michael Selik
On Mon, May 2, 2016 at 8:58 PM Jason N. via Tutor  wrote:

> What is the best way to make dictionary requests case in-sensitive? For
> example, "Apple and "apple" should bring back the same dictionary
> response. Thank you.
>

Take a look at how the requests library solves the problem with a
"CaseInsensitiveDict" (
https://github.com/kennethreitz/requests/blob/master/requests/structures.py)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionary Question

2016-05-03 Thread Michael Selik
On Mon, May 2, 2016 at 5:28 PM Jason N. via Tutor  wrote:

> Hello,
> Wanted to ask if its possible to have a dictionary that can be looked up
> by either values?
> For example,
> mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to
> come. But if the user enter "Apple" I want "A" to respond.
> Please let me know the best way to handle this type cause instead of just
> created duplicate entries to cover all possibilities. Thank you.
>

A dictionary enforces that the keys are unique, but many keys may have the
same value. Do you want to enforce that values are unique? If not, does it
matter which key is returned if many keys have the same value?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best Practices with JSON Data

2016-05-08 Thread Michael Selik
On Sun, May 8, 2016, 12:34 PM Hunter Jozwiak  wrote:

> Hello,
>
>
>
> I am intending to start work on a Python program that will allow me to
> better manage my Digital Ocean droplets, due to the fact that the website
> can be at times a bit overkill for some of the basic tasks I want to do. I
> have a question in regards to the best practice of manipulating JSON data.
> Would it be better to just parse the data that Digital Ocean returns as a
> result of doing such things as a Get command, or would it be better to
> create a Droplet class with functionality specific to Droplets? The reason
> I
> am asking is due to the fact that I haven't found any good information on
> the topic, so am not sure of the Pythonic or standard way to do this.
>

Go the route of least complexity until you need to refactor. Start with
basic collections. Define a class later, if ever.

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


Re: [Tutor] Create a pivot table

2016-05-20 Thread Michael Selik
On Fri, May 20, 2016 at 8:42 AM Peter Otten <__pete...@web.de> wrote:

> jarod_v6--- via Tutor wrote:
> > I have tried the pandas way but unfortunately there is many duplicates .
>
> Please show your code in a small self-contained example,
> the output it produces, and what exact output you want instead.
> Then one of us (not necessarily me) might be able to help you fix it.
>

I haven't seen an Pandas code, yet. What's the error message and traceback?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] R: Re: Create a pivot table (Peter Otten)

2016-05-20 Thread Michael Selik
On Fri, May 20, 2016 at 7:16 AM jarod_v6--- via Tutor 
wrote:

> Thanks s much for  the help. I want to obtain table like this:
>
>
> >csv.writer(sys.stdout, delimiter="\t").writerows(table)
> >A100D33 D34 D35 D36 D37 D38 D39
> >A   5 0 ...
> >B   2 2  ...
> >C  0  ..
> >
> I have tried the pandas way but unfortunately there is many duplicates.
>

If pandas is raising an error, it's possible a "pivot" is not what you
want. What's the code you tried? What's the error message?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python OLS help

2016-06-01 Thread Michael Selik
On Tue, May 31, 2016 at 5:45 PM Vadim Katsemba  wrote:

> I typed in lm = smf.ols(formula='LATITUDE~DIAMETER',data=dataf).fit(), and
> I ended up getting this error: ValueError: For numerical factors,
> num_columns must be an int.
>

You may be using an old version of Patsy, the module that allows you to
specify your OLS formula like R-lang does. What version of patsy are you
using? This seems to have been a problem with Patsy v0.4.0 and was fixed in
v0.4.1 (as per an email thread I read [0])

[0] https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python OLS help

2016-06-01 Thread Michael Selik
You're welcome. A tip for the next bug: Google is pretty good at finding a
discussion of the error if you paste the whole phrase as your search terms.
In this case, I searched for "ValueError for numerical factors num_columns
must be an int" and found the relevant Google Group thread.

PS. I replied to the mailing list in case someone else has the same issue.
These emails are archived and searchable.


On Tue, May 31, 2016 at 10:07 PM Vadim Katsemba  wrote:

> I upgraded to patsy 0.4.1 and got the regression to run. Thank you very
> much for your help!
>
> On Tue, May 31, 2016 at 8:03 PM, Michael Selik 
> wrote:
>
>> On Tue, May 31, 2016 at 5:45 PM Vadim Katsemba 
>> wrote:
>>
>>> I typed in lm = smf.ols(formula='LATITUDE~DIAMETER',data=dataf).fit(),
>>> and I ended up getting this error: ValueError: For numerical factors,
>>> num_columns must be an int.
>>>
>>
>> You may be using an old version of Patsy, the module that allows you to
>> specify your OLS formula like R-lang does. What version of patsy are you
>> using? This seems to have been a problem with Patsy v0.4.0 and was fixed in
>> v0.4.1 (as per an email thread I read [0])
>>
>> [0] https://groups.google.com/forum/#!topic/pystatsmodels/KcSzNqDxv-Q
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Urgent: unicode problems writing CSV file

2016-06-08 Thread Michael Selik
On Wed, Jun 8, 2016 at 12:53 PM Alex Hall  wrote:

> All,
> I'm working on a project that writes CSV files, and I have to get it done
> very soon. I've done this before, but I'm suddenly hitting a problem with
> unicode conversions. I'm trying to write data, but getting the standard
> cannot encode character: ordinal not in range(128)
>

Have you tried ignoring invalid characters?

>>> data = b'\x30\x40\xff\x50'
>>> text = data.decode('utf-8')
Traceback ... UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff
>>> text = data.decode('utf-8', 'ignore')
>>> print(text)
0@P

BTW, most programming volunteers don't like responding to things marked
"Urgent". It's probably not really urgent unless someone's life is in
danger.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loop in pre-defined blocks

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 1:33 PM Ek Esawi  wrote:

> Here is a beginner code that might work for you. Best of luck.   EK
>
> b=[12, 20, 35]
>
> for i in range(len(b)):
>  if i==0:
>   c=0
>  else:
>   c=b[i-1]
>  for j in range(c, b[i]):
>   print(i+1,j+1)
>


If you want to go a little further, you can use zip and enumerate.

py> stops = [3, 5, 9]
py> starts = [0] + stops[:-1]
py> for i, (start, stop) in enumerate(zip(starts, stops)):
... for j in range(start, stop):
... print(i, j)
...
0 0
0 1
0 2
1 3
1 4
2 5
2 6
2 7
2 8
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loop in pre-defined blocks

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 6:28 PM Alan Gauld via Tutor 
wrote:

> On 13/06/16 08:46, Ek Esawi wrote:
> > Here is a beginner code that might work for you. Best of luck.   EK
> >
> > b=[12, 20, 35]
> >
> > for i in range(len(b)):
> >  if i==0:
> >   c=0
> >  else:
> >   c=b[i-1]
> >  for j in range(c, b[i]):
> >   print(i+1,j+1)
>
> The problem here is that it doesn't give the gaps in the output
> data that the OP requested. That's why we said they need the start
> and stop values in the ranges.
>

My apologies. The good news is that makes the solution even easier.

py> blocks=[(2,4), (10,13), (20,22)]
py> for i, (start, stop) in enumerate(blocks):
... for j in range(start, stop):
... print(i, j)
...
0 2
0 3
1 10
1 11
1 12
2 20
2 21
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Py 2.4.4: Inheriting from ftplib.FTP()

2016-06-17 Thread Michael Selik
On Fri, Jun 17, 2016 at 11:42 AM boB Stepp  wrote:

> On Thu, Jun 16, 2016 at 11:40 AM, Alan Gauld via Tutor 
> wrote:
> > On 16/06/16 16:38, boB Stepp wrote:
> >
> >> class FTPFiles(FTP, object):
> >> """FTP files to Windows server location(s)."""
>
> I was struggling to come up with a good name here that would not cause
> me any name collision issues with the contents of ftplib.FTP().


That's why we have namespaces. Your ``FTP`` would not collide with
``ftplib.FTP``, because they are in separate modules.

I looked up LSP last night.  I can see how I can easily get burned
>
even on something seemingly simple.  One example, which I imagine is
> often used, is of a square class inheriting from a rectangle class.
> Squares have same sized sides; rectangles not necessarily so.  So any
> size changing methods from the rectangle class inherited by the square
> class can potentially wreak havoc on squares.  Am I getting the
> essence of the potential issues I might encounter?
>

Yes, that's the gist of it. It's very hard to anticipate what features your
base class may need in the future, months or years down the road. Many of
them may be inappropriate for one or more child classes.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best way to do FTP login?

2016-06-17 Thread Michael Selik
On Fri, Jun 17, 2016 at 12:46 PM boB Stepp  wrote:

> ftp = FTP('ip_address', 'username', 'password')
>
> Or
>
> ftp = FTP('ip_address')
> ftp.login('username', 'password')
>
> Most of the examples I am seeing online use the second approach.  Is
> there some reason why this is to be preferred?


Not that I can see. Perhaps only to show that the login method exists.
I suggest using it in a context manager.

py> with FTP('ftp.example.com', 'username', 'password') as ftp:
... ftp.dir()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with comparing list of tuples in python 2

2016-06-18 Thread Michael Selik
On Fri, Jun 17, 2016, 6:12 PM Lulu J  wrote:

> Hi there,
>
> My apologies if this is a trivial question but I am sort of new to python.
> Here is my problem:
> I have a list of dictionaries. Each dictionary has a word and its position
> in the text  the positions are in the form of a tuple.
> Here is an example:
> [
> {'position': (5, 4), 'term': u'happy',},
>  {'position': (5, 5), 'term': u'something'}
> ]
>
> for the potions, the first element is the paragraph number and the second
> is the word number in that paragraph(sequence from 1...n)
>
> What I would like to is find which words are next to each other. Meaning,
> they will be in the same paragraph and the difference of their word numbers
> is 1.
>

Put the words in a dictionary, key is the location, value is the word.

Sort the location-word pairs by location. Loop over the result pairwise.

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


Re: [Tutor] For-else... Any other handy constructs hiding in Python?

2016-06-25 Thread Michael Selik
On Fri, Jun 24, 2016 at 11:58 AM Alex Hall  wrote:

> I know loops, comprehensions, ifs, and the like,
> but I never knew for-else was available. Are there other constructs that I
> may have missed?
>

Are you familiar with context managers?
https://www.python.org/dev/peps/pep-0343/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dont understand part of a code

2016-07-05 Thread Michael Selik
On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor 
wrote:

> There are arguably easier ways of doing this
>

I think you'll find that for-loops are preferable to while-loops. Here's an
alternative implementation.

https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca

import random
import string

drawings = (
r"""
--|
|
|
|
|
--
""",
r"""
--|
| 0
|
|
|
--
""",
r"""
--|
| 0
|-+-
|
|
--
""",
r"""
--|
| 0
|   /-+-
|
|
--
""",
r"""
--|
| 0
|   /-+-\
|
|
--
""",
r"""
--|
| 0
|   /-+-\
| |
|
--
""",
r"""
--|
| 0
|   /-+-\
| |
||
--
""",
r"""
--|
| 0
|   /-+-\
| |
|| |
--
"""
)

print('Welcome to Hangman.')
print('Good luck!')

words = 'python ruby php java unix linux perl'.split()
target = list(random.choice(words))
known = ['_'] * len(target)
used = []

for drawing in drawings:
print('-'.join(c if c not in used else ' ' for c in
string.ascii_lowercase))
print(drawing, '\n\t', ' '.join(known))
guess = input('\nEnter your guess: ').lower()

while guess in used:
print("You've already guessed that letter")
guess = input('Please enter a new guess: ').lower()

used.append(guess)
if guess in target:
print('Yes, {!r} is in the word!'.format(guess))
for i, letter in enumerate(target):
if guess == letter:
known[i] = letter
else:
print('Sorry, {!r} is not in the word.'.format(guess))

if known == target:
print('\nYou guessed the word correctly!')
break
else:
print('\nYou have been hanged!')

print('The word was {!r}'.format(''.join(target)))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Michael Selik
On Tue, Jul 5, 2016 at 8:24 PM  wrote:

> I'm having trouble with most of the lines here.
>

It looks like you tried to attach a file. This mailing list does not allow
attachments. Instead, could you paste the code into your email?


> things that I don't understand:
> 1. the need to put script into an estipulation for argv (line 3)
> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they
> are)  (line 7)
>

I'm guessing txt is a file object or a file-like object that supports the
.read method to read the entire contents of the file into a single string
object.


> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dont understand part of a code

2016-07-06 Thread Michael Selik
On Tue, Jul 5, 2016 at 5:36 PM Michael Selik 
wrote:

> On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor 
> wrote:
>
>> There are arguably easier ways of doing this
>>
>
> I think you'll find that for-loops are preferable to while-loops. Here's
> an alternative implementation.
>
> https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca
>

On further reflection, unfortunately a for-loop doesn't seem best for this
particular problem. I updated the gist, linked above. I wish the author had
chosen a better problem to emphasize Pythonic iteration.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Michael Selik
On Wed, Jul 6, 2016 at 10:59 AM  wrote:

> why do I have to create a variable txt_again to assign it to the open
> function and them print the file?
> why is it that I can't only write something like open(file_again).read()?
>

Good insight. In fact you don't need to create the variable. The code ``data
= open('filename').read()`` will open the file named "filename" in the
current working directory, read it, and assign the data to a variable.

However, many programmers use variables not because they must, but because
good variable names can make code easier to read. Also, doing less stuff on
a line of code can make that code easier to read.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Counting and grouping dictionary values in Python 2.7

2016-07-14 Thread Michael Selik
On Fri, Jul 8, 2016 at 10:15 AM Bruce Dykes  wrote:

> I'm compiling application logs from a bunch of servers, reading the log
> entries, parsing each log entry into a dictionary, and compiling all the
> log entries into a single list of dictionaries.
>

Seems reasonable. Perhaps instead of having each log entry as a dictionary,
you might prefer to create a namedtuple.


> Now, what I need to do with this arbitrarily count and total the values in
> the dictionaries, ie the total amount and number of items for transaction
> id 387, or the total number of crackers sold in NJ stores.


Use the Counter class from the collections module. Loop over your records,
write an if-statement to determine which records are interesting, then
increment the count for the appropriate key.

If you're having trouble, share your code and the error message.

Also, is there any particular advantage to pickling the list and having two
> files, one, the pickled file to be read as a data source, and the .csv file
> for portability/readability, as opposed to just a single .csv file that
> gets reparsed by the reporting script?
>

Probably simpler to keep just a CSV.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDLE Subprocess Startup Error

2016-07-30 Thread Michael Selik
On Fri, Jul 29, 2016, 2:11 AM Darah via Tutor  wrote:

> "IDLE's subprocess didn't make connection.  Either IDLE can't start a
> subprocess or personal firewall software is blocking the connection.”
>

In the last few days, have you installed any other software? Perhaps
something has changed your firewall settings.

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


Re: [Tutor] Problem with graphics.py

2016-08-09 Thread Michael Selik
On Tue, Aug 9, 2016 at 12:51 PM Cyrus Parvereshi  wrote:

> Hi! I'm starting out with programming by self-studying python with a
> textbook used at my university. I came to a chapter that introduced object
> oriented programming with graphics tools like GraphWin and Point. However,
> even though I downloaded the author's graphics.py file from his website and
> put it in the same folder as the IDLE interpreter, Python command prompt,
> and every other python program, I still cannot use the module. Every single
> time I attempt to use a command like "import graphics" or "from graphics
> import * " it gives an error that there is no module called 'graphics.py.
>
> I would like to know how to fix this issue so that I can access the
> graphics module.
>

Do you mind running the following commands from the python shell?

py> import os
py> os.getcwd()
'/Users/mike'
py> sorted(os.listdir('.'))
['.Trash', 'Applications', 'Desktop', ...]

This will show us what location your python interpreter has as the "current
working directory" and whether or not the "graphics.py" file is present in
that directory.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help

2016-08-11 Thread Michael Selik
On Thu, Aug 11, 2016 at 1:15 PM Pallab Amway  wrote:

> expected an indented block
>

if-statements must have an indented block of code. For example:
```
if age < 12:
print('You are a child')
```
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor