Python Forum
I am a newbie.Help me with this simple piece of code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am a newbie.Help me with this simple piece of code
#4
Maybe following can enhance learning process.

In programming same results can be achieved in different ways.

For example we don't need to compare all list items if we have assigned first value as max value. We can start from second item:

numbers = [11, 2, 23, 45, 67, 99, 101] 
largest_num = numbers[0]
for number in numbers[1:]: 
    if largest_num < number: 
        largest_num = number

# largest_num is 101
We can make an iterator from numbers and assign first item in list with next() as largest_num and then iterate over remaining items:

numbers = [11, 2, 23, 45, 67, 99, 101]
nums = iter(numbers)
largest_num = next(nums)
for num in nums: 
    if largest_num < num: 
        largest_num = num 
# largest_num is 101
After mastering finding largest number from list with own algorithm one can start using built-in max() (no need to invent wheel):

>>> numbers = [11, 2, 23, 45, 67, 99, 101]
>>> max(numbers)
101
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: I am a newbie.Help me with this simple piece of code - by perfringo - Jan-08-2020, 12:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 340 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 494 Nov-07-2023, 04:32 PM
Last Post: snippsat
  newbie question - can't make code work tronic72 2 700 Oct-22-2023, 09:08 PM
Last Post: tronic72
  An unexplainable error in .format statement - but only in a larger piece of code? ToniE 4 728 Sep-05-2023, 12:50 PM
Last Post: ToniE
  First piece of code Bearwulf 2 775 Aug-02-2023, 04:03 PM
Last Post: deanhystad
  help me simple code result min and max number abrahimusmaximus 2 916 Nov-12-2022, 07:52 AM
Last Post: buran
  Simple encoding code ebolisa 3 1,464 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,820 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Understanding a piece of code Michael1 4 1,431 Jan-20-2022, 07:14 PM
Last Post: Michael1
  Simple code question about lambda and tuples JasPyt 7 3,375 Oct-04-2021, 05:18 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020