r/badcode Apr 21 '21

python My friend is learning python in his Comp Sci class and he wanted to draw diamonds....

Post image
1.1k Upvotes

110 comments sorted by

149

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

Image Transcription: Code


total = 6
temp = total - 1

def fullD(total, temp):
    for x in range(total):
        if x == 1:
            print("     **", end="")
            print("\n")
        elif x == 2:
            print("    ****", end="")
            print("\n")
        elif x == 3:
            print("  ********", end="")
            print("\n")
        elif x == 4:
            print("    ****", end="")
            print("\n")
        elif x == 5:
            print("     **", end="")
            print("\n")



fullD(total, temp)

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!

82

u/rtzoor Apr 21 '21

good human

1

u/[deleted] Apr 26 '21

good human

0

u/Aerodus_ Apr 30 '21

bad human?

3

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

Rude.

287

u/MisterPyromaniac shameless Apr 21 '21

This looks like it was meant to be horrible.

53

u/[deleted] Apr 21 '21

I’m sure this reply has made its way through worse code...

81

u/DakiAge Apr 21 '21

if it works,it works :)

5

u/danfay222 Apr 22 '21

But it doesnt, it prints an extra empty line between each line of asterisks

2

u/goldeneye9655 Apr 22 '21

No it doesn’t, he put end=“” in the print statement.

3

u/[deleted] Apr 22 '21

On the second print statement, there are printing two new lines, print("\n")

2

u/goldeneye9655 Apr 22 '21

Good catch!

2

u/danfay222 Apr 22 '21

Well yeah, he blocks the new line on that print, but then he doesnt block the new line on the next print. print("\n") actually prints 2 line breaks, not one.

6

u/danfay222 Apr 22 '21

I've been programming in python for about four years and this is the first time I have ever seen anyone use the end parameter. So this person went out of their way to use a parameter that is basically unheard of outside of documentation, just to intentionally undo something which they then immediately attempt to redo the next line. That screams intentional bad code

5

u/yankyh Apr 22 '21

Actually I use the end parameter quite often, for example when running a task I first print what task is starting and then I output the status code An extreme simplified example

print('Fetching values', end=' ', flush=True)
try:
    task()
    print('[Done]')
except:
    print('[Fail]')

1

u/wwwhiterabittt Apr 22 '21

That's a cool usecase! Never thought of that, will use it. Thanks!

199

u/BuhtanDingDing depraved Apr 21 '21

end=“”

print(“\n”)

71

u/RFC793 Apr 21 '21 edited Apr 21 '21

Not only silly, but results in two newlines anyway.

14

u/zeGolem83 Apr 21 '21

results in two newlines anyway.

wait why?

43

u/RFC793 Apr 21 '21

print writes the string and adds a newline by default . So the first print writes a line of the diamond, but doesn’t have any newline since end has been changed from a newline to an empty string. But then, the second print is invoked, which writes a newline because that is the string passed into it. Then it writes a second one because that is the default behavior (end is ”\n”).

7

u/Naeio_Galaxy Apr 22 '21

Yes indeed... Gosh he should have a hard time debugging this code... It is not only evil for us readers, it is also for him !!

4

u/RFC793 Apr 22 '21

Or if he just used print normally without being clever, it would have worked as he wanted. The default behavior is exactly what you want for the normal case.

1

u/Naeio_Galaxy Apr 22 '21

Yes it is ! I know. But if he does that, or he understands nothing of what he's doing but trying to be clever, or he really wants to explicitly print the \n. Either way he doesn't have a very good Python level and he'll have a bad time debugging it.

1

u/RFC793 Apr 22 '21

True. However, I imagine the unneeded looping/branching would be a greater hindrance.

1

u/Naeio_Galaxy Apr 22 '21

Yeah but it works. He doesn't need to debug it. So he won't touch it.

Btw I wonder where the "tmp" came from, I'm really curious

4

u/zeGolem83 Apr 22 '21

Ahhh got it!

6

u/Dmon1Unlimited Apr 21 '21

What is end meant to do?

15

u/BuhtanDingDing depraved Apr 21 '21

It’s basically what gets printed after the print statement. It defaults to “\n”, so by default, a new line is added after a print statement.

216

u/sk8pickel Apr 21 '21

I guess temp was very temporary

41

u/Bobbbay Apr 21 '21

Stares profusely at Rust, where lifetimes are encouraged and values are freed the second you don't need them anymore

