Stacking "points" for every X over max value - python

I'm a python newbie and currently learning on basics with it. I've come across this task and I would really love to solve it so I can understand how to do similar things in the future. Here is how it goes : Write a function for checking the speed of drivers. This function should have one parameter: speed.
If speed is less than 70, it should print “Ok”.
Otherwise, for every 5km above the speed limit (70), it should give the driver one demerit point and print the total number of demerit points. For example, if the speed is 80, it should print: “Points: 2”.
If the driver gets more than 12 points, the function should print: “License suspended”
This is what I came up with currently, but can't solve bolded part of text. Would appreciate it if you could help me. Thanks !
def speed_check(speed):
warning_point = 0
max_speed = 70
if (speed <= max_speed):
print ("OK")
elif (speed >=130):
print ("Licence suspended, you total warning points is 12.")
elif ("something must go here"):
warning_point +=1
print("Current warning point is {0}".format(warning_point))
speed_check(75)

A global variable will be needed to keep track of how many warning points have been awarded. Below should do it, comment if it makes sense or if there are parts you want explaining.
def speed_check(speed):
global warning_point
max_speed = 70
if speed <= max_speed:
print ("OK")
else:
warning_point += (speed-max_speed) // 5
print("Current warning point is {0}".format(warning_point))
if warning_point >= 12:
print("Licence suspended, you total warning points is at least 12.")
warning_point = 0
speed_check(75)
speed_check(85)
speed_check(115)

You can subtract the speed limit, divide by 5 and then add 1 offset because 1 / 5 = 0
import math
def speed_check(current_speed):
max_speed = 70
if current_speed <= max_speed:
print("OK")
elif (current_speed >=130):
print ("Licence suspended, you total warning points is 12.")
else:
points = math.floor((current_speed - max_speed) / 5) + 1
print("Current warning point is {0}".format(points))

You could divide the speedlimit, 70, and the current speed, 80, by the amount per each point. Then you could just subtract those to get points.
import math
def speed_check(current_speed):
max_speed = 70
if current_speed <= max_speed:
print("OK")
elif (current_speed >=130):
print ("Licence suspended, you total warning points is 12.")
else:
points = (current_speed - max_speed) // 5
print(f"Points: {int(points)}")

Related

Python if statement with multiple condition is messing up?

I'm a beginner with Python. I have a 2-d array called infected that stores values that correspond with the index. This bit of code is messy, but basically what I'm trying to do is simulate an infectious disease spreading over a number of days (T). The individual is infectious for infTime many days and then goes into recovery where they are immune for immTime days. There's also a probability value for whether a node will be infected and a value for how many nodes they will be connected to.
My problem is that I'm also trying to track the number of individuals currently susceptible, infected, or immune, but something is going wrong in the elif statement that is marked "# Messing up in this loop". Currently, the program is running through the statement more times than it should, which is throwing off the variables. If I switch the conditions in the elif statement, the program doesn't go through it and will stay at a very low number of infected individuals the entire time. I'm really stuck and I can't find any reason why it's not working how I want it to.
Code:
# Loop through T days, checking for infected individuals and connecting them to beta num of nodes, possibly infecting
infTime = 5 # Time spent infected before becoming immune
immTime = 20 # Time spent immune before becoming susceptible again
numSus = N - count
day = 0
while day < T:
for a in range(len(infected)):
nextnode = random.randint(0, N-1)
if((infected[a][0] == 1) and (infected[a][3] < infTime)):
num = infected[a][1]
for b in range(num-1):
if((a != nextnode) and (infected[nextnode][0] == 0)):
infected[a][3] += 1
chance = round((random.uniform(0, 1)), 2)
if(infected[nextnode][2] > chance):
infected[nextnode][0] = 1
G.add_edge(a, nextnode)
count += 1
numInf += 1
numSus -= 1
elif((a != nextnode) and (infected[nextnode][0] == 1)):
G.add_edge(a, nextnode)
elif((infected[a][0] == 1) and (infected[a][3] == infTime)): # Messing up in this loop
infected[a][3] = 0
infected[a][4] = 1
numImm += 1
numInf -= 1
G.add_edge(a, nextnode)
elif((infected[a][0] == 0) and (1 < infected[a][4] < immTime)):
infected[a][4] += 1
elif((infected[a][0] == 0) and (infected[a][4] == immTime)):
infected[a][4] = 0
numImm -= 1
numSus =+ 1
day += 1
print("Number of infected on day ", day, ": ", count)

