python,recursion,primes,palindrome

The general approach to writing a recursive function: Handle the simple cases. Simplify the problem and call yourself again. For a function that returns true/false, there will be 3 conditions: you know the answer is true, you know the answer is false, or the problem is still too complicated. Take...

The reason is that you don't scope your variables correctly. You call cubepal and cubepal initializes i=3 now when you perform the recursive call, i is a local variable equal to 3. def cubepal(i): if str(i**3)==str(i**3)[::-1]: return i**3 else: return cubepal(i+1) and call it with cubepal(3). Although for such cases,...

c++,linked-list,boolean,nodes,palindrome

You need to delete one from the left side and one from the right side, and also consider the case of odd number of elements: n.Delete_First(); if (!n.Is_Empty()) n.Delete_Last(); ...

if ( !($i % $j) and length($i/$j)==3) { .. } instead of if ( !($i % $j) && (length $j == 3) ) as you want to check whether $i/$j has three digits, not $j which goes anyway from 100 to 999. As a side-note, if (checkpal($i)) can be replaced...

java,string,algorithm,palindrome

There's no need to be doing difficult loops like that. Something like this will work: boolean isPalindrome(String s) { for (int i = 0; i < s.length()/2; i++) { if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false; } return true; } ...

This should do what you want: public static void Upper(char[] array, string input) { Console.WriteLine("Reverse array :"); Console.Write(new string(input.AsEnumerable().Reverse().ToArray())); } Rather than worrying about the lowercased array, you can simply reverse the original input and make a new string out of the reversed characters....

This reverses num by iterating over the digits of num. For each digit it adds it to the right of rev. digit = num%10; // Find the 1s digit of num rev = (rev*10) + digit; // Push digit to the right of rev num = num/10; // Remove the...

Assuming that I understand your problem, you are going about this in an inefficent way. Here is how I would do this: String toPalindrome(String str){ StringBuilder reverse = new StringBuilder(str).reverse(); for(int idx = 0; idx < str.size()/2; idx++) if(str.getCharAt(idx) < reverse.getCharAt(idx)) reverse.setCharAt(idx, str.getCharAt(idx)); return reverse.subString(0,str.size()/2) + reverse.reverse().subString(str.size()/2); } Aside from...

variable X is the length of the original string. Due to indexes starting at 0, that means the index of the final character is (x-1). Therefore the for loop is initialized with the variable i = x-1, in order to make the loop start on the last character of the...

Add: sentence.gsub!/\W/, '' just after sentence.downcase! Also note, that your method has a side effect: string = 'NeverOddOrEven' p palindrome?(string) #=> true p string #=> neveroddoreven To fix this, change first two lines to: sentence = sentence.downcase.gsub /\W/, '' ...

methods,palindrome,stack-overflow

Complementing Ransom's point, the comparison s.charAt(n-1) == s1.charAt(n-1) will always return true. Try to construct the recursive algorithm like this: check(s){ // insert code: if length is 0 or 1, always return true; if(s.chatAt(0) == s.charAt(s.length-1)) return check(s.subString(1,length-1)) } The key points are: For a recursive algorithm, you cannot put...

At a minimum, you seem to have forgotten to initialize the variable "times". In terms of the actual algorithm, keep in mind that to make the letters match, you can decrement either (or both) of them. I don't think you handle all cases properly....

You can write a effective program by using a string instead of long. I have used it. Here I am giving the code: #include<iostream> using namespace std; #include<string.h> int main() { char s[80]; //you can take any big index instead 80 gets(s); int a=0,l=strlen(s); for(int i=0;i<l;i++) { if(s[i]==s[l-i]) { a++;...

There are efficient algorithms for computing the longest palindromic substring by reversing the original substring. For example, the following: 1) create a generalized string S1#S2$ which takes O(n) 1) construct a suffix array O(n) -> not trivial, but there are easy O(nlogn) and O(nlog^2n) algorithms 2) construct an lcp array...

Change this statement if(a==b) to if ( strcmp( a, b ) == 0 ) Otherwise you are comparing addresses of the first elements of the arrays. Also you need to include header <string.h>. Function main shall have return type int. Change this statement scanf("%s",&a); to scanf( "%s", a); Take into...

python,string,performance,palindrome