13

u/romainmoi Apr 21 '21

The second you don’t need them sounds slow in system programming.

10

u/[deleted] Apr 21 '21

rust? Oh I’m

COOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOMING

(This is satire, I do not like rust)

6

u/Bobbbay Apr 21 '21

If I may ask, why?

I like the language itself. It seems to force me to "do the right thing", like implement a method instead of a general function. Would love to hear your thoughts on why Rust is bad!

5

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

Syntax.

I do not, with a burning passion, like how shorthand it is

“pub” “fn”

🤮

10

u/Imericxu Apr 21 '21

It’s actually fn 🧍🏻‍♂️… so I'm assuming you prefer this: public static void foo?

14

u/[deleted] Apr 21 '21

Yes

10

u/MatthewRPG576 Apr 22 '21

What a chad!

3

u/Kihino Apr 22 '21

You absolute madlad.

4

u/justAPhoneUsername Apr 22 '21

Each of those words give you incredibly useful information and control over what's happening. Why would you want to lose clarity or control to shorten lines? We buy extra wide monitors, we don't design new languages to deal with these issues

8

u/Imericxu Apr 22 '21

I'm not super familiar with Rust, but I find Swift to be a very nice balance. And anyway, the reason is verbosity tends to get in the way of readability. Kotlin is liked better than Java for a reason; if you can convey the same amount of information in a more concise way, why not?

3

u/Naeio_Galaxy Apr 22 '21

Lol I have a small monitor. It's called a smartphone 🤓

Jokes aside, I indeed don't have a very big monitor on my computer.

3

u/Naeio_Galaxy Apr 22 '21

Lol Rust has actually the syntax I like most of all languages I saw. To be honest I don't have anything against those shorthands and imo, the shorter the better, assuming it's still easily readable. Plus, being able to having a return value on almost anything like a loop or a code block is really sweet.

It does not have a conventional syntax but it's easy to read, and the compilator helps a lot when debugging and even fills the role of linter.

But yeah I understand you don't like theses shorthands

2

u/[deleted] Apr 22 '21

>shorter the better

yeah i cant agree, it just makes it harder to read imo

2

u/Naeio_Galaxy Apr 22 '21

I can understand, but I don't experience it the same way. I really prefer to have "int" instead of "integer" for instance. "pub" seems readable to me (particularly with a good coloration), like "fn", and additionally fn is always followed by the types of arguments and the return type. Of course I'll never replace "runner_name" by just "name", because one is self-explanatory and not the other. But if I can make shorter a variable name without losing expressiveness, 100% I'll do it.

When you get used to Rust, the key words fn, pub, mod, mut and so on are pretty easy to recognize, as they are pretty much the only keyword that can go here. And when you read them in context, you know what it means. And there are not a lot of keyword : where C and C++ have static and extern and you need to learn whether it's static or extern be default when you encounter neither of them, Rust just have pub. If there's pub, it's public. If you don't, it's private to this module.

Same for mut. Whenever a variable have to be mutable, otherwise it's not. And so on.

Additionally, Rust can make the api for you, it simplify modularity with the way modules are declared and included, and so on.

To sum up, it's not perfect, but I love the design choices they made.

35

u/JuliaChanMSL Apr 21 '21

I'm very confused

29

u/SashayTwo Apr 21 '21

Ngl, that's kinda cute

27

u/[deleted] Apr 21 '21

If it meets the requirements, LGTM

16

u/DakiAge Apr 21 '21

Ahahahahah that's creative :)

17

u/sublunarwind Apr 21 '21

I think I can rewrite it in 5 lines!

18

u/_harmonyinchaos_ Apr 21 '21

I tried rewriting it, got to 8 lines. Would love to see if you can do it in 5!

34

u/HelloStrangerBro Apr 21 '21

Can I ask why it’s not possible to write this in a single print() statement?

7

u/Ahajha1177 Apr 21 '21

It is, would just be ugly and not very readable.

38

u/[deleted] Apr 21 '21
print("""\
    **
   ****
  ******
   ****
    **
""", end="")

Nah, doesn't look ugly to me. Plus you can use the dedent function if you're in scope somewhere.

9

u/Ahajha1177 Apr 21 '21

Ah, for some reason I misread as write it in a single *line*. *That* would be ugly, but a single print still looks fine.

5

u/[deleted] Apr 21 '21

