· 6 years ago · Jan 09, 2020, 08:22 PM
1import sqlite3
2import csv
3conn = sqlite3.connect('database2.db')
4c = conn.cursor()
5
6
7def init_database():
8 c.execute(
9 "create table if not exists 'init_data' (time, duration, self_evaluate, response_time, username)")
10 c.execute(
11 "create table if not exists 'calc_data' (time_multiply, duration_multiply, times, groups, username)")
12
13# 把時間轉成分鐘數
14
15
16def time_to_min(t): # 定義一時間函數
17 h, m = t.strip().split(":") # 將字串分割成小時跟分鐘
18 h, m = int(h), int(m) # 將字串格式(strip)轉為數字格式(int)
19 if h < 12 and h >= 0: # 將中午12點作為分隔點,分隔前一日或隔日睡眠
20 h = h + 24 # 隔日睡眠加24小時
21 return h * 60 + m # 回報函數值
22
23
24# 對照反應時間給予反應分數
25def calc_response_score(response_time):
26 response_score = 10
27 base_time = 135
28 if response_time <= 135:
29 response_score = 10
30 while base_time < response_time:
31 response_score = response_score - 1
32 base_time = base_time + 25
33 return response_score
34
35# 主要是用來 判斷 csv 裡面 資料 是哪ㄍ group
36
37
38def get_groups(time, duration):
39 if time <= 1410:
40 if duration <= 5:
41 return 1
42 elif duration > 7:
43 return 3
44 else:
45 return 2
46 # 晚於24:30睡
47 elif time > 1470:
48 if duration <= 5:
49 return 7
50 elif duration > 7:
51 return 9
52 else:
53 return 8
54 else:
55 if duration <= 5:
56 return 4
57 elif duration > 7:
58 return 6
59 else:
60 return 5
61
62# 經過權重計算的資料
63
64
65def calc_data(minutes, duration, self_evaluate, response_time, username):
66
67 rep_score = calc_response_score(response_time)
68 rep_score = 8
69 score = (self_evaluate + rep_score)/2 # 用來決定是否採納數據及加權倍率
70 if score < 5:
71 return -1 # 表示 score 小於 5 則不採納
72
73 k = 2.25 # 起始最高倍率
74 base_score = 10 # 起始最高分數
75 if score == 10:
76 time_multiply = minutes * k
77 duration_multiply = duration * k
78 while score < base_score:
79 k = k - 0.25
80 base_score = base_score - 1
81 time_multiply = minutes * k
82 duration_multiply = duration * k
83
84 groups = get_groups(minutes, duration)
85
86 return (time_multiply, duration_multiply, k, groups, username)
87
88
89def init_data():
90 with open("基礎資料.csv", newline='', encoding='utf-8') as csvfile:
91 reader = csv.DictReader(csvfile)
92 members = [
93 (
94 time_to_min(row['time']),
95 float(row['duration']),
96 float(row['self_evaluate']),
97 float(row['response_time']),
98 'init_csv_data'
99 ) for row in reader
100 ]
101 c.executemany("INSERT INTO init_data VALUES (?, ?, ?, ?, ?)", members)
102
103 for i in members: # 把每一筆資料 都經過加權計算後 存到 calc_data
104 data = calc_data(i[0], i[1], i[2], i[3], i[4])
105 if data is -1: # 其實 csv 資料是合法的 不加個也沒關係 可以去掉 if else
106 print("Error!!")
107 else:
108 c.execute('INSERT INTO calc_data VALUES (?, ?, ?, ?, ?)', data)
109 conn.commit()
110
111
112# get avg and sum and k
113def get_user_data(username):
114 sum_time = 0
115 sum_duration = 0
116 k = 0
117 user_group = c.execute(
118 "SELECT * FROM 'init_data' where username = '%s'" % username) # 撈出 username 的 原始輸入資料
119
120 for user_row in user_group: # 把使用者資料與其符合之該組基礎資料庫進行加權
121 data = calc_data(user_row[0], user_row[1],
122 user_row[2], user_row[3], user_row[4])
123 print(data)
124 sum_time = data[0] + sum_time
125 sum_duration = data[1] + sum_duration
126 k = data[2] + k
127 print(sum_time)
128 print(sum_duration)
129 print(k)
130
131 avg_time = '%.2f' % (sum_time / k) # 取到小數第二位
132 avg_duration = '%.2f' % (sum_duration / k) # 取到小數第二位
133 avg_time = float(avg_time)
134 avg_duration = float(avg_duration)
135
136 return (avg_time, avg_duration), (sum_time, sum_duration), k
137
138# 判斷 使用者 avg 資料 是哪一個群 且印出來
139# 回傳 那個群 全部的資料
140
141
142def determine_group(avg_time, avg_duration):
143 if avg_time <= 1410:
144 if avg_duration <= 5:
145 print('你是第一種類型的人,睡得比別人早,又睡得比別人少,真是非常神奇的生物呢!詳情請參閱我們的對照表~')
146 test_group = c.execute('SELECT * FROM calc_data where groups = 1')
147 elif avg_duration > 7:
148 print('你是早睡且睡較久的類型,是不是都在雷隊友?')
149 test_group = c.execute('SELECT * FROM calc_data where groups = 3')
150 else:
151 print('你是早睡且睡眠時長普通的類型')
152 test_group = c.execute('SELECT * FROM calc_data where groups = 2')
153 elif avg_time > 1470: # 晚於24:30睡
154 if avg_duration <= 5:
155 print('你是晚睡且睡較短的類型')
156 test_group = c.execute('SELECT * FROM calc_data where groups = 7')
157 elif avg_duration > 7:
158 print('你是第九種類型的人,睡得比別人晚,卻又睡得比別人多,總是和周圍的人生活在不同時區,好像天天都在出國度假呢')
159 test_group = c.execute('SELECT * FROM calc_data where groups = 9')
160 else:
161 print('你是晚睡且睡眠時長普通的類型')
162 test_group = c.execute('SELECT * FROM calc_data where groups = 8')
163 else:
164 if avg_duration <= 5:
165 print('你是睡眠時間點普通但睡較短的類型')
166 test_group = c.execute('SELECT * FROM calc_data where groups = 4')
167 elif avg_duration > 7:
168 print('你是睡眠時間點普通但睡較長的類型,可以直接省下早餐耶,生活智慧王是尼')
169 test_group = c.execute('SELECT * FROM calc_data where groups = 6')
170 else:
171 print('你是睡眠時間點與睡眠時長都介於普通人的類型,真的好普通喔')
172 test_group = c.execute('SELECT * FROM calc_data where groups = 5')
173 return test_group
174
175# 最後紫色那面
176# 原本 寫code 的 真的資工系?
177# 現正時間 04:15 寫得很累 所以很寫得ㄊ很爛 會動就好啦(X
178def cal(avg_duration):
179 choose = input(
180 "Do you want to enter bed time or wake up time? bed time please enter bed, otherwise please enter wake: ")
181 if choose == "bed":
182 exp_bedtime = input("Enter the time you want to go to bed(ex 20:00): ")
183 exp_h, exp_m = exp_bedtime.strip().split(":")
184 avg_duration = float(avg_duration)
185 best_m = int(exp_m) + (avg_duration - int(avg_duration)) * 60
186 best_h = int(exp_h) + int(avg_duration)
187 if best_m >= 60:
188 best_m = best_m - 60
189 best_h = best_h + 1
190 # print(avg_duration, type(avg_duration))
191 # print(int(avg_duration))
192 if best_h >= 24:
193 best_h = best_h - 24
194 print("The time to wake up is %2d:%2d" % (best_h, best_m))
195 else:
196 exp_wake = input("Enter the time you want to wake up(ex 6:00): ")
197 exp_h, exp_m = exp_wake.strip().split(":")
198 avg_duration = float(avg_duration)
199 best_m = int(exp_m) - (avg_duration - int(avg_duration)) * 60
200 best_h = int(exp_h) - int(avg_duration)
201 if best_m < 0:
202 best_m = best_m + 60
203 best_h = best_h - 1
204 # print(avg_duration, type(avg_duration))
205 # print(int(avg_duration))
206 if best_h < 0:
207 best_h = best_h + 24
208 print("The time you need to go to sleep is %2d:%2d" % (best_h, best_m))
209
210
211def user_mode():
212 print('歡迎使用黃金睡眠,在精確告訴你最佳睡眠時間點與睡眠時長之前,請先輸入7筆資料,以幫助我們較準確的知道你的睡眠狀況唷!')
213 username = input('請輸入你的名字 :')
214 for i in range(7): # 7 次
215 time = input('請輸入你的睡眠時間點,例如23:20 :')
216 duration = float(input('請輸入你的睡眠時長(小時),例如6.5 :'))
217 self_evaluate = float(input('請對本次睡眠品質評分(1~10)),例如8 :'))
218 response_time = int(input('請提供你的測驗反應時間(毫秒),例如225 :'))
219
220 minutes = time_to_min(time)
221 data = calc_data(minutes, duration, self_evaluate,
222 response_time, username)
223 if data is -1: # score < 5 => continue
224 continue
225 c.execute('INSERT INTO init_data VALUES (?, ?, ?, ?, ?)',
226 (minutes, duration, self_evaluate, response_time, username))
227 c.execute('INSERT INTO calc_data VALUES (?, ?, ?, ?, ?)', data)
228 conn.commit()
229 print('加油加油!本次是第', i+1, '次紀錄')
230 avg_data, sum_data, k = get_user_data(username) # get avg and sum and k
231 sum_time, sum_duration = sum_data
232
233 test_group = determine_group(avg_data[0], avg_data[1])
234 for test_row in test_group:
235 sum_time = test_row[0] + sum_time
236 sum_duration = test_row[1] + sum_duration
237 k = test_row[2] + k
238
239 sum_time = '%.4f' % (sum_time / k) # 算出加權後的平均分鐘數
240 sum_time = float(sum_time)
241 avg_time_hour = sum_time//60
242 avg_time_minute = sum_time - (avg_time_hour*60)
243 avg_time_minute = int(avg_time_minute)
244 if avg_time_hour >= 24:
245 avg_time_hour = avg_time_hour - 24
246 avg_duration = '%.1f' % (sum_duration / k)
247
248 # print(username, groups)
249
250 '''告訴使用者他的最佳睡眠時間點與睡眠時長'''
251 print('根據精密的計算之後,你適合', int(avg_time_hour), ':', avg_time_minute,
252 '睡覺,而且最佳的睡眠時長是', avg_duration, '小時!趕快試試看能不能睡飽飽又睡好好~')
253
254 is_asked = False
255
256 while is_asked == False:
257 cal(avg_duration)
258 if(not is_asked):
259 choose = input("Do you want to entering more data? y/n: ")
260 if choose == 'y':
261 return 1 # main 裡面的 flag
262 else:
263 choose = input("Do you want to use other function? y/n: ")
264 if choose == 'y':
265 cal(avg_duration)
266 else:
267 is_asked = True
268 return 0 # 表示 user_mode 結束
269
270 # choose = input(
271 # "Do you want to enter bed time or wake up time? bed time please enter bed, otherwise please enter wake: ")
272 # if choose == "bed":
273 # exp_bedtime = input("Enter the time you want to go to bed(ex 20:00): ")
274 # exp_h, exp_m = exp_bedtime.strip().split(":")
275 # avg_duration = float(avg_duration)
276 # best_m = int(exp_m) + (avg_duration - int(avg_duration)) * 60
277 # best_h = int(exp_h) + int(avg_duration)
278 # if best_m >= 60:
279 # best_m = best_m - 60
280 # best_h = best_h + 1
281 # # print(avg_duration, type(avg_duration))
282 # # print(int(avg_duration))
283 # if best_h >= 24:
284 # best_h = best_h - 24
285 # print("The time to wake up is %2d:%2d" % (best_h, best_m))
286 # else:
287 # exp_wake = input("Enter the time you want to wake up(ex 6:00): ")
288 # exp_h, exp_m = exp_wake.strip().split(":")
289 # avg_duration = float(avg_duration)
290 # best_m = int(exp_m) - (avg_duration - int(avg_duration)) * 60
291 # best_h = int(exp_h) - int(avg_duration)
292 # if best_m < 0:
293 # best_m = best_m + 60
294 # best_h = best_h - 1
295 # # print(avg_duration, type(avg_duration))
296 # # print(int(avg_duration))
297 # if best_h < 0:
298 # best_h = best_h + 24
299 # print("The time you need to go to sleep is %2d:%2d" % (best_h, best_m))
300
301
302# def final():
303# is_asked = False
304# bedTime = int(input("Enter your bed time: "))
305# sleepTime = int(input("Enter how long is your sleep time: "))
306# cal(sleepTime)
307# if(not is_asked):
308# choose = input("Do you want to entering more data? y/n: ")
309# if choose == 'y':
310# # go to connect point
311# print("Going to connect point")
312# else:
313# choose = input("Do you want to use other function? y/n: ")
314# if choose == 'y':
315# cal(sleepTime)
316
317
318def main():
319 init_database()
320 init_data()
321 flag = 1 # 使用 user_mode when = 0 則 跳出
322 while flag:
323 flag = user_mode()
324
325
326if __name__ == '__main__':
327 main()
328 print("\n\ndone!")