Write a function, returning a boolean value, that identifies whether or not a string is a palindrome

Write a function, returning a boolean value, that identifies whether or not a string is a palindrome.

I'll start.

public static boolean palindrome(String teststring){
char[] a = teststring.toLowerCase().toCharArray();

for(int i = 0; i < a.length; i++){
char letter = a[i];
char letter2 = a[a.length - (i+1)];
if(letter != letter2){
return false;
}
}
return true;
}

Other urls found in this thread:

hackage.haskell.org/package/vector-algorithms-0.7.0.1
hackage.haskell.org/package/discrimination-0.2.1/docs/Data-Discrimination-Sorting.html#v:sort
hackage.haskell.org/package/vector-algorithms-0.7.0.1/docs/Data-Vector-Algorithms-Radix.html
twitter.com/NSFWRedditImage

#include
(...)
IsPolidrome(text);


or using or import or whatever out there you use.

>java

I'm not doing your high school introduction to computer science assignment for you user.

class Word {
static boolean isPalindrome(String str) {
String reverse = new StringBuilder(str).reverse().toString();
return str.compareToIgnoreCase(reverse) == 0;
}
}

def isPalindrome(checkword):
if checkword[::-1].upper() == checkword.upper():
return True
else:
return False

print(isPalindrome("chocolate"))
print(isPalindrome("Kek"))

Man, I live Python.

*love
>wtf

bool is_palindrome(const char *s)
{
size_t i, j;
size_t len = strlen(s);

if (len == 0) {
return false;
}
if (len == 1) {
return true;
}

for (i = 0, j = len-1; i < len/2; ++i, --j) {
if (s[i] != s[j]) {
return false;
}
}

return true;
}

>i < a.length
What's the fucking point if you only need to do half of the word

>if condition:
>return True
>else:
>return False

hmmmmmmmmm

>returning a boolean value

>python """programmers"""

You can also return a condition fuckwit

Func _IsPalindrome($s_Str)
$s_Str = StringLower($s_Str)
If $s_Str = StringReverse($s_Str) Then Return True
Return False
EndFunc

>muh minimalistic code
Better code readability and no difference in speed, turd smoker.

But since you're probably a Pajeet javafag or unemployed, you wouldn't understand it.

Only because you don't define the return type beforehand

isPalindrome s = s == reverse s


Haskell

>tfw to intelligent to use strings
2 int main(void){
3 puts("Performing five_digit_palindrome_tester.");
4 puts("This program will test if the number obtained from the user input is symmetrical");
5
6 int num;
7 puts("Enter your 5 digit integer: ");
8 scanf("%d", &num);
9
10 int is_palindrome=0;
11
12 if (num9999){
13 //in a palindrome the total of each side is divisable by 11
14 //21421=(12+21)%11=0
15 int first_two_digits=num/1000;
16 int last_two_digits=num-num/100*100;
17 is_palindrome*=(first_two_digits+last_two_digits)%11==0?1:0;
18 //printf("%d\t%d", first_two_digits, last_two_digits);
19 }else{
20 puts("Input was not of 5 digits.");
21 }
22
23 if (is_palindrome)
24 puts("The number is a palindrome.");
25 else
26 puts("The number is not a palindrome.");
27
28 return 0;
29 }

>21421
>21412*

>reverse
What a bloat

λ length "reverse = foldl (flip (:)) []"
29

Oh god, not the 29 characters! How will my hard disk cope?

>hard disk
what a retard

>le (((SSD))) maymay
you're not fooling anyone, shill

that data doesn't go on your harddrive
or your SSD if you have one

Oh right, it goes into the cloud. I forgot we were all using haskell-as-a-service compilers

>mfw python shows up and absolutely destroys the competition

str(n) == str(n)[::-1]

bool is_palindrome(char *str){
char *end = str + strlen(str) - 1;
do{
if(*str != *end) return false;
} while(++str != end && --end != str);
return true;
}

(in function form)

def check(word):
if word == word[::-1]:
return True

>java

kys pajeet

(define (palindrome? str)
(equal? str (string-reverse str)))

>)))

shorter
def check(word):
return True if word == word[::-1] else False

Parentheses? What parentheses?!

function isPalindrome(str:string):boolean {
if(str == str.split('').reverse().join('')) {
return true;
}
return false;
}

TypeScript to the rescue

check = lambda word: word == word[::-1]

n == reverse n

Hasklel crushing Pyshit as usual

Actually I included the str() when I didn't have to. I'm afraid Python is still superior user

n == n[::-1]

if palindrome == palindrome.reverse

Roooby