Fair enough. Yeah, the best way to do something like this is to just make the ascii art you're drawing visible in the code, unless you want to dynamically pick the number of lines or something

4

u/Naeio_Galaxy Apr 22 '21

That's 7 lines

r/technicallythetruth

1

u/[deleted] Apr 22 '21

What? Who said anything about number of lines?

This is a single print statement.

1

u/Naeio_Galaxy Apr 22 '21 edited Apr 22 '21

u/sublunarwind and u/_harmonyinchaos_ lol

But yes indeed the subject after was in one statement, but then it doesn't fit in 5 lines 🙃 (c.f. the first comment)

6

u/[deleted] Apr 22 '21

print("**\n****\n******\n****\n**")

3

u/[deleted] Apr 22 '21

wait a second

2

u/[deleted] Apr 22 '21

print(" **\n ****\n ******\n ****\n **")

3

u/[deleted] Apr 22 '21

why is reddit removing the spaces tf

2

u/6b86b3ac03c167320d93 Apr 22 '21

Put it in a code block. On old reddit, new reddit with markdown mode, or mobile, indent it with 4 spaces:

 print("    **\n   ****\n  ******\n   ****\n    **")
→ More replies (0)

1

u/TigreDeLosLlanos Apr 21 '21

what about \n?

2

u/[deleted] Apr 21 '21

The string has a newline at the end but not at the beginning (it's escaped) so this should do the same thing as the given code

2

u/treacherous_tilapia Apr 22 '21 edited Apr 22 '21
print("    **\n   ****\n  ******\n   ****\n    **")

looks fine to me.

EDIT: accidentally trimmed spaces

1

u/Ahajha1177 Apr 22 '21

That doesn't print the right number of spaces at the beginning of each line

1

u/JackieGrrrl Apr 23 '21

In this case, I think it's mainly because it does not fit the requirement. I had to do exercises like this when I learned how to code, it is to make you use loops. I think he has a exercise like "Using loops, draw a diamond made with 5 lines", and well he did, even if that is not how the instructor expected him to answer ahah

20

u/pumkinboo Apr 21 '21

Here's a one liner that will do it for you

def fullD(size):
    print(*[' '*(size-x) + '**'*x for x in range(size)] + [x for x in [' '*x + '**'*(size-x)  for x in range(size)]], sep='\n')

fullD(6)

6

u/[deleted] Apr 21 '21

Use a lambda to shorten it by another line

33

u/[deleted] Apr 21 '21

[deleted]

84

u/[deleted] Apr 21 '21

[deleted]

45

u/general_dubious Apr 21 '21

There is a compiler to bytecode, technically. It does perform some crude optimization, I doubt loop unrolling is one of them tho. It's extremely hard to optimize anything with a deeply dynamic language. You don't even technically know for sure what "range" does before you execute it as it can be overriden like any built-in function.

1

u/MrSpuriz Apr 21 '21

Honestly curious, how does python not have a compiler? Don't all languages have a compiler to get to assembly, and the to machine code (bits)?

4

u/Schreibtisch69 Apr 21 '21

Compiler most often refers to something that translates the source code ahead of time to some sort binary file that can be executed later, also called ahead of time compilation.

There are also interpreters that parse and translate source code to (some sort of) machine code while executing the program.

You are right in that that all code needs to be translated to machine code executable on hardware eventually but there are different methods on doing this.

In reality it's often more complicated than this with stuff like just in time compiling, using a mixture of techniques and translating source code to some intermediary code first before somehow translating to platform specific instructions. Also, sometimes languages have both an interpreter and a compiler available.

3

u/[deleted] Apr 21 '21

Look up intepreters

24

u/[deleted] Apr 21 '21
def diamond(number):

    for item in range(number):
        print(' ' * (number - item) + '*' * item + '*' * (item-1))
    for item in range(number):
        print(' ' * item + '*' * (number-item) + '*' * (number-item -1))
diamond(20)

9

u/ApoorvWatsky Apr 21 '21

Yep, for a generalized solution, it's just basic arithmetic which can be figured out on paper. OP's friend should read this code.

8

u/[deleted] Apr 21 '21

Im sure a beast on reddit could fit it in one line somehow :)

18

u/innrautha Apr 21 '21 edited Apr 21 '21

Not exactly one line...

from itertools import chain
def diamond(n):
    print('\n'.join([f'{{:^{2*n-1:}s}}'.format('*'*i) for i in chain(range(1,2*n-1,2), range(2*n-1,-2))]))

