LordNoob - 5 months ago 12

Python Question

I made this algorithm in Python to sort a list of names alphabetically and I can't figure out why it doesn't work properly when given this list:

`for a in range(0,len(V)):`

for b in range(a,len(V)):

equal=True

for N in range(0,min(len(V[a]),len(V[b]))):

if ord(V[b][N])<ord(V[a][N]):

V[b],V[a]=V[a],V[b]

equal=False

break

if equal==True and len(V[a])>len(V[b]):

V[b],V[a]=V[a],V[b]

print(V)

Answer

Ah, I found the problem. Try dry running your code on these two examples:

```
V = ["ABCZ", "XYZA"]
V = ["ABCE", "XYZF"]
```

For the first example, your if condition isn't triggered until the last characters, 'Z'(from "ABCZ") and 'A'(from "XYZA") are compared.

```
if ord(V[b][N])<ord(V[a][N]):
```

This wrongly swaps the two strings.