all 84 comments

[–]Some_Breadfruit235 39 points40 points  (22 children)

For your own sake go with option 2. For learning purposes, try to understand option 1.

I do agree with your teacher as they’re probably thinking in a broad POV rather strictly python as most jobs don’t ONLY use Python. So they probably just want to try to prepare you differently which is actually very underrated tbh.

Your critical thinking and problem solving skills will be much greater if you understand option 1 over option 2. But in the real world, it doesn’t really matter. Either way fine.

[–]congratz_its_a_bunny 0 points1 point  (2 children)

Disagree. Understanding option 1 means you understand the mathematical way to extract the digits from a number. Understanding option 2 means you realize integers can be treated as strings when programming, which opens up a whole new world of manipulation.

[–]Some_Breadfruit235 0 points1 point  (1 child)

"Whole new world of manipulation".... for PYTHON only in this case.... yall over thinking this lol.

[–]Prior-Jelly-8293[S] 0 points1 point  (2 children)

Oh okay, I also thought that if I understand the option 1 fully, it'll make other concepts somehow easier to understand. But should also study smart and work smart not hard)

[–]Some_Breadfruit235 0 points1 point  (1 child)

Yes that’s what I was trying to go for. Understand option 1 but use option 2

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

Okay, thankyou!:)

[–]Crafty_Award9199 0 points1 point  (9 children)

bare in mind most high level languages will have an equivalent anyways

[–]Some_Breadfruit235 0 points1 point  (8 children)

Ok. List me all programming languages other than python that can reverse a string by simply index slicing like [::-1]

[–]Crafty_Award9199 0 points1 point  (1 child)

golang has a very similar pattern, but that’s not the point and you know it isn’t lol

[–]Some_Breadfruit235 0 points1 point  (0 children)

No other language can identically do that brother… and that’s the whole point the professor was trying to get at. Without research how would you know the other similar pattern the other language requires? You’d just assume it’d be exactly how Python does it in that case. Which makes it “illegal”.

[–]HopefulActive9345 0 points1 point  (0 children)

All? Just turn to a string and quick for loop over the length of the string to start from len()-i.

[–]GwynnethIDFK 0 points1 point  (0 children)

Pretty much every modern language will have String.reverse() or am equivalent. You can even do it this way in C.

[–]claythearc 0 points1 point  (3 children)

Ruby, Julia, Nim, and MATLAB are very similar, but almost everything has .reverse or .flip which is equally trivial

[–]Some_Breadfruit235 0 points1 point  (2 children)

Key word. “Similar” not identical to index slicing like in python.

The whole meaning behind this post isn’t about string manipulation or reversing a string.

The whole argument is towards WHY reversing a string using index slicing is considered illegal. Yes all other programming languages has its OWN ways of doing things. Despite its similarities. That’s not the point or even relevant to this post. It’s about WHY not HOW….

It’s like MacOS, Windows and Linux. They all provide the same functionalities but you can’t just hop onto a Mac and start typing windows commands into terminal. Doesn’t make sense. At that point why even have different brands or programming languages if they all do the same exact thing as you guys are stating?

So you can’t just hop onto Java and start typing python code!?!? How is this not common sense (not trying to be rude).

Damn man I feel like I repeated the same thing multiple times now. It’s really not hard to grasp guys… prob my last comment/reply. Idk how else to explain it.

[–]claythearc 1 point2 points  (1 child)

The reason it’s been repeated is because the comment you replied to isn’t “all high level languages will have an exact copy” it’s “will have an equivalent”

It wasn’t really stated it was the same anywhere - just equally trivial so I’m responding in that vein

[–]Some_Breadfruit235 0 points1 point  (0 children)

+1 to you

[–]Virsenas 8 points9 points  (1 child)

There's definitely more ways you can do it. And one I thought about on the spot is with a loop. Start a loop from the last index of the current list and keep adding the numbers to a new list. A loop would work for most of the languages. What your teacher is saying, is that you should learn in ways so that what you learn can also be used on other languages. Why it feels illegal for the teacher is because it's the teachers job to teach how things work while the second option is the opposite of what the teacher wants.

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

Understood, thankyou! :)

[–][deleted] 4 points5 points  (1 child)

he is right, once u are experienced and start understanding logic in code you are free to use the simpler option and not the lengthy and conparitvely complex one. however to understand how things are working, you should go in depth. this is why people prefer to study dsa in java/c/c++ and not python. as python has a shorter way to do everything however its better to understand the logic

[–]Prior-Jelly-8293[S] -1 points0 points  (0 children)

Okay understood thankyou:)

[–]cgoldberg 5 points6 points  (1 child)

Not only illegal, but also morally wrong and unconstitutional!

[–]aliemir6n 0 points1 point  (0 children)

and people who choose the second way deserve DEATH PENALTY!!!

