patternpythonModerate
License and Registration, Sir
Viewed 0 times
andregistrationlicensesir
Problem
The following code will generate a number plate and then generate a random speed and see if it's speeding
Here is a link to the original source
import random, string, time
class Car:
def __init__(self):
self.plate = self.genPlate()
self.limit = 60
self.checkSpeeding()
def checkSpeeding(self):
self.speeding = random.randint(0, 1)
if self.speeding:
self.speed = random.randint(self.limit+3, self.limit+20)
else:
self.speed = random.randint(self.limit-20, self.limit+2)
def genPlate(self):
plateFormat = ['L', 'L', 'N', 'N', 'L', 'L', 'L']
genPlate = []
for i in plateFormat:
if i == 'L':
genPlate.append(random.choice(string.ascii_letters[26:]))
elif i == 'N':
genPlate.append(str(random.randint(0, 9)))
genPlate.insert(4, " ")
return "".join(genPlate)
allCars = []
x = 0
while True:
allCars.append(Car())
print(allCars[x].plate + " was going " + str(allCars[x].speed) + "mph in a " + str(allCars[x].limit) + "mph zone")
if allCars[x].speeding:
print("speeding fine issued")
print("\n")
time.sleep(5)
x += 1Here is a link to the original source
Solution
Consider the real world scenario a little bit. Does a car know what the speed limit is? Does it issue itself a fine if it's speeding? Or do the police do this? Assuming we're talking about the current state of things and not some near future world where cars do these things, police do.
A more proper OOP approach would be to create a
A more proper OOP approach would be to create a
Policeman class with a IsSpeeding method that takes a Car in as an argument. The Policeman would then be responsible for determining whether or not the car was speeding and issuing tickets when necessary.Context
StackExchange Code Review Q#75563, answer score: 19
Revisions (0)
No revisions yet.