aboutsummaryrefslogtreecommitdiff
path: root/challenge-288/paulo-custodio/python/ch-1.py
diff options
context:
space:
mode:
authorPaulo Custodio <pauloscustodio@gmail.com>2024-09-23 21:44:11 +0100
committerPaulo Custodio <pauloscustodio@gmail.com>2024-09-23 21:44:11 +0100
commitbd556209a6cc804912bb6c90aa2c5f8f99faef60 (patch)
treedeee9909eb9a454c2eecef256e9d27910306e790 /challenge-288/paulo-custodio/python/ch-1.py
parentd98ecd4f387132f9c876a3226127f1bb664f3e31 (diff)
downloadperlweeklychallenge-club-bd556209a6cc804912bb6c90aa2c5f8f99faef60.tar.gz
perlweeklychallenge-club-bd556209a6cc804912bb6c90aa2c5f8f99faef60.tar.bz2
perlweeklychallenge-club-bd556209a6cc804912bb6c90aa2c5f8f99faef60.zip
Add Python solution to challenge 288
Diffstat (limited to 'challenge-288/paulo-custodio/python/ch-1.py')
-rw-r--r--challenge-288/paulo-custodio/python/ch-1.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/challenge-288/paulo-custodio/python/ch-1.py b/challenge-288/paulo-custodio/python/ch-1.py
new file mode 100644
index 0000000000..168d6ce085
--- /dev/null
+++ b/challenge-288/paulo-custodio/python/ch-1.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+
+# Challenge 288
+#
+# Task 1: Closest Palindrome
+# Submitted by: Mohammad Sajid Anwar
+# You are given a string, $str, which is an integer.
+#
+# Write a script to find out the closest palindrome, not including itself.
+# If there are more than one then return the smallest.
+#
+# The closest is defined as the absolute difference minimized between two
+# integers.
+#
+# Example 1
+# Input: $str = "123"
+# Output: "121"
+# Example 2
+# Input: $str = "2"
+# Output: "1"
+#
+# There are two closest palindrome "1" and "3". Therefore we return the smallest "1".
+# Example 3
+# Input: $str = "1400"
+# Output: "1441"
+# Example 4
+# Input: $str = "1001"
+# Output: "999"
+
+import sys
+
+def is_palindrome(n):
+ return str(n) == str(n)[::-1]
+
+def next_palindrome(n):
+ out = None
+ i = 1
+ while out is None or i <= n:
+ t = n-i
+ if t >= 0 and is_palindrome(t):
+ if out is None:
+ out = t
+ elif abs(out-n) > abs(t-n):
+ out = t
+ t = n+i
+ if is_palindrome(t):
+ if out is None:
+ out = t
+ elif abs(out-n) > abs(t-n):
+ out = t
+ i += 1
+ return out
+
+n = int(sys.argv[1])
+print(next_palindrome(n))