- isPalindromicWing [10pts]
A number is a "palindromic wing" if it is of the form xxxxxYxxxxx, so the
x's form the "wings" and the Y is the "body" (and where x and Y are single
(non-negative) digits, and the two wings have the same non-zero length).
With this in mind, write the function isPalindromicWing(n), that takes an
integer n and returns True if it is a palindromic wing and False otherwise.
Hint: we found it useful to convert numbers to strings in part of our
sample solution, though that certainly is not required here. Here is a sample test function for you:def testIsPalindromicWing():
print "Testing isPalindromicWing()...",
assert(isPalindromicWing(2223222) == True)
assert(isPalindromicWing(2232322) == False)
assert(isPalindromicWing(2233322) == False)
assert(isPalindromicWing(22) == False) # too small
assert(isPalindromicWing(2222) == False) # must have odd # of digits (right?)
print "Passed!"
- nthPalindromicWingPrime [15pts]
A number is a palindromic wing prime if it is both a palindromic wing and
prime. Here are the first several palindromic wing primes:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929,
11311, 11411, 33533, 77377, 77477, 77977, 1114111, 1117111, 3331333,
3337333, 7772777, 7774777, 7778777, 111181111, 111191111, 777767777,
77777677777,...
With this in mind, write nthPalindromicWingPrime the naive
way -- that is, just as we wrote nthPrime in the course notes. This should work just fine
for small numbers n. Here is a sample test function for you:def testNthPalindromicWingPrime():
print "Testing nthPalindromicWingPrime()...",
assert(nthPalindromicWingPrime(0) == 101)
assert(nthPalindromicWingPrime(1) == 131)
assert(nthPalindromicWingPrime(2) == 151)
assert(nthPalindromicWingPrime(3) == 181)
assert(nthPalindromicWingPrime(4) == 191)
assert(nthPalindromicWingPrime(5) == 313)
assert(nthPalindromicWingPrime(15) == 11311)
print "Passed!"
- fasterNthPalindromicWingPrime [25pts]
Unfortunately, the naive algorithm in the previous solution does not run
fast enough for anything but the smallest n. And so here you must fix
that and write fasterNthPalindromicWingPrime(n), that produces the same
results as nthPalindromicWingPrime(n), only faster. The key: do not
check every possible integer to see if it is a palindromic wing and if it is
prime. Instead, think of a way to generate the palindromic wings in
order... Here is a sample test function for you (and this test
function should run with nearly no delay):def testFasterNthPalindromicWingPrime():
print "Testing fasterNthPalindromicWingPrime()...",
assert(fasterNthPalindromicWingPrime(29) == 111191111)
assert(fasterNthPalindromicWingPrime(30) == 777767777)
assert(fasterNthPalindromicWingPrime(31) == 77777677777)
print "Passed!"