string = "Python, program!"
result = []
for x in string:
if x not in result and x.isalnum():
result.append(x)
print(result)
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.
CodePudding user response:
Here is one way you could do it in a while loop:
text = "Python, program!"
text = text[::-1] # Reverse string
result = []
while text:
if text[-1] not in result:
result.append(text[-1])
text = text[:-1]
print(result)
CodePudding user response:
There are several ways of doing this.
Emulating the for
loop
This is what a for
loop does under the hood:
it = iter(string)
while True:
try:
# attempt to get next element
x = next(it)
except StopIteration:
# no next element => get out of the loop
break
if x not in result and x.isalnum():
result.append(x)
The C way
You can simply index into your string:
i = 0
while i < len(string):
x = string[i]
if x not in result and x.isalnum():
result.append(x)
i = 1
This is analogous to how one would iterate over a container in the C language - by indexing into it and incrementing the index afterwards:
for (int i = 0; i < strlen(string); i )
printf("%c", string[i]);
However, indexing doesn't always work because some objects that one can iterate over don't support indexing:
a_generator = (i for i in range(5))
for elem in a_generator:
print(a) # works fine
a_generator = (i for i in range(5))
a_generator[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable