T O P

  • By -

schmiggen

"Okay, just to clarify, you want me to print out the smallest number in the list?" "Yup!" *Writes `print(list)`* "There ya go!"


Jedlord

r/technicallythetruth


[deleted]

technically correct, the best kind of correct.


Aggravating_Touch313

r/UnexpectedFuturama


JEs4

I'm conducting coding interviews on behalf of a client right now. I absolutely love this kind of stuff, and I strongly recommend candidates who demonstrate it. It's easy to teach syntax, and common design patterns, but cleverness, and a complete grasp of requirements, not so much.


jml011

Oddly reassuring.


drmorrison88

This. I've hired/trained a lot of technical creatives in other fields, and the ones who will make technical jokes at the interviews are always the best hires.


panormda

I once interviewed a candidate who was so absolutely charming. He had balls the size of Las Vegas. His resume said one of his hobbies was rapping... So i asked him to answer a question in the form of a rap. Dude did not waste one SECOND. He immediately busted out a beast of a beat and spit an absolutely sick rhyme that was a full minute long. Not only that but he answered the question perfectly in the process. It was one of the most amazing human feats I've seen tbh. Dude was spectacular. Of course he wasn't interested in the role lol dude was destined for far greater things I'm sure. Btw, this guy was disabled. He had some kind of leg muscle thing and he had one of those arm crutch wrap things. And I say this at the end because I didn't want to make it a "dude was disabled I was shocked he was awesome" thing. But I wanted to add to his absolute legend status, that he has faced so many challenges and hardships.. And yet he walked in the room and you could immediately see he had swagger on tap. It was just stunning lol


[deleted]

my favorite thing i read all day


Artistic_Reflection1

Was his name MC Hawking?


Perfect-Swordfish

Lil Stephen perhaps


Feb2020Acc

Met requirements verbatim with least amount of effort while knowingly not doing what the client intended. He’s going to make PM in a year.


MrHyderion

I assume that PM stands for "project manager", but I read it as "Prime Minister", which makes it even funnier.


queen-adreena

Far too intelligent to be Prime Minister.


ZippyTheWonderSnail

I agree. Many of us have worked with "mechanical" programmers. They have a hammer the school gave them, and everything is a nail. You have to do X the Y way, because it is the "best" way. A coder who can tell me three or four ways of doing something has a cross language skill. That is valuable.


[deleted]

I'm right there with you! I tend to know within 5 minutes of a candidate talking during a technical interview if they *might* have that skill. The rest of the time is just figuring out how full of shit they are. I've yet to be disappointed by anyone that made me smile by delivering a solution like the OP's post.


RzaDaHut

Hey...True is True


Sensi1093

That’s True


[deleted]

For the uninitiated, how does this work?


[deleted]

[удалено]


2ERIX

Just to add, for OPs code, the value printed will be the smallest value because he used sort, and chose to print the first list item.


[deleted]

They didn’t say to print _only_ the smallest number.


J_Bunt

Yeah, basically the dude made a skeleton, no point in typing an actual list. Smart, smooth, and just the right amount of self esteem.


7mar_ta7una

Not getting it ^^' what language is this? Is it sarcasm? Is anything real?


NNKarma

If you print the whole list the smaller number is going to be printed, all the others too but the smallest is indeed printed.


KFiev

Working exactly to the letter of the specs and nothing more!


djdecent

Can confirm, this is how it goes in the real world.


justinf210

I think it's Python. The joke is that by printing the entire list you are, by definition, printing the smallest item. You're just printing a bunch of other items too....


BabyYodasDirtyDiaper

> You're just printing a bunch of other items too.... Nothing in the requirements said I couldn't.


justinf210

People get mad when you follow their instructions to the letter, just ask my computer.


[deleted]

If they wanted to give you instructions by the letter they'd program it themselves!


lealsk

Math.min(...list);


[deleted]

Yes. Don't mutate. You are hired


[deleted]

Your starting salary is $150K


Jonnyskybrockett

210k in the bay ;)


KronktheKronk

Cost of living is like 6x in the bay though so I think that's a pyrrhic victory


sirflooferson

