COPYING LISTS
>>> y = 798798 >>> y 798798 >>> x [1000, 2, 3, 4, 5]
Slice Copy
SORTING LISTS
>>> x=[3,0,6,3,5,7] >>> x.sort() >>> x [0, 3, 3, 5, 6, 7] >>> y=[[2, 9], [2, 1], [3, 2, 2], [3, 2, 1]] >>> y.sort() >>> y [[2, 1], [2, 9], [3, 2, 1], [3, 2, 2]] >>> z=["melon", "apple", "banana"] >>> z.sort() >>> z ['apple', 'banana', 'melon'] >>> f=["melon", "apple", "banana", "apricot"] >>> f.sort() >>> f ['apple', 'apricot', 'banana', 'melon'] >>> t=["melon", "apple", "banana", "Apricot"] >>> t.sort() >>> t ['Apricot', 'apple', 'banana', 'melon'] >>> t=["melon", "apple", "banana", "Apricot"] >>> t.sort(reverse=True) >>> t ['melon', 'banana', 'apple', 'Apricot']
sorted() vs sort() function
>>> z=[[1,3],[5,4],[1,2],[3,4,1,7,2,9]] >>> r=sorted(z) >>> z [[1, 3], [5, 4], [1, 2], [3, 4, 1, 7, 2, 9]] >>> r [[1, 2], [1, 3], [3, 4, 1, 7, 2, 9], [5, 4]] >>> z.sort() >>> z [[1, 2], [1, 3], [3, 4, 1, 7, 2, 9], [5, 4]]
Example from Armindo
z = [[1,3],[5,4],[1,2],[3,4,1,7,2,9]] print("Initial z:") print(z) print("__________") # Sort a specific element print("Sorted z[3] using sorted():") print(sorted(z[3])) print("__________") # Sort all elements, then sort the data inside each element. z.sort() print("Sorted z, using sort() method:") print(z) print("__________") print("Sorted z, using sorted() function:") for l in z: print(sorted(l)) String Examples |
Initial z: [[1, 3], [5, 4], [1, 2], [3, 4, 1, 7, 2, 9]] __________ Sorted z[3] using sorted(): [1, 2, 3, 4, 7, 9] __________ Sorted z, using sort() method: [[1, 2], [1, 3], [3, 4, 1, 7, 2, 9], [5, 4]] __________ Sorted z, using sorted() function: [1, 2] [1, 3] [1, 2, 3, 4, 7, 9] [4, 5] |
>>> names = [["Kim", "Mike", "Alex", "Bob"],["Jim", "John", "Mary"],["Joe", "Tom", "Amy"]] >>> names [['Kim', 'Mike', 'Alex', 'Bob'], ['Jim', 'John', 'Mary'], ['Joe', 'Tom', 'Amy']] >>> sorted(names) [['Jim', 'John', 'Mary'], ['Joe', 'Tom', 'Amy'], ['Kim', 'Mike', 'Alex', 'Bob']]
print("\nAlphabetic Example 2") names = [["Kim", "Mike", "Alex", "Bob"],["Jim", "John", "Mary"],["Joe", "Tom", "Amy"]] print("initial list:") print(names) print("_____________") sortedNames = [] for n in names: n.sort() sortedNames.append(n) print("each sub-list is sorted individually:") print(sortedNames) print("_____________") print("entire list is sorted at once:") print(sorted(sortedNames))
initial list: [['Kim', 'Mike', 'Alex', 'Bob'], ['Jim', 'John', 'Mary'], ['Joe', 'Tom', 'Amy']] _____________ each sub-list is sorted individually: [['Alex', 'Bob', 'Kim', 'Mike'], ['Jim', 'John', 'Mary'], ['Amy', 'Joe', 'Tom']] _____________ entire list is sorted at once: [['Alex', 'Bob', 'Kim', 'Mike'], ['Amy', 'Joe', 'Tom'], ['Jim', 'John', 'Mary']]
DEEP COPY OF NESTED LISTS
x=[[1,2], [3,4], [5,6]] y=x x[0][0]=100 x[0]=[88,99]
Let's look at the slice copy now
x=[[1,2], [3,4], [5,6]] y=x[:] x[0][0]=100 x[0]=[88,99]
this is a SHALLOW COPY
Let's look at how we achieve a deep copy
import copy x=[[1,2], [3,4], [5,6]] y=copy.deepcopy(x) x[0][0]=100 x[0]=[88,99]
TUPLES
Tuples are very similar to Lists, except they cannot be modified (immutable).
Tuples are faster than lists, because they are constant size
Tuples are faster than lists, because they are constant size
>>> t=(1,2,3,4,5,6) >>> t (1, 2, 3, 4, 5, 6) >>> t[0] 1 >>> 3 in t True >>> min(t) 1 >>> t[2]=4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
Concatenating tuples
>>> t=(2,4,5,6) >>> t+=(1,1,1) >>> t (2, 4, 5, 6, 1, 1, 1)
Copying tuples with slice notation doesn't work the same as with lists
however copying through concatenation does create a new tuple
One element tuple needs a comma
with comma:
Keep in mind the nature of references:
Tuples can be converted to Lists and vice versa:
>>> t=(1,2,3) >>> x=list(t) >>> x [1, 2, 3] >>> w=tuple(x) >>> w (1, 2, 3)
Strings can be converted to lists and tuples
>>> list("Hello") ['H', 'e', 'l', 'l', 'o'] >>> tuple("Hello") ('H', 'e', 'l', 'l', 'o')
PACKING and UNPACKING
>>> (one, two, three, four)=(1,2,3,4) >>> one 1 >>> two 2 >>> three 3 >>> four 4 #You can do same with >>> [one, two, three, four]=[1,2,3,4] #or without brackets >>> o,t,e=1,2,3 >>> o 1 >>> t 2 >>> e 3 #You can also use * notation to absorb any not matching elements : >>> x=(1,2,3,4,5,6) >>> a,b,*c = x >>> a 1 >>> b 2 >>> c [3, 4, 5, 6] >>> a,b,c (1, 2, [3, 4, 5, 6]) >>> x=(1,2,3) >>> a,b,c,*d=x >>> d []
ZIPPING
a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica") x = zip(a, b) s = tuple(x)
SETS
#Set is an unindexed, mutable collection of unique, immutable, hashable elements: >>> s={1,2,3,4} >>> s {1, 2, 3, 4} >>> s={1,1,1,2,3,4} >>> s {1, 2, 3, 4} #sets cannot have indexes (unordered): >>> s[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'set' object does not support indexing >>> s.add(77) >>> s {1, 2, 3, 4, 77} >>> s.remove(77) >>> s {1, 2, 3, 4} >>> 4 in s True #you can use other sequences to create a set using set function: >>> q=set([1,1,1,2,2,2]) >>> q {1, 2} >>> q=set("Hello") >>> q {'H', 'e', 'l', 'o'} >>> s={1,2,3} >>> q={3,4,5} >>> s {1, 2, 3} >>> q {3, 4, 5} #UNION: >>> s|q {1, 2, 3, 4, 5} #INTERSECTION: >>> s&q {3} #SYMMETRIC DIFFERENCE (elements in s or q but not in both): >>> s^q {1, 2, 4, 5}
Elements of a set have to be hashable
>>> s={1,2,[4]} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
Frozensets are immutable, hashable sets:
>>> s={1,2,3} >>> q={1,2,s} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set' >>> s=frozenset(s) >>> q={1,2,s} >>> q {1, 2, frozenset({1, 2, 3})}
len(q) returns the size of the set
>>> s={1,2,3,5,5,5} >>> s {1, 2, 3, 5} >>> len(s) 4
Looping through sets, lists, tuples
Looping through sets, lists and tuples follows the same syntax
for s in a: print(s) a=(1,2,3,4,5,6) for s in a: print(s) a={1,2,3,4,5,6} for s in a: print(s)
String functions
#remove extra line feed in print statement: >>> s="r\n" >>> s 'r\n' >>> print(s) r >>> print(s, end="") r >>>
#join() method (creates new string every time you join, use sparingly): >>> l=list("Hello") >>> l ['H', 'e', 'l', 'l', 'o'] >>> "".join(l) 'Hello' >>> " ".join(l) 'H e l l o' >>> "_".join(l) 'H_e_l_l_o'
#split() method: >>> str1="Hello Hello" >>> str1.split("l") ['He', '', 'o He', '', 'o']
#strip() - remove leading and trailing white spaces >>> s=" \tHello World\n\n\t" >>> s.strip() 'Hello World' #lstrip() - remove leading white spaces >>> s.lstrip() 'Hello World\n\n\t' #rstrip() - remove trailing white spaces >>> s.rstrip() ' \tHello World' #You can pass a specific character to these methods to be removed (only leading and trailing matching characters will be removed): >>> x="www.python.org" >>> x.strip("w") '.python.org' #following examples strips all trailing g's o's and r's >>> x="www.python.org" >>> x.rstrip("gor") 'www.python.'
find() - finds leftmost substring in a string, if additional numeric parameter is passed, it starts searching at (and including) passed position
When 2 numeric parameters are passed, it searches starting at first up to (and not including) the second parameter
When 2 numeric parameters are passed, it searches starting at first up to (and not including) the second parameter
>>> s="Hello World" >>> s.find("l") 2 >>> s.find("l", 4) 9 >>> s.find("z") -1 >>> s.find("l", 2) 2 >>> s.find("l", 3) 3 >>> s.find("l", 5, 9) -1 >>> s.find("l", 5, 10) 9
rfind() - same as find, but searches from right to left: >>> s.rfind("l") 9 >>> s.rfind("l", 9) 9 >>> s.rfind("l", -2) 9 >>> s.rfind("l", 5, 9) -1 >>> s.rfind("l", 5, 10) 9
index() and rindex() are respectively identical to find and rfind, however instead of returning -1 when substring is not found, they raise an exception:
>>> s.rindex("l", 5, 9) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
#startswith() and endswith() can be used to check if string starts #or ends with a passed as a parameter string: >>> s="New Haven" >>> s.startswith("New") True >>> s.endswith("Haven") True >>> s.endswith("New") False
#replace() replaces an occurrence of a string with another string: >>> s="New Haven" >>> s.replace("New", "Old") 'Old Haven' >>> s 'New Haven' #String doesn't have reverse method, but list does, so if needed you could do: >>> s="New Haven" >>> s.reverse() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'reverse' >>> l=list(s) >>> l.reverse() >>> l ['n', 'e', 'v', 'a', 'H', ' ', 'w', 'e', 'N'] #Note that while strings don't get modified by their methods - #they return new strings instead, #the list actually gets modified. >>> s="123" >>> s.isdigit() True >>> s.isalpha() False >>> s="Apple" >>> s.isalpha() True >>> s="Apple33" >>> s.isalpha() False >>> s.islower() False >>> s="apple" >>> s.islower() True >>> s.isupper() False
>>> s="32sk43" >>> s.isalnum() True >>> s="32sk43___" >>> s.isalnum() False
>>> s = “Whereof one cannot speak, thereof one must be silent.” >>> s 'Whereof one cannot speak, thereof one must be silent.' >>> s.upper() 'WHEREOF ONE CANNOT SPEAK, THEREOF ONE MUST BE SILENT.' >>> s.lower() 'whereof one cannot speak, thereof one must be silent.'
In Class Exercise - Round Robin Load Balancer
You are building a load balancer that serves requests in round-robin fashion.
Your input is array of IP addresses to balance the load across, ex:
lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1"]
another example:
lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1", "D.1.1.1", "E.1.1.1"]
write a program that produces output similar to the output below
Your input is array of IP addresses to balance the load across, ex:
lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1"]
another example:
lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1", "D.1.1.1", "E.1.1.1"]
write a program that produces output similar to the output below
$ python round_robin_lb.py Redirected to A.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to B.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to C.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to A.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to B.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to C.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to A.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to B.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to C.1.1.1 Enter 'r' for request, any other character to quit:t Serverd 9 requests
$ python round_robin_lb.py Redirected to A.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to B.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to C.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to D.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to E.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to A.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to B.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to C.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to D.1.1.1 Enter 'r' for request, any other character to quit:r Redirected to E.1.1.1 Enter 'r' for request, any other character to quit:5 Serverd 10 requests
Sample solution:
#lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1"] lb_ips = ["A.1.1.1", "B.1.1.1", "C.1.1.1", "D.1.1.1", "E.1.1.1"] round_robin = 0 request = "r" while request == "r": print("Redirected to ", end="") print(lb_ips[round_robin%len(lb_ips)]) round_robin+=1 request = input("Enter 'r' for request, any other character to quit:") print("Serverd {} requests".format(round_robin))
The example below iterates through the list of Strings and searches for an occurrence of the word user has entered
https://github.com/gnurmatova/Python/blob/master/lecture2/QuotesSearchLoop1.py
data_list=["And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.", "All grown-ups were once children... but only few of them remember it.", "People have forgotten this truth,\" the fox said. \"But you mustn’t forget it. You become responsible forever for what you’ve tamed. You’re responsible for your rose.", "It is the time you have wasted for your rose that makes your rose so important.", "The most beautiful things in the world cannot be seen or touched, they are felt with the heart.", "What makes the desert beautiful,' said the little prince, 'is that somewhere it hides a well...", "You - you alone will have the stars as no one else has them...In one of the stars I shall be living. In one of them I shall be laughing. And so it will be as if all the stars were laughing, when you look at the sky at night...You - only you - will have stars that can laugh.", "Well, I must endure the presence of a few caterpillars if I wish to become acquainted with the butterflies.", "You see, one loves the sunset when one is so sad.", "You're beautiful, but you're empty...One couldn't die for you. Of course, an ordinary passerby would think my rose looked just like you. But my rose, all on her own, is more important than all of you together, since she's the one I've watered. Since she's the one I put under glass, since she's the one I sheltered behind the screen. Since she's the one for whom I killed the caterpillars (except the two or three butterflies). Since she's the one I listened to when she complained, or when she boasted, or even sometimes when she said nothing at all. Since she's my rose.", "If you love a flower that lives on a star, it is sweet to look at the sky at night. All the stars are a-bloom with flowers...", "And when your sorrow is comforted (time soothes all sorrows) you will be content that you have known me. You will always be my friend. You will want to laugh with me. And you will sometimes open your window, so, for that pleasure . . . And your friends will be properly astonished to see you laughing as you look up at the sky! Then you will say to them, 'Yes, the stars always make me laugh!' And they will think you are crazy. It will be a very shabby trick that I shall have played on you...", "You become responsible, forever, for what you have tamed.", "Of course I’ll hurt you. Of course you’ll hurt me. Of course we will hurt each other. But this is the very condition of existence. To become spring, means accepting the risk of winter. To become presence, means accepting the risk of absence.", "Where are the people?\" resumed the little prince at last. \"It’s a little lonely in the desert…\" \"It is lonely when you’re among people, too,\" said the snake.", "All men have stars, but they are not the same things for different people. For some, who are travelers, the stars are guides. For others they are no more than little lights in the sky. For others, who are scholars, they are problems... But all these stars are silent. You-You alone will have stars as no one else has them... In one of the stars I shall be living. In one of them I shall be laughing. And so it will be as if all the stars will be laughing when you look at the sky at night..You, only you, will have stars that can laugh! And when your sorrow is comforted (time soothes all sorrows) you will be content that you have known me... You will always be my friend. You will want to laugh with me. And you will sometimes open your window, so, for that pleasure... It will be as if, in place of the stars, I had given you a great number of little bells that knew how to laugh", "She cast her fragrance and her radiance over me. I ought never to have run away from her... I ought to have guessed all the affection that lay behind her poor little stratagems. Flowers are so inconsistent! But I was too young to know how to love her...", "A rock pile ceases to be a rock pile the moment a single man contemplates it, bearing within him the image of a cathedral.", "I did not know how to reach him, how to catch up with him... The land of tears is so mysterious.", "I remembered the fox. One runs the risk of crying a bit if one allows oneself to be tamed.", "When someone blushes, doesn't that mean 'yes'?", "You're beautiful, but you're empty. No one could die for you.", "In those days, I didn't understand anything. I should have judged her according to her actions, not her words. She perfumed my planet and lit up my life. I should never have run away! I ought to have realized the tenderness underlying her silly pretensions. Flowers are so contadictory! But I was too young to know how to love her.", "I have lived a great deal among grown-ups. I have seen them intimately, close at hand. And that hasn’t much improved my opinion of them.", "Grown-ups love figures... When you tell them you've made a new friend they never ask you any questions about essential matters. They never say to you \"What does his voice sound like? What games does he love best? Does he collect butterflies? \" Instead they demand \"How old is he? How much does he weigh? How much money does his father make? \" Only from these figures do they think they have learned anything about him.", "The proof that the little prince existed is that he was charming, that he laughed, and that he was looking for a sheep. If anybody wants a sheep, that is a proof that he exists.", "No one is ever satisfied where he is.", "I was too young to know how to love her.", "I am who I am and I have the need to be.", "But the conceited man did not hear him. Conceited people never hear anything but praise.", "Men have no more time to understand anything. They buy things all ready made at the shops. But there is no shop anywhere where one can buy friendship, and so men have no friends any more. If you want a friend, tame me...", "For millions of years flowers have been producing thorns. For millions of years sheep have been eating them all the same. And it's not serious, trying to understand why flowers go to such trouble to produce thorns that are good for nothing? It's not important, the war between the sheep and the flowers? It's no more serious and more important than the numbers that fat red gentleman is adding up? Suppose I happen to know a unique flower, one that exists nowhere in the world except on my planet, one that a little sheep can wipe out in a single bite one morning, just like that, without even realizing what he'd doing - that isn't important? If someone loves a flower of which just one example exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars. He tells himself 'My flower's up there somewhere...' But if the sheep eats the flower, then for him it's as if, suddenly, all the stars went out. And that isn't important?", "I have always loved the desert. One sits down on a desert sand dune, sees nothing, hears nothing. Yet through the silence something throbs, and gleams...", "People have stars, but they aren't the same. For travelers, the stars are guides. For other people, they're nothing but tiny lights. And for still others, for scholars, they're problems... But all those stars are silent stars. You, though, you'll have stars like nobody else... since I'll be laughing on one of them, for you it'll be as if all the stars are laughing. You'll have stars that can laugh!... and it'll be as if I had given you, instead of stars, a lot of tiny bells that know how to laugh ...", "What does tamed mean? It's something that's been too often neglected. It means to create ties.", "The only things you learn are the things you tame", "One runs the risk of weeping a little, if one lets himself be tamed.", "You're not at all like my rose. You're nothing at all yet. No one has tamed you and you haven't tamed anyone. You're the way my fox was. He was just a fox like a hundred thousand others. But I've made him my own and now he is unique in the world.", "I ought not to have listened to her,' he confided to me one day. 'One never ought to listen to the flowers. One should simply look at them and breathe their fragrance. Mine perfumed all my planet. But I did not know how to take pleasure in all her grace.", "You will have five hundred million little bells, and I shall have five hundred million springs of fresh water...", "…if you tame me, then we shall need each other. To me, you will be unique in all the world. To you, I shall be unique in all the world…if you tame me, it will be as if the sun came to shine on my life. I shall know the sound of a step that will be different from all the others. Other steps send me hurrying back underneath the ground. Yours will call me, like music, out of my burrow", "If you tame me, it would be as if the sun came to shine on my life.", "Men have no more time to understand anything. They buy ready-made things in the shops. But since there are no shops where you can buy friends, men no longer have any friends.", "All grown-ups were children first. (But few remember it).", "Of course, I love you,' the flower said to him. 'If you were not aware of it, it was my fault.", "The thing that is important is the thing that is not seen.", "It is much more difficult to judge oneself than to judge others.", "You know...my flower...I'm responsible for her. And she's so weak! And so naive. She has four ridiculous thorns to defend her against the world...", "\"Ephemeral\" It means 'which is in danger of speedy disappearance.", "He fell as gently as a tree falls. There was not even any sound..", "The house, the stars, the desert -- what gives them their beauty is something that is invisible!", "\"My life is very monotonous,\" the fox said. \"I hunt chickens; men hunt me. All the chickens are just alike, and all the men are just alike. And, in consequence, I am a little bored.\"", "Sometimes, there is no harm in putting off a piece of work until another day.", "Only the children know what they are looking for.", "Grown ups never understood anything by themselves. And it is rather tedious to have to explain things to them time and again", "It is much more difficult to judge oneself than to judge others. If you succeed in judging yourself rightly, then you are a man of true wisdom.", "Words are the source of misunderstandings.", "And the little prince broke into a lovely peal of laughter, which irritated me very much. I like my misfortunes to be taken seriously.", "\"What a queer planet!\" he thought. \"It is altogether dry, and altogether pointed, and altogether harsh and forbidding. And the people have no imagination. They repeat whatever one says to them . . . On my planet I had a flower; she always was the first to speak . . .", "I know a planet where there is a certain red-faced gentleman. He has never smelled a flower. He has never looked at a star. He has never loved any one. He has never done anything in his life but add up figures. And all day he says over and over, just like you: 'I am busy with matters of consequence!' And that makes him swell up with pride. But he is not a man - he is a mushroom!", "But if you tame me, my life will be filled with sunshine. I'll know the sound of footsteps that will be different from all the rest. Others send me back underground. Yours will call me out of my burrow like music.", "I believe that for his escape he took advantage of the migration of a flock of wild birds.", "He had taken seriously words which were without importance, and it made him very unhappy.", "If you come at four in the afternoon, I'll begin to be happy by three.", "One must require from each one the duty which each one can perform. Accepted authority rests first of all on reason.", "Straight ahead you can't go very far.", "One sees clearly only with the heart. Anything essential is invisible to the eyes.", "I wonder if the stars are lit up so that each one of us can find her own star again.", "My drawing was not a picture of a hat. It was a picture of a boa constrictor digesting an elephant.", "To you I am just a fox, like a hundred thousand others, but if you tame me we shall need one another and I shall be unique to you in all the world.", "Don't linger like this. You have decided to go away. Now go!", "But I, alas, do not know how to see sheep through the walls of boxes. Perhaps I am a little like the grown-ups. I have had to grow old.", "I remembered the fox. You risk tears if you let yourself be tamed.", "Wait for a time, exactly under the star. Then, if a little man appears who laughs, who has golden hair and refuses to answer questions, you will know who he is, If this should happen, please comfort me. Send me word that he has come back.", "If I am attempting to describe him, it is in order not to forget him. It is sad to forget a friend. Not every one has had a friend.", "The thing that is important is the thing that is not seen", "Nevertheless he is the only one of them all who does not seem to me ridiculous. Perhaps that is because he is thinking of something else besides himself.", "If someone loves a flower of which just one exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars.", "If you want to build a ship, don't drum up people to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.", "Will you draw me a sheep?", "It's good to have a friend. Even if you're going to die.", "If you love a flower that lives on a star, then it's good at night, to look up at the sky. All the stars are blossoming."] query=input("query:") print(query) for quote in data_list: found_at = quote.find(query) if( found_at >= 0): print("Found:", "..."+quote[found_at:found_at+50], "...")
Output:
query:fox fox Found: ...fox said. "But you mustn’t forget it. You become r ... Found: ...fox. One runs the risk of crying a bit if one allo ... Found: ...fox was. He was just a fox like a hundred thousand ... Found: ...fox said. "I hunt chickens; men hunt me. All the c ... Found: ...fox, like a hundred thousand others, but if you ta ... Found: ...fox. You risk tears if you let yourself be tamed. ...
You can also use enumerate that will give you an index of the found element
query=input("query:") print(query) for i,quote in enumerate(data_list): found_at = quote.find(query) if( found_at >= 0): print("Found at ", i, "..."+quote[found_at:found_at+50], "...")
Output
query:fox fox Found at 2 ...fox said. "But you mustn’t forget it. You become r ... Found at 19 ...fox. One runs the risk of crying a bit if one allo ... Found at 37 ...fox was. He was just a fox like a hundred thousand ... Found at 51 ...fox said. "I hunt chickens; men hunt me. All the c ... Found at 69 ...fox, like a hundred thousand others, but if you ta ... Found at 72 ...fox. You risk tears if you let yourself be tamed. ...
HOMEWORK
Quote Search Program Improvements
part A (submit as a separate program). Make the search case InSensitive, i.e. With the current program, the "Will" and "will" are searched as two different entities, see examples below. Modify program such, that all occurrences of the searched word will be found regardless of the case, i.e. the search for "will" or "Will" should return results containing all "will", "Will", "WILL"
part A (submit as a separate program). Make the search case InSensitive, i.e. With the current program, the "Will" and "will" are searched as two different entities, see examples below. Modify program such, that all occurrences of the searched word will be found regardless of the case, i.e. the search for "will" or "Will" should return results containing all "will", "Will", "WILL"
$ python quote_search.py query:Will Will Found: ...Will you draw me a sheep? ...
$ python quote_search.py query:will will Found: ...will have the stars as no one else has them...In o ... Found: ...will be content that you have known me. You will a ... Found: ...will hurt each other. But this is the very conditi ... Found: ...will have stars as no one else has them... In one ... Found: ...will have five hundred million little bells, and I ... Found: ...will be unique in all the world. To you, I shall b ... Found: ...will be filled with sunshine. I'll know the sound ... Found: ...will know who he is, If this should happen, please ...
part B (submit as a separate program). Allow multiple, not joined query terms. See example below, if I search for "this should happen" I get a result, however, if I search for "this happen" I get no results, because the current search implementation searched for exact string match. Modify the program such that each query term separated by the white spaces is searched. Only results containing ALL keywords should be returned
$ python quote_search.py query:this should happen this should happen Found: ...this should happen, please comfort me. Send me wor ...
$ python quote_search.py query:this happen this happen (base) Gulas-MacBook-Pro:lecture3 gulanurmatova$
part C (submit as a separate program). If not results found, print "No results found". in the example above, if no results found, the program does not provide a good feedback to the user, please add a feedback message in the case when no results are found
part D (submit as a separate program): Introduce AND and OR operators for at least 2 keywords, ok to limit to only 1 operator (either AND used or OR used, ok if program doesn't work well for combination of both or for more than 2 keywords):
a search query "love AND flower" should return only results containing both "love" and "flower":
"If you love a flower that lives on a star, it is sweet to look at the sky at night. All the stars are a-bloom with flowers...",
"Of course, I love you,' the flower said to him. 'If you were not aware of it, it was my fault."
"If you love a flower that lives on a star, then it's good at night, to look up at the sky. All the stars are blossoming."
optional (ok if it is returned or not): "If someone loves a flower of which just one exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars.",
a search query "love OR flower" should return results containing either "love" or "flower":
optional (ok if it is returned or not): "You see, one loves the sunset when one is so sad."
"If you love a flower that lives on a star, it is sweet to look at the sky at night. All the stars are a-bloom with flowers..."
"Grown-ups love figures... When you tell them you've made a new friend they never ask you any questions about essential matters. They never say to you \"What does his voice sound like? What games does he love best? Does he collect butterflies? \" Instead they demand \"How old is he? How much does he weigh? How much money does his father make? \" Only from these figures do they think they have learned anything about him."
"I was too young to know how to love her."
optional (ok if it is returned or not):"I have always loved the desert. One sits down on a desert sand dune, sees nothing, hears nothing. Yet through the silence something throbs, and gleams..."
"Of course, I love you,' the flower said to him. 'If you were not aware of it, it was my fault.",
optional (ok if it is returned or not):"And the little prince broke into a lovely peal of laughter, which irritated me very much. I like my misfortunes to be taken seriously."
"If someone loves a flower of which just one exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars.",
"If you love a flower that lives on a star, then it's good at night, to look up at the sky. All the stars are blossoming."
optional (ok if it is returned or not):"For millions of years flowers have been producing thorns. For millions of years sheep have been eating them all the same. And it's not serious, trying to understand why flowers go to such trouble to produce thorns that are good for nothing? It's not important, the war between the sheep and the flowers? It's no more serious and more important than the numbers that fat red gentleman is adding up? Suppose I happen to know a unique flower, one that exists nowhere in the world except on my planet, one that a little sheep can wipe out in a single bite one morning, just like that, without even realizing what he'd doing - that isn't important? If someone loves a flower of which just one example exists among all the millions and millions of stars, that's enough to make him happy when he looks at the stars. He tells himself 'My flower's up there somewhere...' But if the sheep eats the flower, then for him it's as if, suddenly, all the stars went out. And that isn't important?"
"You know...my flower...I'm responsible for her. And she's so weak! And so naive. She has four ridiculous thorns to defend her against the world..."
part E (submit as a separate program): Analyze the inputs and outputs from the program above, what happens if the user enters same keyword multiple times, ex: "flower AND flower", does your program still search for each one? If yes, modify your program such that it does not search for repeated keywords. Also, ensure that the output quotes are only displayed once, i.e. there should be no repeating quotes in the output.
part D (optional, extra credit): research on the concepts of "inverted index", "stop words" and "word stemming and synonym expansion". Think how you could implement them in your program. If you do attempt to implement any of them, submit as a separate program for up to 5 points extra credit (1.5 times the value of homework submission and 0.5 value of a quiz). You will not be quizzed on these concepts, it is a general computer science knowledge.
Load Balancers research (optional, extra credit): research on other implementations for the load balancers routing algorithms, modify the load balancer program we built in class to implement one of those algorithms. Explain in the comments what approach you have chosen. Submit for up to 3.3 points extra credit