Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of names which start with certain letters [closed]

I need to implement a function that takes as a parameter a list of names(strings) and another parameter that takes a list of characters. The function should print out the names in the first list that start with the letters in the second list. If the list is empty, the function doesnt print anythig.

here is how the function call would look like and its outputs

>>> selectSome(["Emma", "Santana", "Cam", "Trevor", "Olivia", "Arthur"], ['A', 'B', 'C', 'D', 'E', 'F'])
Emma
Cam
Arthur
>>> selectSome(["Holly", "Bowel", "champ", 'Fun', 'Apu'], ['a', 'F', 'C'])
champ
Fun
Apu

>>> selectSome([], ['a', 'b', 'c'])

>>> selectSome(['Eva', 'Bob'], [])
>>>
like image 831
GelatinFox Avatar asked Apr 13 '12 02:04

GelatinFox


2 Answers

Here's the gist of what you need:

>>> names = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']
>>> first_letters = ['A','B','C']
>>> output_names = [name for name in names if (name[0] in first_letters)]
>>> output_names
['Alpha', 'Bravo', 'Charlie']

I'll leave wrapping that as a function up to you.

Test your understanding:

  1. how do you make this case-insensitive?
  2. Do you understand what line 3 does? (it's called a list comprehension.) Can you write the equivalent for loop?
like image 194
Li-aung Yip Avatar answered Nov 13 '22 15:11

Li-aung Yip


Check Python's documentation for the "startswith" string method: http://docs.python.org/library/stdtypes.html#str.startswith

str.startswith(prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

Changed in version 2.5: Accept tuples as prefix.

like image 27
jsbueno Avatar answered Nov 13 '22 15:11

jsbueno