Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for YAML. More Types by donnythelegend
def yaml(a):
# Loop though a.
for char in a:
# Check if char is not in the list to omit from the beginning.
# You can include more characters in the list.
# '\n' is the only necessary one for this specific challenge.
if char not in ['\n', ' ']:
# Slice a from the index of char and point a to the slice.
a = a[a.index(char):]
# Break the loop.
break
# Split a using '\n' to create a list.
# Join the elements back into a string using an uncommon character. I chose '`'.
# Replace duplicate dividers '``' with single dividers '`'.
# Replace '\\' with ''.
# Split the final string using '`' and point a to it.
a = '`'.join(a.split('\n')).replace('``', '`').replace('\\', '').split('`')
# Initialize empty variable.
b = None
# Loop through a.
for e in a:
# Split e using ': ' if the element is separated by whitespace. Just ':' otherwise.
if ': ' in e:
b = e.split(': ')
else:
b = e.split(':')
# Try to convert the second element of b to integer.
try:
b[1] = int(b[1])
# If an exception is raised, run other conversions.
except:
# Convert b[1] to corresponding bool if able.
if b[1].lower() in ['true', 'false']:
b[1] = eval(b[1].capitalize())
# Otherwise, assign b[1] to None if it's blank, whitespace, or 'null'.
elif b[1] in ['', ' ', 'null']:
b[1] = None
# Otherwise, cut out encompassing quotations and end spaces, if any exist.
elif len(b[1]) > 1:
while b[1][-1] in ['\n', ' ']:
b[1] = b[1][:-1]
if b[1][0]==b[1][-1]=='"':
b[1] = b[1][1:-1]
# Finally, point a's value at the index of e to b.
finally:
a[a.index(e)] = b
# Return a as a dictionary.
return dict(a)
if __name__ == '__main__':
print("Example:")
print(yaml('name: Alex\nage: 12'))
# These "asserts" are used for self-checking and not for an auto-testing
assert yaml('name: Alex\nage: 12') == {'age': 12, 'name': 'Alex'}
assert yaml('name: Alex Fox\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex Fox"\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex \\"Fox\\""\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex "Fox"'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'alive: false') == {'alive': False,
'children': 6,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding:') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: null') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: "null" ') == {'children': 6,
'coding': 'null',
'name': 'Bob Dylan'}
print("Coding complete? Click 'Check' to earn cool rewards!")
May 18, 2021