This is a memo for myself.
▼ Question
--There is a list that contains any number of integers. --The values in the list represent the color numbers of the socks. --One set when two of the same color are available. --Calculate the number of sets.
▼sample input
python
9
10 20 20 10 10 30 50 10 20
▼sample output
python
3
▼my answer
python
def sockMerchant(n, ar):
pair=0
for i in set(ar):
pair += int(ar.count(i)/2)
return pair
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
** ・ int () ** ** Truncate ** after the decimal point
** ・ count method **
Object.count (i)
Returns the number of i's in the object.
It can also be used as a character string.
python
aaa = "Ai Ue Ai Ue Ai"
aaa.count("Ah")
▼ my answer (included notation)
python
ar=[10,20,20,10,10,30,50,10,20]
def sockMerchant(n, ar):
return sum([int((ar.count(i))/2) for i in set(ar)])
sockMerchant(9, ar)
--Substitutions such as "+ =" cannot be used in comprehensions. -In case of [], list type is returned. --sum (list) returns the total value of each element of list
Recommended Posts