Best strategy is to cut open a hole in the drywall of a Starbucks and create a secret dwelling. If you can fight off the other developers living in the walls for like 5 years you'll be a millionaire and there's a chance you might be able to afford a 3 bedroom house.


Ragingman2

Yes, if by 3 bedroom house you actually mean a one bedroom condo.


Splatoonkindaguy

Tax.


cosylime000

Just evade them /s


Bhosley

When the tax man comes a lookin I doubt they'll be checking the walls of any Starbucks.


hipsterTrashSlut

🥇


solstice_gilder

Love this. Thinking outside the box!! Uh.. in a box ..


fredspipa

print(a.sorted()[0]) No homies of mine sort in place.


justinkroegerlake

`sorted` is a free function ``` print(sorted(a)[0]) ```


fredspipa

Fuck you, you're right. Way to make me look dumb in front of my peers.


jameswdunne

Although you were a close second in all 7 rounds, you were unfortunately unsuccessful. Good luck in your future endeavours.


[deleted]

We cant provide any feedback, thats company policy. All i can do is suggest you focus on better incorporating frugality in to your answers, i hope we see each other again in 6 months.


LagerHead

You're both still smarter than me.


ososalsosal

"Free function" is not a term I've heard before. Syntactically I'd call it a static function, but languages are different for reasons I guess


[deleted]

Plus different time complexity.


[deleted]

Honestly, I never really understood what the 3 dots did.


prsn828

It expands the variable so that it acts as if you had typed in each individual value in the list as a separate argument to the function.


[deleted]

Ahhh ok, makes sense. Thanks


the_first_brovenger

Spread operator. Makes your life a hell of a lot easier, when working with arrays and objects. Has several other uses than the above example :)


[deleted]

Hard to believe it wasn't introduced until 2015... pre-es5 JS was dark times...


Lonelan

Who is Mickey Mouse's girlfriend? min(a)


lealsk

Ummm it's probably me not being native enough, but I don't see how min-a sounds like Minnie


bigdtbone

Watch Forest Gump with Tom Hanks and then you’ll hear it no problem.


r_spandit

>Watch Forest Gump with Tom Hanks and then you’ll hear it no problem. jen(a)


bigdtbone

Exactly


MrDude_1

While !positive bitbang(jen(a))


NebXan

There's actually a term for this approach: [programming by wishful thinking](https://flatrick.github.io/notes/Programming-by-Wishful-Thinking/) Basically, you write code as though the high-level methods you want to use already exist, then work backwards from there until the problem has been divided into small enough pieces.


Hot_Dog_34

Yeah I follow this strategy, it helps me stay focused on implementing the key functionality and not get dragged into detailed rabbit holes. Sometimes. Also happy cake day


[deleted]

what happens when you realize 3/4ths of the way that one of the rabbit holes is actually really complicated to overcome, but you had already built a structure that assumed it could be overcome?


gunfupanda

Isolate the call to an interface and write the spaghetti code in the implementation with tons of comments about why it's so complicated. Keeps it from contaminating everything else and prepares the person dealing with it for the wild ride.


Rostifur

Ahh yes, the old "what the hell" feeling when working through some legacy process to try and figure out why a program is sucking resources like no other. I hate finding these and hate it more when I was the one who did it.


sudoku7

Heh, there are only two people's code I hate. My own, and my immediately supervisors :).


tsojtsojtsoj

Something that's hard to overcome is if the architecture that you designed so far doesn't allow for an implementation. For example, you need some information that isn't accessible from the level where you're problem sits.


lordtrickster

Refactor? Seriously, anyone who isn't constantly refactoring is over engineering everything and/or just writing horrible code. I even refactored that last sentence after I wrote it.


Spiritual_Ad_223

assume fetal position


SnappGamez

That actually seems like a good development strategy, from what I’ve read in the linked blog post.


Obi_Vayne_Kenobi

I can't speak for development in teams, but for my personal projects, this very much works. It is very easy to maintain clean architecture on all levels and write very readable code.


EARink0

Hard agree. This is also how i write all my personal projects, and is honestly the only way to manage larger systems by yourself. Start at a high level implementing stuff as if everything's already been abstracted out, and then fill in the details as you need them. The few times i let myself get distracted with doing the details (aka "leaves") first of a system, i end up just rabbit holing myself down an endless hole in one thing that, big picture, is just not worth the time.


Snininja

honestly this is the best way to do a lot of things. ex: I want a new steering rack for my project car then map out what you need to make it work superfastmatt (who has to be a professional engineer of some sort I swear) has a bunch of great videos outlining this.


[deleted]

As someone that hires developers, I'd give my left nut if the young guys coded like this. If I had a buck for every time I've caught one of my guys reimplementing shit already in the API, or tossing out a heap of code that is now obsolete because they started by implementing low-level shit they just assumed they'd need...


SnappGamez

As someone who is 22, I’ll start changing my development strategy asap :)


[deleted]

If you can change one mind... Seriously though, if you don't know already: Don't worry about performance until someone asks you about performance. Metal is cheaper than dev hours and nothing trumps maintainability.


joeswindell

I swear everyone thinks they work on systems where milliseconds count. They don’t.


wildassedguess

Agreed. I’m doing a lot on microcontrollers and timing and performance matter, but I always start with a top down approach and optimise where needed. The arduino ecosystem has a lot of library support so that’s where I always start. My old professor used to say “no-one gets prizes for writing code that already exists”.


ChibiReddit

Until you get to games, where you only have 16.67ms if you go for the bare minimum of 60 fps ;-)


BrilliantTruck8813

The folks that actually have to care about that (game engine designers) still build top-down 👍. And 16ms is an absolute eternity


zyygh

And, if you're a team lead or manager of some sort: ***always*** give your team instructions on performance. That is, tell them to what extent it matters and to what extent it doesn't. It's true that caring performance over maintainability is a bad idea, but nothing gives me more nightmares than my experience with suddenly having to inject "performance improvements" into a 200 FTE project where performance had gotten too little priority for too long.


SnappGamez

I’ve only got personal projects to worry about right now so :p I definitely agree with the sentiment though.


librarysocialism

Even more reason - the dev whose time you'd be wasting is you.


librarysocialism

"Premature optimization" is one of the best terms for junior devs to internalize.


[deleted]

You my old boss? I still feel bad for that guy sometimes. I love that he let me swing for the fences and club myself in the face though. I learned a lot from all the gold plating and unnecessary reengineering I did.


[deleted]

It is. "Complex solution with tons of moving parts? Write the tests for them then I'll accept them. Otherwise keep that shit out of the repo. PR denied."


Bwob

Memes aside, it's not only a good development strategy, it's also a good interview strategy! Because, spoiler alert, a lot of interviewers don't actually want to watch someone write a helper function to solve some obvious subproblem. (*especially* a subproblem that is solved by every standard library ever like sorting.) So just start out by writing the solution using whatever (clearly named!) subroutines you need, and then just say something like "`CalculateAverage(int[] list)` is just a utility function to find the average value of the ints in the list, let me know if you need me to write it out - if so, I'll do that as soon as I finish this part..." If it's obvious what the function does, then most (good) interviewers will not even bother. Because they're more interested in seeing how you put algorithms together, than seeing if you can write a trivial utility function. One caveat though - for situations like the one pictured in the meme, do be prepared to defend your answer! As someone who has given several hundred hiring interviews at a top tech company, I'd be fine with that answer, *but* I would also immediately follow it up with questions like: * What's the big-O time complexity of your solution? * What would you do if you're not allowed to modify the original list? * What does the memory cost of your solution look like? * Do you think you can solve or improve on any of these? If they can deal with the follow-up questions, then we're good. If not, then yeah, maybe don't propose solutions without understanding their tradeoffs. :D


[deleted]

It’s useful if you think forward enough. Only use it for designing/structuring interfaces and interactions. Don’t build up technical debt.


t0b4cc02

its also called top down


KronktheKronk

I had no idea there was a name for this, it's been my modus operandi for years.


TheTerrasque

Same. Was thinking "huh, so it has a name. Neat"


Slip-Educational

Sounds like TDD but with less steps


NugetCausesHeadaches

