Answer to Question #75361 in Python for Andrew

Question #75361
Write a function flipSwitches that accepts one argument, a sequence of upper or lower case letters (the sequence can either be a str or a list, if you write your code correctly, it shouldn’t matter). This is a sequence of switches, uppercase means to turn a switch on, and lowercase to turn a switch off. For example, ‘A’ means to turn the switch ‘A’ on, and ‘a’ means to turn the switch ‘A’ off. The function should then return the set of those switches that are still on at the end of the sequence of switches. To receive full credit, your code must use a set that keeps track of the switches that are on.You can then iterate over the sequence and modify the set of switches that are on as appropriate.
>>> flipSwitches( ['A','A','a','B'] )
{'B'}
1
Expert's answer
2018-04-03T10:54:59-0400
def flipSwitches(arr):
tracking_set = set() # a set that keeps track of the switches that are on

for c in arr: # loop over all elements in set
if c.isupper(): # if an element is upper letter add to the tracking set (turn on)
tracking_set.add(c)
if c.islower() and (c.upper() in tracking_set): # if an element is lower letter and the upper letter is in the tracking set than remove it (turn off)
tracking_set.remove(c.upper())

return tracking_set

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS