# FP 2021-11-30

Nov 30th, 2021 (edited)
782
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import art
2. import random
3. import time
4. from enum import IntEnum
5.
6. class GameState (IntEnum):
7.     NOT_STARTED = -1
8.     PLAY_HIGHER = 1
9.     PLAY_LOWER = 2
10.     FINISHED = 3
11. #class GameState
12.
13. #guess_number.py
14. """
15. The computer randomly picks a number from
16. some range 1..10K
17. A human player will try to guess the number
18. picked by the computer
19. It will be a guided process, allowing some
20. rational playing
21. score
22. ++++++++++++++++++++++++ = amplitude
23. ------------------------ = attempts, time
24. """
25.
26. class GuessTheNumberGame:
27.     def __init__ (
28.         self,
29.         pMin=1,
30.         pMax=10000
31.     ):
32.         self.mMin = pMin
33.         self.mMax = pMax
34.         self.mStart = None
35.         self.mEnd = None
36.         #self.mAttempts = 0
37.
38.         #historic of the played numbers
39.         #QUEU => FIFO => First In First Out
40.         self.mListOfPlays = []
41.         #self.mListOfAttempts = list()
42.
43.         #historic of the times (in seconds) when the numbers were played
44.         self.mListOfPlaySeconds = []
45.
46.         #this is the number that the human player must guess
47.         self.mGuessMe = random.randint(
48.             self.mMin,
49.             self.mMax
50.         )
51.
52.         self.mState = GameState.NOT_STARTED
53.     #def __init__
54.
55.     def __str__(self):
56.         strAll = ""
57.
58.         strAll+="min: %d ; max: %d ; guessMe: %d\n"
59.         strAll+="plays: %s ; time (seconds): %s\n"
60.         strAll+="state: %s\n"
61.         strAll = strAll%(
62.             self.mMin, self.mMax, self.mGuessMe,
63.             self.mListOfPlays.__str__(),
64.             self.mListOfPlaySeconds.__str__(),
65.             self.mState.__str__()
66.         )
67.         return strAll
68.     #def __str__
69.
70.     #assuming FIFO for plays
71.     def getHumanPlayerLastPlay(self):
72.         #return self.mListOfAttempts[len(self.mListOfAttempts)-1]
73.         if (len(self.mListOfPlays)>0):
74.             return self.mListOfPlays[-1]
75.         else:
76.             return None
77.     #def getHumanPlayerLastPlay
78.
79.     def getNumberOfAttempts(self):
80.         return len(self.mListOfPlays)
81.     #def getNumberOfAttempts
82.
83.     def play(self, piPlayerNumber):
84.         bCanPlay = self.mState!=GameState.FINISHED
85.
86.         if (bCanPlay):
87.             bFirstPlay = len(self.mListOfPlays)==0
88.             if (bFirstPlay):
89.                 self.mStart = time.time()
90.             #if
91.
92.             iHowManySecondsSinceStart = time.time()-self.mStart
93.
94.             self.mListOfPlays.append(piPlayerNumber)
95.             self.mListOfPlaySeconds.append(iHowManySecondsSinceStart)
96.
97.             if(piPlayerNumber < self.mGuessMe):
98.                 # suggest PLAY HIGHER
99.                 self.mState = GameState.PLAY_HIGHER
100.                 pass
101.             elif (piPlayerNumber > self.mGuessMe):
102.                 #suggest PLAY LOWER
103.                 self.mState = GameState.PLAY_LOWER
104.                 pass
105.             else:
106.                 #congratulations
107.                 self.mState = GameState.FINISHED
108.                 self.mEnd = time.time()
109.
110.             strFeedback = self.feedback()
111.             print (strFeedback)
112.         #if can play
113.         else: #could not play, but played
114.             #TODO
115.             pass
116.     #def play
117.
118.     def feedback(self):
119.         strF = self.__str__()+"\n"
120.
121.         if (self.mState==GameState.NOT_STARTED):
122.             pass
123.         elif (self.mState==GameState.PLAY_HIGHER):
124.             strF+=\
125.                 "Your number %d is LOWER than mine, play HIGHER"\
126.                 %(self.getHumanPlayerLastPlay())
127.         elif (self.mState==GameState.PLAY_LOWER):
128.             strF += \
129.                 "Your number %d is HIGHER than mine, play LOWER" \
130.                 % (self.getHumanPlayerLastPlay())
131.         else:
132.             #congratulations
133.             strF += art.text2art("Congratulations!!")
134.             pass
135.         #if
136.         strF+="\n"+("-"*40)
137.         return strF
138.     #def feedback
139.
140.     def gameFinished(self):
141.         return self.mState==GameState.FINISHED
142.     #def
143. #class GuessTheNumberGame
144.
145. #g1.instructions()
146. g1 = GuessTheNumberGame(1, 5000)
147. #print (g1)
148. while (not g1.gameFinished()):
150. #while
151.
152. import matplotlib.pyplot as plt
153. x = g1.mListOfPlays
154. y = g1.mListOfPlaySeconds
155. plt.plot(x, y)
156. plt.show()
157.
158.
159. ***************************************
160.
161.
162. #mylist.py
163.
164. class MyList:
165.     #dunder double underscore
166.
167.     BATATA = "batata frita"
168.
169.     #initializer of instances of the MyList datatype
170.     def __init__(
171.         self,
172.         pValues = None
173.     ):
174.         if (pValues is None):
175.             self.mList = []
176.         else:
177.             self.mList = pValues
178.     #def __init__
179.
180.     #how instances of type MyList should be
181.     #represented as string
182.     def __str__(self):
183.         strAll = ""
184.         strAll+=self.mList.__str__()
185.         return strAll
186.     #def __str__
187.
188.     #dynamic
189.     def min (self):
190.         theSmallest = None
191.
192.         for v in self.mList:
193.             if (theSmallest is None):
194.                 theSmallest = v
195.             else:
196.                 if (v<theSmallest):
197.                     theSmallest = v
198.                 #if
199.             #else
200.         #for
201.         return theSmallest
202.     #def min
203.
204.     def max(self):
205.         theGreatest = None
206.         for v in self.mList:
207.             if (theGreatest is None):
208.                 theGreatest = v
209.             else:
210.                 if(v>theGreatest):
211.                     theGreatest = v
212.                 #if
213.             #else
214.         #for
215.         return theGreatest
216.     #def max
217.
218.     def howManyValues(self):
219.         return len(self.mList)
220.     #def howManyValues
221.
222.     #mean / average / média
223.     def mean (self):
224.         howMany = self.howManyValues()
225.         if (howMany>0):
226.             theSum = 0
227.             for v in self.mList:
228.                 #theSum = theSum+v
229.                 #cumulative sum +=
230.                 theSum+=v
231.             #for
232.             theMean = theSum / howMany
233.             return theMean
234.         else:
235.             return None
236.     #def mean
237.
238.     """
239.    p1 p2 p3 ... pn
240.    pM
241.
242.    sum = (p1-pM)^2 + (p2-pM)^2 + (p3-pM)^2 ... (pn-pM)^2
243.    sum/howMany
244.    """
245.     def variance(self):
246.         howMany = self.howManyValues()
247.         theMean = self.mean()
248.         theSum = 0
249.         if (howMany>0 and (theMean!=None)):
250.             for v in self.mList:
251.                 diff = v-theMean
252.                 diffSquared = diff**2
253.                 theSum += diffSquared
254.             #for
255.             theVariance = theSum / howMany
256.             return theVariance
257.         else:
258.             return None
259.     #def variance
260.
261.     #stdevp = sqrt(variance)
262.     #stdevp = variance ** (1/2)
263.     def standardDeviation(self):
264.         if (self.howManyValues()>0):
265.             #return self.variance()**(1/2)
266.             variance = self.variance()
267.             squareRoot = variance**(1/2)
268.             return squareRoot
269.         else:
270.             return None
271.         #else
272.     #def standardDeviation
273.
274.     """
275.    example:
276.    working on list [10, 20, 40, 40]
277.    set([10, 20, 40, 40]) --> [10, 20, 40]
278.    working over a collection without repetitions...
279.    set
280.    the return should be this dictionary:
281.    {10:1, 20:1, 40:2}
282.    """
283.     def absoluteFrequencyOfElements(self):
284.         retDict = {}
285.         if (self.howManyValues()>0):
286.             setWithoutRepitions = set(self.mList) #[10, 20, 40] #optimization => does not question repeated elements
287.             #for v in self.mList: #[10, 20, 40, 40] #would count 40 twice
288.             for v in setWithoutRepitions:
289.                 iCount = self.count(v)
290.                 retDict[v] = iCount
291.
292.                 #retDict[v] = self.count(v)
293.             #for
294.             return retDict
295.         else:
296.             return None
297.     #def absoluteFrequencyOfElements
298.
299.     def count(self, pEl):
300.         bShouldWork = self.howManyValues() and \
301.                       pEl!=None
302.         if (bShouldWork):
303.             iCounter = 0
304.             for v in self.mList:
305.                 if (pEl==v):
306.                     iCounter+=1
307.                 #if
308.             #for
309.             return iCounter
310.         else:
311.             return 0
312.     #def count
313.
314.     def mostFrequentValues (self):
315.         #dictionary of absolute frequencies
316.         daf = self.absoluteFrequencyOfElements()
317.         if (daf!=None):
318.             theKeys = daf.keys()
319.             theGreatest = None
320.             for k in theKeys:
321.                 v = daf[k]
322.                 if (theGreatest is None):
323.                     theGreatest = v
324.                 else:
325.                     if (v>theGreatest):
326.                         theGreatest = v
327.                     #if
328.                 #else
329.             #for
330.
331.             #what do I have?????
332.             #in var theGreatest we capture the most
333.             #frequent value in the collection (self.mList)
334.
335.             listMode = []
336.             for k in theKeys:
337.                 if (daf[k]==theGreatest):
338.                     listMode.append(k)
339.                 #if
340.             #for
341.             return listMode
342.         else:
343.             return None
344.     #def mostFrequentValues
345.
346.     #TPC: leastFrequentValues
347.
348.     def mode(self):
349.         return self.mostFrequentValues()
350.     #def
351.
353.         self.mList.append(pEl)
354.
357.         removedElement = None
358.         if (len(self.mList)>0):
359.             removedElement = self.mList[0]
360.             self.mList = self.mList[1:]
361.
362.         return removedElement
363.
366.             removedElement = None
367.             if (len(self.mList) > 0):
368.                 removedElement = self.mList[0]
369.                 self.mList = self.mList[1:]
370.
371.             return removedElement
373.
374.         # @tail?
375.         def removeTail(self):
376.             removedElement = None
377.             if (len(self.mList) > 0):
378.                 removedElement = self.mList[-1]
379.                 #[start:end-exclusive]
380.                 self.mList = self.mList[0:-1]
381.
382.             return removedElement
383.         #def removeTail
384. #class MyList
385.
386. l1 = MyList()
387. l2 = MyList([10, 20, 30])
388. smallestInL1 = l1.min()
389. greatestInL2 = l2.max()
390.
391. print ("l1: ", l1)
392. print ("l2: ", l2)
393.
394. print ("smallest in l1: ", smallestInL1)
395. print ("greatest in l2: ", greatestInL2)
396.
397. print ("How many elements in l1: ",
398.     l1.howManyValues()
399. )
400.
401. print ("How many elements in l2: ",
402.     l2.howManyValues()
403. )
404.
405. theMeanL1 = l1.mean()
406. theMeanL2 = l2.mean()
407.
408. print ("The mean of l1: ", theMeanL1)
409. print ("The mean of l2: ", theMeanL2)
410.
411. l3 = MyList([20, 20, 40, 40, 50, 50, 50])
412. v3 = l3.variance()
413. dp3 = l3.standardDeviation()
414. print("The variance of {} is {}".format(l3, v3))
415. print("The standard deviation of {} is {}".\
416.       format(l3, dp3))
417.
418. daf = l3.absoluteFrequencyOfElements()
419. print (daf)
420.
421. theModeList = l3.mode()
422. print ("The mode (as a list) for {} is {}".\
423.        format(l3, theModeList))
424.
425. l2 = MyList()
426. l44 = MyList([44, 44, 44])
427. l2.mode()
428. l44.mode()
429.
430. #the left-operand is NOT an instance of the class
431. #but the class's name
432. print(MyList.BATATA) #static
RAW Paste Data