3) j. Conversion between data-structures Examples




Risaga Py Nasamura wants to know how many letters in his full name are unique. He needs a list that contains all of the different characters in his name exactly once. How can he do that? (Hint: convert a list to a set and back).

1
2
3
4
5
Output:
Using List =  ['R', 'i', 's', 'a', 'g', 'a', ' ', 'P', 'y', ' ', 'N', 'a', 's', 'a', 'm', 'u', 'r', 'a']
Set removes duplicates =  set(['R', 'i', 's', 'a', 'g', ' ', 'P', 'y', 'N', 'm', 'u', 'r'])
Final list of unique characters =  ['R', 'i', 's', 'a', 'g', ' ', 'P', 'y', 'N', 'm', 'u', 'r']
Total number of unique characters =  12




Erica has learned that, while focusing on sets, she was missing out on many basic data-structures: tuples, lists, and dictionaries she never thought of! Help Erica grasp these ideas by converting her set set1 = {3,4,7,2} to a) list and b) tuple.

1
2
3
Output:
List =  [2, 3, 4, 7]
Tuple =  (2, 3, 4, 7)




Domenico needs to ‘seal’ his dictionary into an immutable data structure, for extra safety. Help Domenico convert his dictionary to a tuple. What is that you notice?

1
2
3
4
5
6
7
8
9
Output:
Method 1
converted tuple =
(1, 2, 3, 4, 5, 6)
('crowd', 'bells', 'operation', 'line', 'clock', 'stamp')


Method 2
('1. crowd', '2. bells', '3. operation', '4. line', '5. clock', '6. stamp')




Domenico, who is a master at dictionaries, wants to work for Dang, which owes tons of lists. How can they together convert one list to a dictionary, where every other list element (even-indexed elements) can serve as dictionary keys and the other half of the list elements (odd-indexed ones)serve as dictionary values? (Hint: use zip or itertools).

1
2
3
Output:
Starting List =  ['1', 'crowd', '2', 'bells', '3', 'operation', '4', 'line', '5', 'clock', '6', 'stamp']
Dictionary =  {'1': 'crowd', '2': 'bells', '3': 'operation', '4': 'line', '5': 'clock', '6': 'stamp'}




The Earth is threatened by its sun. Solar flares are happening day by day and they are getting stronger. You have a system that detects the flares, but the sensors must be placed on the moon. To know when is the time, from where going out is not safe anymore you have to know when will be the strength of a solar flare be more than 8 (on a scale from 1 till 10), but you get the data in text format. Develop a function that converts the given number from a string into a number.

1
2
Output:
You can go outside