Re: [Tutor] A Python Newbie Requesting help with Lambdas, Filters, Maps, and Built-in Functions to solve problems for a List of Songs

2019-05-21 Thread Alan Gauld via Tutor
On 21/05/2019 14:30, Rahul Alawani wrote:

> # 4. The longest song title in the entire songs list
> def longest_title (songmix):
> temp = max(songmix, key=lambda num: len(max(num['titles'])))
> return list(map(lambda x: max(songmix, key=lambda num: 
> len(max(num['titles'])))['artist'],
>  filter(lambda title: max(len('title')), temp)))
> print (longest_title (songmix))

There are several problems here.
The first and the one that the error is reporting lies in the call to
max() max() expects a sequence of values and returns the biggest.
But you are passing len('title') which is a single integer value.
Hence the error about int not being iterable...

But there is another problem with len('title')
That will give the result 5 each time since its taking the length of the
string 'title'.
I suspect you wanted len(title) without the quotes?

Finally max() applied to strings returns the highest in lexical value -
ie 'b' is higher than 'a'... So

>>> max(['a','aa','','aaa','baa'])
'baa'
>>>

Which I don't think is what you want?

However, there is also a problem with the filter call.
filter expects a function that returns a boolean result. It then applies
that test to each member of its sequence parameter and returns a list
containing only those members for which the test was true.

In your case the lambda would return a number - the result of max.
All non zero numbers are treated as true by Python so you will get back
the same list you started with since all the max calls will (probably)
return >0 results.

Also I notice you are using key functions to max but that is hardly ever
necessary since max will return the largest item regardless of the
order. It only needs a key if there are multiple items of the same size
and you want to return a specific one of those. Sorting will ensure the
right value is picked. But in your case you don't need any sorting.

I know you want to practice lambdas but I think initially it would be
better for you to practice with map and filter using small named
functions. You can then convert them to lambdas later.

So for example(untested, so probably buggy):

def title_with_size(song): return (len(song), song)

def song_lengths(singer): return map(title_with_size, singer['titles'])

def max_title(singer): return max(song_lengths(singer))

def longest_title (songmix):
titles = map(max_title, songmix)
return max(titles)[1]

Removing the lambdas makes everything easier to read and therefore
easier to understand.

Once you understand how the map/filter etc work you can
decide where the named functions can be replaced by lambdas.
As it stands your code is a fine demonstration of why
lambdas are relatively rarely used!

-- 
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] A Python Newbie Requesting help with Lambdas, Filters, Maps, and Built-in Functions to solve problems for a List of Songs

2019-05-21 Thread Rahul Alawani
Reposting a somewhat shortened version of my earlier ask based on a fellow 
user's feedback (thanks Alan G). I still think it's important to share/repeat 
some background.  Admin/moderator, please feel free to delete my prior post.  
Thx.

Hello Tutors!

I am an ambitious Python newbie without any CS background!  I am currently 
taking an online Python programming course.  I have quite some ways to go.  But 
based on what I have learned so far (data types, 
lists/dictionaries/tuples/sets, conditional statements, for and while loops, 
functions, lambdas, maps and filters, simple built-in functions like 
min/max/any/all/abs/round/len/ sorted/reversed),

I am trying to solve what I think is an interesting set of problems pertaining 
to a list of songs (Bollywood artists and songs are listed in the example, but 
that's NOT important, although it might be too distracting for some people).

I would appreciate it if you could simply focus on the nature of the data to be 
used and the multi-part problem.  Those willing to help, it might be easier if 
you copy and paste the below code into a Python 3 text editor/interpreter 
(whatever works for you).

I have added some comments, too, and hope they will be useful.  I am not 
looking for a spoon-fed solution to every single unsolved problem.  Just 
something that would push me over to the next step would suffice.  I know how 
to solve each of these problems conceptually (anyone can solve them in their 
mind).  What I'm struggling the most with is the syntax and order of certain 
functions when solving.  Perhaps I am not considering some intermediate code 
steps that are required and/or helpful.

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. 
 Any help will be greatly appreciated with heartfelt thanks and email 
fist-bumps.  Thank you for your time and consideration.

Regards,
Rahul A.

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!):
# 4. The longest song title in the entire song list
# 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
# 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"]}
]

# 4. The longest song title in the entire songs list
def longest_title (songmix):
temp = max(songmix, key=lambda num: len(max(num['titles'])))
return list(map(lambda x: max(songmix, key=lambda num: 
len(max(num['titles'])))['artist'],
 filter(lambda title: max(len('title')), temp)))
print (longest_title (songmix))

# Error Message in PowerShell:

# Traceback (most recent call last):
#   File ".\Lambdas_Built_in_Functions_Min_Max_Sorted_Adv_short.py", line 33, 
in 
# print (longest_title