Discuss Scratch

bybb
Scratcher
1000+ posts

Are these good bits of code?

Sorry for the generic question, but I have been writing some simple pieces of code in Python to see how well I can do things and wanted some opinions
I coded all of this without googling or anything so it may be bad.
Factorial calculator:
def factorial(n, t = 1):
	if n != 1:
		factorial(n - 1, t * n)
	else:
		print(t)

FizzBuzz:
for i in range(0, 100):
	fb = ""
	if not i % 3: fb += "Fizz"
	if not i % 5: fb += "Buzz"
	if fb == "": fb = str(i)
	print(fb)

Last edited by bybb (July 31, 2017 18:47:15)


Game Over
You'll find me on @LastContinue from now on.
herohamp
Scratcher
1000+ posts

Are these good bits of code?

bybb wrote:

FizzBuzz:
for i in range(0, 100):
	fb = ""
	if not i % 3: fb += "Fizz"
	if not i % 5: fb += "Buzz"
	if fb == "": fb = str(i)
	print(fb)

Hey that looks just like a version of fizzbuzz I saw in tom scotts latest video. Do you watch him?
bybb
Scratcher
1000+ posts

Are these good bits of code?

herohamp wrote:

bybb wrote:

FizzBuzz:
for i in range(0, 100):
	fb = ""
	if not i % 3: fb += "Fizz"
	if not i % 5: fb += "Buzz"
	if fb == "": fb = str(i)
	print(fb)

Hey that looks just like a version of fizzbuzz I saw in tom scotts latest video. Do you watch him?
Yes I watch him, I did what he said and paused the video and tried to code FizzBuzz. I went though a couple variants but ended up choosing that one. I was more than shocked when I saw the similarities

Game Over
You'll find me on @LastContinue from now on.
herohamp
Scratcher
1000+ posts

Are these good bits of code?

bybb wrote:

herohamp wrote:

bybb wrote:

FizzBuzz:
for i in range(0, 100):
	fb = ""
	if not i % 3: fb += "Fizz"
	if not i % 5: fb += "Buzz"
	if fb == "": fb = str(i)
	print(fb)

Hey that looks just like a version of fizzbuzz I saw in tom scotts latest video. Do you watch him?
Yes I watch him, I did what he said and paused the video and tried to code FizzBuzz. I went though a couple variants but ended up choosing that one. I was more than shocked when I saw the similarities
Yeah I was also shocked as I go mostly the same code as tom scott and you.
Blaze349
Scratcher
1000+ posts

Are these good bits of code?

Who is Tom Scott?
StackMasher
Scratcher
100+ posts

Are these good bits of code?

herohamp wrote:

Blaze349 wrote:

Who is Tom Scott?
… I am blown away that you do not know the god called Tom Scott. https://www.google.com/search?q=who+is+tom+scott&oq=who+is+tom+scott&aqs=chrome..69i57j0l5.2598j0j7&sourceid=chrome&ie=UTF-8
I didn't know him either
Looks like some sort of a youtuber, some people don't like google's products you know .-.
Blaze349
Scratcher
1000+ posts

Are these good bits of code?

funfunfunction is good.
gtoal
Scratcher
1000+ posts

Are these good bits of code?

bybb wrote:

Sorry for the generic question, but I have been writing some simple pieces of code in Python to see how well I can do things and wanted some opinions
I coded all of this without googling or anything so it may be bad.
Factorial calculator:
def factorial(n, t = 1):
	if n != 1:
		factorial(n - 1, t * n)
	else:
		print(t)
should use a function, not an extra parameter.
what if you're give non-integer-valued parameters?
what about n <= 0 ?

bybb wrote:

FizzBuzz:
for i in range(0, 100):
	fb = ""
	if not i % 3: fb += "Fizz"
	if not i % 5: fb += "Buzz"
	if fb == "": fb = str(i)
	print(fb)

it's usually specified as 1 to 100, not 0.
Only works if “FizzBuzz” is a single word. If you were asked for “Fizz-Buzz” or “Fizz Buzz” this wouldn't work - or other cases would have extra characters in the output.
joefarebrother
Scratcher
500+ posts

Are these good bits of code?

4kun wrote:

bybb wrote:

def factorial(n, t = 1):
	if n != 1:
		factorial(n - 1, t * n)
	else:
		print(t)
It's better to do have functions return a value rather than print it, so that function in a variety of places. I would do either this:
def factorial(n, t=1):
    if n != 1 :
        return factorial(n - 1, t * n)
    else:
        return(t)
or if you want a simpler version, this:
def factorial(n):
    if n!=1:
        return n*factorial(n-1)
    else:
        return 1
Your simpler version is less effecient, since it can't be tail-call optimised. Basically it takes up more stack space than it needs to.

________


@OP: I would suggest in your fizbuzz code to use `if (i % 3) == 0` instead of `if not i % 3`, since it's much more clear what it does. To me the second one looks like it reads “if not i divides 3”, which is the opposite of what it means, so I have to think about it for longer.
“not” should really only be used on booleans IMO since it gets confusing otherwise.


