[Tutor] A Python Newbie Requesting help with Lambdas, Filters, and Maps

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 21 08:24:28 EDT 2019


On 20/05/2019 20:43, Rahul Alawani wrote:
> ...created a long problem statement for an interesting self-exercise.  
> However, I might have gotten a tad bit too ambitious and need help.

That's fine and we are here to help. However....
We are all volunteers and most of us have busy lives
so don't really have time to go digging deep into
complex problem statements or wading through long
code listings.

So it is best if you can reduce your post to specific
questions (only one or two per post) with trimmed down
code to show the specific issues you need help with.
That is far more likely to get a reply than a show
everything approach.

Sometimes we might ask to see everything because we need
the wider picture but usually a function or two will be
enough. Just be sure to post the actual code that gives the
error(if there is one) otherwise it's just confusing!
Oh yes, and always post the entire error message if there
is one, don't summarize or send just the last line.

Onward...

> I would appreciate it if you could simply focus on the nature 
> of the data to be used and the multi-part problem.  


> Those who might be willing to help, it would be easier 
> if you copy and paste the entire code below 

That's a big ask. How confident are we that your code
won't damage our environment? Running someone else's
unknown code is a lot like running some unknown binary,
just to see what it does! A bit scary and a huge act of trust.

> problems anyone can solve them in their mind.  
> What I'm struggling the most with is the syntax and order of 
> certain functions when solving.  

It's probably best to tackle these one by one and send the
problem code here for us to look at rather than ask us to
tackle it all at once.

> Please note that the primary objective is to solve these problems 
> using lambdas, filters, maps, etc. and NOT for or while loops 
> or list comprehensions.

That's fair enough except for the last one. List comprehensions
(and the more general generator expressions) explicitly replace
map and filter in many cases being more concise, faster and,
once you get used to them easier to read. So I would treat
LC (and GE) as being part of the same idiom set as map/reduce/filter etc.

You might find the functional programming topic in my tutorial
a useful resource too (see link below)

> So here it goes......................... 
> 
> # This function accepts a list of several dictionaries that contain song artists' names and their song titles and 
> # returns the following outputs in tuples (remember to return a tuple for each output!):
> # 1. The highest number of songs sung by any artist
> # 2. The name of the artist with the highest number of songs
> # 3. A tuple containing the name of the artist and their number of songs sung
> # 4. The longest song title in the entire song list
> # 5. The name of the artist with the longest song title
> # 6. A tuple containing the name of the artist w/ longest song title and their longest song title
> # 7. A tuple containing the name of the artist w/ longest song title and the length of their longest song title
> # 8. A list of artists and their number of songs sung sorted (default ascending order) by the number of song titles
> # 9. A list of artists and their longest song titles sorted in descending order of the length of the song title
> # 9a. Similar list as original but longest title listed first and shortest title listed last for each artist
> # 9b. BONUS: same as 9a above with artists sorted in default ascending order.  Thus the artists will be listed
> # in regular alphabetical order, but their song titles will listed in the descending order of title length
> 
> songmix = [
> 	{"artist":"Rafi","titles":["Pukarta chala hoon main","Aapke haseen rukh pe","Thaheriye hosh main aaloon","Woh jab yaad aaye","Deewana hua badal","Ehsan tera hoga mujhpar"]},
> 	{"artist":"Asha","titles":["Aja aja main hun pyar tera","Dil cheez kya hai","Aaiye meherban","Aao huzur tum ko","In aankhon ki masti mein","Paan khaye saiyan humaro"]},
> 	{"artist":"Suman","titles":["Rahete kabhi jinke dil mein","Na tum hamen jano","Jo hum pe guzarti hai","Rahe na rahe hum","Aajkal tere mere pyar ke","Tujhe dekha tujhe chaha","Parbaton ke pedon par","Tumne pukara aur"]},
> 	{"artist":"Kishor","titles":["Beqarar dil","Nile nile ambar pe","Muqaddar ka sikandar","Mere mehboob kayamat hogi","Mere sapno ki rani kab","Pyar diwana hota hai","O mere dil ke chain","Yeh shaam mastani","Pal pal dil ke paas"]},
> 	{"artist":"Lata","titles":["Lag ja gale","Tera jana dil ke armanon ka","Tera mera pyar amar","Yoon hasraton ke daag","Awaz deke hamen tum bulao","Mujhe kitana pyar hai tumse","Mausam hai aashiqana","Tujhe dekha to jana sanam","Salam-e ishq meri jaan","Yeh dil aur unki"]},
> 	{"artist":"Hemant","titles":["Tumhe yaad hoga","Tum pukar lo","Jane wow kaise log the","Neend na mujhko aye","Beqarar karke humein",]},
> 	{"artist":"Talat","titles":["Jalte hain jisake liye","Jayen to jayen kahan"]},
> 	{"artist":"Manna","titles":["Zindagi kaisi hai paheli haye","Poochho na kaise maine rain bitayee","Laga chunari mein daag"]},
> 	{"artist":"Alka","titles":["Akele hain to kya gam hai","Jane kyun log pyar karte hain","Kuchh kuchh hota hai","Pardesi pardesi jana nahi"]}
> ]
> 
> # 1. The highest number of songs sung by any artist
> # def most_titles (songmix):
> # 	return len(max(songmix, key=lambda num: len(num['titles']))['titles']) # 1. Most titles
> # print (f"Max song count for any artist", most_titles (songmix)) # !!! # Gives CORRECT answer (10)
> 
> # 2. The name of the artist with the highest number of songs
> # def artist_most_titles (songmix):
> # 	return max(songmix, key=lambda num: len(num['titles']))['artist'] # 2. Artist w/ most titles
> # print (f"The artist with max song count is", artist_most_titles (songmix)) # Gives CORRECT answer (Lata)
> 
> # 3. A tuple containing the name of the artist w/ most titles and their number of songs sung
> # def artist_most_titles (songmix):
> # 	artist_titles = (max(songmix, key=lambda num: len(num['titles']))['artist'], len(max(songmix, key=lambda num: len(num['titles']))['titles']))
> # 	return artist_titles

Shouldn't this just use the first two functions?

def artist_and_most_titles (songmix):
    return(artist_most_titles(songmix), most_titles(songmix))

The whole point of defining functions is that you can reuse
them elsewhere...

> # print (artist_most_titles (songmix)) # Gives CORRECT pair as tuple ('Lata', 10)
> # print (f"Artist, {artist_titles[0]}, has the highest song titles at, {artist_titles[1]}") # ERROR: Does NOT recognize artist_titles!

artist_titles is a variable you created inside the function. It is not
seen outside the function. The return statement returns the value not
the name.
So you need to store the result if you want to reference it multiple times:

result = artist_most_titles(songmix)
print(....result[0])
print(...result[1])

I've run out of time... I'll leave others to add more.

One final comment. Just because these functions are short does not
necessarily mean they are fast. Hidden behind the scenes these
functions are iterating over your data many times, you might find
in real world cases that traditional loops with more complex bodies
are actually faster because they can do the work on one iteration
of the data. But for learning purposes that's not an issue.

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




More information about the Tutor mailing list