回答編集履歴

1

tableをそのまま使うのをやめて辞書に変換

2019/11/27 12:47

投稿

退会済みユーザー
test CHANGED
@@ -12,19 +12,13 @@
12
12
 
13
13
 
14
14
 
15
-
16
-
17
- def solve(x, y, table, ys, xs):
15
+ def solve(x, y, val_dic, ys, xs):
18
16
 
19
17
  y_pos = bisect_right(ys, y)
20
18
 
21
19
  x_pos = bisect_right(xs, x)
22
20
 
23
- if not 0 < y_pos < len(ys) or not 0 < x_pos < len(xs):
24
-
25
- return -1 # 表の範囲外だった場合
26
-
27
- return table[y_pos-1][x_pos-1]
21
+ return val_dic.get((x_pos, y_pos), -1)
28
22
 
29
23
 
30
24
 
@@ -44,6 +38,12 @@
44
38
 
45
39
  ]
46
40
 
41
+ # tableを(x, y)をキーにした辞書でアクセスできるように変換
42
+
43
+ val_dic = {(x, y): val for y, row in enumerate(table, start=1) for x, val in enumerate(row, start=1)}
44
+
45
+
46
+
47
47
  ys = [200, 500, 1000, 5000, 30000]
48
48
 
49
49
  xs = [0.5, 2.0, 5.0, 10.0, 20.0, 50.0]
@@ -62,7 +62,7 @@
62
62
 
63
63
  for x, y, exp in data:
64
64
 
65
- res = solve(x, y, table, ys, xs)
65
+ res = solve(x, y, val_dic, ys, xs)
66
66
 
67
67
  assert res == exp, f'x, y = {x}, {y} -> {res} != {exp}'
68
68