And it was delicious! Play TBGs! Check out my Scheme Interpreter!
;
Jonathan50
Scratcher
1000+ posts

Are these good bits of code?

(C)Python doesn't have tail-call optimization so you might as well do it the second way or if you really want to you can do it like this
def factorial(n):
    t = 1
    while n != 1:
        (n, t) = (n-1, t*n)
    return t

Last edited by Jonathan50 (Aug. 2, 2017 00:30:02)


Not yet a Knight of the Mu Calculus.
NickyNouse
Scratcher
1000+ posts

Are these good bits of code?

Jonathan50 wrote:

(C)Python doesn't have tail-call optimization so you might as well do it the second way or if you really want to you can do it like this
def factorial(n):
    t = 1
    while n != 1:
        (n, t) = (n-1, t*n)
    return t
^^^ I was gonna say, recursion can be risky and unnecessarily expensive, so it might be worth doing it with loops instead.
novice27b
Scratcher
1000+ posts

Are these good bits of code?

In the interest of maximum future-proofing, this would be my solution to FizzBuzz:

divisor_table = [
	(3, "Fizz"),
	(5, "Buzz")
]
 
for i in range(1, 100+1):
	output = ""
	for divisor, word in divisor_table:
		if not i % divisor:
			output += word
	print(output or i)

More compact, but less readable alternative loop code:

for i in range(1, 100+1):
	output = "".join(word for divisor, word in divisor_table if not i % divisor)
	print(output or i)

Needlessly compact and totally unreadable version:

dt = [
	(3, "Fizz"),
	(5, "Buzz")
]
 
print("\n".join("".join(w for d, w in dt if not i % d) or str(i) for i in range(1, 100+1)))

Last edited by novice27b (Aug. 2, 2017 10:52:45)


i use arch btw
gtoal
Scratcher
1000+ posts

Are these good bits of code?

novice27b wrote:

print("\n".join("".join(w for d, w in dt if not i % d) or str(i) for i in range(1, 100+1)))

I haven't seen people outputting the \n before the text rather than after since the 60's. I was never sure why they did it athough I did hear someone suggest it was to avoid throwing an extra page on the line printer if the last line was at the foot of a page.
novice27b
Scratcher
1000+ posts

Are these good bits of code?

gtoal wrote:

novice27b wrote:

print("\n".join("".join(w for d, w in dt if not i % d) or str(i) for i in range(1, 100+1)))

I haven't seen people outputting the \n before the text rather than after since the 60's. I was never sure why they did it athough I did hear someone suggest it was to avoid throwing an extra page on the line printer if the last line was at the foot of a page.
Python .join() is strange, that code actually only puts the \n between lines, as you are probably more used to.

i use arch btw
IcyCoder
Scratcher
1000+ posts

Are these good bits of code?

Why not just this:

import math
print(math.factorial(n))

Last edited by IcyCoder (Aug. 4, 2017 00:40:21)


Because JS is the future (echos) future future futur futu fut fu f
bybb
Scratcher
1000+ posts

Are these good bits of code?

IcyCoder wrote:

Why not just this:

import math
print(math.factorial(n))
Because I wanted to implement my own factorial thing

Game Over
You'll find me on @LastContinue from now on.
Jonathan50
Scratcher
1000+ posts

Are these good bits of code?

gtoal wrote:

novice27b wrote:

print("\n".join("".join(w for d, w in dt if not i % d) or str(i) for i in range(1, 100+1)))

I haven't seen people outputting the \n before the text rather than after since the 60's. I was never sure why they did it athough I did hear someone suggest it was to avoid throwing an extra page on the line printer if the last line was at the foot of a page.
It's done in SICP.

Not yet a Knight of the Mu Calculus.
MegaApuTurkUltra
Scratcher
1000+ posts

Are these good bits of code?

No

$(".box-head")[0].textContent = "committing AT crimes since $whenever"
MartinBraendli2
Scratcher
100+ posts

Are these good bits of code?

Generally its really hard to say, whether something is coded well, because there are so many aspects. You can optimize your code on:
- Readability
- Maintainability
- “Reusability”
- “Parallelization”
- Scaling
- Performance
- Memory use
- Size
- Portability
- Time spent on writing the code
- How easy it is to debug

Aspects like performance and memory use have lost importance while maintainability has gained lots of importance in the last decades.
Every code is bad at some of those aspects.

novice27b wrote:

divisor_table = [
	(3, "Fizz"),
	(5, "Buzz")
]
 
for i in range(1, 100+1):
	output = ""
	for divisor, word in divisor_table:
		if not i % divisor:
			output += word
	print(output or i)
I generally like this approach . Its both readable (except for the ugly “if not 1%divisor:”) and easy to extend/ maintain. But it still has its theoretical flaws. For example its not allowing for parallelization (I don't know whether python allows for that at all, but Fizzbuzz as a task would be ideal to parallelize).
You could also argue, that it doesn't scale well with the number of Fizzbuzz numbers, => O(n²). If you leave away the string concatenation and use stdout.write() and stdout.flush() instead, you could get O(n).

TLDR: Code is always only good in certain aspects (but it can be generally bad).

Powered by DjangoBB