JavaScript
x
8
1
string = "Python, program!"
2
3
result = []
4
for x in string:
5
if x not in result and x.isalnum():
6
result.append(x)
7
print(result)
8
This program makes it so if a repeat letter is used twice in a string, it’ll appear only once in the list. In this case, the string “Hello, world!” will appear as
[‘H’, ‘e’, ‘l’, ‘o’, ‘w’, ‘r’, ‘d’]
My question is, how would I go about using a while loop instead of a for loop to achieve the same result? I know there’s really no need to change a perfectly good for loop into a while loop but I would still like to know.
Advertisement
Answer
Here is one way you could do it in a while loop:
JavaScript
1
11
11
1
text = "Python, program!"
2
3
text = text[::-1] # Reverse string
4
result = []
5
while text:
6
if text[-1] not in result:
7
result.append(text[-1])
8
text = text[:-1]
9
10
print(result)
11