bool res = true;
for (int i = 0; i < str.length/2; i++) {
if (str[i] != str [str.length - 1 - i]) {
red = false;
break;
}
}

Integer division ensures a word with odd number of letters leaves middle letter unchecked and even number of letters means both middles are checked.

>python is one of the slowest languages out there
>if you're not careful enough with what language features you use haskell, even though compiled, manages to still be slower than python

uh haslelbabs?

>mfw Python has blown everyone out of the water with the shortest solution in the thread

too bad it's only useful for toy programs

That's a variable not a function dude

how dare you

Is it unicode compatible?

???

I am far from an expert at Python, but I have done a couple of semi-serious projects in the language and will try to recall specifically what I didn't like.

- Everything you write will be open source. No FASLs, DLLs or EXEs. Developer may want to have control over the level of access to prevent exposure of internal implementation, as it may contain proprietary code or because strict interface/implementation decomposition is required. Python third-party library licensing is overly complex. Licenses like MIT allow you to create derived works as long as you maintain attrubution; GNU GPL, or other 'viral' licenses don't allow derived works without inheriting the same license. To inherit the benefits of an open source culture you also inherit the complexities of the licensing hell.
- Installation mentality, Python has inherited the idea that libraries should be installed, so it infact is designed to work inside unix package management, which basically contains a fair amount of baggage (library version issues) and reduced portability. Of course it must be possible to package libraries with your application, but its not conventional and can be hard to deploy as a desktop app due to cross platform issues, language version, etc. Open Source projects generally don't care about Windows, most open source developers use Linux because "Windows sucks".
- Probably the biggest practical problem with Python is that there's no well-defined API that doesn't change. This make life easier for Guido and tough on everybody else. That's the real cause of Python's "version hell".

I've never used a lambda function before. Neat, I leaned something new today

- Global Interpreter Lock (GIL) is a significant barrier to concurrency. Due to signaling with a CPU-bound thread, it can cause a slowdown even on single processor. Reason for employing GIL in Python is to easy the integration of C/C++ libraries. Additionally, CPython interpreter code is not thread-safe, so the only way other threads can do useful work is if they are in some C/C++ routine, which must be thread-safe.
- Python (like most other scripting languages) does not require variables to be declared, as (let (x 123) ...) in Lisp or int x = 123 in C/C++. This means that Python can't even detect a trivial typo - it will produce a program, which will continue working for hours until it reaches the typo - THEN go boom and you lost all unsaved data. Local and global scopes are unintuitive. Having variables leak after a for-loop can definitely be confusing. Worse, binding of loop indices can be very confusing; e.g. "for a in list: result.append(lambda: fcn(a))" probably won't do what you think it would. Why nonlocal/global/auto-local scope nonsense?
- Python indulges messy horizontal code (> 80 chars per line), where in Lisp one would use "let" to break computaion into manageable pieces. Get used to things like self.convertId([(name, uidutil.getId(obj)) for name, obj in container.items() if IContainer.isInstance(obj)])
- Crippled support for functional programming. Python's lambda is limited to a single expression and doesn't allow conditionals. Python makes a distinction between expressions and statements, and does not automatically return the last expressions, thus crippling lambdas even more. Assignments are not expressions. Most useful high-order functions were deprecated in Python 3.0 and have to be imported from functools. No continuations or even tail call optimization: "I don't like reading code that was written by someone trying to use tail recursion." --Guido

- Python has a faulty package system. Type time.sleep=4 instead of time.sleep(4) and you just destroyed the system-wide sleep function with a trivial typo. Now consider accidentally assigning some method to time.sleep, and you won't even get a runtime error - just very hard to trace behavior. And sleep is only one example, it's just as easy to override ANYTHING.
- Python's syntax, based on SETL language and mathematical Set Theory, is non-uniform, hard to understand and parse, compared to simpler languages, like Lisp, Smalltalk, Nial and Factor. Instead of usual "fold" and "map" functions, Python uses "set comprehension" syntax, which has overhelmingly large collection of underlying linguistic and notational conventions, each with it's own variable binding semantics. Using CLI and automatically generating Python code is hard due to the so called "off-side" indentation rule (aka Forced Indentation of Code), also taken from a math-intensive Haskell language. This, in effect, makes Python look like an overengineered toy for math geeks. Good luck discerning [f(z) for y in x for z in gen(y) if pred(z)] from [f(z) if pred(z) for z in gen(y) for y in x]
- Python hides logical connectives in a pile of other symbols: try seeing "and" in "if y > 0 or new_width > width and new_height > height or x < 0".
- Quite quirky: triple-quoted strings seem like a syntax-decision from a David Lynch movie, and double-underscores, like __init__, seem appropriate in C, but not in a language that provides list comprehensions. There are better ways to mark certain features as internal or special than just calling it __feature__. self everywhere can make you feel like OO was bolted on, even though it wasn't.

