python programming help

R

rafaellasav

i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age.
please help
 
Y

YBM

Le 08.12.2013 18:59, (e-mail address removed) a écrit :
i have a dictionary with names and ages for each name.
I want to write a function that takes in an age and returns
the names of all the people who are that age.
please help

ageDict = { 'john':42, 'jane':36, 'paul':42 }
peopleWithAge = lambda age: [ name for name in ageDict if
ageDict[name]==age]
 
R

rafaellasav

Le 08.12.2013 18:59, (e-mail address removed) a �crit :
i have a dictionary with names and ages for each name.
I want to write a function that takes in an age and returns
the names of all the people who are that age.
please help



ageDict = { 'john':42, 'jane':36, 'paul':42 }

peopleWithAge = lambda age: [ name for name in ageDict if

ageDict[name]==age]


sorry but i'm new to python ;p
1. it has to be in a form of a function called people and
2. how this code takes in an age and returns the names?
 
Y

YBM

Le 08.12.2013 19:14, (e-mail address removed) a écrit :
Le 08.12.2013 18:59, (e-mail address removed) a �crit :
i have a dictionary with names and ages for each name.
I want to write a function that takes in an age and returns
the names of all the people who are that age.
please help



ageDict = { 'john':42, 'jane':36, 'paul':42 }

peopleWithAge = lambda age: [ name for name in ageDict if

ageDict[name]==age]


sorry but i'm new to python ;p
1. it has to be in a form of a function called people and
2. how this code takes in an age and returns the names?
ageDict = { 'john':42, 'jane':36, 'paul':42 }
people = lambda age: [ name for name in ageDict if ... ageDict[name]==age]
people(42)
['paul', 'john']
 
G

Gary Herron

i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age.
please help

This looks like homework for a beginning programming class. Correct?

We like helping people use Python, and we like helping people learn
Python, but neither of those purposes are served by us *doing* your
homework for you.

Please, you try to solve the problem, and when you get stuck, show us
your code, and ask a specific question.

Hint: You will almost certainly need a loop (through the dictionary
entries), an 'if' conditional to test for the age matching the given
age, and a print,

Gary Herron
 
R

Roy Smith

i have a dictionary with names and ages for each name. I want to write a
function that takes in an age and returns the names of all the people who are
that age.
please help

Homework problem?

In any case, this is a classic example of a real-life problem, and thus
worth exploring. The general case is you have a many-to-one mapping and
you want to find the inverse one-to-many map.

I'm assuming when you say, "a dictionary with names and ages for each
name", you mean the names are the keys and the ages are the values.
That would also imply that the names are unique; that's a poor
assumption for real data sets, but let's assume that's the case here.

So, we're going to take your original dictionary and create a new one
where the keys are the ages, and the values are lists of names. That's
pretty straight forward. Here's the most brute-force way (which is a
good place to start):

d2 = {}
for name, age in d1.items():
if age not in d2:
d2[age] = []
d2[age].append(name)

Work through that code in your head to convince yourself that you
understand what's going on.

This is such a common pattern, Python has a neat tool to make this
easier. It's called a defaultdict. Bascially, this is a dictionary
which has built into it the "if key doesn't exist, initialize something"
logic. It works like this:

from collections import defaultdict

d2 = defaultdict(list)
for name, age in d1.items():
d2[age].append(name)

The "defaultdict(list)" creates one of these and tells it that the
"initialize something" part should be "create an empty list". It's
hugely convenient and used all the time.
 
M

Mark Lawrence

Le 08.12.2013 18:59, (e-mail address removed) a �crit :
i have a dictionary with names and ages for each name.
I want to write a function that takes in an age and returns
the names of all the people who are that age.
please help



ageDict = { 'john':42, 'jane':36, 'paul':42 }

peopleWithAge = lambda age: [ name for name in ageDict if

ageDict[name]==age]


sorry but i'm new to python ;p
1. it has to be in a form of a function called people and
2. how this code takes in an age and returns the names?