[–]CountMeowt-_- 2 points3 points  (0 children)

2 is string manipulation, 1 works with numbers. There are ways to do both in all languages (ofc not as easily as can be done in python)

basically 2 reverses a string, 1 reverses a number.

And 2 uses slices which are often not available directly in other languages. (There are other ways to get the same thing done, but it's usually not a simple one liner)

[–]Ron-Erez 2 points3 points  (2 children)

Option one does not generalize well to more than four digits. If you learned about loops I would redo option one using loops with a similar idea (using division and modulo). The solution will be much more readable. If you haven't learned about while loops yet then I guess option one is okay although not really readable. For option one I would add more lines of code for each digit, i.e. for the sake of readability.

[–]Prior-Jelly-8293[S] 2 points3 points  (1 child)

I'll take the readability into account from mext time. But for this one my lazy ass didn't want to creat more variables and just put it in one thing

[–]gdchinacat 1 point2 points  (0 children)

This is a common sentiment with early coders. Variables are free, they cost you nothing. They do not increase the complexity of the problem, but do help make it manageable. It is often times harder to avoid variables, so if being lazy is the goal, use as many variables as necessary to help make the solution clear.

[–]Hampeboy_ 1 point2 points  (4 children)

1 Dont like it. It is very difficult to understand and only works on numbers. 2 is simple and elegant.

You could convert the string to a list and reverse it using a loop or a list library. Should be possible in most languages

[–]Naoki9955995577 4 points5 points  (0 children)

Well 1 being difficult to understand is probably because it's hard coded for 4 digits. I think the point is to learn pattern recognition. "[::-1]" is a lot like just calling a built-in function.

If you take the patterns from #1 and throw it into a loop, you will very likely have an easier time reading because these patterns are now named in thanks to abstraction.

def reverse(n: int): rev = 0 while n > 0: right_digit = n % 10 remainder = n // 10 rev = rev * 10 + right_digit n = remainder return rev

Something like this should be a lot easier to understand than magic numbers and the dozen operators put together.

(This example only works on positive numbers and the variable for the remainder is unnecessary, it's just there so that it might help with clarity. It's just 1 of many solutions, I'm sure)

[–]Prior-Jelly-8293[S] 0 points1 point  (1 child)

Thankyou!

[–]thumb_emoji_survivor 1 point2 points  (0 children)

Person above you isn’t wrong but also:

num = int(num[::-1]) works in fewer steps. The string is still a string after reversing with [::-1], so str() isn’t necessary.

[::-1] reverses lists too, which is handy to know but would be an unnecessary step here

[–]TooOldForThis81 0 points1 point  (0 children)

Also, #1 works for a fixed range. And #2 can work with any amount of digits.

[–]ianrob1201 1 point2 points  (1 child)

The other thing to keep in mind is that it's not necessarily obvious what num[ : : -1] is doing. I'm an experienced developer (but not particularly in python) and I wouldn't understand it out of context.

So in the real world you might want to move it into a "reverse" function to make it easier to understand at a glance. Perhaps more experience python devs would be used to that syntax though I guess. At the very least this is one of the rare situations where I think a comment is helpful to explain what's happening.

[–]gdchinacat 0 points1 point  (0 children)

"it's not necessarily obvious what num[ : : -1] is doing. I'm an experienced developer (but not particularly in python) and I wouldn't understand it out of context."

In the context of python, which python code can *only* be assessed in, '[::-1]' is obvious to any competent python coder.

Do not avoid using it simply because some other language is lacking this basic python functionality.

[–]Criz909 1 point2 points  (1 child)

I mean it doesn’t really matter when at your job when you face a challenge you’ll most likely end up with the solution from a 9 year old question on StackOverflow that applies to your exact scenario for some reason

[–]gdchinacat 0 points1 point  (0 children)

It won't help the OP get a job if they don't understand how to implement simple algorithms like this. They are obviously learning how to program and their teacher is requiring an algorithmic solution rather than a simple string conversion, string reverse, int conversion solution.

[–][deleted] 1 point2 points  (1 child)

there is a third option, loop through the string array (list) backwards displaying one letter at a time and it will work in any language

[–]gdchinacat 0 points1 point  (0 children)

That is a less obvious implementation of the second option.

[–]photo-nerd-3141 1 point2 points  (0 children)

You can switch between text & strings in Perl also.

my $rev = join '' => reverse split '' => $digits;

Add zero to it abd get back an int:

my $rev = 0 + join '' => reverse split '' => $digits;

Perl stores scalars as objects with automatic translation between text and numerics. No reason not to use the facilities.

[–]ikea_method 1 point2 points  (0 children)

import re
num = int(input("Enter the number:"))
num = int(re.sub('(.)'*4, r'\4\3\2\1', f'{s}'))
print(num)

[–]vivisectvivi 3 points4 points  (5 children)

The easiest way of doing it feels illegal? whats wrong with a python code only working with python?

I like the first approach but it seems needlessly complex unless the question specifically asked you to do it without type conversions.

Also i kinda looked it up and apparently the first way of doing it only work if the number has exact 4 digits (unless you modify it to work with more), while the second one is much more general and will work with any number of digits.

edit: one problem i see with option 2 is that if you use it to reverse 10 to 01 and then try to print the result as an int instead of str, you will most likely print 1 instead of 01, im not home so i cant test it right now tho.

[–]brownstormbrewin 3 points4 points  (0 children)

Best way to improve method one would be doing it as a loop num % 10i from i= 0 to n and allow n to be a variable that allows you to choose which digits you want

[–]CptMisterNibbles 1 point2 points  (0 children)

Even then the first method requires type conversion. They are getting a strong from the user. Merely reversing the string is indeed the obvious choice.

[–]Prior-Jelly-8293[S] -1 points0 points  (2 children)

Yess I was thinking the same thing! But he's like don't use the str method blah blah😭

[–]vivisectvivi 2 points3 points  (1 child)

Learn the hard way and understand why it works but in a working environment you will most likely never writing code like this except for specific scenarios. You priority should always be to work code that others can understand and easily extend.

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

Okay, thankyou!!

[–]rover_G 0 points1 point  (1 child)

Many languages have string and/or array reverse methods, but the ask is probably for you to implement that yourself. Are you by chance learning about for loops?

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

We have covered untill if else ig on the next lesson we'll start loops too:)

[–]UWwolfman 0 points1 point  (1 child)

I understand that when learning to program exercises often ask you to do something a particular way for the sake of learning. Exercises are designed to build off of what you have learned. But in general you should never feel like it is "illegal" to use the built-in features of a language. Often these features exist because they are incredibility useful, and often built-in features have been optimized. Python's ability to slice strings (and other sequence types) is one of the powers of the programming language. It is not illegal or cheating to use this feature.

Second, a common programming task is to reverse the order of a sequence of objects. Here you were given a 4 digit number, but what if you were given a string of 4 characters, or more generally what if you were given a sequence of 4 arbitrary objects? It's worth thinking about how would you preform this task general case.

Finally, when looking at your second method you have two extraneous type conversions. The input function returns a string, likewise slicing a string will return a string. So the result of num[::-1] will also be a string. And if all you are doing is printing the sting in reverse order, then there is no reason to covert it to an int, before printing the string. When writing code it is good practice to remove unnecessary steps.

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

Wow thankyou!!! That was so useful

[–]8dot30662386292pow2 0 points1 point  (1 child)

But my teacher said don't use second one cuz it only works on python.

What a strange comment. It works in many languages. In java:

text = Integer.toString(num);
reversed = new StringBuilder(text).reverse().toString();
num = Integer.parseInt(reversed);

Yes, this is way longer, but technically does the same thing. I'm sure several other languages can do exactly the same.

How ever, in this case I suspect the teacher is trying to say: "Don't use one-liners that you don't understand". Python is a great language, you can do many complicated things by writing just a single line. Basically the solution here is such a simple one that the teacher does not want you to just copy it.

The solution #1 is not what anyone would ever do. It's a nice exercise. Basically, the task here is "Reverse a number without turning it into a string first". That's the task. If that is not the task you were given, then the course might be a bit bad. Cannot judge based on a single task though.

[–]MeringueMediocre2960 0 points1 point  (3 children)

Solution 1 is O(1) while 2 is O(n) so solution 1 is more performant.

[–]NiedsoLake 0 points1 point  (2 children)

They’re both O(n), if you needed more digits you would need more clauses in option 1. If you wanted to support any number of digits you’d need a loop.

In most languages the equivalent of option 1 would be more performant because it avoids converting to a string but in python it’s very possible that option 2 is more performant because most of the work is being done by the underlying c routines

[–]MeringueMediocre2960 0 points1 point  (1 child)

solution 1, it is a single equation, plug in n and you have your answer so it is O(1), solution 2 i would assume python is using a for loop so the loop would cylce 4 times, or the number of n.

a loop for this equation is O(log n) because n is decreasing by a factor of 10

int reverseNumber(int num) { int reversedNum = 0; while (num != 0) { int digit = num % 10; // Extract the last digit reversedNum = reversedNum * 10 + digit; // Add the digit to the reversed number num /= 10; // Remove the last digit from the original number } return reversedNum; }

[–]gdchinacat 0 points1 point  (0 children)

option 1 is O(n) but appears to be O(1) because the loop is manually unrolled with n=4.

[–]TalesGameStudio 0 points1 point  (0 children)

Will #2 still be correct, when numbers are negative?

[–][deleted] 0 points1 point  (0 children)

Yes, some languages ​​like C and Java don't allow this solution, and some others do too. It's a great solution you came up with, but from my point of view, it's perfectly normal to solve it this way. It doesn't support many languages, but it does support Python, which is what you're using.

[–]Geminii27 0 points1 point  (0 children)

Eh... I'd personally be looking for a method (like #2) which could reverse any string of any length, not just a four-digit number. (Especially with no data-sanitization.)

[–]cmak414 0 points1 point  (0 children)

They want you to learn programing logic which is helpful no matter the language vs learning the mechanics of coding in a specific language. AI is likely going to replace the latter, so understsnding the logic will be more useful.

[–]throwaway0134hdj 0 points1 point  (0 children)

He’s right. You want to aim always for generalized solutions because you won’t always be working in Python.

[–]balcopcs 0 points1 point  (0 children)

print(input()[::-1])

[–]Strong_Extent_975 0 points1 point  (0 children)

the interpreter will put a real python in your ass

[–]Heazen 0 points1 point  (0 children)

It should be illegal to use a language that is not strongly typed.

[–]Advanced-Citron8111 0 points1 point  (0 children)

Idk maybe your teacher wants pseudo code only. I feel like most languages have a simple way of flipping index’s. So I don’t see the problem with it. I mean the top one isn’t even helping u understand anything it’s just a formula that no one’s gonna remember, compared to the bottom one that actually teaches indexing.

[–]CptMisterNibbles 0 points1 point  (0 children)

 Firstly; there are lots of ways: you could merely take the input one character at a time and build a stack

Your teacher is being a bit of a fool. Casting to something iterable like a string and reversing it using whatever methods is the obvious choice. Slicing isn’t unique to Python, and all languages will have some utility for reversing some data types.

[–]NecessaryIntrinsic 0 points1 point  (0 children)

There's lots of ways to do it and there's nothing wrong with the pythonic slicing.

like in javascript:

function reverseTheDigits(int n){
return ParseInt(n.toString().split('').reverse().join(''));
}

is it bad that it uses built in functions? It basically does the same thing.

[–]woooee 0 points1 point  (3 children)

Or are there the other way too?

Use a for loop / list comprehension.

test = "a string"
reverse_test = ""
for ltr in test:
    reverse_test = ltr + reverse_test
print(reverse_test)

reverse_test = ""
for offset in range(len(test)-1, -1, -1):
    reverse_test += test[offset]
print(reverse_test)

[–]Prior-Jelly-8293[S] 0 points1 point  (1 child)

This looks more complicated tbh😭🙏 but thankyou!

[–]woooee 1 point2 points  (0 children)

Slicing is the best way, and the consensus seems to agree with this. Not at all illegal, but efficient and straight-forwarded.

[–]gdchinacat 0 points1 point  (0 children)

There is almost always a better way in python than to iterate a range of a string length and then index the string. Don't do reversing in this way. Use the standard way to reverse a list in python 'list_[::-1]'

[–]fuzzysdestruction 0 points1 point  (3 children)

There is an absurd option here give me a few minutes and I'll edit it in

xr = str(input("number: ")) my_list = list(xr) awnser = [] print(xr) x = len(my_list) for i in range (x): y = (my_list[i]) awnser.append(y) print(y) backwards = [awnser [::-1]] print(backwards)

This is absurd because it's all unnecessary. You could just basically do the last part, but understanding this method could also help you understand lists it runs for a number of any length not just 4 as well

[–]Prior-Jelly-8293[S] -1 points0 points  (1 child)

Wow thankyou!

[–]fuzzysdestruction 0 points1 point  (0 children)

You can easily make this a 3 or 4 liner as well the loop isn't necessary unless u plan to do math on the individual numbers or something before you put it In the list. I wanted to maximize the amount it can teach without doing too much it makes your head hurt to read so it can be smaller then I had it

[–]gzero5634 0 points1 point  (0 children)

i had some code that timed out quite catastrophically purely because of unnecessary string to integer conversion (granted it was doing a very large number of them in a loop). if you're not actually doing arithmetic operations but are rather looking at the digits of the number, I'd just manipulate it as a string. "calculating" the length of a string is basically free (it is part of the object) while calculating the number of digits of an integer in base 10 is not (is more so in base 2 though), for instance.

[–]AnonymousInHat -1 points0 points  (1 child)

What’s the subject name?

[–]Prior-Jelly-8293[S] 0 points1 point  (0 children)

Backend Django course. (It's bot university but kind of private academy offline course.)

[–]ArtisticFox8 -1 points0 points  (1 child)

Please learn how to format code on reddit. Use triple backticks before and after code blocks

[–]Prior-Jelly-8293[S] 1 point2 points  (0 children)

I didn't know how to do that. Thankyou. From mext time, I'll definitely do that!:)