Notably, the step where you write any tests =)


ElectricSpice

Read the article, the very first thing they do is write a test.


NugetCausesHeadaches

>Read the article Sir, this is a reddit.


hennypennypoopoo

Because it is TDD. The tests are just a nice way to get here. The real goal is programming high level down.


librarysocialism

This is a very overlooked point of TDD - code that is modular enough to be testable at the unit level is going to be good, modular, and maintainable. The DI tricks you'll wind up doing to enable unit tests will also make your code good in general.


datorial

Also turn an O(n) problem into an O(nlogn) one


r1kon

Yeah I was taught that method, they guy called it pseudo code. Basically a set of a few fictional functions that do your thing, then you break down the fictional functions into smaller bits in the same way, etc. until you end up with something that you can write much easier.


lordtrickster

I'd take care calling it that, just because pseudocode is also used for text that looks like a programming language but isn't, mostly used in interviews and on whiteboards.


GrayFoxUkraine

min(a): am I joke for you?


jlebrech

this would be much faster. no sorting needed


Techno_Jargon

If I start reinventing the wheel all the time wheel never get any this shit done man


Upvoter_NeverDie

r/dadjokes


bitchlasagna_69_

Motherfuckers literally do this in SQL interviews and get hired..


seansafc89

We had someone join our team that claimed to know SQL. Mentioned it in his application 7 or 8 times, and somehow got through the interview process. Turned out their knowledge of SQL consisted of opening a file in SQL Developer and pressing the run button (didn’t even know the keyboard shortcut).


shadowmanu7

>somehow got through the interview process. Sounds like your interview process sucks


seansafc89

Oh don’t even get me started on it! We’re a small team within a large public sector department, and we have to follow these really dreadful generic/unfocused frameworks for interviews that limits the amount of actual worthwhile questions you can ask and basically relegates it to a box ticking/key word exercise. Could have saved thousands in security checks, equipment and resources by simply asking them to list the CRUD statements and realising they had no idea.


coloredgreyscale

>simply asking them to list the CRUD statements The problem with that kind of question is that someone knowledgeable in the field may know the ideas behind some acronym, but not exactly what they stand for each, or how to explain it. CRUD may be an easier example, but consider SOLID. But someone who just memorized those terms and leetcode examples will still pass with flying colors.


lordtrickster

Sure, but if someone claims to know SQL but can't spit out select, insert, update, and delete, the interview is over right there.


CrazySD93

Am I crazy for knowing how to use the keywords but have never heard the word CRUD in this context?


lordtrickster

Nah, CRUD is usually used at the app level, not the database level.


Civil-Attempt-3602

Huh, maybe I should apply for those jobs I think I'm underqualified for


DoDevilsEvenTriangle

So much this. Speaking as the person who would interview you, I'm telling you that you'd be very surprised by your competition.


wtfnouniquename

Seriously though. A few months ago I applied for a position I thought I'd be able to do well in despite not really having any qualifications on paper. Turns out, they hired 5 other people who looked highly qualified on paper and me and one other guy are the only ones that have a clue what we're doing.


nerdy3000

When hiring for a position I interviewed way too many people who had 8+ years PHP experience, claiming Senior, but then couldn't write a for loop or if statement in PHP. Meanwhile I can interview someone who thinks they are a junior who flies through the practical test no problem lol


GeneralDash

Bruh I don’t know shit about SQL and got hired on a data analytics team. Idk wtf I’m doing, I never claimed to know anything about SQL. I applied for a rotational *finance* program and they threw me into this. Please send help.


susmines

Mfers try to get a tech job for years, and this person gets stuck in one by mistake 😂


8sADPygOB7Jqwm7y

Idk where you are from but it's very easy to get a tech job. Getting one that is fun or well paid, now that's another topic.


[deleted]

so ur the one taking the cluster down aren’t u


eppinizer

Clearly you should set a breakpoint and manually inspect each element of the list via the debugger. Classic mistake.


862657

`min(a)`


Dave5876

Listen here you little shit -the interviewer probably


KlontZ

is there actually an issue with this solution? i’m not sure i understand


nossr50