I'm awfully sorry but I'm not doing your homework for you :)
 
B

bob gailer

i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the people who are that age.
please help
Welcome to the python list. Thanks for posting a question.

If you were hoping for one of us to write the program for you ... well
that's not what we do on this list.

Please post the code you have so far and tell us exactly where you need
help.

Also tell us what version of Python, what OS, and what you use to write
and run Python programs.
 
R

rafaellasav

Welcome to the python list. Thanks for posting a question.



If you were hoping for one of us to write the program for you ... well

that's not what we do on this list.



Please post the code you have so far and tell us exactly where you need

help.



Also tell us what version of Python, what OS, and what you use to write

and run Python programs.

name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
dic={}
def combine_lists(name,age):
for i in range(len(name)):
dic[name]= age
combine_lists(name,age)
print dic

def people(age):
people=lambda age: [name for name in dic if dic[name]==age]

people(20)




this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result
 
R

rafaellasav

On 12/8/2013 12:59 PM, (e-mail address removed) wrote:



Welcome to the python list. Thanks for posting a question.



If you were hoping for one of us to write the program for you ... well

that's not what we do on this list.



Please post the code you have so far and tell us exactly where you need





Also tell us what version of Python, what OS, and what you use to write

and run Python programs.



name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']

age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]

dic={}

def combine_lists(name,age):

for i in range(len(name)):

dic[name]= age

combine_lists(name,age)

print dic



def people(age):

people=lambda age: [name for name in dic if dic[name]==age]



people(20)









this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result


and I'm sorry but this is the first time i ask for help in a forum and i just didn't know how it works. I'm not looking for someone to do my homework i just need someone to help me with my code :)
 
B

Benjamin Kaplan

Welcome to the python list. Thanks for posting a question.



If you were hoping for one of us to write the program for you ... well

that's not what we do on this list.



Please post the code you have so far and tell us exactly where you need

help.



Also tell us what version of Python, what OS, and what you use to write

and run Python programs.

name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
dic={}
def combine_lists(name,age):
for i in range(len(name)):
dic[name]= age
combine_lists(name,age)
print dic

def people(age):
people=lambda age: [name for name in dic if dic[name]==age]

people(20)




this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part. and this code doesn't give me any result


To return a value from a function, you need to use the "return"
statement with the value you want to pass back out. You're not doing
that here. Also, you're using a lot of shorthand stuff that you should
probably avoid until you're more comfortable with the language

* Lambda is shorthand for a function. foo = lambda bar : bar + 2 is
the same thing as the function
def foo(bar) :
return bar + 2

* a list comprehension is short-hand for a loop. spam = [foo for foo
in bar if baz(foo)] is the same thing as
spam = []
for foo in bar :
if baz(foo) :
spam.append(foo)

You don't need a lambda here- just call the code that you need to call directly.
 
R

rafaellasav

On 12/8/2013 12:59 PM, (e-mail address removed) wrote:

i have a dictionary with names and ages for each name. I want to write a function that takes in an age and returns the names of all the peoplewho are that age.

please help

Welcome to the python list. Thanks for posting a question.



If you were hoping for one of us to write the program for you ... well

that's not what we do on this list.



Please post the code you have so far and tell us exactly where you need

help.



Also tell us what version of Python, what OS, and what you use to write

and run Python programs.
name = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
age = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]

def combine_lists(name,age):
for i in range(len(name)):
dic[name]= age
combine_lists(name,age)

print dic
def people(age):

people=lambda age: [name for name in dic if dic[name]==age]
people(20)

this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find.but i don't get the lambda age part. and this code doesn't give me any result



To return a value from a function, you need to use the "return"

statement with the value you want to pass back out. You're not doing

that here. Also, you're using a lot of shorthand stuff that you should

probably avoid until you're more comfortable with the language



* Lambda is shorthand for a function. foo = lambda bar : bar + 2 is

the same thing as the function

def foo(bar) :

return bar + 2



* a list comprehension is short-hand for a loop. spam = [foo for foo

in bar if baz(foo)] is the same thing as

