Python 从列表中找到几双袜子

Python find pairs of socks from a list

我对编程还很陌生 python。我被要求从给定的数字列表中找出一双袜子。 我的问题是 - “有一大堆袜子必须按颜色配对。给定一个表示每只袜子颜色的整数数组,确定有多少双颜色匹配的袜子。” 样本输入

STDIN                       Function
-----                       --------
9                           n = 9
10 20 20 10 10 30 50 10 20  ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]

示例输出

3

所以我的逻辑非常简单,遍历列表,取一个数字,与其他数字进行比较。如果找到两个相同的数字,将它们算作一对并将它们从列表中删除。然后做同样的事情,直到剩下 none

# Complete the sockMerchant function below.
def sockMerchant(n, ar):
    print(ar)
    l=[]
    result=0
    for i in ar:
        a=i
        c=0
        print("a",a)#line for checking
        ar.remove(i)
        l=ar
        print("ar",ar)#line for checking
        print("l", l)#line for checking
        for j in l:
            f=l.index(j)
            print("index", f))#line for checking
            print("j",j))#line for checking
            if j == a:
                c=c+1
                print("c",c))#line for checking
                ar.remove(j)
                print("ar2",ar))#line for checking
             

             
    result=c/2
    print("c2",c))#line for checking
    return result
n=9
ar=[10, 20, 20, 10, 10, 30, 50, 10, 20]
sockMerchant(n, ar)

请忽略评论旁边的代码行。他们只是在那里查看控制流。这是我的输出:

[10, 20, 20, 10, 10, 30, 50, 10, 20]
a 10
ar [20, 20, 10, 10, 30, 50, 10, 20]
l [20, 20, 10, 10, 30, 50, 10, 20]
index 0
j 20
index 0
j 20
index 2
j 10
c 1
ar2 [20, 20, 10, 30, 50, 10, 20]
index 3
j 30
index 4
j 50
index 2
j 10
c 2
ar2 [20, 20, 30, 50, 10, 20]
a 20
ar [20, 30, 50, 10, 20]
l [20, 30, 50, 10, 20]
index 0
j 20
c 1
ar2 [30, 50, 10, 20]
index 1
j 50
index 2
j 10
index 3
j 20
c 2
ar2 [30, 50, 10]
a 10
ar [30, 50]
l [30, 50]
index 0
j 30
index 1
j 50
c2 0

Python 充满了有用的实用工具。 Counters from collections 可用于计算您获得的每种颜色的袜子数量,然后除以 2 即可得到双数。

from collections import Counter
from typing import List

def sock_merchant(socks: List[int]) -> int:
    counter = Counter(ar)
    return sum((count // 2 for count in counter.values())

用数组初始化计数器会给你类似的东西

Counter({10: 4, 20: 3, 30: 1, 50: 1})

这是数组中的值(即袜子的颜色)及其在数组中出现的次数。 与普通的字典一样,计数器也有一个 .values() 方法,它只会给你值,因为我们想要对的数量,所以我们在对每个值进行整数除法后取值的总和。