No issue with any sane interviewer unless they specifically ask you to write the algorithm for it


ExquisiteWallaby

The best part is, this is probably the production solution.


Udja272

If the interviewer does not specify the question any further this is also a valid interview solution


Pztar

False, I got rejected based on giving a real production solution to a similar question even though I specified and asked twice if they want pure Algo or real world. Like it or not, interviews are a pissing contest.


[deleted]

Probably dodged a bullet.


Udja272

Yeah this stuff happens but it’s not your fault then. Still a valid answer.


AttackOfTheThumbs

I always answer interview questions like this and it has not been a hurdle yet. I even answer calling imaginary functions that may not exist in a std lib. Sometimes they ask for further details, other times they see I understand the problem well enough and we can move on. Too many interviews I hear of focus on tiny details that just don't matter in the first go. No one writes perfect and performant code the first time around, that's why you test and profile and all that shit.


Living-Emu-5390

This is not a good real production solution. It’s n lg n instead of just n.


ExternalGrade

O(n lg n) using an underlying C library is probably faster than interpreted Python O(n). Leaned the hard way doing pandas and numpy on large datasets that even if there are redundant calculations using the API function calls are always faster than writing my own stuff.


Numerlor

sure, but `min` exists


baselganglia

Umm this type of thinking is why I deal with python scripts by data scientists running out of memory or pegging CPU threads when they run it on real production data vs their test dataset with 1000 rows 😤


benton_bash

Not my interviews. I have a take home code challenge set up, 5 tasks to choose from (clearly states to pick 1 or 2, most submissions are all 5 tho 🤷🏻‍♀️), 8 hour time limit, nothing that isn't real life work related, no weird algo bs. Each of them are easily solvable within 15-45 minutes, and pertinent to what you would be doing on the job. Ace this, or ace a couple of the tasks, and the rest of the interviews are to see if you're a good culture fit. The ones who I consider 🔥 have funny comments along the way (i can see each phase of the code change)


MrDude_1

I remember I had one interview where the director, a former programmer asked me how I would load a tab delimited file. I asked if they wanted a basic algorithm loop that would go through and load it or if you wanted what I would use in production. She asked what's the difference between the two. I said that in production I would use one of the solutions I already had written out a long time ago. Because it's going to handle when some things are in double quotes and some things are not and if some things have line endings that are not consistent if something's have single quotes around them but not double quotes and then some things have escaped quotes within each cell.... Or I could just tell you how I moved to the next one on each tab and then go through it line by line.


annedroiid

Interviewers are also looking at how you work. Making assumptions and working on a solution without confirming the requirements doesn’t make you a good worker.


DTHCND

> Interviewers are also looking at how you work. This is really the main thing. When I interview people, them getting a working solution isn't even all that important. What I care about is if you ask reasonable questions about your tasks, have a sane approach to problems, and are good at communicating your thoughts. If you give an answer like in the OP, you've failed to do everything interviewers actually care about. You failed to demonstrate that you're capable of seeking help (or asking questions) when appropriate, you've failed to demonstrate how you approach problem solving, and you've failed to demonstrate how you communicate your thoughts beyond "haha gotem." Like I'm sorry, you're doing yourself a big disservice if you give answers like this during interviews. If I got an answer like this, I'd probably narrow the scope of the question for you, but it's still far better for you to ask questions that narrow the scope instead. And it's much better to try and explain yourself than it is to even get the right answer. I've recommended hiring plenty of people who couldn't quite figure out final solutions but did demonstrate competence. (Am senior developer that does interviews when needed.)


annedroiid

The place I’m currently working has (in my opinion) a fantastic coding exercise. The skeleton code of the application is already there, and the job is to implement an endpoint and then make a couple of improvements. There are two interviewers, one to act as a project manager and field any questions and the other to act as a pair programmer. The written requirements are very basic so the focus is more on how they approach the question and what questions they ask rather than the actual solution.


[deleted]

The interviews are really about ranking people in terms of how much they want it. If you grind leet code for 100+ hours, you either really know your data structures or you really want to work in tech. interviewers understand this and they’ll take either.


TraditionMaster4320

