# isPalindrome: string -> bool # return True if and only if the input string is a palindrome def isPalindrome(s): index1 = 0 index2 = len(s) - 1 while index1 < index2: if s[index1] != s[index2]: return False index1 += 1 index2 -= 1 return True # noneDivisible: int, [int] -> bool # return True if and only if the first input is not divisible by any number in the second input def noneDivisible(n, nums): for x in nums: if n % x == 0: return False return True # primesBelow: int -> [int] # return a list of primes less than the input integer # note, there are many ways to make this function run MUCH faster, but # we don't yet care about efficiency in this class (just getting a working program) def primesBelow(cap): if cap <= 2: return [] primesSoFar = [2] for num in xrange(3, cap, 2): # check only odd numbers if noneDivisible(num, primesSoFar): primesSoFar.append(num) return primesSoFar # palindomePrimesBelow: int -> [int] # return a list of primes below the given input integer which are also palindromes def palindromePrimesBelow(cap): return [x for x in primesBelow(cap) if isPalindrome(str(x))] if __name__ == "__main__": from unittest import test test(True, isPalindrome('abba')) test(True, isPalindrome('aba')) test(True, isPalindrome('abananaba')) test(False, isPalindrome('abxyba')) test(False, isPalindrome('xabbay')) test(True, noneDivisible(9, [2,4,6,8])) test(False, noneDivisible(90, [2,5,9,11])) test(True, noneDivisible(13, [2,3,5,7,11])) test([2], primesBelow(3)) test([2,3,5,7], primesBelow(8)) test([2,3,5], primesBelow(7)) test([2,3,5,7,11,13,17,19], primesBelow(20)) test([2,3,5,7], palindromePrimesBelow(10)) test([2,3,5,7], palindromePrimesBelow(11)) test([2,3,5,7,11], palindromePrimesBelow(100)) test([2,3,5,7,11,101,131,151,181,191,313,353,373,383,727,757,787,797,919,929,10301], palindromePrimesBelow(10302)) print "My tests pass!"
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question