Search Results

Search found 34 results on 2 pages for 'palindrome'.

Page 1/2 | 1 2  | Next Page >

  • java palindrome help

    - by jdbeverly87
    I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome { public static void main(String args[]) { String s=""; int i; int n=s.length(); String str=""; for(i=n-1;i>=0;i--) str=str+s.charAt(i); if(str.equals(s)) System.out.println(s+ " is a palindrome"); else System.out.println(s+ " is not a palindrome"); } }

    Read the article

  • Given an integer, determine if it is a Palindrome in less than O(n) [on hold]

    - by user134235
    There is an O(n) solution to the problem of determining if an integer is a palindrome below. Is it possible to solve this problem in O(log n) or better? static void IsPalindrome(int Number) { int OrignalNum = Number; int Reverse = 0; int Remainder = 0; if (Number > 0) { while (Number > 0) { Remainder = Number % 10; Reverse = Reverse * 10 + Remainder; Number = Number / 10; } if (OrignalNum == Reverse) Console.WriteLine("It is a Palindrome"); else Console.WriteLine("It is not a Palindrome"); } else Console.WriteLine("Enter Number Again"); }

    Read the article

  • Palindrome Golf

    - by Claudiu
    The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python: R=lambda s:all(a==b for a,b in zip(s,reversed(s))) 50 characters. The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.

    Read the article

  • How to check for palindrome using Python logic

    - by DrOnline
    My background is only a 6 month college class in basic C/C++, and I'm trying to convert to Python. I may be talking nonsense, but it seems to me C, at least at my level, is very for-loop intensive. I solve most problems with these loops. And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language. I see on this website: http://hyperpolyglot.org/scripting (serach for "c-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this. I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop? I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site btw. def isPalindrome(n): lst = [int(n) for n in str(n)] l=len(lst) if l==0 || l==1: return True elif len(lst)%2==0: for k in range (l) ##### else: while (k<=((l-1)/2)): if (list[]): ##### for i in range (999, 100, -1): for j in range (999,100, -1): if isPalindrome(i*j): print(i*j) break I'm missing a lot of code here. The five hashes are just reminders for myself. Concrete questions: 1) In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python? 2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python? 3) Does anybody have any good advice, or good websites or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing. 4) Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops... PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

    Read the article

  • Programming challenge: can you code a hello world program as a Palindrome?

    - by Assaf Lavie
    So the puzzle is to write a hello world program in your language of choice, where the program's source file as a string has to be a palindrome. To be clear, the output has to be exactly "Hello, World". Edit: Well, with comments it seems trivial (not that I thought of it myself of course [sigh].. hat tip to cobbal). So new rule: no comments. Edit: I feel kind of bad editing someone else's question to say this, but it will eliminate a lot of non-palindromes that keep popping up, and I'm tired of seeing the same simple mistake over and over. The following is NOT a palindrome: ()() The following IS a palindrome: ())( Brackets, parenthesis, and anything else that must match are a major barrier to palindrome-ing, yes, but that doesn't mean you can ignore them and post non-palindrome answers. Languages represented thus far: C, C++, Bash, elisp, C#, Perl, sh, Windows shell, Java, Common Lisp, Awk, Ruby, Brainfuck, Funge, Python, Machine Language, HQ9+, Assembly, TCL, J, php, Haskell, io, TeX, APL, Javascript, mIRC Script, Basic, Orc, Fortran, Unlambda, Pseudo-code, Befunge, CFML, Lua, INTERCAL, VBScript, HTML, sed, PostScript, GolfScript, REBOL, SQL

    Read the article

  • Write a function that returns the longest palindrome in a given string. e.g "ccddcc" in the string "

    - by Learner
    I thought of a solution but it runs in O(n^2) time Algo 1: Steps: Its a brute force method Have 2 for loops for i = 1 to i less than array.length -1 for j=i+1 to j less than array.length This way you can get substring of every possible combination from the array Have a palindrome function which checks if a string is palindrome so for every substring (i,j) call this function, if it is a palindrome store it in a string variable If you find next palindrome substring and if it is greater than the current one, replace it with current one. Finally your string variable will have the answer Issues: 1. This algo runs in O(n^2) time. Algo 2: Reverse the string and store it in diferent array Now find the largest matching substring between both the array But this too runs in O(n^2) time Can you guys think of an algo which runs in a better time. If possible O(n) time

    Read the article

  • Taking User Input in Java

    - by jdbeverly87
    I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome { public static void main(String args[]) { String s=""; int i; int n=s.length(); String str=""; for(i=n-1;i>=0;i--) str=str+s.charAt(i); if(str.equals(s)) System.out.println(s+ " is a palindrome"); else System.out.println(s+ " is not a palindrome"); } }

    Read the article

  • How to compute palindrome from a stream of characters in sub-linear space/time?

    - by wrick
    I don't even know if a solution exists or not. Here is the problem in detail. You are a program that is accepting an infinitely long stream of characters (for simplicity you can assume characters are either 1 or 0). At any point, I can stop the stream (let's say after N characters were passed through) and ask you if the string received so far is a palindrome or not. How can you do this using less sub-linear space and/or time.

    Read the article

  • Find the closest palindrome number C#

    - by user294837
    Hi All, I am trying to create a console application that reads number from a file all underneath each other like so: 101 9 and then outputs into another file the closest palindrome number. So far what I have is not quite rightm i.e. I don't think I can put the class inside a method which is a bit more Java I was wandering if anyone could help at all? Thanks :) namespace PalidromeC { class Program { static public void Main(string[] args) { #region WriteAnswers try { StreamWriter sw = new StreamWriter("C://Temp/PalindromeAnswers.txt"); sw.WriteLine("Answers"); sw.Close(); }//try catch (Exception e) { Console.WriteLine("Exception: " + e.Message); }//catch #endregion #region ReadFile try { string numbers; StreamReader sr = new StreamReader("C://Temp/Palindrome.txt"); numbers = sr.ReadLine(); while (numbers != null) { Console.WriteLine(numbers); numbers = sr.ReadLine(); }//while sr.Close(); Console.ReadLine(); }//try catch (Exception e) { Console.WriteLine("Exception: " + e.Message); }//catch #endregion NearPalindromeFinder f = new NearPalindromeFinder(); int palindrome = f.findNearPalindrome(n); Console.WriteLine("Nearest Palindrome = " + palindrome); }//main public static void testFindNearestPalindrome(int n) { class NearPalindromeFinder { int findNearPalindrome(int start) { if (testPalindrome(start)) return start; else { int neg = start; int pos = start; for (int i = 0; i < start; i++) { if (testPalindrome(start-i)) { neg = start-i; break; }//if if (testPalindrome(start+i)) { pos = start+i; break; }//if }//for return (start == neg) ? pos : neg; }//else }//findNearPalindrome bool testPalindrome(int start) { if (start == 0 || start == 1) return true; String str = String.valueOf(start); String rev = new if (str.equals(rev)) return true; else return false; }//testPalindrome }//NearPalindromeFinder class }//testFindNearestPalindrome }//Program Class

    Read the article

  • user input question

    - by jdbeverly87
    My program checks to test if a word or phrase is a palindrome (reads the same both backward and forward, ex "racecar"). The issue I'm having is after someone enters in "racecar" getting it to actually test. In the below code, I marked where if I type in "racecar" and run, Java returns the correct answer so I know I'm right there. But what am I missing as far as entering it into the console. I think my code is ok, but maybe I have something missing or in the wrong spot? Not really looking for a new answer unless I'm missing something, but if possible perhaps a pro at this moving my code to the correct area bc I'm stuck! `import java.util.*; public class Palindrome { public static void main(String[] args) { String myInput; Scanner in = new Scanner(System.in); System.out.println("Enter a word or phrase: "); **//this asks user for input but doesn't check for whether or not it is a palindrome** myInput = in.nextLine(); in.close(); System.out.println("You entered: " + myInput); } { String s="racecar"; **//I can type a word here and it works but I need** int i; **//I need it to work where I ask for the input** int n=s.length(); String str=""; for(i=n-1;i>=0;i--) str=str+s.charAt(i); if(str.equals(s)) System.out.println(s+ " is a palindrome"); else System.out.println(s+ " is not a palindrome"); } }` I'm new at programming so I'm hoping what I got is ok. I know the palindrome test works I'm just needing helping having it test thru where I'm entering it into the console. Thanks

    Read the article

  • Count double palindromes in given int sequence

    - by jakubmal
    For a given int sequence check number of double palindromes, where by double palindrome we mean sequence of two same palindromes without break between them. So for example: in 1 0 1 1 0 1 we have 1 0 1 as a palindrome which appears 2 times without a break, in 1 0 1 5 1 0 1 we have 1 0 1 but it's separated (apart from the other palindromes in these sequences) Problem example test data is: 3 12 0 1 1 0 0 1 1 0 0 1 1 0 12 1 0 1 0 1 0 1 0 1 0 1 0 6 3 3 3 3 3 3 with answers 8 0 9 Manacher is obvious for the begging, but I'm not sure what to do next. Any ideas appreciated. Complexity should be below n^2 I guess. EDIT: int is here treated as single element of alphabet

    Read the article

  • Finding Palindromes in an Array

    - by Jack L.
    For this assignemnt, I think that I got it right, but when I submit it online, it doesn't list it as correct even though I checked with Eclipse. The prompt: Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes. My code: public static void main(String[] args) { String[] input = new String[6]; //{"aay", "bee", "cee", "cee", "bee", "aay"} Should return true input[0] = "aay"; input[1] = "bee"; input[2] = "cee"; input[3] = "cee"; input[4] = "bee"; input[5] = "aay"; System.out.println(isPalindrome(input)); } public static boolean isPalindrome(String[] input) { for (int i=0; i<input.length; i++) { // Checks each element if (input[i] != input[input.length-1-i]){ return false; // If a single instance of non-symmetry } } return true; // If symmetrical, only one element, or zero elements } As an example, {"aay", "bee", "cee", "cee", "bee", "aay"} returns true in Eclipse, but Practice-It! says it returns false. What is going on?

    Read the article

  • How to check if the given string is palindrome?

    - by Prakash
    Definition: A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction How to check if the given string is a palindrome? This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C. Looking for solutions in any and all languages possible.

    Read the article

  • regular expression of 0's and 1's

    - by Lopa
    Hello all I got this question which asks me to figure out why is it foolish to write a regular expression for the language that consists of strings of 0's and 1's that are palindromes( they read the same backwards and forwards). part 2 of the question says using any formal mechanism of your choice, show how it is possible to express the language that consists of strings of 0's and 1's that are palindromes?

    Read the article

  • python and palindromes

    - by tekknolagi
    i recently wrote a method to cycle through /usr/share/dict/words and return a list of palindromes using my ispalindrome(x) method here's some of the code...what's wrong with it? it just stalls for 10 minutes and then returns a list of all the words in the file def reverse(a): return a[::-1] def ispalindrome(a): b = reverse(a) if b.lower() == a.lower(): return True else: return False wl = open('/usr/share/dict/words', 'r') wordlist = wl.readlines() wl.close() for x in wordlist: if not ispalindrome(x): wordlist.remove(x) print wordlist

    Read the article

  • Project Euler 4: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 4.  As always, any feedback is welcome. # Euler 4 # http://projecteuler.net/index.php?section=problems&id=4 # Find the largest palindrome made from the product of # two 3-digit numbers. A palindromic number reads the # same both ways. The largest palindrome made from the # product of two 2-digit numbers is 9009 = 91 x 99. # Find the largest palindrome made from the product of # two 3-digit numbers. import time start = time.time() def isPalindrome(s): return s == s[::-1] max = 0 for i in xrange(100, 999): for j in xrange(i, 999): n = i * j; if (isPalindrome(str(n))): if (n > max): max = n print max print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • F# exercise help - Beginner

    - by bobjink
    I hope you can help me with these exercises I have been stuck with. I am not in particular looking for the answers. Tips that help me solve them myself are just as good :) 1. Write a function implode : char list - string so that implode s returns the characters concatenated into a string: let implode (cArray:char list) = List.foldBack (+) 0 cArray;; Error. I am thinking that i need to cast every char to strings before I do the above. I bet however, that there is a much simpler and better solution. 2. Write a function palindrome : string - bool, so that palindrome s returns true if the string s is a palindrome let isIdentical cArray1 cArray2 = (cArray1 = cArray2);; let palinDrome (word:string) = isIdentical(word.ToCharArray(), Array.rev(word.ToCharArray()));; I get the value: val palinDrome : string - (char [] * char [] - bool), which is not what I want. 3. Write a function combinePair : int list - int list so that combinePair xs returns the list with elements from xs combined into pairs. If xs contains an odd number of elements, then the last element is thrown away: I have no idea for this one.

    Read the article

  • python - sys.argv and flag identification

    - by tekknolagi
    when I accept arguments how do I check if two show up at the same time without having a compound conditional i.e. #!/usr/bin/python import random, string import mymodule import sys z = ' '.join(sys.argv[2:]) q = ''.join(sys.argv[3:]) a = ''.join(sys.argv[2:]) s = ' '.join(sys.argv[1:]) flags = sys.argv[1:5] commands = [["-r", "reverse string passed next with no quotes needed."], ["-j", "joins arguments passed into string. no quotes needed."], ["--palindrome", "tests whether arguments passed are palindrome or not. collective."],["--rand","passes random string of 10 digits/letters"]] try: if "-r" in flags: if "-j" in flags: print mymodule.reverse(q) if not "-j" in flags: print mymodule.reverse(z) if "-j" in flags: if not "-r" in flags: print a if "--palindrome" in flags: mymodule.ispalindrome(z) if (not "-r" or not "-j" or not "--palindrome") in flags: mymodule.say(s) if "--rand" in flags: print(''.join([random.choice(string.ascii_letters+"123456789") for f in range(10)])) if not sys.argv[1]: print mymodule.no_arg_error if "--help" in flags: print commands except: print mymodule.no_arg_error i just want to be able to say if "-r" and "-j" in flags in no particular order: do whatever

    Read the article

  • I just learned about C++ functions; can I use if statements on function return values?

    - by Sagistic
    What I am confused on is about the isNumPalindrome() function. It returns a boolean value of either true or false. How am I suppose to use that so I can display if it's a palindrome or not. For ex. if (isNumPalindrome == true) cout << "Your number is a palindrome"; else cout << "your number is not a palindrome."; #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include <iostream> #include <cmath> using namespace std; int askNumber(); bool isNumPalindrome(); int num, pwr; int main() { askNumber(); return 0; } bool isNumPalindrome() { int pwr = 0; if (num < 10) return true; else { while (num / static_cast<int>(pow(10.0, pwr)) >=10) pwr++; while (num >=10) { int tenTopwr = static_cast<int>(pow(10.0, pwr)); if ((num / tenTopwr) != (num% 10)) return false; else { num = num % tenTopwr; num = num / 10; pwr = pwr-2; } } return true; } } int askNumber() { cout << "Enter an integer in order to determine if it is a palindrome: " ; cin >> num; cout << endl; if(isNumPalindrome(num)) { cout << "It is a palindrome." ; cout << endl; } else { cout << "It is not a palindrome." ; cout << endl; } return num; }

    Read the article

  • Vector iterators in for loops, return statements, warning, c++

    - by Crystal
    Had 3 questions regarding a hw assignment for C++. The goal was to create a simple palindrome method. Here is my template for that: #ifndef PALINDROME_H #define PALINDROME_H #include <vector> #include <iostream> #include <cmath> template <class T> static bool palindrome(const std::vector<T> &input) { std::vector<T>::const_iterator it = input.begin(); std::vector<T>::const_reverse_iterator rit = input.rbegin(); for (int i = 0; i < input.size()/2; i++, it++, rit++) { if (!(*it == *rit)) { return false; } } return true; } template <class T> static void showVector(const std::vector<T> &input) { for (std::vector<T>::const_iterator it = input.begin(); it != input.end(); it++) { std::cout << *it << " "; } } #endif Regarding the above code, can you have more than one iterator declared in the first part of the for loop? I tried defining both the "it" and "rit" in the palindrome() method, and I kept on getting an error about needing a "," before rit. But when I cut and paste outside the for loop, no errors from the compiler. (I'm using VS 2008). Second question, I pretty much just brain farted on this one. But is the way I have my return statements in the palindrome() method ok? In my head, I think it works like, once the *it and *rit do not equal each other, then the function returns false, and the method exits at this point. Otherwise if it goes all the way through the for loop, then it returns true at the end. I totally brain farted on how return statements work in if blocks and I tried looking up a good example in my book and I couldn't find one. Finally, I get this warnings: \palindrome.h(14) : warning C4018: '<' : signed/unsigned mismatch Now is that because I run my for loop until (i < input.size()/2) and the compiler is telling me that input can be negative? Thanks!

    Read the article

  • I just learned about C++ functions, can i use if statements onto functions?

    - by Sagistic
    What I am confused on is about the isNumPalindrome() function. It returns a boolean value of either true or false. How am I suppose to use that so I can display if its a palindrome or not. For ex. If (isNumPalindrome = true) cout "Your number is a palindrome" else "your number is not a palindrome." #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include <iostream> #include <cmath> using namespace std; int askNumber(); bool isNumPalindrome(); int num, pwr; int main() { askNumber(); isNumPalindrome(); return 0; } bool isNumPalindrome() { int pwr = 0; if (num < 10) return true; else { while (num / static_cast<int>(pow(10.0, pwr)) >=10) pwr++; while (num >=10) { int tenTopwr = static_cast<int>(pow(10.0, pwr)); if ((num / tenTopwr) != (num% 10)) return false; else { num = num % tenTopwr; num = num / 10; pwr = pwr-2; } } return true; } } int askNumber() { cout << "Enter an integer in order to determine if it is a palindrome: " ; cin >> num; cout << endl; return num; }

    Read the article

  • Change Variable back to original value after Regex matching.

    - by Brad Johansen
    I just "finished" expanding my Palindrome Tester, made in C#. To allow for phrases I added a simple regex match for all non-alphanumeric characters. At the end of the program it states " is(n't) a palindrome." But now with the regex it prints the no spaces/punctuation version of it. I would like to be able to print the original user input. How do I do that? Here is my program: http://gist.github.com/384565

    Read the article

  • color letters in a div

    - by Growler
    I've created a palindrome checker. I want to take it one step further and show the letters being compared as it is being checked. HTML: <p id="typing"></p> <input type="text" id="textBox" onkeyup="pal(this.value);" value="" /> <div id="response"></div> <hr> <div id="palindromeRun"></div> JS: To do this, I run the recursive check... Then if it is a palindrome, I run colorLetters(), which I'm trying to highlight in green each letter as it is being checked. Right now it is just rewriting palindromeRun's HTML with the first letter. I know this is because of the way I'm resetting its HTML. I don't know how to just grab the first and last letter, change only those letters' css, then increment i and j on the next setTimeout loop. var timeout2 = null; function pal (input) { var str = input.replace(/\s/g, ''); var str2 = str.replace(/\W/, ''); if (checkPal(str2, 0, str2.length-1)) { $("#textBox").css({"color" : "green"}); $("#response").html(input + " is a palindrome"); $("#palindromeRun").html(input); colorLetters(str2, 0, str2.length-1); } else { $("#textBox").css({"color" : "red"}); $("#response").html(input + " is not a palindrome"); } if (input.length <= 0) { $("#response").html(""); $("#textBox").css({"color" : "black"}); } } function checkPal (input, i, j) { if (input.length <= 1) { return false; } if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) { return true; } else { if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) { return checkPal(input, ++i, --j); } else { return false; } } } function colorLetters(myinput, i, j) { if (timeout2 == null) { timeout2 = setTimeout(function () { console.log("called"); var firstLetter = $("#palindromeRun").html(myinput.charAt(i)) var secondLetter = $("#palindromeRun").html(myinput.charAt(j)) $(firstLetter).css({"color" : "red"}); $(secondLetter).css({"color" : "green"}); i++; j++; timeout2=null; }, 1000); } } Secondary: If possible, I'd just like to have it colors the letters as the user is typing... I realize this will require a setTimeout on each keyup, but also am not sure how to write this.

    Read the article

1 2  | Next Page >