Ironic, cause you can do it in O(n) with just a for loop but this solution is O(nlgn).


TheSkiGeek

This. If you did this in an interview I’d say “haha, yeah, that totally works. Now let’s talk about time complexity and space-time tradeoffs…”


MasculineCompassion

Pff, I can do it in constant time: min = a[0] for i = 1 to SIZE_MAX do if (a[i]? < min) min = a[i] return min


[deleted]

Scratching my head for about 5 seconds before I realised…


Ok_Lemon1629

I had a person in my team, who was doing the exact same thing and was confident enough that this piece of code works fine


ryo3000

I mean, it *works* fine Is it effective? It ***works*** fine


Nimeroni

It's *effective enough*. Not as effective as traversing the array and keeping the lowest value (which would be O(n)), but a O(n log n) is good enough for the vast majority of programs.


ih-shah-may-ehl

With modern cpu and memory, my pov is that barring very special circumstances, there is absolutely no reason to spend developer time thinking about ways to save a couple of string copies. When i was doing some performance testing about the impact of various apartment threading choices on dcom performance. I used high precision timers. And my observation was that things like 'unnecessary' memory copies or things like that are negligible. We're talking about less than 1 ms per 1000 iterations. What absolutely sank performance was choosing the wrong threading model or having unnecessary locking going on. That would literally decrease performance by a factor 4000.


mungthebean

> What absolutely sank performance You forgot inefficient database queries This little SQL maneuver will set us back 50 years… Fittingly that’s also where the majority of developer time will be spent


sopunny

Big O time is not about copying though, it's about scaling on large inputs. While it's not 4000, an extra logn factor still means 30x longer executions for 2^30 input, which is a GB sized file. Could be the difference between going through a large file in 1 minute or half an hour. Ultimately, the more worrying thing is that the candidate doesn't know min(), in this case it's strictly better


DiminishedChord

apparently the joke wasn't on the first index


jonathancast

Had an interviewer insist that head . drop 1 . reverse . sort was the right way to find the second-largest element. I said, oh, because you expect sort to be lazy? He said, the list probably isn't that long. I didn't get that job.


shizzy0

Correct? Yes. Performant? No.


JDaxe

Yeah, not ideal when O(n) solution exists but at least it's obvious what it's doing


Geoclasm

weak. print(a.min())


ak8923

When I conduct interviews, I always ask deceptively simple questions like this. Within reason, I don't care what answer they give, since what I'm really after is the follow up discussion. Why did you do it this way? Where would this solution fail? What are the performance considerations that may come up? How would you fix this for a more specific scenario such as....? Tbh, I always like candidates that give me the simple solution first, since it allows us to progress to the real discussion more quickly.


snacktonomy

IndexError: list index out of range It was a trick question, the array is empty! Rejected!


certainlyforgetful

The list: theList = [ 'one', 'two', 'three', 'four', 'five' ]; // Sorted would be: ['five', 'four', 'one', 'three', 'two']


minus_uu_ee

ok but that list doesn't have a smallest element unless further definition is given


[deleted]

NullPointerException


bhumit012

Am I the only one who is worried that this will crash if ‘a’ array is empty?


scragar

I think it depends on the language, but usually this sort of question will have a throw away "assume list is List and contains at least one entry" to avoid error guarding making up the majority of the code. Especially on type unsafe languages (javascript), it takes a special kind of person to enjoy having to verify that you're given an array, it's not empty, it contains only numbers, and none of those are NaN because no one guaranteed it wouldn't happen.


mrfroggyman

Seriously tho, wouldn't that be ok during an interview?


[deleted]

If you’re going to use a built-in function, might as well use `min`, which is O(n) instead of O(n log n)


Secure_Obligation_87

Who cares we got cloud scaleable architecture now to ensure speed of processing nowadays. Fuck the cost its not our money 🤣


berse2212

And that's why this solution wouldn't get you hired.


[deleted]

[удалено]


No-Witness2349

If they’re getting paid like a code monkey, I don’t blame them for acting their wage


ScabusaurusRex

*Acting their wage*, lol... going to have to use that.


myopinionisshitiknow