Because Python code is only compiled to bytecode, which is then interpreted. That's going to be a lot slower than creating a new reversed string in C code, then comparing the string to another string with more C code. Note that both algorithms are essentially O(N) complexity; the Python code...

recursion,lisp,common-lisp,palindrome

Here is a recursive, single function palindrome: (defun palindrome(l) (cond ((null l) nil) (t (append (list (car l)) (palindrome (cdr l)) (list (car l)))))) The recursion is structured in this way: make a palindrome of the rest of the list, and put at the beginning and at the end the...

numbers,scheme,racket,palindrome

The error reported occurs in the check procedure. All those references to the variables called c and x will fail, what are those variables supposed to be? where do they come from? Remember: in Scheme = is used for comparing two numbers, not for assignment. There are other problems. The...

java,debugging,recursion,palindrome

It's because you stop the recursion if the length is 2. Wait until it's less than 2 to stop. So change this: if (str.length() <= 2) return true; to this: if (str.length() < 2) return true; The problem then is that it will crash it in the earlier checks, so...

java,algorithm,numbers,palindrome,time-limiting

Maybe not "the very best way", but works fine. And it does the job in less than 1 sec (depending of your hardware). I've tested here. import java.util.Scanner; public class HelloWorld{ public static void main(String []args){ Scanner read = new Scanner(System.in); System.out.println("Enter values as much as you want (lower than...

