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 Liam_Lau
import re
def yaml(a):
# your code here
result = {}
lst1 = a.split('\n')
lst1.sort()
for i in lst1:
a = i.split(': ')
if(len(a)>=2):
if(a[1].lower()=='true'):
result[a[0]] = True
elif(a[1].lower()=='false'):
result[a[0]] = False
else:
try:
result[a[0]] = int(a[1])
except:
if(a[1].lower()=='null'):
result[a[0]] = None
else:
c = ''
tmpA = a[1].replace('\n','')
tmpA = tmpA.replace('"','\(****)')
tmpA = tmpA.replace('\\\\(****)','"')
tmpA = tmpA.replace('\(****)','')
for i in reversed(range(len(tmpA))):
if(tmpA[i]==' '):
tmpA = tmpA[:-1]
else:
break
#tmpA = a[]
b = re.findall('[0-9a-zA-Z",. ]', tmpA)
for x in b:
c += x
result[a[0]] = c
elif(len(a)==1):
if(a[0]!='' and a[0][-1]==':'):
result[a[0][0:-1]] = None
return result
if __name__ == '__main__':
print("Example:")
print(yaml("name: \"Bob Dylan \"\nchildren: 6\ncoding: \"null\" "))
# 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!")
June 25, 2020