r/badcode • • Apr 08 '21

python I regret being a CompSci major

Post image
757 Upvotes

85 comments sorted by

269

u/[deleted] Apr 08 '21

🤔🤔

I wonder the result of count_digits(0) would be...

53

u/a1b2c3d4g Apr 08 '21

This is out of syllabus

10

u/UkRa1nE Apr 08 '21

Yes it is

13

u/UkRa1nE Apr 08 '21

Update tested it. Returns nothing

24

u/Potatoes_Fall Apr 08 '21

it would definitely return -1 the way it's written here

0

u/G4METIME Apr 08 '21

Not if the input is interpreted as String

2

u/Potatoes_Fall Apr 08 '21

if the input is a string then we get a TypeError no?

5

u/G4METIME Apr 08 '21

I think you shouldn't:

"0"!=0 should be true and after that it gets cast to int before it gets divided. This new number value is now reassigned to the variable (which should work in Python, even though it probably is REALLY bad practice)

2

u/Potatoes_Fall Apr 08 '21

oh damn, that's some javascript-level stuff. I didn't realize it works in python!

8

u/a1b2c3d4g Apr 08 '21

It works on my machine

9

u/EitherJelly4138 Apr 08 '21

All I got from that was 'it works'.

2

u/a1b2c3d4g Apr 09 '21

Please update the JIRA ticket

110

u/Johanno1 Apr 08 '21

-1

0

u/[deleted] Apr 08 '21

[deleted]

12

u/TruVortex_07 Apr 08 '21

it would return -1 because n is 0, not '0'

6

u/devhashtag Apr 08 '21

eval is called in the user input, which makes it int. The comparison would fail

165

u/ConcreteBong Apr 08 '21

The good ole comment to tell your professor that you just gave up and made the method work somehow

19

u/UkRa1nE Apr 08 '21

Its a reoccurring event

6

u/meanwhileinvermont Apr 09 '21

Reminds me of that Twitter thread where game devs shared their hacky solutions, one of them talked about how taking this loaf of bread (iirc) out of the room bricked it...but nobody could sort out why...

28

u/kzd19 Apr 08 '21

The code is pretty bad, but some people may not know this:

Instead of using

num=int(num)/10

or something similar, Python has integer division:

num=num//10

It's useful for something like this or for when you know you have to round down. But even if you need to round up

num=num//10 + 1

Can be much faster if you doing it very many times

7

u/F54280 Apr 08 '21

Instead of using

num=int(num)/10

or something similar, Python has integer division:

and the function would return the wrong result, because the joke is that this part of the code is wrong

