Forum Posts

C. Kevin Chen
Jul 05, 2020
In Introduction to Python
Now that going on vacation isn't going to be an option for the foreseeable future, you'll have to spice up your quarantine by bringing the destination to you. Suddenly, you have a craving for tropical fruit salad. Perfect for a hot summer day! You decide to store the fruits you wish to include in your salad in a set. >>> fruit_salad = {} >>> fruit_salad.add('mango') >>> fruit_salad.add('pineapple') >>> fruit_salad.add('grapes') >>> fruit_salad {'mango', 'pineapple', 'grapes'} The .add() command adds the item to a set. Note that unlike a list, the items in a set are not ordered. So in this case, it doesn't matter whether you add the mango or the pineapple first, your salad will still taste the same. Furthermore, the items in a set are unique - that is, there will never be more than one of the same thing. Let's say you really like mango and would like to add some more of it to your salad. >>> fruit_salad.add('mango') >>> fruit_salad {'mango', 'pineapple', 'grapes'} As you can see, that didn't change anything. So you'll have to keep track on your own how much of each type of fruit you want. We'll dive further into that in a later post (dictionaries). You call your friend on Zoom to exchange ideas for ingredients. Your friend shares their favorite fruits with you as follows: >>> friend_salad = {'strawberry', 'kiwi', 'mango', 'apple'} Which fruits do your recipe and your friend's have in common? >>> fruit_salad.intersection(friend_salad) {'mango'} Which fruits do you like, but not your friend? >>> fruit_salad.difference(friend_salad) {'pineapple', 'grapes'} Can you write a command that tells you which fruits your friend likes, but you don't? Now, you and your friend decide to combine your recipes together. >>> fruit_salad.update(friend_salad) >>> fruit_salad {'mango', 'strawberry', 'pineapple', 'grapes', 'apple', 'kiwi'} >>> len(fruit_salad) 6 The .update() method adds every item in the set being passed as an argument (friend_salad0 to the set that .update() is being called on (fruit_salad). The built in method len() in this case returns the number of elements in the set, also known as the cardinality. If your salad recipe has three fruits and your friend's has four, why does the combined recipe have six fruits and not seven? Note that the same result could have been accomplished with >>> big_salad = fruit_salad.union(friend_salad) >>> big_salad {'mango', 'strawberry', 'pineapple', 'grapes', 'apple', 'kiwi'} Note that .update() changes the contents of fruit_salad, but .union() does not, which is why we had to save the result in a new variable. You are about to serve the fruit salad to your family, when you suddenly remember your dad is allergic to strawberries, so you must remove them. >>> fruit_salad.remove('strawberry') >>> fruit_salad {'mango', 'pineapple', 'grapes', 'apple', 'kiwi'} Your sister, who wasn't aware you were making fruit salad, tells you she doesn't like raspberries and asks you to remove them as well. >>> fruit_salad.remove('raspberry') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'raspberry' This caused an error, because your sister didn't know you never added raspberries to the fruit salad in the first place. And obviously you cannot remove something from a set that isn't there. If your sister is not comfortable with seeing the error message, use .discard() instead of .remove(); .discard() will NOT print an error message if the item you want to discard doesn't exist. >>> fruit_salad.discard('raspberry') >>> fruit_salad {'mango', 'pineapple', 'grapes', 'apple', 'kiwi'} However, in practice, .discard is rarely used because the suppression of the error message increases the risk of an uncaught bug in the set itself being propagated through the code. You can make your code more robust by checking that the element is already inside before discarding. if 'raspberry' in fruit_salad: fruit_salad.remove('raspberry') Your brother doesn't like kiwi. He is familiar with most list methods, including .pop(). He infers that if he calls .pop() on your salad, the kiwi will disappear since it's the "last" element in the set. Before trying this out in your console, do you agree or disagree with your brother? >>> fruit_salad.pop() 'grapes' >>> fruit_salad {'mango', 'pineapple', 'apple', 'kiwi'} Well, as it turns out, he was wrong. The .pop() method removes an element from a set and returns it. However, your brother forgot that sets, unlike lists, are unordered, so there's no way to know the order in which the items are being stored; instead, Python will remove an item at random. And now, after the fruit salad has been finished, don't forget to clear the dishes: >>> fruit_salad.clear() >>> fruit_salad set() The .clear() method removes all the elements from a set, but keeps it in memory. It is not to be confused with del fruit_salad which removes fruit_salad from the variable space entirely.
0
0
18
C. Kevin Chen
Jun 29, 2020
In Introduction to Python
Oh, no! The second wave is coming, and you need to gather supplies for another extended quarantine. You quickly make a LIST of essential items to buy at Target: >>> my_supplies = ['hand sanitizer', 'toilet paper', 'face masks', 'spam', 'board games', 'gummy bears'] Your mom is concerned when she sees how quickly your neighbors are buying up toilet paper, and she wants to grab as much as possible before it totally runs out. She asks you to add another pack of toilet paper to your list. >>> my_supplies.append('toilet paper') >>> print(my_supplies) ['hand sanitizer', 'toilet paper', 'face masks', 'spam', 'board games', 'gummy bears', 'toilet paper'] Your younger brother has been making his own list. He wants to add his list to the end of yours. >>> bro_supplies = ['pasta', 'instant coffee', 'toilet paper', 'nintendo'] >>> my_supplies.extend(bro_supplies) >>> print(my_supplies) ['hand sanitizer', 'toilet paper', 'face masks', 'spam', 'board games', 'gummy bears', 'toilet paper', 'pasta', 'instant coffee', 'toilet paper', 'nintendo'] After you get your brother’s list, your mom drives you to Target, only to find that it has been closed in order to maintain social distancing guidelines. Instead, you are greeted by a shopping robot. “Good day, my name is Bulls-Eye,” he introduces himself. “In order to accommodate the needs of all our customers, I would like you to give me a list of items you want, and I will sent one of my minions to fetch them in the order they appear on the list.” You hand Bulls-Eye my_supplies (in its state up to this point) and ask, “When will I get my gummy bears?” >>>my_supplies.index('gummy bears') 5 Bulls-Eye also warns you, “Due to unexpected demand, we have a strict limit of 2 packs of toilet paper per customer. I will need to check how many packs you are requesting.” >>> my_supplies.count('toilet paper') 3 "I'm sorry, that's too much toilet paper. When this happens, I will have to remove it every time it appears in your list until you reach the limit." EXERCISE: Write a method that Bulls-Eye could use to accomplish this task. You will need a while loop and the method list.remove(x), which removes the first appearance of x from the list. "Well, that's too long to wait for toilet paper," your mom grumbles, only to be distracted by her phone going off. She checks it, and turns to you with a concerned look on her face. "I have bad news, your dad has been given a pay cut, and now we can't afford everything on your list." EXERCISE: You'll have to delete items from your list by calling my_supplies.pop(), which returns the item to be removed. When you call this for the first time, what item will be removed? Meanwhile, Bulls-Eye says that customers can call sorted(list) if they want to receive their items in alphabetical order, or reverse(sorted(list)) to receive them in reverse alphabetical order. EXERCISE: If you sort my_supplies before submitting your list for purchase, which item will be returned second, or at index 1? What if you reverse your list after removing the last item, but do not sort in alphabetical order? What if you do both? HW: Write a program that removes the last element from the list by calling .pop() until the element that has been removed is 'toilet paper'.
0
0
74
C. Kevin Chen
Sep 09, 2018
In Java Question Bank
You have been sent to a remote island to negotiate a trade agreement. Three representatives arrive in a limo to greet you at the airport. The island is divided into three social castes: knight, cannibal, and knave, from highest to lowest. Knights always tell the truth, knaves always lie, and cannibals are equally as likely to tell the truth or lie with any utterance. You know that the contingent sent to meet you consists of exactly one of each, but it is impossible to tell them apart from physical appearance alone. Under no circumstances would your homeland conduct business with a cannibal, because someone will get eaten over the most inconsequential dispute. During the limo ride to the hotel, you are allowed to ask only one person one binary question (that can be answered with a simple yes/no), and it should give you enough information to stay away from the cannibal, guaranteed. What do you ask? Let's designate one representative each as A, B, C. Regardless of how we designate, there are six possible alignments as follows: A – knight, B – cannibal, C – knave A – knight, B – knave, C – cannibal A – cannibal, B – knight, C – knave A – cannibal, B – knave, C – knight A – knave, B – knight, C – cannibal A – knave, B – cannibal, C – knight You ask A, “Is B higher ranked than C?” If the answer is yes, open negotiations with C; otherwise, choose B. If A responds “yes”, either he is telling the truth (he is a knight), which also requires that B is a cannibal and thus higher ranked than C, a knave; or he is lying (he is a knave), which also requires that B is a cannibal and thus lower ranked than C, a knight. If A is a cannibal, the case is closed; in either case, C is definitely not a cannibal. Similarly if A responds “no”, either he is telling the truth (he is a knight), which also requires that B is a knave and thus lower ranked than C, a cannibal; or he is lying (he is a knave), which requires that B is a knight and thus higher ranked than C, a cannibal. Again, if A is a cannibal, the case is closed; in either case, B is definitely not a cannibal.
0
0
13
C. Kevin Chen
Sep 03, 2018
In Java Question Bank
You have been sent to a remote island to negotiate a trade agreement. Three representatives arrive in a limo to greet you at the airport. The island is divided into three social castes: knight, cannibal, and knave, from highest to lowest. Knights always tell the truth, knaves always lie, and cannibals are equally as likely to tell the truth or lie with any utterance. You know that the contingent sent to meet you consists of exactly one of each, but it is impossible to tell them apart from physical appearance alone. Under no circumstances would your homeland conduct business with a cannibal, because someone will get eaten over the most inconsequential dispute. During the limo ride to the hotel, you are allowed to ask only one person one binary question (that can be answered with a simple yes/no), and it should give you enough information to stay away from the cannibal, guaranteed. What do you ask?
0
0
19
C. Kevin Chen
Sep 03, 2018
In Java Question Bank
Due to a Bitcoin deal gone wrong, you have been convicted along with Alex and Bob, two members of rival gangs. The only other way to settle the case is with a triangular shootout, where the last man standing goes free. As you are a much more seasoned crypto-analyst than marksman, you will hit any target you shoot at with probability 0.4. On the contrary, Alex is a sure shot who hits with probability 1, and Bob's rate is 0.7. The moderator has declared that you will shoot first, Bob will shoot second, and Alex will shoot third. If no one is dead after the first round (raising suspicions of sabotage), or if anyone shoots out of turn, you will all be sentenced to 20 years in prison. You are confident that Alex and Bob will do whatever it takes to a) stay out of jail and b) remain the last man standing. You have 5 minutes to decide on a strategy. What do you do? It may sound counterintuitive, but you should throw your shot away. The key from Alex and Bob’s respective POV’s is that they’d rather defeat their strongest opponents (each other) first and deal with the weaker ones (yourself) later. For example, if it was Bob’s turn to shoot and he shot you, Alex would definitely kill him. Instead, if he took out Alex first, he’d have an easier time fending you off because you only hit with p=0.4. By similar logic, if you had to deal with Alex on your own, you’d survive with p=0.4. If Alex got to shoot first, which he would if you got rid of Bob with your first shot, you’re toast. So there is no incentive for you to shoot at Bob. If you shot at Alex, you will hit with p=0.4. Your chances in a subsequent duel with Bob are p=0.3*0.4 (P(Bob misses) P(you hit)) + 0.3*0.6*0.3*0.4 (P(Bob misses) P(you miss) P(Bob misses) P(you hit)) + 0.3*0.6*0.3*0.6*0.3*0.4 + …, which is an infinite geometric series with initial value 0.12 and ratio = 0.18. This series sums up to 0.12/(1 – 0.18) = 0.146. Doesn’t sound promising, but it’s better than Alex finishing you off for sure. Now, what if you shoot at someone and miss (p=0.6)? Then it’s Bob’s turn. He would almost certainly shoot at Alex first. This gives a probability of 0.7 that you get to deal with Bob one-on-one and 0.3 that you have to face Alex instead. But in either case, you get to shoot first, and this turns out to be a significant difference. If you face Alex, the calculations are simple. There is a 0.4 chance you’ll hit him; if not, game over. For Bob, the probability is p=0.4 (P(you hit)) + 0.6*0.3*0.4 (P(you miss) P(Bob misses) P(you hit)) + 0.6*0.3*0.6*0.3*0.4 (P(you miss twice) P(Bob misses twice) P(you hit)) +…, which is the same geometric series as the previous case, except with a starting rate of 0.4, which is the probability of a hit when you shoot first. The sum is 0.4/(1 – 0.18) = 0.488. The weighted probability of survival, given you miss your first shot, is 0.488*0.7 + 0.4*0.3 = 0.461. And if you knew your chances were that much better if you missed and pitted Alex and Bob against each other, why would you not make certain of it, by firing a blank with your first shot? At this point, if you’re wondering if Bob would consider shooting a blank as well, the answer is that he would not. If he did, Alex’s theoretical options are to either shoot Bob, or shoot a blank. He would not shoot you because that would decrease his chances of survival to 0.3. But if Alex did not shoot Bob either, everyone goes to prison—a fate Alex knows he can avoid by killing Bob. Bob should be aware of this and take matters into his own hands by shooting Alex.
0
0
8
C. Kevin Chen
Aug 27, 2018
In Java Question Bank
Due to a Bitcoin deal gone wrong, you have been convicted along with Alex and Bob, two members of rival gangs. The only other way to settle the case is with a triangular shootout, where the last man standing goes free. As you are a much more seasoned crypto-analyst than marksman, you will hit any target you shoot at with probability 0.4. On the contrary, Alex is a sure shot who hits with probability 1, and Bob's rate is 0.7. The moderator has declared that you will shoot first, Bob will shoot second, and Alex will shoot third. If no one is dead after the first round (raising suspicions of sabotage), or if anyone shoots out of turn, you will all be sentenced to 20 years in prison. You are confident that Alex and Bob will do whatever it takes to a) stay out of jail and b) remain the last man standing. You have 5 minutes to decide on a strategy. What do you do? Hint will be posted in the comments section on Wednesday, August 29. Solution will be posted in the comments section on Saturday, September 1.
1
1
60
C. Kevin Chen
Admin
More actions