21
loading...
This website collects cookies to deliver better user experience
a=[]
for i in range(0,4):
try:
a.append(ord(input("Please enter a character ")))
except:
print("Error!")
a=sorted(a)
#The sorted() method sorts the list and returns the sorted list
# This is an inbuilt function to sort the list. You can also use insertion sort.
for i in range(0,len(a)):
a[i]=chr(a[i])
print(a)
Please enter a character a
Please enter a character d
Please enter a character b
Please enter a character h
['a', 'b', 'd', 'h']
Note- The inbuilt sorted() method is so nice, that it will directly sort the values in alphabetical order even if we do not convert them into integers! Try removing the chr() and ord() functions and running the code.
Please enter a character 123
Error!
Please enter a character abc
Error!
Please enter a character -2
Error!
Please enter a character 1a
Error!
[]
[1, 2, [1, 2], [1, 2, [1, 2]], [1, 2, [1, 2], [1, 2, [1, 2]]]]
a=[1,2]
for i in range(0,3):
a.append(a)
print(a)
[1, 2, [...], [...], [...]]
a=[1,2]
for i in range(0,3):
temp=a
a.append(temp)
print(a)
[1, 2, [...], [...], [...]]
temp=a
and append temp,, then we are doing the same thing as before! The solution is using the copy() method.a=[1,2]
for i in range(0,3):
temp=a.copy()
a.append(temp)
print(a)
[1, 2, [1, 2], [1, 2, [1, 2]], [1, 2, [1, 2], [1, 2, [1, 2]]]]
In: [[1,2,3],4,[5,6],[7,[8,9],10],[11,12,13,14],15]
Out: [[3, 2, 1], 4, [6, 5], [10, [8, 9], 7], [14, 13, 12, 11], 15]