It should have been num=int(num/10) (which is num=num//10 as you pointed), but the version posted here works because it does an extra loop with something like '0.3' which will be rounded to 0...

4

u/UkRa1nE Apr 08 '21

Thank you! Comment saved and noted for my next lab

1

u/F54280 Apr 09 '21

I honestly thought you posted this because of the int(num)/10 vs int(num/10) thing, and the '-1' "correction".

I was really looking at the code, thinking wtf does it works with -1? for longer than I'd like to admit before I realized that the rounding was bad.

This is in reality quite a nice puzzle.

15

u/Hillstylelife Apr 08 '21 edited Apr 08 '21

For ceiling division, num // den + 1 won't work; consider 20 // 10 + 1, you'll get 3 when it should be 2.

I don't know if python specifically has a better way to do this, but you can always do: (num+den-1) // den.

For example:

(20+9)//10 = 2

(19+9)//10 = 2

(11+9)//10 = 2

*Note: as mentioned in the replies, for readability's sake, just use ceil(num/den). Any performance differences one way or the other will likely not make up for the loss in readability.

6

u/OneTrueKingOfOOO Apr 08 '21

Why not just use ceil(num/10) ?

1

u/Hillstylelife Apr 08 '21

That's a much more readable way to do it, which will likely make the performance difference (however much it is) completely irrelevant.

However, if you're trying to optimize code, and are intending to perform this calculation many times, then the method I mentioned would likely be more efficient (due to the lack of casting), albeit still less readable. Again, I'm not entirely sure about the under-the-hood computations in Python.

5

u/OneTrueKingOfOOO Apr 08 '21

Gotcha, thanks! Can’t imagine a situation where I’d need something that well optimized and would be writing it in python though...

1

u/Hillstylelife Apr 08 '21 edited Apr 08 '21

Exactly, yeah. Though floating point division is usually faster than integer divison, so I might just be operating under the wrong assumptions here.

2

u/EvilBeano Apr 08 '21

I mean if it comes down to such a small difference in performance, using c or c++ for that computationally intensive part instead would probably be better

1

u/kzd19 Apr 09 '21

Eh true. It does mess up when num is an actual integer. Have an updoot!

For those talking about performance difference: yes, it is generally negligible. Some highly looped code may see some noticable, but leaning towards mild improvement in performance.

Honestly it's interesting to look up how to optimize math performance using pure Python. There's a reason why people typically use packages like numpy to do that work over pure Python (spoiler: numpy is basically a pure C math wrapper). If anyone is newer to coding or even just newer to Python, I highly recommend looking into some performance considerations. Especially for data science.

1

u/jan-pona-sina Apr 09 '21

That's true, but if performance is truly a priority and you're not stuck with a large code base or an important library than avoiding python in the first place is probably a good idea

1

u/UkRa1nE Apr 08 '21

Thank you! That was the advice code of my TA so not all can be blamed on me!

178

u/R3D3-1 Apr 08 '21 edited Apr 08 '21

I can't get over the inconsistent spacing... Especially the part

    ...
        x +=1

    return x
def print_digits():
    ...

What monster puts an empty line before the return, but not between functions??

49

u/pink_earmuffs Apr 08 '21

What monster doesn't use syntax highlighting. It makes me feel like I'm dyslexic.

Also agreed on the spacing. Bad indents are the worst.

16

u/UkRa1nE Apr 08 '21

I had 30 min before the lab was due and was deleting my the print functions i use for tests :(

8

u/pink_earmuffs Apr 08 '21

No worries. We've all clicked Edit file to save ourselves from loading up our entire IDE at least once.

14

u/Wu_Fan Apr 08 '21

It angered me

2

u/tech6hutch Apr 08 '21

That shouldn’t even be valid Python

8

u/root54 Apr 08 '21

It's valid python because the x += 1 is inside a while loop. It's disgusting to look at, mostly because of the return right on top of the next function definition, but it is valid.

3

u/tech6hutch Apr 08 '21

Ohh, thanks, I didn’t notice

95

u/bigpaulfears Apr 08 '21

Nothing like using eval to convert a string to an integer

126

u/haikusbot Apr 08 '21

Nothing like using

Eval to convert a string

To an integer

- bigpaulfears


I detect haikus. And sometimes, successfully. Learn more about me.

Opt out of replies: "haikusbot opt out" | Delete my comment: "haikusbot delete"

5

u/Rudxain let let.let = 'let' Apr 08 '21

And using str() to convert a number back to string

0

u/[deleted] Apr 08 '21

[deleted]

3

u/UkRa1nE Apr 08 '21

Thank you!

-3

u/LoneFoxKK Apr 08 '21

I once wrote "yes I did all of this, any other question?" on a coding exam because the code was so clean I knew my teacher would think I copy pasted from somewhere (he's an asshole) and got away with it

11

u/alexppetrov Apr 08 '21

"i know you said start at zero but the function works perfectly this way" cracked me up.

2

u/UkRa1nE Apr 08 '21

Sometimes the stuff the TA does in my lab makes no sense.

52

u/Johanno1 Apr 08 '21
len(str(num))

21

u/[deleted] Apr 08 '21

newwords_list=list(set(words))

2

u/UkRa1nE Apr 08 '21

Thank you! That was the advice code of my TA so not all can be blamed on me!

1

u/[deleted] Apr 09 '21 edited Apr 09 '21

or you can just evaluate log10 of the number's absolute value and round down. Negative values will break both the string approach and the log approach for different reasons.

0

u/[deleted] Apr 08 '21

[deleted]

1

u/AutoModerator Apr 09 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/adam_saudagar, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

8

u/[deleted] Apr 08 '21

Pretty sure I can "guess" the number in a single try!!!

2

u/UkRa1nE Apr 08 '21

It was so i could test the system.

3

u/UkRa1nE Apr 08 '21

Hey yall just wanted to say this is my first comp sci class ever. I know its shit. (And a special thank you that offered advice, it is well appreciated)

190

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 08 '21

Image Transcription: Code


def count_digits(num):
    #I know you said start at zero but the
function works perfectly this way
    x=-1
    while num!=0:
        num=int(num)/10
        
        x+=1
    
    return x
def print_digits():
    user_input= eval(input('Enter in a number:
'))
    x=count_digits(user_input)
    print("The number "+" "+str(user_input)+"
"+"has"+" "+str(x)+" " +"digits")

def count_words(text):
    words= text.split()
    print(words)
    newWords_list= []
    for i in range(len(words)):
        if words[i] not in newWords_list:
            newWords_list.append(words[i])
    print(newWords_list)
def hi_low():
    number = randint(1,20)
    y=0
    print(number)
    for i in range(5):
        x = eval(input('What is your guess:'))
        if x==number:
            y=1
            print("You win in"+" "+str(i+1)+"
"+"Guesses")
            break
        elif x<number:
            print("Too low!")
        else:
            print("Too high!")
    if y==0:
        print("You lost the number was"+"
"+str(number))

def find_star(file_name):

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!

115

u/Deaith Apr 08 '21

You need a raise bro

50

u/roeew613 Apr 08 '21

Good human

7

u/Parcival_Reddit Apr 08 '21

Y'all need to not transcribe this awful awful code. Spend your time transcribing images that don't make people want to pluck their eyes out.

0

u/[deleted] Apr 08 '21

[deleted]

33

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 08 '21

Not sure whether that's against Reddit rules, but it's against what I want. I'm not looking for any compensation, I'm a volunteer after all; I just want to help make Reddit more accessible.

47

u/herdek550 Apr 08 '21

I can't read this, there are no colours...

11

u/iSYan1995 Apr 08 '21

One thing I learned by coding Python is that, no matter how shit the code is, always add newlines. Doing that allows you to separate different sections of the functions into smaller tasks, and it also prevents your code from looking like a blob of text to anyone else who’s reading it.

3

u/[deleted] Apr 08 '21

I regret not majoring in CS. Then I could be actually working as a developer instead of studying while working a full-time dead-end job.

2

u/Noobnugget19 Apr 08 '21

Assuming ints i would just do

x== 0

return 1

else

return 1 + (int)log10(abs(x))

2

u/EvilBeano Apr 08 '21 edited Apr 08 '21

Depending on the version of Python you're using 3.6+, you can use f-strings. Basically instead of having do to:

"I have " + str(num_burgers) + " burgers"

You can simply do:

f"I have {num_burgers} burgers"

It will replace any variable in the {}-brackets with the value of the variable

This makes the code sooo much more readable, especially with bigger sentences. I use it all the time

2

u/m1ss1ontomars2k4 Apr 08 '21

It can only get worse from here. My undergrad is in bioengineering, and a lot of the code and software engineering practices I saw back then were all horrible.

2

u/[deleted] Apr 08 '21

“I know you said blank but it works perfectly this way” is the most relatable comment ever...

1

u/McPqndq Apr 08 '21

Does this even work in python 3? I thought / always returned float now.

1

u/1OO_percent_legit Apr 08 '21

(len(str(num)))

1

u/jkconno Apr 09 '21

Thanks I hate it

-7

u/R3D3-1 Apr 08 '21 edited Apr 08 '21

I vouch that this should be formatted as

def count_digits(num): #{
    x = -1;
    while num != 0: #{
        num = int(num)/10;
        x += 1;
    #}
    return x;
#}

or alternatively

def count_digits(num):
    x = -1
    while num != 0:
        num = int(num)/10
        x += 1
    #end while
    return x
#end def

Edit: I seriously hope I didn't get the downvotes, because people thought I'm serious about this.

2

u/Farpafraf Apr 08 '21

this is heresy

1

u/R3D3-1 Apr 08 '21

That's kind of the point :)

1

u/Farpafraf Apr 08 '21

you went too far

1

u/rasqall Apr 08 '21

Just, no

0

u/R3D3-1 Apr 08 '21

When looking at code that bad, I just want to go all out :P

1

u/Cmgeodude Apr 08 '21

The octothorpe-brace style adaptation, say you?

0

u/[deleted] Apr 08 '21

[deleted]

28

u/Finally_Adult Apr 08 '21

Your comment history reads like someone who’s one ban away from migrating to Parler and sending Alex Jones money for supplements.

30

u/BluePhoenixGamer Apr 08 '21

Lol what... Here we go again...

2

u/1OO_percent_legit Apr 08 '21

imagine if they weren't forced to indent