Could you give an example of for loops failing? It sounds like you were just using them wrong, and if you learn the proper way you'll start to love them. Below I will show incremental improvement over your current code
Remove two unnecessary lines, use += operator
- Code: Select all
while x<max:
if statement[x] not in key:
key += statement[x]
x += 1
Switched to for loop; this will not ever get an index error (no indexing, yay!) and won't get a memory error unless
key grows too large (unlikely). This gets rid of three lines, one in the body of the loop, the
x indexing variable and the
max variable
- Code: Select all
for char in statement:
if char not in key:
key += char
We like for loops because we can know exactly what the loop is going over by just looking at the head (not checking the body to see how the counter gets incremented, by one or two or something else) and when we look at the body we're not bothered with the details in the header.
Appending to a string in a loop in Python is not guaranteed to be efficient, and so it is considered bad style to do so. Building a list and then using str.join() is preferred. Here is a complete example
- Code: Select all
statement = "xyz123<><><><>x3"
key_contents = []
for char in statement:
if char not in key_contents:
key_contents.append(char)
print ("key is %s" % ''.join(key_contents))
print ("statement is %s" % statement)
If order doesn't matter, you can skip the loop and let Python do it for you
- Code: Select all
key = ''.join(set(statement))
You could use sorted() on the set, too.