spam = []

for foo in bar :

if baz(foo) :

spam.append(foo)



You don't need a lambda here- just call the code that you need to call directly.


i get it, thanks a lot i wrote a different one and it works

def people(age):
people=[name for name in dic if dic[name]==age]
print(people)

people(20)

i have one last question

it asks me to test my program function by running these lines:
print ’Dan’ in people(18) and ’Cathy’ in people(18)
print ’Ed’ in people(19) and ’Helen’ in people(19) and\
’Irene’ in people(19) and ’Jack’ in people(19) and ’Larry’in
people(19)
print ’Alice’ in people(20) and ’Frank’ in people(20) and ’Gary’ in
people(20)
print people(21) == [’Bob’]
print people(22) == [’Kelly’]
print people(23) == []

but when i wrote these lines it returns me an error
Traceback (most recent call last):
File "/Users/rafaellasavva/Desktop/people.py", line 19, in <module>
print 'Dan' in people(18) and 'Cathy' in people(18)
TypeError: argument of type 'NoneType' is not utterable

do you know what it might be wrong?
 
C

Chris Angelico

but when i wrote these lines it returns me an error
Traceback (most recent call last):
File "/Users/rafaellasavva/Desktop/people.py", line 19, in <module>
print 'Dan' in people(18) and 'Cathy' in people(18)
TypeError: argument of type 'NoneType' is not utterable

do you know what it might be wrong?

Hehe. The first thing that's wrong is that you're retyping the error
instead of copying and pasting it. The problem is actually that it's
not *iterable* here. And the reason for that is that you're printing
the result instead of returning it, as has been mentioned by a few
people.

Also, your posts are acquiring the slimy stain of Google Groups, which
makes them rather distasteful. All your replies are getting
double-spaced, among other problems. Please consider switching to an
alternative newsgroup reader, or subscribing to the mailing list:

https://mail.python.org/mailman/listinfo/python-list

The content is the same, but it comes by email instead of netnews.

ChrisA
 
M

Mark Lawrence

i get it, thanks a lot i wrote a different one and it works

def people(age):
people=[name for name in dic if dic[name]==age]
print(people)

people(20)

i have one last question

it asks me to test my program function by running these lines:
print ’Dan’ in people(18) and ’Cathy’ in people(18)
print ’Ed’ in people(19) and ’Helen’ in people(19) and\
’Irene’ in people(19) and ’Jack’ in people(19) and ’Larry’in
people(19)
print ’Alice’ in people(20) and ’Frank’ in people(20) and ’Gary’ in
people(20)
print people(21) == [’Bob’]
print people(22) == [’Kelly’]
print people(23) == []

but when i wrote these lines it returns me an error
Traceback (most recent call last):
File "/Users/rafaellasavva/Desktop/people.py", line 19, in <module>
print 'Dan' in people(18) and 'Cathy' in people(18)
TypeError: argument of type 'NoneType' is not utterable

do you know what it might be wrong?

You've typed up the error message instead of using cut and paste, which
is why it says "utterable" instead of "iterable"? :) Seriously, it's
already been pointed out that your people function needs a return
statement. Without it, the default returned is always None.

Would you also please read and action this
https://wiki.python.org/moin/GoogleGroupsPython as it prevents us seeing
huge numbers of unwanted newlines which some find extremely irritating.
 
J

John Ladasky

On Sunday, December 8, 2013 10:32:31 AM UTC-8, (e-mail address removed) wrote:

[snip]
def people(age):
people=lambda age: [name for name in dic if dic[name]==age]

people(20)
[snip]

this is the code i have so far(with the help of the first post ;p). i understand how a function and a dictionary works and what I'm asked to find. but i don't get the lambda age part.

Well then, don't use it! It's clear that you are new, and at least you have posted some code now, so let me try to help.
and this code doesn't give me any result

Right, for TWO reasons.

First problem: if your function does not end with a statement like "return people", the function returns a special Python object called None.

