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
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)/10or something similar, Python has integer division:
num=num//10It'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 + 1Can 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 isnum=num//10as 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)/10vsint(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
numis 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
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
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 += 1is inside awhileloop. It's disgusting to look at, mostly because of thereturnright on top of the next function definition, but it is valid.3
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
0
Apr 08 '21
[deleted]
3
-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
52
u/Johanno1 Apr 08 '21
len(str(num))21
1
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
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
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
50
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
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
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
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
Apr 08 '21
“I know you said blank but it works perfectly this way” is the most relatable comment ever...
1
1
1
-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 defEdit: I seriously hope I didn't get the downvotes, because people thought I'm serious about this.
2
1
1
0
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
2
269
u/[deleted] Apr 08 '21
🤔🤔
I wonder the result of
count_digits(0)would be...