I'm trying to make a dive table that has some numbers that aren't in a pattern that I can see so I have to manually add all the values, but I need to grab the input and round it to the nearest number in the dictionary.
I'll need to convert the input back to string for the output to be correct:
CODE:
class DepthTable:
def __init__(self):
self.d35 = {"10": "A",
"19": "B",
"25": "C",
"29": "D",
"32": "E",
"36": "F",
}
def getpressureGroup(self, depth, time):
if depth == "35":
output = self.d35[time]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = input()
print("Please Enter time!")
time = input()
depthtable.getpressureGroup(depth,time)
So when the "player" inputs the number 15 for time, I need to round it UP to 19 (Always up even if it's 13 or something like that.) I don't see how I can do this with round() or I might have to make a function that checks EVERY number..
Using your idea of a "function that checks EVERY number", an instance variable keys
can be used to get the key if it exists, or the next highest key:
class DepthTable:
def __init__(self):
self.d35 = {10: "A",
19: "B",
25: "C",
29: "D",
32: "E",
36: "F",
}
self.keys = self.d35.keys()
def getpressureGroup(self, depth, time):
if depth == 35:
rtime = min([x for x in self.keys if x >= time]) # if exists get key, else get next largest
output = self.d35[rtime]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = int(input())
print("Please Enter time!")
time = int(input())
depthtable.getpressureGroup(depth,time)
Demo:
Please enter Depth (Use numbers!)
35
Please Enter time!
13
B
Please enter Depth (Use numbers!)
35
Please Enter time!
19
B
Please enter Depth (Use numbers!)
35
Please Enter time!
10
A
Convert the d35
dictionary to a sorted list and step through it:
In [4]: d35 = {"10": "A",
...: "19": "B",
...: "25": "C",
...: "29": "D",
...: "32": "E",
...: "36": "F",
...: }
In [5]: sorted(d35.items())
Out[5]: [('10', 'A'), ('19', 'B'), ('25', 'C'), ('29', 'D'), ('32', 'E'), ('36', 'F')]
In [7]: time = 15
In [11]: for max_time, group_name in sorted(d35.items()):
...: if int(max_time) >= time:
...: break
...:
In [12]: max_time
Out[12]: '19'
In [13]: group_name
Out[13]: 'B'
Modifying your method gives this. I added an else to the for loop to handle times not covered by any group.
def getpressureGroup(self, depth, time):
if depth == "35":
for max_time, group_name in sorted(self.d35.items()):
if int(max_time) >= time:
output = group_name
break
else:
output = "No info for that depth"
else:
output = "No info for that depth"
print(output)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With