>two sentences in and he's wrong
stopped reading there

- Python has too many confusing non-orthogonal features: references can't be used as hash keys; expressions in default arguments are calculated when the function is defined, not when it’s called. Why have both dictionaries and objects? Why have both types and duck-typing? Why is there ":" in the syntax if it almost always has a newline after it? The Python language reference devotes a whole sub-chapter to "Emulating container types", "Emulating callable Objects", "Emulating numeric types", "Emulating sequences" etc. -- only because arrays, sequences etc. are "special" in Python.
- Python's GC uses naive reference counting, which is slow and doesn't handle circular references, meaning you have to expect subtle memory leaks and can't easily use arbitrary graphs as your data. In effect Python complicates even simple tasks, like keeping directory tree with symlinks.
- Patterns and anti-patterns are signs of deficiencies inherent in the language. In Python, concatenating strings in a loop is considered an anti-pattern merely because the popular implementation is incapable of producing good code in such a case. The intractability or impossibility of static analysis in Python makes such optimizations difficult or impossible.
- Problems with arithmetic: no Numerical Tower (nor even rational/complex numbers), meaning 1/2 would produce 0, instead of 0.5, leading to subtle and dangerous errors.
- Poor UTF support and unicode string handling is somewhat awkward.
- No outstanding feature, that makes the language, like the brevity of APL or macros of Lisp. Python doesn’t really give us anything that wasn’t there long ago in Lisp and Smalltalk.

>sees that python has won the thread's competition
>proceeds to copy / paste a bunch of excuses written by someone else

how mad are you right now? python rules, everyone else drools

what did he mean by this?

haskell is shorter if you write a function like the op wanted

It means he copy pasted someone complaining about Python 2 (which was replaced 8-9 years ago). Python 3 fixed a lot.

I might believe you if you showed some code, instead of just talking about it

>replaced

f = lambda s: s == s[::-1]

vs

f s = s == reverse s

mixed up the posts but you get the point

cool, thanks for showing proof

[citation needed]

#include
#include
#include
#include

#define MAX_INPUT 200

int main(int argc, char *argv[])
{
char input[MAX_INPUT];
switch (argc) {
case 1:
fgets(input, MAX_INPUT, stdin);
char *nl = strchr(input, '\n');
if (nl)
*nl = 0;
else
input[MAX_INPUT] = 0;
break;
case 2:
strcpy(input, argv[1]);
break;
default:
printf("Usage: %s [str]\n", argv[0]);
exit(EXIT_FAILURE);
}
size_t i = 0;
size_t j = strlen(input) - 1;
while (!isalpha(input[i]))
++i;
while (!isalpha(input[j]))
--j;
char palyndromic = 1;
while (i < j) {
if (tolower(input[i]) != tolower(input[j])) {
palyndromic = 0;
break;
} else {
do
++i;
while (!isalpha(input[i]));
do
--j;
while (!isalpha(input[j]));
}
}
if (palyndromic)
puts("breddy gud :^)");
else
puts("smhtbhfam :^(");
return EXIT_SUCCESS;
}
If your code does not ignore punctuation and digits, it's wrong.

import Data.Text (reverse)

now it is :^)

f = ap (==) reverse

holy shit that's convoluted compared to

At least it works, faggot.
Also,
>calculating a new string just to check if the original one is a palindrome
Functional programmers should be hung.

>pretends to understand functional programming
okay

Okay fags, how about disassembly size?

SBCL
CL-USER> (disassemble (lambda (x) (string= x (reverse x))))
; disassembly for (LAMBDA (X))
; Size: 94 bytes. Origin: #x10055E076C
; 6C: 498B4C2460 MOV RCX, [R12+96] ; thread.binding-stack-pointer
; no-arg-parsing entry point
; 71: 48894DF8 MOV [RBP-8], RCX
; 75: 488D5C24F0 LEA RBX, [RSP-16]
; 7A: 4883EC18 SUB RSP, 24
; 7E: 498BD0 MOV RDX, R8
; 81: 488B0588FFFFFF MOV RAX, [RIP-120] ; #
; 88: B902000000 MOV ECX, 2
; 8D: 48892B MOV [RBX], RBP
; 90: 488BEB MOV RBP, RBX
; 93: FF5009 CALL QWORD PTR [RAX+9]
; 96: 4C8B45D8 MOV R8, [RBP-40]
; 9A: 488BFA MOV RDI, RDX
; 9D: 498BD0 MOV RDX, R8
; A0: 31F6 XOR ESI, ESI
; A2: 48C745F017001020 MOV QWORD PTR [RBP-16], 537919511
; AA: 488975E8 MOV [RBP-24], RSI
; AE: 48C745E017001020 MOV QWORD PTR [RBP-32], 537919511
; B6: 488B055BFFFFFF MOV RAX, [RIP-165] ; #
; BD: B90C000000 MOV ECX, 12
; C2: FF7508 PUSH QWORD PTR [RBP+8]
; C5: FF6009 JMP QWORD PTR [RAX+9]
; C8: CC10 BREAK 16 ; Invalid argument count trap

