palindrome

Peter Otten __peter__ at web.de
Tue Nov 17 04:31:37 EST 2015


Seymore4Head wrote:

> http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
> 
> Here is my answers.  What would make it better?

1. Break the code into functions: one to generate a random string (the 
desired length could be a parameter) and one to check if the string is a 
palindrome. With that the loop will become

tries = 0
while True:
    tries += 1
    candidate = random_string(length=4)
    print(candidate)
    if is_palindrome(candidate):
        break
print(tries, "tries")

2. If you plan to reuse these functions put the above code in a function 
(let's call it main), too, that you invoke with

if __name__ == "__main__":
    main()

to avoid that the code is executed when you import the module instead of 
running it as a script.

3. For better readability add spaces around operators. There is a tool 
called pep8 that will point out where you are breaking the standard Python 
coding conventions.

4. Minor rewrites:
4.1 Can you rewrite the while loop as a for loop?

for tries in ...:
   ...

Hint 1: you can put a while loop into a generator
Hint 2: there's a ready-made solution in itertools.

4.2 Can you build the random string using a generator expression and 
"".join(...)?

> import random
> str1=""
> letcount=4
> count=0
> abc='abcdefghijklmnopqrstuvwxyz'
> while True:
>     for i in range(letcount):
>         a=random.choice(abc)
>         str1+=a
>     print str1
>     count+=1
>     if str1==str1[::-1]:
>         break
>     else:
>         str1=""
> print "Tries= ",count
> print str1





More information about the Python-list mailing list