FP: Aula10 updated guide with 2 more exercices and their solutions
This commit is contained in:
parent
dc52d5dbd4
commit
28e9083bf9
Binary file not shown.
|
@ -0,0 +1,27 @@
|
||||||
|
def explodeObject(name, obj):
|
||||||
|
"""Print the name and representation (repr) of an object,
|
||||||
|
followed by the name and representation of each of its elements,
|
||||||
|
if the object is a list, tuple or dict.
|
||||||
|
"""
|
||||||
|
print(f"{name} = {obj!r}") # !r converts object to its repr!
|
||||||
|
# print("{} = {!r}".format(name, obj)) # equivalent
|
||||||
|
|
||||||
|
if type(obj) in (list, tuple, set): # if obj is a list, tuple or set...
|
||||||
|
for i, item in enumerate(obj):
|
||||||
|
explodeObject(f"{name}[{i}]", item)
|
||||||
|
elif type(obj) is dict: # if obj is a dict...
|
||||||
|
for key, value in obj.items():
|
||||||
|
explodeObject(f"{name}[{key!r}]", value)
|
||||||
|
# call recursively for each of its elements
|
||||||
|
# Then do something similar for tuples and dicts
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
obj1 = [1, ["a", ["b", 2], 3], 4]
|
||||||
|
obj2 = [1, "ola", (2, [[3, 4], 5, ("adeus", 6)], 7)]
|
||||||
|
obj3 = [1, {"ola": "hello", "adeus": ["bye", "adieu"]}, (2, [[3, 4], 5], 6)]
|
||||||
|
eval(input())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -0,0 +1,27 @@
|
||||||
|
def getAllStrings(obj):
|
||||||
|
"""Get a list with all the strings contained in the given object."""
|
||||||
|
|
||||||
|
lst = []
|
||||||
|
if isinstance(obj, str): # if obj is a string, just store it
|
||||||
|
lst.append(obj)
|
||||||
|
# If obj is a list, etc., we must call recursively for each of its elements
|
||||||
|
elif type(obj) in (list, tuple, set):
|
||||||
|
for elem in obj:
|
||||||
|
lst.extend(getAllStrings(elem))
|
||||||
|
elif type(obj) is dict:
|
||||||
|
for key in obj:
|
||||||
|
lst.extend(getAllStrings(key))
|
||||||
|
lst.extend(getAllStrings(obj[key]))
|
||||||
|
|
||||||
|
return lst
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
obj1 = ["one", 2, ["three", 4, [5, "six"]]]
|
||||||
|
obj2 = [1, "a", ("b", [{"c", "d", 2}, 3, (4, "e")], "f")]
|
||||||
|
obj3 = {"a": 1, "b": ["c", "d"], (2, ("x", 3)): obj1}
|
||||||
|
print(eval(input()))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
Loading…
Reference in New Issue