The error is here: if ( string[j] != string [k-j] ){ The second character should be string[k-j-1]. For instance, when j = 0, you should compare with string[k-1] to compare the first and last characters of the string. Also, you have a memory leak. At the bottom of the outer...

Your helper method checkPalindrome seems correct. Your thinking is also correct (append characters until the result is a palindrome), but the way you're going about it is wrong. To reiterate: Our logic is, while our result is not a palindrome, take the next character from the end (moving towards the...

You confused the pre-increment and post-increment operators. In C, x++ means "increment the value of x after this statement" and ++x means "first increment the value of x and then execute the statement." The following code should work: int is_palindrome(char str[]) { int j, top = -1; char stk_item, s[30];...

If I understand your task correctly, the following should do the trick: def reverse(num): return num[::-1] def is_pal(num): return num == reverse(num) inp = input("Enter a positive number:") if is_pal(inp): print("{} is a palindrome".format(inp)) else: print("Generating...") while not is_pal(inp): inp = str(int(inp) + int(reverse(inp))) print(inp) The variable inp is always...

You aren't returning the result of the function. replace : if word[0] == word[-1]: isPalindrome(word[1:-1]) with if word[0] == word[-1]: return isPalindrome(word[1:-1]) ...

If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works). Here's an example: import javax.swing.JOptionPane; public class Palindromechkr { public static void main(String[] args) { //Declare Variables String Palin, input, Rinput = ""; int...

arrays,algorithm,perl,bioinformatics,palindrome

Take a look at perlretut - Recursive patterns. It includes an example of testing for palindromes that you can no doubt adapt to your purposes, whatever they are exactly: use strict; use warnings; my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix; for $s ( "saippuakauppias", "A...

Your reverseCurrentList rule is missing a base clause, so it never succeeds. The recursive invocation continues taking items from the list until the list is empty, at which point [H|T] no longer unifies, so the rule fails. Add this second clause to your program: reverseCurrentList([], []). ...

By initializing the local variable: boolean pali = false; // Default value before you know it is a palindrome ...

java,string,algorithm,palindrome

This problem can be solved by applying the Longest Common Subsequence algorithm (LCS). LCS basically solves the following problem: Given two strings a and b, what is the longest string c that is a subsequence of both a and b? A subsequence of a string is a sequence of characters...

list,prolog,palindrome,dcg,difference-lists

Use a definite clause grammar! palindrome --> []. palindrome --> [_]. palindrome --> [X],palindrome,[X]. As an alternative we could also write: palindrome --> [] | [_] | [X],palindrome,[X]. dcg offer an automatic way of using difference-lists. On the prolog-toplevel we use the builtin listing/1 to get the code the DCG...

isPalindrome is a member function of PalindromeDetector, but you are trying to call it from within a PalindromeDetectorTest method. If the test class derived from PalindromeDetector this would work, but there isn't (and almost certainly shouldn't be) any such relationship between them. You need a PalindromeDetector object to call the...

but wish to ignore white space and commas You don't need to put \d in your regex. Just replace the spaces or commas with empty string. string = string.gsub(/[\s,]/ ,"") The above gsub command would remove all the spaces or commas. [\s,] character class which matches a space or...

palindrome,coq,theorem-proving

This is a nice example where "direct" induction does not work well at all because you don't directly make the recursive call on the tail, but on part of the tail. In such cases, I usually advice to state your lemma with the length of the list, not on the...

python,sorting,python-3.x,palindrome

As we traverse B, we can use a set to keep track of what elements have an odd number so far (using a set here is much faster than a list): odds = set() for i in B: if i in odds: odds.remove(i) else: odds.add(i) Then if the length of...

You can find it easily by searching the string S in S+S. The first index you find is the cycle number you want (may be the entire string). In python it would be something like: In [1]: s = "abaabaabaabaaba" In [2]: print (s+s).index(s, 1) 3 The 1 is there...

In Logic 1, try if i<int(length/2): instead of if i<int((length/2+1)): In Logic 2, even removing i+=1 gives the correct result: if n[i] == n[-i-1]: pass else: break You can also use the following code for the same: def reverse(text): if len(text) <= 1: return text return reverse(text[1:]) + text[0] n...

Why does it have to be i/2? It does not have to be this way: i would work too, but it would not be optimal. If you have checked all character pairs going at it from both ends, and the letters are the same up to the middle of...

c++,algorithm,search,palindrome

The algorithms is correct, or at least it gets quite close. There are minor technical issues. In step 4. one should save the proposition of a solution if it's better than the current one, and in step 7. return it, or say it was impossible to make a palindrome. The...

You might try this function: def is_palindrome(text): return text[:len(text)//2] == text[:(len(text)-1)//2:-1] Here is example usage for reference: >>> is_palindrome('') True >>> is_palindrome('a') True >>> is_palindrome('b') True >>> is_palindrome('aa') True >>> is_palindrome('ab') False >>> is_palindrome('ba') False >>> is_palindrome('bb') True >>> is_palindrome('aaa') True >>> is_palindrome('aab') False >>> is_palindrome('aba') True ...

c++,bit-manipulation,palindrome

You can use strtol or any other function #include <iostream> int main(int argc, _TCHAR* argv[]) { long x; std::string str; std::cin >> str; char * pEnd; x = strtol(str.c_str(), &pEnd, 2); std::cout << x << std::endl; return 0; } ...

list,prolog,reverse,palindrome

Why not pal([]). pal([_]). pal(Pal) :- append([H|T], [H], Pal), pal(T). ...

c++,function,extract,palindrome,digit

There are many ways to solve this. I like most the solution that builds the mirror number and checks whether it is identical to the original (even though, it is arguably not the most efficient way). The code should be something like: bool isPalindrom(int n) { int original = n;...

java,for-loop,methods,palindrome,perfect-numbers

The idea for how to solve perfect numbers is incorrect in the original and this "fix". public static void printWordBackwards (String s) { //Please note that this is greater than or equal to not less than or equal to. //for (int i = s.length()-1 ; i<= 0 ; i--) ORIGINAL...

As it has been said before, It is easier to prove this theorem using the length of the list : Theorem rev_pal_aux {X:Type} : forall (l:list X) (n:nat) , length l<= n -> l = rev l -> pal l. Then you can start an induction on n. The key...

In the given year, there will be only one palindromic date. Hence, to find previous palindromic date, you need to decrement the year and convert it to palindromic date. Example: for 2030, valid month and day will be 03 and 02 which will lead to 2030/03/02. So, it must be...

c,segmentation-fault,palindrome

The way to use large arrays is to allocate memory on the heap not on the stack. I have done this in your program to show you. Instead of doing that in main I lazily moved input[] to be a global var. You can't do that in find_palin because of...

java,methods,boolean,palindrome,arrays

There were some issues in the main-method, for example the char-array was never updated and the palindrome-method was far to complicated, here is the working version: public static void main(String args[]) { System.out.print("#Enter word: "); String word = BIO.getString(); while (!word.equals("END")) { char[] letters = word.toLowerCase().toCharArray(); if (isItPalindrome(letters) == true)...

Your word-searching function is basically okay, but there are two points: You scan beyond the buffer, because the null terminator isn't a space. And you don't catch white-space characters other than space, which will not catch the new-line character the fgets leaves at the end of the line. The solution...

A straightforward approach begins by looking at each of the O(n3) subsequences and checking to see if it's a palindrome. Once we know which subsequences are palindromic, we can do dynamic programming in O(n2) time to find the minimal number of consecutive subsequences that cover the whole sequence. For the...

Your program works as expected. (At least how I expect it to work; "taco cat" does not equal "tac ocat" so it should not be regarded as a palintrome.) If you want to disregard from spaces, you could do word = word.replaceAll("\\s", ""); right after reading the input string....

java,java.util.scanner,do-while,palindrome

Move the declaration of backward into the loop body (so it resets on each iteration), String word = "", exit = ""; int length; do { String backword = ""; However, it's a better idea to use StringBuilder for String concatenation but I'll leave optimization as an exercise for the...

You have several bugs. First, you need to give the input to the Palindrome class. Second, when you reverse the input using stack, you push the index on the stack, not the character. Third, it's not a good practice to do everything une constructor. Palindrome class doesn't need to know...

java,performance,optimization,palindrome

Your solution is quadratic, this is definitely not what that site is looking for, you can do much better. Consider this. If the first and last characters are not equal to each other, then one of them is the answer. If they are equal, the same logic can be applied...

c++,algorithm,recursion,dynamic-programming,palindrome

For this case: if(S[x] == S[y]) ret = solve(x+1,y-1,val+2 - (x==y)); it should be: if(S[x] == S[y]) ret = max(solve(x + 1, y - 1, val + 2 - (x==y)), max(solve(x + 1, y, 0),solve(x, y - 1, 0))); Because, in case you cannot create a substring from x to...

Change this for(num>0;num<=lim;num++) to this for(num=0;num<=lim;num++) in order to initialize num. then actually you need to make more changes. This should work: #include<iostream> using namespace std; bool checkPalindrom(int); int main() { int num; int lim; cout << "Insert limit number: "; cin >> lim; cout << "Palindrome numbers within the...

java,for-loop,palindrome,charat,off-by-one

the for loop should be something like this for (reverseCountdown = stringLength-1; reverseCountdown >=0; reverseCountdown--){ //have changed the loop variables here reverse += forward.charAt(reverseCountdown); } the ; at the end of for loop was causing the for loop to run on empty statement(only ; is considered as empty statement). remove...

java,string,for-loop,palindrome,charat

You're setting the value of last to one character at a time. You're basically resetting it every time, which is why it ends on the last character of the reversed string (which is the first character). Change it to last = String.valueOf(output.charAt(k)) + last;...

java,methods,compilation,palindrome

You need a return value in the second method. It needs to return true or false. Return isPalindrome. You should ideally use SublimeText or Eclipse. That way it'll debug your text realtime with JAVAC, and tell you where your errors are. It's much easier to troubleshoot realtime. import java.util.Scanner; public...

I spotted an error in your code here with the wrong limit for x length=strlen(reading); while(x<=length){ so I made quite a few changes to the way the probem is tackled rather than figuring out what other limits you might be breaking. I have written output to stdout rather than to...

Here are my results so far: L=1-7: "aabbaba" -> "aabbabaa" (or the mirror, confirming your result) L=8: "aaabbaba" -> "aaabbabaa" (or the mirror) L=9: "aaaabbbaba" -> "aaaabbbabaa" (or the mirror) All futher L can be solved just by prefixing an additional a to the starting string....

arrays,ruby,null,palindrome,fixnum

You have a bunch of nils that you are adding to your array. Max can't work with nils - it compares each element. Just add palindromes << palintest(i*j) if palintest(i*j) But really might read better like: def palindrome?(number) num = number.to_s len = num.length num[(len/2).floor] = '' unless len.even? num[0..(len/2)-1]...

javascript,function,slice,palindrome

Let's pop open the console and take a look! > var s = 'abcde' "abcde" > s[0] "a" > s.slice(-1) "e" > s.slice(-1)[0] "e" > s[1] "b" > s.slice(-1 - 1) "de" > s.slice(-1 - 1)[0] "d" As I hope you can see by now, slicing with a negative number...