How to calculate distance difference between pixels in tuple over frames?

Good day,
In each iteration step, I have a p1 that describe the location of each person. p1 is a tuple, such that p1 = (x_point, y_point), p1 describes the location of a person in frame i goes.
Based on this article, https://www.pyimagesearch.com/2015/09/21/opencv-track-object-movement/ between line 95 to 109. I am trying to modify the lines in 95 to 109 to measure the distance difference of a person in terms of movement.
The problem can be reproduced as following code, suppose I am getting p1 as each i iteration goes (Originally p1 is the value supplied by SORT Tracking). Since I am dealing with a video with approximately 29 fps as well as multiple objects. Based on following code (inner for loop j), it might provide a false result as following image?
EDIT: It appears to me that inner loop fails to handle multiple objects detection as sample image provided.
Thank you for your time as well.
from collections import deque
from random import randint
import numpy as np
(direction_x, direction_y) = (0, 0)
direction = ""
points_list = deque(maxlen=32)
def sample_of_p1():
return (randint(0, 100),randint(0, 100))
for i in range(100):
p1 = sample_of_p1()
points_list.appendleft(p1)
for j in range(1, len(points_list)):
if(i >= 10):
direction_x = points_list[-10][0] - points_list[j][0]
direction_y = points_list[-10][1] - points_list[j][1]
if np.abs(direction_x) > 0:
dirx = "Right" if np.sign(direction_x) == 1 else "Left"
if np.abs(direction_y) > 0:
diry = "Top" if np.sign(direction_y) == 1 else "Bottom"
if dirx != "" and diry != "":
direction = "{} {}".format(diry, dirx)
else:
direction = dirx if dirx != "" else diry
else:
continue
the code seems to compute correctly but there are some optimizations you can make.
You can put the condition if i >= 10 outside of the loop for j, it is a little optimization but more elegant.
if i >= 10:
for j in range(1, len(points_list)):
//some code
else:
continue
Also, you don't define dirx and diry before the conditions, so you program may throw an exception if you don't move along one axis. In the article, they are initialized at line 109.
Finally, the condition np.abs(direction_x) > 0 seems a bit loose. Usually, when you want to define a movement, you set a minimum value (20 in the article, line 113) to catch a significant movement, and not just a shiver or a negligible movement.
Hope that helps.

How to improve run time of while loop

I'm trying to use a greedy algorithm to solve the problem of refueling a car minimum number of times on a road trip. Unfortunately my code so far has exceeded the time limit in place for this problem.
I wanted to ask if the problem is coming from my nested while loop, because this seems to be the process that iterates the highest number of times. Here is the code:
def compute_min_refills(distance, tank, stations):
trip = distance
dist_traveled = 0
tank_capacity = tank
refills = 0 ##keeps track of total refills
stations = stations
stations.append(trip)
if tank > trip:
return 0
elif station[-1] - station[-2] > tank:
return -1
else:
dist_traveled = tank
while dist_traveled < trip:
n = 0
while stations[n] <= dist_traveled:
n+=1
if dist_traveled - stations[n-1] <= tank:
refills+=1
else:
return -1
dist_traveled = stations[n-1] + tank
stations = stations[n-1:]
return y
The constraints are as follows:
1 < distance < 10^5
1 < tank < 400
stations is an array containing at most 300 elements.
This is my first time dealing with problems of runtime so any advice even in how to approach the problem would be greatly appreciated.
You have several mistakes. First, you seem to assume that station is sorted, but I don't see where it's guaranteed. Even if it is, your append of append(trip) may break it.
elif station[-1] - station[-2] > tank:
return -1
station[-1] and station[-2] may not matter, because they can be outside trip range. Moreover, they may not even exist.
while stations[n] <= dist_traveled:
n+=1
Possible arrayIndexOutOfBounds.
if dist_traveled - stations[n-1] <= tank:
Same issue.
n = 0
...
stations = stations[n-1:]
Better to just set n = 0 outside outer while loop (and reuse n throughout different iterations).
if dist_traveled - stations[n-1] <= tank
Probably the cause of TL. This condition is satisfied when dist_traveled = stations[n-1] + tank; after that you will assign dist_traveled to the exactly same value as it was before. Test: you have stations at coordinates 0 and tank + 1.

MIT Open course, Lecture 3 - Math problems

