中学社会668760 views
高校物理160203 views
教育149510 views
小学算数1200427 views
Computer368106 views
英語613639 views
小学社会310485 views
世界の国564520 views
高校化学2924392 views
高校国語788336 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsRolling DiceCross SectionsMotion PathMechanicsWavesElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

Python の高階関数 reduce で最大公約数を求める

functools の reduce は「2 つの値から別の値を求める関数」をリストに適用します。複数個の整数から最大公約数を求めるコードはこうなります。

from functools import reduce
from math import gcd

numbers = [24, 60, 90]
divisor = reduce(gcd, numbers)

print(divisor)
# 6

reduce(gcd, numbers)

  1. numbers から最初の 2 つ(24、60)をとる
  2. それを gcd する
  3. その値と numbers の次の要素(90)を gcd する
  4. 以下くりかえし…

を意味します。

応用:総和

from functools import reduce


def add(x, y):
	return x + y


numbers = [1, 2, 3, 4, 5]

total = reduce(add, numbers)

print(total)

注意:型

reduce を使うときは「適用する関数の返り値」と「リストの要素」の型は同じである必要があります。

from functools import reduce


def say(x, y):
	return 'Hello'


numbers = [1, 2, 3, 4, 5]

total = reduce(say, numbers)

print(total)
# Hello

Hello が出力されているものの、reduce は誤って使われています。

reduce は 2 つの値から別の値を求める関数をリストに適用したいときに使う。