简体   繁体   中英

Find the smallest number in a list and how many times it occurs

So far I have written this much

def find_num_min(xlst):

    x = []
    count = 0
    w = 0

   for i in range(len(xlst)):
        if len(xlst) == 0:
              return ()
   else:
        y = sorted(xlst)
        w = y[0]


   return w 

You could do it like that, but python has many built in functions that can help you write shorter, more readable code:

def find(xlst):

    smallest = min(xlst)
    count = xlst.count(smallest)
    
    print(f"The smallest number is {smallest}, it occurs {count} times.")

    return smallest, count

In old boring inefficient longhand, just to show you what this could look like,

def find_num_min(xlst):
    smallest = None
    count = 0
    for elt in xlst:
        if not count or elt < smallest:
            smallest = elt
            count = 1
        elif elt == smallest:
            count += 1
    return smallest, count

The condition if not count takes care to set smallest to something in the first iteration (and prevents us from attempting to compare elt to smallest when the latter is None , which woud cause Python to error out); in every subsequent iteration, count will be at least 1. (Go over this with pen and paper on a few simple example lists to make sure this is true.)

But definitely learn to look for existing code before writing your own. Both of the subtasks here are easily - and in many ways, better - done with existing functions from Python's standard library.

use numpy

import numpy as np

x = np.array(xlst)
minimum = x.min()
count = (x == minimum).sum()

using Counter

from collections import Counter

lst = [2,1,2,3,2,1,1,2,3,4,2,2]
c = Counter(lst)
lowest = min(c.keys())
print(f"lowest key: {lowest}, how many times: {c[lowest]}")

Using lambda function:

find_num_min = lambda xlst: (None, 0) if len(xlst) == 0 else (
    (smallest := min(xlst)),
    xlst.count(smallest)
)

Here is how a lambda function works, showing the same function in lambda form and normal function form:

# normal function
def func(param1, param2):
    return param1 + param2

# lambda function
func = lambda (param1, param2): param1 + param2

Next, there are shortened if statements called ternary operators. These two statements are the same, as an example:

# normal if statements
if num > 0:
    print("positive")
else:
    print("negative")

# ternary
print("positive" if num > 0 else "negative")

The := operator is the same as the = operator, but it returns the value in addition to setting the value of whatever is on the left. Example:

print(n := 5) # prints 5 while setting n to 5
print(n) # also prints 5, as n was set to 5

This is useful because it means we don't have to find the minimum value twice.

Finally, the min function is built into Python and can be used to find the minimum value in an list. You can also use the count method on a list to find the number of times a value occurs in the list.

Putting all of these pieces together, we arrive at the final, optimized, one-line function at the beginning of this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM