the other way is just to do return not val & 1 and it is faster since it just checks the least significant bit EDIT: changed first bit to " least significant bit "
Does it actually shortcut the & though? I would have thought it'd still do a full and across all bits and return a full sized int. Checking ==0 shouldn't be any slower than not x either.
Edit: it should be faster, just because a binary And is faster than a division & remainder calculation - but it's not because it`s only checking the final bit
Doing == 0 vs "not value" is probably more style than anything, any performance lost or gained from doing == or & would be very minimal I imagine.
And I am pretty sure the & 1 will stop when the lower bit count is reached, so it should just check the least significant and that's it, at least in theory
It stores 1 as a full sized 32 bit integer (in CPython at least). So it does a full 32 bit And, and dumps out a new 32 integer that's ==1 or ==0. You can confirm this with type(x & 1)
I have a bad habit of checking null and for 'null' string and string length and if sting is empty using language method.
do you know why? it Because I am an idiot with 10 years of swe experience. I have worked with legacy code most of my life which make me a bitter developer.
At the end. I bet over checking stuff has to have a limit . ..
At least from the output message it looks like the function should work both ways - tell you if a number is even (isodd = false) or if a number is odd (isodd=true). So an example input of 3 with the flag set to true will yield a true.
Then again, I didn't attempt to decypher the chain of if statements leading there to see whether my assumption is right or not, sooooo...
Well, like, also, there's 2 options. It's either even or odd (or I guess it could throw an error, but that's another conversation). So if isEven returns bool you can just do if not isEven and not even have to alter the function.
I would do it with modulo 2. Modulo is an operator which returns the rest of an devision. E.g. 15/12 = 1 rest 3. And the modulo would look like 15%12=3. For an uneven number something like: if (number % 2 != 0):
Well just using modulo is the simplest way, or you could use bitwise and operator if you want to be fancy.
Modulo:
def is_even(val):
return val % 2 == 0
With modulo when val is even val % 2 will be 0 and if it's odd it will be 1. So the function returns true or false.
Bitwise "and" operator:
def is_even(val):
return not(val & 1)
In this case what happens, is if you look at a number in binary, if the least significant (most left) digit is 1 that number is odd, if it's 0 that number is even. So if you do an "and" operation on val with number 1, you'll get 1 if the number is odd and 0 if that number is even. We just invert this to get true when even and false when odd.
... if the least significant (most left) digit ...
I'll point out, only because novices could get tripped up by this, that this is inaccurate.
The internal representation of binary strings can change 'endianness' (i.e. which side the least significant digit of a binary string is located on), so it's something you may need to be aware of for lower-level programming. But in Python, the most significant digit is the leftmost.
Just for the benefit of anyone who isn't familiar with the concept of endianness - endianness isn't really about bit-ordering, but about byte-ordering. So if you have a 4 byte (32 bit) integer, the bytes might be arranged like this on a big endian system (where each number is the address of the byte in memory):
MSB | 0x01 0x02 0x03 0x04 | LSB
But on little endian systems, the memory would be laid out like this:
MSB | 0x04 0x03 0x02 0x01 | LSB
In most (all?) systems, specific bits aren't addressable, so there isn't really an "ordering" of bits specifically. Bit-endianness exists, but it's like, a hardware level thing that as a programmer you won't ever have to worry about or really have access to. You'd probably only see it if you designed hardware for a network device.
This means if your integer is just a byte, it's the same representation, regardless of big endian/little endian. It's only relevant for multi-byte data.
Anyways, all that to say that I don't think I've ever seen a textual representation of binary where the left-most binary digit is the least significant. Even if it was little endian, I'd still write each byte from most significant bit to least significant bit:
1 in Big endian (2-bytes): 00000000 00000001 (0x00 0x01)
1 in Little endian (2-bytes): 00000001 00000000 (0x01 0x00)
I hope this is sarcastic, but in case it isn't, just look at this part:
if(c==False)==True:
if(b)==True:
print("nubmer is not odd")
if(b==False)==True:
print("number is not even")
What is b or c? Unless you use variables in a very limited context (like in one line of a small loop), don't use single letters for your variables but give them meaningful names.
Never do if variable == True:, that's just if varaible:, perhaps combined with a type check before.
Don't use if x and then if not x, that's what else is for. Otherwise you need to keep the two conditions in sync, and someone reading your code needs to read both conditions to check if it's always one of the two happening.
What do you think about using "if not x" and then an "else"? Sometimes I do that to put the focus in the first part, just to make easier to understand the whole code.
But being overly robust doesn't hurt your code or make it less readable. Some people prefer seeing the full command and that's not "wrong" it's just a preference.
The other issues you mentioned are accurate and the (variable==true)==false is super obtuse and definitely hinders any readability.
Maybe it depends on the culture and background a bit?
I programed mainly in JS and Python, and now in Ruby. Ruby is even more extreme in the idiomatic way. Now it isn't even accepted to write if var == nil, but I have to use the built in nil? function.
In curly brace languages I prefer to write if x == false because when I'm reading my eyes will often fail to notice the single character ! which is sandwiched next to another non alphanumeric character, (. But I don't do it at work because my coworkers don't agree.
Everyone already told you about the modulo "trick" but they are other lessons to get out of this mess.
The function is even takes three arguments. It's unusual for what we expect a function named "is even" should do : it needs only 1 argument. If you function has more than its fair share of argument, you're most likely doing something wrong.
It is good practice to name a function <verb>whatever because the function does something. So iseven, isEven or is_even are good names. If you can't do that, it might mean that your code is getting convoluted and parts no longer have clear purposes.
There is no need to check wether it is true that something is false, check wether something is false instead; i.e (x == False) == True should be replaced by x == False. Those little trick are not really important but they really ease up the code.
Unlike what many may tell, it is fine to be a bit more verbose than absolutely necessary.
print("is even" if isEven(x) else "is odd")
Is fine but also is
even = isEven(x)
if (x):
print("is even")
else:
print("is odd")
It is fair to ask : why 9999 at the top of the function isEven ? A numbers that appear without clear reason are called magic numbers. They are a menace to the well being of your code : hard coded values are hard to make sens of but also will make debugging a pain if they pop up everywhere.
If you can avoid the heap of indentation we see in the function there, it is recommended to avoid it. If you end up with if with too long expression, it is fine to calculate the value of the condition in multiple steps before the if and give the result to the if.
If (birthdayMoney + christmassMoney +
...)
Can be replaced by
money = birthdayMoney
money += christmassMoney
money -= costOfPS5
... # big calculations
if (money > 0):
...
Counterintuitively it is just as fast as it will most probably gets optimized and will help in extrem cases.
First problem, I have no idea what these parameters are. I assume val is the value you're checking but having an isodd parameter is very odd indeed and I'm at a TOTAL loss as to what abc is supposed to be. At a bare minimum abc should be named more descriptively.
You're comparing val to 9999 and setting it to -1 if it's larger. Why? Why can I only tell if a number is even provided that it's less than 10000?
The == True stuff has already been discussed enough
Reassigning variables like this in a loop is a bad thing to do, it makes your program flow complicated and you can't step through it in your head anymore. It's 10 times worse when the variables aren't named well.
All the casting of int and bool is confusing because it means you don't know what type your variable is supposed to be, which means I definitely don't know what type it's supposed to be. Casting should be rare in languages without explicit types, and almost never happen, outside of specific situations, in languages with them.
This is a poor choice of algorithm for finding if a number is even. Even assuming you don't know about the existence of better ones, if you're implementing an algorithm (as opposed to following a protocol or definition), then you should comment it heavily.
The line abc=bool(int(1-abc)) is subtracting a bool from 1. Even if this technically runs, you really shouldn't do this, because it means that now I have to look up obscure rules of python to see if this is doing what you mean for it to be doing, which on top of that I have to guess at what you mean for it to be doing.
I'm pretty sure this algorithm doesn't even work, although I haven't tested it
After a lot of banging my head against a wall, I think I figured out what all the variables mean.
val = the value it's checking
isodd = flag for telling the function if it should check if the number is odd instead of even (even though this could be done with a not)
abc = the bool it flips back and forth until the value it's checking is reached
As for why abc is passed as a parameter, I don't know. It should really be a local variable.
I belive the comparison to 9999 is a clever way to kinda-break the loop, even though a for loop would've worked better. Heck even a break would've worked better. I did teach him about for loops and breaks (and the modulus operator too!) but I guess he forgot.
I think abc=bool(int(1-abc)) was supposed to actually be abc=bool(1-int(abc)), as an attempt to invert abc. That would make more sense, but I guess he forgot about not?
The algorithm does indeed work, even though it only has a range of 0-9999 that could be extended to -9999-9999 with an abs. It's very slow too, and gets even slower when you want a larger range of inputs. This is due to the fact that the loop isn't properly broken, so it always runs to whatever the upper bound is.
I'd start by not comparing the conditions in the if statements to true, as it's not necessary. Then a very simple way of checking if a number is even or odd is using the % (modulus) operator. It gives the reminder of dividing 2 numbers, so if you divide an even number by 2 itll give 0, and if it's odd I'll give something else than 0. Some other stuff can be made smaller like instead of checking if ABC is true or false and then returning true or false, you can just return ABC and itll do the same. Also the lines directly on top do nothing, if ABC is true it sets it to true which it already is and same if its false, they serve no purpose. In general it's way more complicated for what it should do, but for a complete beginner it's not that bad
Use modulo. Basically, if x%2=0, then even, else odd. You may also want to verify that x is a number first, but that's optional depending on use and data quality.
I dont know what language youre using, but in the ones im using that // will just turn the rest into a comment and if I have to ask what this does, its too much for a beginner
Aside from the lowercase true and false, this looks like Python.
In Python // and / are used for division, but // rounds down to an integer and / doesn’t. If x is odd, x//2 will get rid of the .5. so x - (x//2)*2 will be 1.
Otherwise x//2 will be exactly half of x and x - (x//2)*2 will be 0.
is a hard thing for new developers to conceptualize at first. I've seen lots of iterations of if thing = True and if thing != False but this is truly a masterpiece.
def IsEven(val,isodd,abc):
print("calculating if number is odd or even...")
a=0
while bool(a+1)==True:
if(a>=9999)==True:
a=-1
else:
a=a+1
if(isodd!=False)==True:
if(val-a>0)==True:
abc=bool(int(1-abc))
if(isodd)==True:
isodd=False
abc=True
if(isodd==False)==True:
if(val-a>0)==True:
abc=bool(int(1-abc))
if(abc)==True:
abc=True
if(abc==False)==True:
abc=False
if(abc)==True
return True
if(abc==False)==True:
return False
a=int(input("enter number to be checked if even"))
b=bool(int(input("check if odd?")))
c=False
c=IsEven(a,b,c)
if(c)==True:
if(b)==True:
print("nubmer is odd")
if(b==False)==True:
print("number is even")
if(c==False)==True:
if(b)==True:
print("number is not odd")
if(b==False)==True:
print("number is not even")
exit()
Additionally, your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.
Your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.
Your bot breaches the botiquette on at least 3 fronts; it's not commenting only when specifically called, it isn't adding anything to this conversation, and you haven't listed your username or a dedicated subreddit in the comment.
The parameter isOdd being passed into the method, the use of ==True and ==False
The single letter variable names that don't give any hint of what they store
The 5 levels deep of nesting whiles and if/elses
Using ==True after every conditional
if(abc==False)==True: abc=False. Like, if it's already false, then why set it to false?
The reading input in, casting it to an int, then casting that to a bool: b=bool(int(input("check if odd?"))). What is the user supposed to put here? What if they type "yes", what's the expected result?
Declaring a variable by doing c=False and then immediately on the next line reassigning it to c=IsEven(a,b,c)
Having a section for "is odd" and "is even" (the only possible two outcomes), and then somehow another section for "is not odd" and "is not even" (the same two cases but worded differently).
In fact, the sections at the end, and the b variable are entirely useless. He could've just done something like this: print("number is even? " + c)
Going further, the variable c is useless too, just do print("number is even? " + IsEven(a)), and now get rid of the extra parameters being passed to IsEven, and then rewrite that entire mess of a function.
It's only semi legit. After seeing all these memes I challanged him to write an is even function. He only knows the very basics for now and I thought this would be a good way to find what needs improvement. Still it was too good(bad?) not to share.
Honestly this is a legitimate case of "you can't make that shit up". There is no way this was written by someone who actually knows what they are doing and wanted to write bad code for the sake of humour. No way in the world. It's bona fide, no doubt in my mind.
This is the best worst code I've ever seen, and it's not even close. It should be stickied on this sub to shame all posts that follow it.
354
u/[deleted] Apr 14 '21
Asked about the extra
== True-s. He said they were there to make sure "it" checked that the statements are true.He also didn't belive me when I said that the entire thing could be written as
return val%2 == 0.50
u/incredible-mee Apr 14 '21
He could have simply used this api https://isevenapi.xyz/. It would be much easier. /s
79
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21
Doesn't even run. Syntax error on line 22.
646
u/boniqmin Apr 14 '21
This is truly a monstrosity.
is_oddas a parameter to calculate whether a number is even, that's a big brain move.13
u/Blyatman72 Apr 14 '21
How can you make this code better? I'm still a bit of beginner
330
u/Capitalist_Kerbal Apr 14 '21
Genuinely grotesque.
(isodd!=False)==TrueInsanity.
185
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 14 '21 edited Apr 14 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
56
u/bisnark Apr 14 '21
"nubmer". Ha!
24
u/robert-at-pretension Apr 14 '21
BRO WHAT?!
59
u/Ciaranhappy Apr 14 '21
While this code isn't great, you can't not be happy that your friend is proud. They made a thing, and maybe its terrible, but its their thing.
19
u/dvof Apr 14 '21
Lol'd
43
u/[deleted] Apr 14 '21
we all start somewhere. good for him for trying.
15
u/LeCrushinator Apr 14 '21 edited Apr 14 '21
This code truly disgusted me.
Everything about this:
isOddbeing passed into the method, the use of==Trueand==False==Trueafter every conditionalif(abc==False)==True: abc=False. Like, if it's already false, then why set it to false?b=bool(int(input("check if odd?"))). What is the user supposed to put here? What if they type "yes", what's the expected result?c=Falseand then immediately on the next line reassigning it toc=IsEven(a,b,c)bvariable are entirely useless. He could've just done something like this:print("number is even? " + c)cis useless too, just doprint("number is even? " + IsEven(a)), and now get rid of the extra parameters being passed to IsEven, and then rewrite that entire mess of a function.12
u/gsjoy99 Apr 14 '21
This is so bad its kinda cute
7
u/Kyn21kx Apr 14 '21
r/Eyebleach
6
u/only_bad_comments Apr 14 '21
After reading this code, I cannot even...
6
u/CowboyBoats Apr 14 '21
My favorite part of this symphony is
sys.exit()at the end of the function definition4
u/tailfra Apr 14 '21
You must be proud! This one was good hahah
4
u/iamafraazhussain Apr 14 '21
Where does your friend buy his weed?
1
u/Shinkegeeek Apr 14 '21
II dont get the
if (abc )==True: abc =True
3
u/hsantefort12 Apr 14 '21
Oh my sweet summer child
2
u/ay88407 Apr 14 '21
Maybe you should have uhh. You should have taught him basic math functions python has. Specifically mod. Had a good laugh though.
2
u/[deleted] Apr 14 '21
Well. He’s taking the time to try and learn.
I wouldn’t bash him for it man. Ofc the code would be bad.
2
u/SMTG_18 Apr 14 '21
What. The. Hell?!?
2
u/deleted1357 Apr 14 '21
I.. I mean, I'm not mad. This is some creative horrendous code.
2
u/AnnualUnderstanding7 Apr 14 '21
Seems like they needs a bit more math and a little less code 😅
2
u/TSReactReduxSASSDev Apr 14 '21
Here we see a disciple who is not one with the boolean. You must find peace and harmony, a "boolean zen" between you and your code.
...this currently is not so
2
u/mplaczek99 Apr 14 '21
Let's not be so harsh, the code style looks like he's new
2
u/Alkyen Apr 14 '21
That's amazing. Tell him I'm proud of him too!
2
u/bitcraft Apr 14 '21
This nicely demonstrates how easy it is to develop a bad idea by powering through errors.
2
u/HerissonMignion Apr 14 '21
r/badIsEven
2
u/TheRealCCHD Apr 14 '21
You need to teach him about % man! :D
2
u/using_mirror Apr 25 '21
Just wait until he learns recursion
2
u/[deleted] Apr 14 '21
why people fuck up isEven that often? just
(x & 1) == 01
u/RobzillaMyNilla Apr 14 '21
Lol wut??
1
u/[deleted] Apr 14 '21
Tmw you’re missing the 5 key.
Also, CS1301 by David Joyner is a godsend (or Joynersend).
1
u/KuchDaddy Apr 14 '21
isOdd parameter. You have to already know the answer to use the method. lol
1
u/klc3rd Apr 14 '21
This simple task, is making my brain hurt
1
u/deytookourjewbs Apr 14 '21
Yeah aight
1
u/MrtinDew Apr 14 '21
Yeaaah
1
u/burritoboy76 depraved Apr 14 '21
Lines 18-25 annoy me the most, but all of this code is horribly formatted overall
1
u/[deleted] Apr 14 '21
JS developers confused why you can’t just import is-even.
1
u/Samuql Apr 14 '21
If (abc == True): abc = True
XD
1
u/[deleted] Apr 14 '21
I punched a whole through my monitor so I wouldn't have to look at this
1
u/campbellm Apr 14 '21
Keep this as an answer to the perennial, "Do I need to be good at maths to be a developer?" question.
Well, maybe not, but you need to have a basic understanding.
1
u/Frennish Apr 14 '21
What the absolute shit
1
u/Deadly_chef Apr 14 '21
r/programminghorror
1
u/Socialimbad1991 Apr 14 '21
I refuse to believe this is not parody
1
u/jjman72 Apr 14 '21
Needs more True
1
u/fzammetti Apr 15 '21
Insert Monty Python "Doctor! My brain hurts!" image.
1
u/schlaubi Apr 15 '21
It's beautiful.
1
u/allstreamer_ Apr 15 '21
He tryed, he gave it his best
1
u/Builtwnofoundation Apr 15 '21
Holy hell
1
u/usedtoliveonmars Apr 15 '21
Wow this could be one line of code but it's as if they had a minimum word count
1
u/dwightshru Apr 20 '21
when code is long and looks all pretty i’m proud too no matter what it says
1
u/SquigglyHL May 27 '21
print("nubmer is odd")1
u/Clayrock78 Jan 22 '22
return val % 2 == 0
1
u/thedarklord176 Oct 03 '22
Ah yes, the true here is made of true
1
u/eidron06 Apr 14 '21
Not your brightest friend, i suppose
0
u/[deleted] Apr 14 '21
[deleted] — view deleted comment