Now, if it were me, I would not "wrap" the calculation of your "people" list inside a "people" function for such a short program. But this is apparently a requirement of your assignment. My guess is, in the future, you willwrite a program that calls the people function multiple times.

The "lambda" word has to do with creating something called an "anonymous one-line function." You don't need that here. It's more advanced Python.

What you want to do is compute and, importantly, return a list calculated from your dictionary. That is accomplished by this expression:

"[name for name in dic if dic[name]==age]"

This is called a "list comprehension." Do you understand what this does? It's fairly advanced. I don't teach list comprehensions to my Python students for the first several lessons.

So, now that you have created the list, let's make sure that Python doesn'tlose it. Let's assign a NAME to it. By the way, it's probably not good form to use the same name for a function and any of its internal variables. Pick a different name for your list: for example, "p". Then, return p from your function to your main program. My suggested rewrite of your function would be:

"""
def people(age):
p = [name for name in dic if dic[name]==age]
return p
"""

The truth is that you can cut this down by even one more line. This function doesn't need to hold on to the result after it is done returning it, butthe computation of the result can be accomplished in one line. Therefore this will also work:

"""
def people(age):
return [name for name in dic if dic[name]==age]
"""

OK, that takes care of Problem 1.

Second problem: you call the "people" function with your statement "people(20)", but you don't do anything with the output. Once you fix the people function by providing a proper return statement, what does the main program do with the output of the function? Right now, it just throws it away.

One solution to the problem is to make sure that the function's output getsa name. Try:

"""
result = people(20)
"""

Now, what do you want to do with result? I will wait to see your answer onthat one before I intervene again.
 
T

Terry Reedy

On 12/8/2013 2:06 PM, (e-mail address removed) wrote:

Even when you do get what lambda means and how use it,
name = lambda args: expression
which is a carryover from other languages, is inferior to
def name(args): return expression
because the function object resulting from lambda does not have a proper
name attribute.
def people(age):
people=[name for name in dic if dic[name]==age]

An alternative is
[name for name, value in dic.itervalues() if value == age]

In Python 3, remove 'iter'. It this is not homework and you are not
otherwise forced to start with Python 3, I (and some others here)
recommend starting with Python 3.
 
G

Gregory Ewing

def people(age):
people=lambda age: [name for name in dic if dic[name]==age]

but i don't get the lambda age part.

Just to explain: YBM has tried to sabotage you by posting a
solution that uses a couple of advanced Python features
(lambda and list comprehensions) that a beginner would be
unlikely to know about. The idea is that if you had simply
handed that code in as-is, your teacher would know that you
had almost certainly not written it yourself.

Anyhow, you seem to be almost there. The only thing now
is that your function needs to *return* the result instead
of printing it out. To illustrate with a different example,
you currently have a function like this:

def add(a, b):
print a + b

This is fine as far as it goes, but the drawback is that
printing out the result is all it will ever do. You're
being asked to write a function like this:

def add(a, b):
return a + b

This is much more useful, because you can do anything you
like with the result, e.g.

print add(2, 3) * add(4, 5)
 
R

rurpy

Also, your posts are acquiring the slimy stain of Google Groups, which
makes them rather distasteful. All your replies are getting
double-spaced, among other problems. Please consider switching to an
alternative newsgroup reader, or subscribing to the mailing list:
https://mail.python.org/mailman/listinfo/python-list

To the OP:

First, my apologies if my reply ends up trashing your
discussion here, but you should know what is behind Mr.
Angelico's response.

For some time now the Google Group Wars are being fought
in this group.

There is a (probably very small) clique of Google haters
who try present themselves as "the community" and who try
to intimidate anyone posting from Google Groups into using
some other means of posting, completely disregarding the
fact that for many new people or occasional posters, Google
Groups is an order of magnitude easier to use. These people
are extremely noisy and obnoxious but *do not* represent
"the community" except in their own minds. I suspect many
of them are motivated by political dislike of Google as
a corporation, or want to stay with the 1990's technology
they invested time in learning and don't want see change.

