r/PythonLearning • u/RegularBother614 • 2d ago
What do you guys think?
I made a program that finds the second largest digit in a list.
Using the list method "remove()" and "max" function. Python is COOL!
20
u/NoMakeSenseOk 2d ago
You can keep the list intact and print the second-to-last value of a sorted list.
numbers = [3, 10, 21, 54]
numbers.sort()
print(numbers[-2])9
u/NoMakeSenseOk 2d ago
Or if you want to write fewer lines:
numbers = [3, 10, 21, 54] print(sorted(numbers)[-2])3
u/RegularBother614 2d ago
Thanks! Is there any way I can ask for user input and store it in a variable list?
variable_name = input() variable_name = [ ]
2
u/Potential_Fix_5007 2d ago
my_list = []
my_list.append[input("Enter a number:")]
Like this the Program will wait untill the User enters something, but keep in mind that input() will always return a string so if you need a number you need tho convert it.
1
u/Money_Ad_5277 2d ago
How your input should look like?
If you just want a list with single user input, you could do
variable_name = [input()]6
u/Potential_Fix_5007 2d ago
But you have to keep in mind, that sorted() creates a new list so the original list is still chaotic. That can be intentional.
2
u/NoMakeSenseOk 2d ago
I should've mentioned this, since every new list or copy thereof increases memory usage. For less memory usage we use references rather than copies.
2
u/Potential_Fix_5007 2d ago
You are right but as far as i know "memory usage" is a topic you dont need to keep an eye on while learning. Early projects will nearly always count as "low memory" so dont panic over this directly
7
3
u/Vigintillionn 2d ago
well, to be honest, their solution is more efficient being O(3n) ~ O(n) while yours is O(nlogn). Not that it makes much of a difference, for small lists O(nlogn) might even beat theirs but asymptotically theirs is more efficient
1
u/PureWasian 2d ago
What if the array is [0, 1, 2, 2]?
What if the list has 1mil numbers? Why would you sort for O(NlogN) when it can be found in O(N)?
1
u/Strong_Essay1176 1d ago
I hope you are not dev.
1
u/NoMakeSenseOk 1d ago
I'm indeed not a dev, no. Still learning.
2
u/Strong_Essay1176 1d ago
Just do a,b=numbers[0],numbers]0] In loop set max to a and prev max to b.
Any kind sort - is like rebuilding whole building just to open 2 doors.
3
u/Potential_Fix_5007 2d ago
Im not sure, but it would change your list, so it would be "numbers = [10, 3, 21]" So you "lost" the largest number. You could sort the list and print the second number from the end.
numbers = [10, 54, 3, 21] #your starting list numbers.sort() # sort list to [3, 10, 21, 54] print(numbers[len(numbers) - 2]) #create the correct index from len()
1
u/RegularBother614 2d ago
I didn't know there's a list method of sort() 😂. I still have a lot to learn
1
u/Potential_Fix_5007 2d ago
Thats okay. Im still learning, too. Your way would donthe trick but you will lose the highest number, if you fine with that its a legit way to solve the problem.
1
u/RegularBother614 2d ago
Thanks! Can you recommend sources for me to learn more? It'll be really helpful
1
u/Potential_Fix_5007 2d ago
Sorry not really, i use AI to explain things to me and fumble me through my ideas, im not sure if that would be a good recommendation.
1
u/MarkRems 2d ago
The source I typically recommend beginners is "Automate the Boring Stuff with Python". It's free: https://automatetheboringstuff.com/
3
u/PranDopp 2d ago
Good stuff! Progress always comes with small wins! Now next task: test if sorting the list and pulling the second highest number is faster than running two max functions with a remove. Let me know!
1
u/RegularBother614 2d ago
I really don't know LOL, I just started learning an hour ago on YouTube. But can you give me a hint and what functions I'm gonna be using on this task?
0
2d ago
[deleted]
1
u/RegularBother614 2d ago
It says error everytime I run the program? Do u mean "sorted"? Cause that's what the error is
1
3
u/halfjmp 2d ago edited 2d ago
Several possible problems: 1/ you modify the list 2/ if the max has duplicates it will remove only one, so depends whether or not you want the first number below the max and 3/ If the list has length <2 it will fail (but it's bound to fail anyway, just mentioning you have a corner case waiting to bite)
For 1/ you may sort, or loop other the list and do the bookkeeping by hand (sort is O(n log(n)), bookkeeping is O(n) but it's a Python loop, so slower than compiled code).
For 2/, you may convert to set first.
It all depends on the specs you want, and you didn't give any.
0
u/Inevitable-Study502 2d ago edited 1d ago
thats a little bit destructive
numbers=[10, 54, 3, 21]
import heapq
print(heapq.nlargest(2, numbers)[1])1
u/RegularBother614 2d ago
What's "haepq" ?
1
1
0
u/sexiestsaxiestman 2d ago
The easy solution is to convert to set, sort, then get the second to last sorted value. Some points to consider:
your original solution modifies the array
sorting has O(nlogn) time complexity
doing a partial sort of the max 2 elements would be O(n) instead which is better
consider edge cases, <2 element array, array of only 1 unique element ex: [1,1,1,1,1], return None or raise an error maybe
1
u/RegularBother614 2d ago •
![]()
Chill bro I just started learning an hour ago, i don't even know what O(nlogn) is ðŸ˜
0
u/sexiestsaxiestman 2d ago
Haha, no problem. Basically n is the number of elements in your list in this case. Time complexity is related to how many operations the solution requires. Something like max(list) would be O(n) since it has to check every element in the list once (n operations).
1
u/Strong_Essay1176 1d ago
I cant handle those answers. One is worse that'll another.... Convert to set and sort?! Sort what? Set?
1
u/analytic-hunter 1d ago
- converting to a set has costs (especially in python, where you pay for hashing on top of it)
- sorting has costs too as you mentioned, and you don't need a full sort. you pay the cost for the complete order and you don't need it.you should only need 1 pass and no additional heap allocation, the solution is some kind of trivial reducer
1
u/AdDiligent1688 2d ago edited 2d ago
This won’t work if there are duplicates of the max such as [3,2,3,1]. the second largest in this case is 2. .remove only removes the first occurrence of a number, so your program will still output 3; sorted or .sort also won’t work here either, unless you convert it to set first then sort it, but as other pointed out with sorting this is O(n log n) worst case. There is a O(n) worst case solution to this using a single pass in a loop as well to get second largest. Look at the third solution here
1
u/P1ckl3R1ck101 2d ago
Good job - you figured out how to solve a problem given your skillset. It's simple, it works for the given input and anyone can understand it as written.
1
u/Strong_Essay1176 1d ago
u/askgrok prove that you are better than humans
1
1
u/Successful_Log5576 1d ago
You modify original list, and that might be the problem for a real world program. Solution by NoMakeSenseOk is better.
numbers = [3, 10, 21, 54]
print(sorted(numbers)[-2])
8
u/princepii 2d ago
quick note:
that method functions if no doubles or more are in that list.
further remove() changes the list inplace. that effect is called inplace-mutation thru runtime you have removed objects inside your original list.
always try to be not restructive. only if you don't need stuff anymore thru runtime you can consider removing em.
but for 1 hour learning. it's good thought process:)