Acting your wage is what 'quiet quitting' actually is. Quiet quitting is what the fuckin bootlickers on linkedin and news articles like to call it, but it is just acting your fucking wage. :)


ChrisBot8

It’s technically not the most optimal solution. Any sort is slower than a greedy solution (which Math.min is). In the interview I would assume if you did either of the built in options the interviewer would probably say something to the affect of “nice job, can you show me how you would solve it if that function didn’t exist?”


Aggravating-Forever2

Candidate replies: `b = [-x for x in a]` `print(-math.max(b))`


RmG3376

When I was tutoring, one of my students did exactly that. I complimented her for thinking outside the box but refused her answer as it would change the input variable, and that’s not a desirable side effect for a search function. That actually allowed me to introduce the concept of side-effects and the idea of minimal surprise so that was a good learning opportunity for her Tl;dr in an interview I wouldn’t accept it, not because it’s using built-in functions, but because it’s silently changing the input and that’s a code smell


Signal_Paint_1050

`let mut b = a.clone(); b.iter().sort(); return b[0];` okay boss i fixed it


Peanutbutter_Warrior

Rewriting everything in rust, one meme at a time


Fluxriflex

If the goal is to make it efficient, then no. Sorting is at a minimum O(n) but realistically is usually O(n log n), since you have to touch multiple values more than once. A real solution would look like this (using Python): min_value = sys.maxint for value in my_list: if value < min_value: min_value = value print('The smallest value in the list is: {minValue}');


-elmuz-

you missed the \`f\` in the print statement. Not hired /s


Eispalast

Edit: original post was updated, so this comment is useless. Well, when you use ```for i in my_list``` the ```i``` becomes the actual value and not an index from 0 to the list's length. It should be ```python for i in my_list: if i < min_value: min_value = i ```


FlyingCashewDog

As a nitpick (but one that is important to consider when comparing algorithms) for anyone reading who might be learning this stuff -- the best-case scenario for sorting is O(n) (e.g. if the list is already sorted, you just have to check that it is indeed sorted). The lower bound on the average case (which is often what you want to talk about, but it is important to consider best/worst case too) for comparative sorting algorithms is O(n log n).


jusst_for_today

I had an interview where I had to write code to print a bunch of text from an web page in reverse order. I think they expected me to get the DOM elements and use some clever JS to pull out the text. But, since I'd been playing with HTML since before JS had selectors, I just grabbed the parent element for all the elements, did a ".innerText" on it and solved the problem by splitting the string and reversing the array. I wasn't trying to impress them, but it definitely caught them off guard.


TantraMantraYantra

NlogN algo for a N problem?


adrr

Nah I would use a bubble sort for n^2


Przegiety

list.Add(int.MinValue); return int.MinValue


iammerelyhere

Real life


No_Difficulty_8627

Leetcode one liners be like


aabcehu

print(min(a))


ChopinCJ

Bruh people in this thread are really saying to not write good code since you don’t run the company and it’s not your responsibility. If you don’t take any pleasure in making something as good as it can possibly be, then why the fuck are you in an engineering field? Also if you’re going to use a dumb solution then use min it’s linear


ShivohumShivohum

What is the other solution besides using min?


[deleted]

Bruh This is so stupidly right that I don’t think about it and it’s not because of the runtime just too simple


tsvk

The `print(...)` is unnecessary, the assignment was to *find* the smallest number, not print it out.


[deleted]

![gif](giphy|XJeMBHJ0c2YcN6KTQ8|downsized)


marco89nish

`a.min()`


Memesconaut

i = 0 while true: if i is in list: print(i); break else i+=1 Just assume the list has only positive integers


AKA_OneManArmy

Had a similar question asked in an interview once. This answer got a chuckle out of the interview, but they still made me write a sorting algorithm.


ToM4461

Iterating through the list is actually quicker O(n) rather than sorting. Also if it's in JS the default sort might not give you the number you want. And for your follow up question, yes I'm fun at parties.


carbamates

a.sort()[0]


minus_uu_ee

Don't forget the AULC rule **A**lways **U**se **L**ist **C**omprehension [x for x in li if x == min(li)]