I and many other people post here from Google Groups and
you should feel free to too if it is more convenient for
you. (Of course you can also use the maillist or usenet
if you find them a good solution for *you* but please don't
feel compelled to by some loud obnoxious bullies.)

As another poster pointed out, if you are able to follow
some of the advice at,

https://wiki.python.org/moin/GoogleGroupsPython

it will help quiet down the anti-Google crowd a little but
even if you don't, those without a Google chip on their shoulder
will simply skip your posts if they find the Google formatting
too annoying. Most of us though will deal with it as adults
and try our best to answer your questions.

I just thought you should have both sides of the story so
to won't take the anti-Google crowd here as gospel.

Addressing you last question, I presume you understood the
other responses about replacing the "print (people)"
statement in your people() function with "return people".

The only additional thing I wanted to add is that,

people=[name for name in dic if dic[name]==age]

is (I would guess) a rather advanced way of doing what
you are doing, given where you seem to be in learning
about python (but maybe not, in which case ignore the
following).

The [....] thing is called as "list comprehension and
in described here
http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

However, it is just a more concise way of writing:

people = []
for n, a in dic.items():
if a == age: people.append (n)
return people

To understand the above (if you don't already) you'll want
to read about the the items() method of dicts:
http://docs.python.org/3/tutorial/datastructures.html#looping-techniques
http://docs.python.org/3/library/stdtypes.html#mapping-types-dict
the append() method of lists,
http://docs.python.org/3/tutorial/controlflow.html#for-statements
http://docs.python.org/3/library/stdtypes.html#mutable-sequence-types
and of course "for" loops;
http://docs.python.org/3/tutorial/controlflow.html#for-statements

Hope this helps.
 
M

Mark Lawrence

To the OP:

First, my apologies if my reply ends up trashing your
discussion here, but you should know what is behind Mr.
Angelico's response.

For some time now the Google Group Wars are being fought
in this group.

There is a (probably very small) clique of Google haters
who try present themselves as "the community" and who try
to intimidate anyone posting from Google Groups into using
some other means of posting, completely disregarding the
fact that for many new people or occasional posters, Google
Groups is an order of magnitude easier to use. These people
are extremely noisy and obnoxious but *do not* represent
"the community" except in their own minds. I suspect many
of them are motivated by political dislike of Google as
a corporation, or want to stay with the 1990's technology
they invested time in learning and don't want see change.

I and many other people post here from Google Groups and
you should feel free to too if it is more convenient for
you. (Of course you can also use the maillist or usenet
if you find them a good solution for *you* but please don't
feel compelled to by some loud obnoxious bullies.)

As another poster pointed out, if you are able to follow
some of the advice at,

https://wiki.python.org/moin/GoogleGroupsPython

it will help quiet down the anti-Google crowd a little but
even if you don't, those without a Google chip on their shoulder
will simply skip your posts if they find the Google formatting
too annoying. Most of us though will deal with it as adults
and try our best to answer your questions.

I just thought you should have both sides of the story so
to won't take the anti-Google crowd here as gospel.

To the OP, please ignore the above, it's sheer, unadulterated rubbish.
Nobody has ever been bullied into doing anything. People have however
been asked repeatedly to either A) use the link referenced above to
avoid sending double spaced crap here from the inferior google groups
product or B) use an alternative technology that doesn't send double
spaced crap.
 
Y

YBM

Le 09.12.2013 01:00, Gregory Ewing a écrit :
def people(age):
people=lambda age: [name for name in dic if dic[name]==age]

but i don't get the lambda age part.

Just to explain: YBM has tried to sabotage you by posting a
solution that uses a couple of advanced Python features
(lambda and list comprehensions) that a beginner would be
unlikely to know about.

Oh! I've been caught!

;-)

My point is not that I had a problem with the OP (btw asking for
homework in a public group always irrates me), but that the teacher of
the OP is incredibly stupid and illiterate (or should I say
illluterate ?)

So I tried to catch both.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top