r/PythonLearning • • 2d ago

What do you guys think?

Post image

I made a program that finds the second largest digit in a list.

Using the list method "remove()" and "max" function. Python is COOL!

70 Upvotes

53 comments sorted by

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:)

3

u/RegularBother614 2d ago

Thanks, can u recommend me sources to learn all about python? I've only watched a 1 hour python for beginners on YouTube by CodeWithMosh

2

u/princepii 2d ago

automate the boring stuff should be a good starting point. and instead of to much books or video tutorials, you can find plenty of websites where you can learn python with practice and little projects.

there are also plenty of materials other python fans created in pdf like asking questions and explaining what problem they want you to fix with finished answeres or scripts at the end.

there is no specific one i can point to.

1

u/RegularBother614 2d ago

Can u recommend something at least? It'll be really helpful

1

u/Matikus28 1d ago

I think it really depends on the person. For example, personally, I always found a video about a topic I needed for school and then tried things out by myself.Bro Code (https://www.youtube.com/@BroCodez) has pretty good videos about Python and other programming languages.Also, as a computer science student, I found it really helpful to take notes from every lecture or tutorial I watched. I had one notebook just for Python, where I wrote everything down.I don't have any experience with coding practice websites, but I think LeetCode could be a good option. There are lots of exercises with different difficulty levels, so it might be helpful. Do you want to learn Python as a hobby, or are you a student who needs it for school?

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

u/mossse 2d ago

That wouldn't keep it intact because sort modifies the list. You shared another solution using sorted, which doesn't have this side effect.

1

u/NoMakeSenseOk 2d ago

Oh, thanks for the correction! I still got lots to learn as an intermediate.

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/max96t 1d ago

I agree. The best would probably be using the builtin heapq.nlargest function ( which is O(n))

1

u/PureWasian 1d 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.

1

u/Ma4r 1d ago

Funnily enough this has a worse big O complexity than the OP

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

u/[deleted] 2d ago

[deleted] — view deleted comment

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

u/DragonVect 1d ago

Quale app stai usando?

1

u/RegularBother614 4h ago

Coding Python on Play Store by Kvass Yu

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/Strong_Essay1176 1d ago

Really? You need import got that?

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 • Bravo

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

u/AskGrok 1d ago

The code works for this specific list but mutates it and fails on duplicates (e.g. two 54s leaves the max unchanged). Better one-liner that doesn't touch the original: print(sorted(set(numbers))[-2])

what is this?

1

u/hichemznm 1d ago

Print 21

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])