@@ -56,7 +56,7 @@ def winnerSet(cls, ballots, numWinners=1):
5656 def honBallot (cls , utils , ** kw ):
5757 """Takes utilities and returns an honest ballot
5858 """
59- raise NotImplementedError ("{ } needs honBallot". format ( cls ) )
59+ raise NotImplementedError (f" { cls } needs honBallot" )
6060
6161 @classmethod
6262 def vaBallot (cls , utils , electabilities , ** kw ):
@@ -100,10 +100,9 @@ def realisticBullets(cls, utils, electabilities, baseBullets=0.3, slope=0.35, ot
100100 r = random .Random (utils .id ).random ()
101101 if r < baseBullets + slope * margin :
102102 return cls .bulletBallot (utils )
103- else :
104- if otherStrat is None :
105- otherStrat = cls .honBallot
106- return otherStrat (utils , electabilities = electabilities )
103+ if otherStrat is None :
104+ otherStrat = cls .honBallot
105+ return otherStrat (utils , electabilities = electabilities )
107106
108107 @classmethod
109108 def diehardBallot (cls , utils , intensity , candToHelp , candToHurt , electabilities = None , polls = None ):
@@ -152,7 +151,7 @@ def winner(results):
152151 >>> 2 < Method().winner([1,2,1,3,3,3,2,1,2]) < 6
153152 True
154153 """
155- winScore = max ([ result for result in results if isnum (result )] )
154+ winScore = max (result for result in results if isnum (result ))
156155 winners = [cand for (cand , score ) in enumerate (results ) if score == winScore ]
157156 #return random.choice(winners)
158157 return winners [0 ] #made it deterministic to prevent nondeterministic behaviors in useful functions
@@ -176,7 +175,7 @@ def stratThresholdSearch(cls, targetWinner, foundAt, bgBallots, fgBallots, fgBas
176175 midpoint = int (floor ((maxThreshold + minThreshold )/ 2 ))
177176 midpointBallots = bgBallots + fgBallots [:midpoint ] + fgBaselineBallots [midpoint :]
178177 midpointWinner = cls .winner (cls .results (midpointBallots ))
179- if not any (midpointWinner = = w for w , _ in winnersFound ):
178+ if all (midpointWinner ! = w for w , _ in winnersFound ):
180179 winnersFound .append ((midpointWinner , midpoint ))
181180 if midpointWinner == targetWinner :
182181 maxThreshold = midpoint
@@ -189,15 +188,15 @@ def resultsFor(cls, voters):
189188 """Create (honest/naive) ballots and get results.
190189 Again, test on subclasses.
191190 """
192- return cls .results (list ( cls .honBallot (v ) for v in voters ) )
191+ return cls .results ([ cls .honBallot (v ) for v in voters ] )
193192 @staticmethod
194193 def stratTarget2 (places ):
195- ((frontId ,frontResult ), (targId , targResult )) = places [0 :2 ]
194+ ((frontId ,frontResult ), (targId , targResult )) = places [:2 ]
196195 return (frontId , frontResult , targId , targResult )
197196
198197 @staticmethod
199198 def stratTarget3 (places ):
200- ((frontId ,frontResult ), (targId , targResult )) = places [0 :3 :2 ]
199+ ((frontId ,frontResult ), (targId , targResult )) = places [:3 :2 ]
201200 return (frontId , frontResult , targId , targResult )
202201
203202 stratTargetFor = stratTarget2
@@ -247,8 +246,9 @@ def rememberBallot(fun):
247246 """
248247 def getAndRemember (cls , voter , tally = None ):
249248 ballot = fun (cls , voter )
250- setattr (voter , cls .__name__ + "_" + fun .__name__ [:- 6 ], ballot ) #leave off the "...Ballot"
249+ setattr (voter , f" { cls .__name__ } _ { fun .__name__ [:- 6 ]} " , ballot )
251250 return ballot
251+
252252 getAndRemember .__name__ = fun .__name__
253253 getAndRemember .allTallyKeys = lambda :[]
254254 return getAndRemember
@@ -263,9 +263,10 @@ def getAndRemember(cls, voter, tally=None):
263263 ballots = fun (cls , voter )
264264 for bType , ballot in ballots .items ():
265265
266- setattr (voter , cls .__name__ + "_" + bType , ballot )
266+ setattr (voter , f" { cls .__name__ } _ { bType } " , ballot )
267267
268268 return ballots [fun .__name__ [:- 6 ]] #leave off the "...Ballot"
269+
269270 getAndRemember .__name__ = fun .__name__
270271 getAndRemember .allTallyKeys = lambda :[]
271272 return getAndRemember
@@ -302,9 +303,10 @@ def paramStrat(strategy, **kw):
302303 def strat (voter , polls = None , electabilities = None , candToHelp = None , candToHurt = None ):
303304 return strategy (voter , polls = polls , electabilities = electabilities ,
304305 candToHelp = candToHelp , candToHurt = candToHurt , ** kw )
306+
305307 strat .__name__ = strategy .__name__
306308 for key , value in kw .items ():
307- strat .__name__ += "_" + str (key )[:4 ]+ str (value )[:4 ]
309+ strat .__name__ += f"_ { str (key )[:4 ]} { str (value )[:4 ]} "
308310 return strat
309311
310312def wantToHelp (voter , candToHelp , candToHurt , ** kw ):
@@ -313,7 +315,8 @@ def wantToHelp(voter, candToHelp, candToHurt, **kw):
313315def selectAB (candA , candB ): #candA and candB are candidate IDs
314316 def fgSelect (voter , ** kw ):
315317 return max (voter [candA ] - voter [candB ], 0 )
316- fgSelect .__name__ = "select" + str (candA )+ str (candB )
318+
319+ fgSelect .__name__ = f"select{ str (candA )} { str (candB )} "
317320 return fgSelect
318321
319322def selectRand (polls , ** kw ):
@@ -353,16 +356,25 @@ def selectV(v, **kw):
353356 "pivotalUtilDiff" , "deciderUtilDiffSum" , "deciderMargUtilDiffs" , "numWinnersFound" ,
354357 "factionSize" , "factionFraction" ]
355358for prefix in ["" , "min" , "t1" , "o" ]:
356- for columnName in ["fgUtil" , "fgUtilDiff" , "fgSize" ,
357- "fgNumHelped" , "fgHelpedUtil" , "fgHelpedUtilDiff" ,
358- "fgNumHarmed" , "fgHarmedUtil" , "fgHarmedUtilDiff" ,
359- "helpCandElected" , "hurtCandElectedR1" ]:
360- resultColumns .append (prefix + columnName )
359+ resultColumns .extend (
360+ prefix + columnName
361+ for columnName in [
362+ "fgUtil" ,
363+ "fgUtilDiff" ,
364+ "fgSize" ,
365+ "fgNumHelped" ,
366+ "fgHelpedUtil" ,
367+ "fgHelpedUtilDiff" ,
368+ "fgNumHarmed" ,
369+ "fgHarmedUtil" ,
370+ "fgHarmedUtilDiff" ,
371+ "helpCandElected" ,
372+ "hurtCandElectedR1" ,
373+ ]
374+ )
361375
362376def makeResults (** kw ):
363- results = {c : kw .get (c , None ) for c in resultColumns }
364- results .update (kw )
365- return results
377+ return {c : kw .get (c , None ) for c in resultColumns } | kw
366378
367379def makePartialResults (fgVoters , winner , r1Winner , prefix , candToHelp , candToHurt ):
368380 fgHelped = []
@@ -527,10 +539,7 @@ def tieFor2Estimate(probs):
527539
528540
529541def adaptiveTieFor2 (polls , uncertainty = .15 ):
530- if False and len (polls ) < 6 :
531- return tieFor2Probs (polls , uncertainty )
532- else :
533- return tieFor2Estimate (tuple (pollsToProbs (polls , uncertainty )))
542+ return tieFor2Estimate (tuple (pollsToProbs (polls , uncertainty )))
534543
535544def appendResults (filename , resultsList , globalComment = dict ()):
536545 """append list of results created by makeResults to a csv file.
@@ -548,17 +557,7 @@ def appendResults(filename, resultsList, globalComment = dict()):
548557
549558 with open (baseName + str (i ) + ".csv" , "a" ) as myFile :
550559 if needsHeader :
551- print ("# " + str (globalComment ),
552- #dict(
553- #media=self.media.__name__,
554- # version=self.repo_version,
555- # seed=self.seed,
556- ## model=self.model,
557- # methods=self.methods,
558- # nvot=self.nvot,
559- # ncand=self.ncand,
560- # niter=self.niter)),
561- file = myFile )
560+ print (f"# { str (globalComment )} " , file = myFile )
562561 dw = csv .DictWriter (myFile , keys , restval = "NA" )
563562 dw .writeheader ()
564563 for r in resultsList :
0 commit comments