>he uses 52 lines
>other programmers require 1

==================== Asm code ====================
.section .text
.align 8
.align 8
.quad 8589934607
.quad 0
.quad 15
.globl Palin.palin_info
.type Palin.palin_info, @object
Palin.palin_info:
_c1Lz:
leaq -24(%rbp),%rax
cmpq %r15,%rax
jb _c1LA
_c1LB:
movq $block_c1Lx_info,-24(%rbp)
movq %rsi,%rax
movl $GHC.Types.[]_closure+1,%esi
movq %r14,%rbx
movq %rax,%r14
movq %rbx,-16(%rbp)
movq %rax,-8(%rbp)
addq $-24,%rbp
jmp GHC.List.reverse1_info
_c1LA:
movl $Palin.palin_closure,%ebx
jmp *-8(%r13)
.align 8
.quad 2
.quad 32
block_c1Lx_info:
_c1Lx:
movq %rbx,%rdi
movq 16(%rbp),%rsi
movq 8(%rbp),%r14
addq $24,%rbp
jmp GHC.Classes.$fEq[]_$c==_info
.size Palin.palin_info, .-Palin.palin_info

>use MAX_INPUT + 3*8 + 1 bytes of RAM
>others require 1 MB

>pretends to understand functional programming
okay

OK cuckoo. Call me back when you can sort an array in O(1) space.
>inb4 MUH ABSTRAKSHUN

kek, call me back when you can sort an array of arbitrary types in O(n) time

>should be hung
I bet they are.

hackage.haskell.org/package/vector-algorithms-0.7.0.1

>store numbers of occurrences in hash table
>trivially get your sorted array
Go on, Pajeet.

Pajeet doesn't know a thing about functional programming, at least get your insults right.

So how do you sort an array of strings?

>side effect
>functional programmers have to not be purists to get reasonable complexities in their own paradigm
really makes u think

>he doesn't know what an increasing function is

>>side effect
>>functional programmers have to not be purists to get reasonable complexities in their own paradigm
That code doesn't have side effects

>>he doesn't know what an increasing function is
But your curryshit's Object.GetHash() won't be homomorphic on comparison, so good luck building your abstraction

hackage.haskell.org/package/discrimination-0.2.1/docs/Data-Discrimination-Sorting.html#v:sort
Meanwhile I can just do ‘sort foo’ and get a sorted version

Then I'm right.
hackage.haskell.org/package/vector-algorithms-0.7.0.1/docs/Data-Vector-Algorithms-Radix.html
>though it also uses O(n) auxiliary space
Before you ridicule yourself, passing a pointer dereferenced by the function is side effect.

>good luck building your abstraction
>MUH ABSTRAKSHUN
Why aren't you memeing constraint programming; Pajeet?

HLists are a degenerate abomination that should never have existed.

APL
f←{∧/=⌿↑⍵(⌽⍵)}

Nice cherry picking out the single one of those sorting algorithms that uses an extra array as auxiliary space. I'm sure your idea of using a separate hash table is magically O(1) space though

Who mentioned HLists?

This shows how retarded python fags are:
>return True if word == word[::-1] else False
>return True if True else False
Why do you need an if/else?
def check(word):
return word == word[::-1]

J code is pretty short too.

How else are you going to achieve this?

>nobody has solved it recursively yet
This board is shit

>implying the recursive solution is any better than any of the one-liners

I like this one

Yeah but using libraries is for niggers

>literally no-one using a library

...

Are you retarded? That wasn't even related to the problem in OP at all.

isPal :: String -> Bool
isPal s = s == reverse s

Haskell master race

Idris master race.

>Nice cherry picking out the single one of those sorting algorithms that uses an extra array as auxiliary space.
No, I "cherrypicked" the only algorithm whose space complexity was actually given.

>I'm sure your idea of using a separate hash table is magically O(1) space though
It's not but that wasn't asked.