-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcatenate.py
More file actions
68 lines (52 loc) · 2.28 KB
/
concatenate.py
File metadata and controls
68 lines (52 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from typing import List, Any, Union, Type, Dict, TypeVar
def concatenate_same_type(data_list: List[Any]) -> Union[int, float, str, list, dict, None]:
if not data_list:
return None
first_type: Type = type(data_list[0])
if not all(type(item) == first_type for item in data_list):
raise TypeError("All items in the list must be of the same exact type.")
#int/float
if first_type in (int, float):
return sum(data_list)
#str
elif first_type is str:
return "|".join(data_list)
# bool
elif first_type is bool:
return "".join('1' if item else '0' for item in data_list)
# list
elif first_type is list:
result_list: list = []
for sublist in data_list:
if isinstance(sublist, list):
result_list.extend(sublist)
else:
raise TypeError("Expected a list of lists, but found other type within it.")
return result_list
# dict
elif first_type is dict:
result_dict: dict = {}
for d in data_list:
if isinstance(d, dict):
result_dict.update(d)
else:
raise TypeError("Expected a list of dictionaries, but found other type within it.")
return result_dict
# Exception for different types
else:
raise TypeError(f"Unsupported type for concatenation: {first_type.__name__}")
'''
You can uncomment the following to ask for a user prompt, but be careful with the formatting of the list provided.
try:
list_provided = input("Enter a list of items to concatenate (the list should be [item1, item2, item3, ...] and elementstypes int/float, str, bool, list or dict): ")
result = concatenate_same_type(list_provided)
print(f"The concatenated result is {result}")
except TypeError as e:
print(f"Error: {e}")
'''
#print(concatenate_same_type([1, 2, 'en'])) # Output: exception
print(concatenate_same_type([1, 2, 3])) # Output: 6
print(concatenate_same_type(['hello', 'world', 'python'])) # Output: hello|world|python
print(concatenate_same_type([True, False, True, True])) # Output: 1011
print(concatenate_same_type([[1, 2], [3, 4], [5, 6]])) # Output: [1, 2, 3, 4, 5, 6]
print(concatenate_same_type([{'a': 1}, {'b': 2}, {'c': 3}])) # Output: {'a': 1, 'b': 2, 'c': 3}