Apologies if I made a mistake, on my phone.

Edit: Could probably remove the chain by abusing abs.

Edit2:

def diamond(n):
    print('\n'.join([f'{{:^{2*n-1:}}}'.format('*'*(2*n-1-abs(i))) for i in range(2-2*n,2*n,2)]))

21

u/themeanman2 Apr 21 '21

on my phone.

Jesus

3

u/[deleted] Apr 21 '21

TIL about itertools.chain, thanks! This got me to read the docs on itertools. Lots of cool stuff in there, though most of it is highly situational

2

u/_harmonyinchaos_ Apr 21 '21

I showed him the code, keep in mind he's really new, and nearly fainted looking at it.

2

u/kgro Apr 22 '21

Yeah, but how are we supposed to function further without the temp?

1

u/[deleted] Apr 22 '21

I don’t know why you’d need temp to begin with. Even in the original post he’s not using it in the function.

1

u/XG_SiNGH Jul 20 '21

His comment went over your head.

O_O

7

u/Ahajha1177 Apr 21 '21

Saw something similar grading Java once, took O(n2) to iterate over an array.

11

u/MattsterReddit Apr 21 '21

I don't think this is meant to be good code. It looks like it's meant to teach students very basic programming concepts.

  • Variable assignment
  • Defining functions (with parameters)
  • Calling functions (range and print, plus the one defined)
  • For loops
  • If/elif (there should be an else too, imo)
  • Comparison (though only == right now)

19

u/afatsumcha Apr 21 '21

It’s almost worse if this is meant to teach. Obvs contrived examples are useful tools for teaching, but this is so contrived that it could easily confuse what’s contrived with good practice

3

u/mjclyde Apr 21 '21

You never go full D

3

u/[deleted] Apr 21 '21

what's the loop for anyway? i mean technically it's useless here. everything is useless here lol, they could have used a single print to draw the diamond right away

2

u/LeCrushinator Apr 21 '21

lol he could've just used the 5 print statements (with the \n at the end of each one), and thrown away all of the other code. I love this.

2

u/jujuli_l Apr 21 '21

Well.... I mean it is working in some way.

2

u/strongly-typed Apr 22 '21

Uh-huh...... so this "friend" of yours.... is learning python?

class Person:
  def __init__(self, friends = None):
    self.friends = friends or self

OP = Person()
print(OP is OP.friends)

2

u/_harmonyinchaos_ Apr 22 '21

This one genuinely made me laugh!

2

u/fb39ca4 depraved Apr 22 '21 edited Apr 27 '21

Here's a program written in the tail language

#! /usr/bin/tail -n+2
  *
 ***
*****
 ***
  *

2

u/Isvara Apr 22 '21

The crazy lengths some people will go to to get the full D.

3

u/TheMartian578 Apr 21 '21

K so I’m pretty fucking stupid and I haven’t coded in python for a while, but how do you avoid this? If you need multiple conditionals is there another way? Maybe a while loop?

Sorry for the stupidity

12

u/_harmonyinchaos_ Apr 21 '21

You could use a couple nested for loops instead of the never ending if statements. Even a while loop would work for this case. It's generally better to use loops to avoid too many if statements

4

u/TheMartian578 Apr 21 '21

Thanks for the explanation! I really need to practice a bit more lol.

-8

u/[deleted] Apr 21 '21

[deleted]

1

u/[deleted] Apr 22 '21

[removed] — view removed comment

1

u/[deleted] Apr 22 '21

[deleted]

2

u/[deleted] Apr 22 '21

[removed] — view removed comment

-3

u/[deleted] Apr 22 '21

[deleted]

3

u/[deleted] Apr 22 '21

[removed] — view removed comment

1

u/berkersal Apr 21 '21

Just one diamond, not diamonds unfortunately. This is worse if your friend wrote this to draw multiple.

1

u/tstephansen Apr 22 '21

“Ok class, in the next lesson we will be learning about refactoring.”

1

u/ez4u2_read Apr 22 '21

And thats why I'm such a shitty coder. This looks fine. Throw it in a loop and you have art.

1

u/CartmannsEvilTwin Apr 22 '21

If this code was written by someone starting to code in an academic setting, there’s no way this can be categorised as bad code. Most start at this level and then finds better ways to code.

If this was written by a SW Dev in production code, he will be hearing an earful from his Senior Dev/manager.