I have a problem regarding the MIT OCW Python Lecture 3.
According to simple math, the code she uses shouldn't be succesful.
## EXAMPLE: approximate cube root
####################
#cube = 27
##cube = 8120601
##cube = 10000
#epsilon = 0.1
#guess = 0.0
#increment = 0.01
#num_guesses = 0
## look for close enough answer and make sure
## didn't accidentally skip the close enough bound
#while abs(guess**3 - cube) >= epsilon and guess <= cube:
# guess += increment
# num_guesses += 1
#print('num_guesses =', num_guesses)
#if abs(guess**3 - cube) >= epsilon:
# print('Failed on cube root of', cube, "with these parameters.")
#else:
# print(guess, 'is close to the cube root of', cube)
This is the code she uses, the problem I'm having is understanding this part:
while abs(guess**3 - cube) >= epsilon and guess <= cube:
# guess += increment
If guess is 0.0, cube is 27 and increment is 0.01 then the math by this term should be:
abs(0**3 - 27) = 27 #----- This is fine according to the code but the next step would be:#
abs(27.01**3 - 27) = 19677.878101
This should stop the loop from working any further. My understanding is obviously wrong somewhere but I can't see where!
Please halp...
You can try using Python visualizer to see how the value of guess changes with each iteration. Try here.

If/Elif/Else statement issue. If if and elif not met, not going into else

sorry for the probably extremely obvious question, but I've been having trouble with this if/elif/else statement. The statement never proceeds into the "else" area. Even if difference is equal to 0.
if difference > 0:
difference_string = "The combination will have a %s cm gap from being fully enclosed." % (difference)
elif difference < 0:
difference_string = "The combination will exceed the dimensions of the shelf unit by %s cm." % (difference)
else:
difference_string = "The combination completely enclose a %s cm shelf unit." % (uh)
I don't get what's not right. I guess I could just do elif == 0, but I want to understand my error before I work on fixing it.
Here is the whole code:
def x38door_fit(uh):
"""uh = unit height
door_fit(uh) --> x*38 door heights will fit on uh.
"""
uh = int(uh)
doors = uh / int(38)
if uh % int(38) is not 0:
tuh = 0
counter = 0
d38 = int(38)
while tuh < uh:
d38 += 38
tuh = d38
counter += 1
tdh = counter * 38 #total door height = tdh
difference = uh - tdh
if difference > 0:
difference_string = "The combination will have a %s cm gap from being fully enclosed." % (difference)
elif difference < 0:
difference_string = "The combination will exceed the dimensions of the shelf unit by %s cm." % (difference)
else:
difference_string = "The combination completely enclose a %s cm shelf unit." % (uh)
print difference_string
print doors
return doors
Your problem is this line of code:
if uh % int(38) is not 0:
If you pass in 0, which is assigned to uh, this conditional evaluates to 0. Your if/else block in question is never executed because it never reached.
My guess is that difference is a float. The typical problem is shown below
>>> 0.1 + 0.1 + 0.1 - 0.3 == 0
False
This is because most decimal fractions can't be represented exactly as floats.
One possible fix would be to replace your float with Decimal
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3') == 0
True
Another is to allow for a small error. ie. treat very small numbers as zero
>>> abs(0.1 + 0.1 + 0.1 - 0.3) < 1e-10
True
You have not provided a runnable example, so I will provide as clear of an answer as I can:
One possibility is that difference is a string. You can check this by typing in print repr(difference) before your if statement, to get what difference is.
>>> difference = '9'
>>> print repr(difference)
'9'
>>> difference = 9
>>> print repr(difference):
9
There are actually two things which are causing you grief here, neither of which have been explained properly.
First of all, on this line,
if uh % int(38) is not 0:
if uh is any multiple of 38 is passed in, the entirety of the logic will be skipped. So 38, 76, 114, etc... will all be passed through and nothing will be printed.
Secondly, apart from being wildly bad design with numerous unused variables, with this code:
tuh = 0
counter = 0
d38 = int(38)
while tuh < uh:
d38 += 38
tuh = d38
counter += 1
tdh = counter * 38
will never allow a difference of more than 0 to occur. It appears you are trying to find the closet multiple of 38 to uh here. Lets simplify it up a little. We can remove d38 and just reassign the commands that alter it to tuh and get rid of counter completely.
tuh = 0
while tuh < uh:
tuh += 38
tdh = tuh
Now, as long as tuh is less than uh we will add another 38, so tuh (and tdh) will always be greater than uh, in every case. Which means the only case that will ever be executed is this one, since difference = uh - tdh :
elif difference < 0:
difference_string = "The combination will exceed the dimensions of the shelf unit by %s cm." % (difference)

Categories

Resources