def findCheapestPrice(self, n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ graph = [[0 for i in xrange(n)] for j in xrange(n)] for edge in flights: graph[edge[0]][edge[1]] = edge[2] heap = [(0, src, K + 1)] while heap: costsofar, curvartex, disleft = heapq.heappop(heap) if (curvartex == dst): return costsofar if (disleft > 0): for vartex in range(n): if graph[curvartex][vartex] != 0: heapq.heappush(heap, ((costsofar + graph[curvartex][vartex]), vartex, disleft - 1)) return -1
def combinationSum2(self, candidates, target): candidates.sort() dp = [set() for _ in xrange(target + 1)] dp[0].add(()) for num in candidates: for t in xrange(target, num - 1, -1): for prev in dp[t - num]: dp[t].add(prev + (num,)) return list(dp[-1])
def printBoard(self, queens): ret.append([]) from urllib3.connectionpool import xrange for i in xrange(self.limit): row = [] for j in xrange(self.limit): if j == queens[i][j]: row.append('Q') else: row.append('.') ret[-1].append(row)
def download_img(start, count): for i in xrange(start, count): src = "https://lns.hywly.com/a/1/" + str(i) + "/" for j in xrange(50): document = get_document(src + str(j) + '.jpg') if str(document).find("404 Not Found") > 0: break path = 'd:/SanMu/image/' + str(i) + '/' if not os.path.exists(path): os.makedirs(path) open(path + str(j) + '.jpg', 'wb').write(document)
def countBinarySubstrings(self, s): groups = [1] for i in xrange(1, len(s)): if s[i - 1] != s[i]: groups.append(1) else: groups[-1] += 1 ans = 0 for i in xrange(1, len(groups)): ans += min(groups[i - 1], groups[i]) return ans
def multiply(num1, num2): res = [0] * (len(num1) + len(num2)) for i in xrange(len(num1) - 1, -1, -1): carry = 0 for j in xrange(len(num2) - 1, -1, -1): tmp = int(num1[i]) * int(num2[j]) + carry # take care of the order of the next two lines carry = (res[i + j + 1] + tmp) // 10 res[i + j + 1] = (res[i + j + 1] + tmp) % 10 # or simply: carry, res[i+j+1] = divmod((res[i+j+1] + tmp), 10) res[i] += carry res = "".join(map(str, res)) return '0' if not res.lstrip("0") else res.lstrip("0")
def pIx(self): data = self.Im w = self.w h = self.h try: for x in xrange(1, w - 1): if x > 1 and x != w - 2: left = x - 1 right = x + 1 for y in xrange(1, h - 1): up = y - 1 down = y + 1 if x <= 2 or x >= (w - 2): data.putpixel((x, y), 255) elif y <= 2 or y >= (h - 2): data.putpixel((x, y), 255) elif data.getpixel((x, y)) == 0: if y > 1 and y != h - 1: up_color = data.getpixel((x, up)) down_color = data.getpixel((x, down)) left_color = data.getpixel((left, y)) left_down_color = data.getpixel((left, down)) right_color = data.getpixel((right, y)) right_up_color = data.getpixel((right, up)) right_down_color = data.getpixel((right, down)) if down_color == 0: if left_color == 255 and left_down_color == 255 and \ right_color == 255 and right_down_color == 255: data.putpixel((x, y), 255) data.save("text2.png", "png") elif right_color == 0: if down_color == 255 and right_down_color == 255 and \ up_color == 255 and right_up_color == 255: data.putpixel((x, y), 255) data.save("text3.png", "png") if left_color == 255 and right_color == 255 \ and up_color == 255 and down_color == 255: data.putpixel((x, y), 255) else: pass data.save("test.png", "png") except: return False
def resize_images(input_path, output_path, number_of_columns): sorted_files = sorted(glob.glob(input_path)) batch_size = number_of_columns row = 0 for i in xrange(0, len(sorted_files), batch_size): batch_files = sorted_files[i:i + batch_size] col = 0 t = time() for file in batch_files: original_image = cv2.imread(file, 1) height, width, depth = original_image.shape for j in range(6): level = output_path + "LEVEL_" + str(j) if os.path.exists(level): pass else: os.mkdir(level) file_name = "LEVEL_" + str(j) + "_R_" + str(row) + "_C_" + str( col) + ".jpg" resized = cv2.resize(original_image, (width, height)) cv2.imwrite(os.path.join(level, str(file_name)), resized) original_image = resized width = int(width / 2) height = int(height / 2) col = col + 1 row = row + 1 print(time() - t)
def commonChars(self, A: List[str]) -> List[str]: answer=None for a in A: work = {} for b in a: if b in work: work[b]+=1 else: work[b]=1 if answer !=None: keys=list(answer.keys()) for k in keys: if k in work: answer[k] = min(answer[k], work[k]) else: del answer[k] else: answer=work answerArr = [] for key in answer: count = answer[key] for _ in xrange(count): answerArr.append(key) return answerArr
def logic(): global sorted_solution_libraries global sorted_libraries for library in libraries: for i, book in enumerate(library['books']): library['books'][i] = (book, books_scores[int(book)]) sorted_library = sorted(library['books'], key=lambda x: x[1], reverse=True) sorted_libraries.append(sorted_library) print(sorted_libraries) seen = set() repeated = set() for l in sorted_libraries: for i in set(l): if i in seen: repeated.add(i) else: seen.add(i) print("repeated: " + str(repeated)) for a, element_to_remove in enumerate(repeated): for i in [x for x in xrange(len(sorted_libraries)) if x != a]: if element_to_remove in sorted_libraries[i]: sorted_libraries[i].remove(element_to_remove) solution_libraries = [] for i, library in enumerate(sorted_libraries): if len(library) > 0: solution_libraries.append( (library, libraries[i]['signup_time'], i)) print("solution libraries: " + str(solution_libraries)) sorted_solution_libraries = sorted(solution_libraries, key=lambda x: x[1]) print("-------------------------") print("sorted_solution_libraries: " + str(sorted_solution_libraries))
def recoverTree(self, root): nodes = [] # 中序遍历二叉树,并将遍历的结果保存到list中 def dfs(root): if not root: return dfs(root.left) nodes.append(root) dfs(root.right) dfs(root) x = None y = None pre = nodes[0] # 扫面遍历的结果,找出可能存在错误交换的节点x和y for i in xrange(1, len(nodes)): if pre.val > nodes[i].val: y = nodes[i] if not x: x = pre pre = nodes[i] # 如果x和y不为空,则交换这两个节点值,恢复二叉搜索树 if x and y: x.val, y.val = y.val, x.val
def take_screenshot(url, save_fn="captura3.png"): browser = webdriver.Chrome(executable_path='../Selenium_WebDriver/chromedriver.exe') # WebDriver Local con Chrome. browser.set_window_size(1200, 900) #1200,900 valores originales estos se pueden cambiar a conveniencia de la captura que se requiere. browser.get(url) # Carga de la pagina web browser.execute_script(""" (function () { var y = 0; var step = 100; window.scroll(0, 0); function f() { if (y < document.body.scrollHeight) { y += step; window.scroll(0, y); setTimeout(f, 100); } else { window.scroll(0, 0); document.title += "scroll-done"; } } setTimeout(f, 1000); })(); """) for i in xrange(30): if "scroll-done" in browser.title: break time.sleep(10) browser.save_screenshot(save_fn) browser.close()
def test_delete(self): """Delete record""" self.passtimes = 0 self.assertTrue(self.enter_app("Camera"), msg='Cannot enter Camera') self.d(resourceId='com.mediatek.camera:id/thumbnail', clickable=True).click() for self.currentcycle in xrange(0, int(self.cycle)): with self.subTest(delete_cycle=self.currentcycle + 1): try: self.printlog('Start the %d time delete.' % (self.currentcycle + 1)) self.d(description='More options').click() self.d(resourceId='android:id/title', text='Delete').click() self.d(className='android.widget.Button', text='OK').click() self.passtimes += 1 self.printlog('The %d time test Pass!' % (self.currentcycle + 1)) except UiObjectNotFoundError as err: self.d.screenshot('screenshot.png') self.printlog('The %d time test failed!' % (self.currentcycle + 1)) self.fail('Reason:\tCan not find %s' % err.message) except Exception as err: self.fail("Unexcept Error:%s" % str(err)) self.printlog('END Record Delete Test!') self.printlog('Pass %d times in %s times' % (self.passtimes, self.cycle)) self.remove_app()
def test_switch(self): """Constant switching between main camera and front camera""" self.assertTrue(self.enter_app("Camera"), msg='Cannot enter Camera') for self.currentcycle in xrange(0, int(self.cycle)): try: with self.subTest(switch_cycle=self.currentcycle + 1): self.printlog('Start the %d time shooting.' % (self.currentcycle + 1)) self.Shooting[self.Android_version]() self.printlog('Main camera shoot success.') self.d(resourceId=self.Switch[self.Android_version], clickable=True).click() self.Shooting[self.Android_version]() self.printlog('Front camera shoot success.') self.d(resourceId=self.Switch[self.Android_version], clickable=True).click() self.passtimes += 1 self.printlog('The %d time shooting success!' % (self.currentcycle + 1)) except UiObjectNotFoundError as err: self.d.screenshot('screenshot.png') self.printlog('The %d time test failed!' % (self.currentcycle + 1)) self.fail('Reason:\tCan not find %s' % err.message) except Exception as err: self.fail("Unexcept Error:%s" % str(err)) self.printlog('END Switch Camera Test!') self.printlog('Pass %d times in %s times' % (self.passtimes, self.cycle)) self.remove_app()
def test_record_stress(self): """Record stress test""" self.assertTrue(self.enter_app("Camera"), msg='Cannot enter Camera') for self.currentcycle in xrange(0, int(self.cycle)): with self.subTest(recode_cycle=self.currentcycle + 1): try: self.printlog('Start the %d time test.' % (self.currentcycle + 1)) self.Record[self.Android_version]() sleep(60) self.RecordStop[self.Android_version]() self.printlog('Record success.') self.passtimes += 1 self.printlog('The %d time test pass!' % (self.currentcycle + 1)) except UiObjectNotFoundError as err: self.printlog(str(err)) self.d.screenshot('/screenshot.png') self.printlog('The %d time test failed!' % (self.currentcycle + 1)) self.fail('Reason:\tCan not find %s' % err.message) except Exception as err: self.fail("Unexcept Error:%s" % str(err)) self.printlog('END Record Stress Test!') self.printlog('Pass %d times in %s times' % (self.passtimes, self.cycle))
def set_mode(self, mode, timeout): """mode: PX4 mode string, timeout(int): seconds""" rospy.loginfo("setting FCU mode: {0}".format(mode)) old_mode = self.state.mode loop_freq = 3 # Hz rate = rospy.Rate(loop_freq) mode_set = False for i in xrange(timeout * loop_freq): print(self.state.mode, mode) if self.state.mode == mode: mode_set = True rospy.loginfo("set mode success | seconds: {0} of {1}".format( i / loop_freq, timeout)) break else: try: print("setting mode") res = self.setModeSRV(0, mode) # 0 is custom mode if not res.mode_sent: print("#######################") rospy.logerr("failed to send mode command") except rospy.ServiceException as e: rospy.logerr(e) try: rate.sleep() except rospy.ROSException as e: self.fail(e)
def show_login(): state = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state # return "The current session state token is %s"%login_session['state'] return render_template('login.html', STATE=state, login=False)
def test_run(self): """Input and Exit Camera stress test""" for self.currentcycle in xrange(int(self.cycle)): try: with self.subTest(cycle=self.currentcycle + 1): self.printlog('Start the %d time test!' % (self.currentcycle + 1)) self.remove_app() self.enter_app("Camera") sleep(2) self.assertTrue(self.d( resourceId=self.Preview[self.Android_version]).exists, msg='Enter camera failure!') self.printlog('Enter camera success') self.d.press('back') self.assertTrue(self.d(description="Camera").exists, msg='Exit camera failure!') self.printlog('Exit camera success') self.passtimes += 1 self.printlog('The %d time test Pass!' % (self.currentcycle + 1)) except UiObjectNotFoundError as err: self.printlog('The %d time test failed!' % self.currentcycle + 1) self.fail('Reason:\tCan not find %s' % err.message) except Exception as err: self.fail("Unexcept Error:%s" % str(err)) self.printlog('END Camera Test!') self.printlog('Pass %d times in %s times' % (self.passtimes, self.cycle)) self.remove_app()
def showLogin(): """Open login home page contains google+ button""" # Create anti-forgery state token state = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state return render_template('login.html', STATE=state)
def _init_hashtables(self): """ Initialize the hash tables such that each record will be in the form of "[storage1, storage2, ...]" """ self.hash_tables = [ storage(self.storage_config, i) for i in xrange(self.num_hashtables) ]
def d_l_distance(first_word, second_word): distance = {} len_1 = len(first_word) len_2 = len(second_word) for i in xrange(-1, len_1 + 1): distance[(i, -1)] = i + 1 for j in xrange(-1, len_2 + 1): distance[(-1, j)] = j + 1 for i in xrange(len_1): for j in xrange(len_2): if first_word[i] == second_word[j]: difference = 0 else: difference = 1 distance[(i, j)] = min(distance[(i - 1, j)] + 1, distance[(i, j - 1)] + 1, distance[(i - 1, j - 1)] + difference) if i and j and first_word[i] == second_word[j - 1] and first_word[i - 1] == second_word[j]: distance[(i, j)] = min(distance[(i, j)], distance[i - 2, j - 2] + difference) return distance[len_1 - 1, len_2 - 1]
def module_td(request, id): ''' 模块的事务 :param request: :return: ''' account = request.session["now_account"] presentModule = ModuleInfo.objects.values('module_name').filter(id=id) projectlist = projectAndModule fav_opt = FavTd.objects tdinfo = TdInfo.objects.filter(belong_module__id=id).order_by("-run_count") kwargs = {} tdlist = [] for k in xrange(len(tdinfo)): td = {} flag = fav_opt.get_fav_by_tdAndUser(account, tdinfo[k].id) if flag == 1: td.setdefault('isFav', 'true') else: td.setdefault('isFav', 'false') if k % 2 == 0: td.setdefault('right', 'true') else: td.setdefault('right', 'false') td.setdefault('id', tdinfo[k].id) td.setdefault('title', tdinfo[k].title) td.setdefault('td_url', tdinfo[k].td_url) td.setdefault('author', tdinfo[k].author) td.setdefault('params', eval(tdinfo[k].params)) td.setdefault('instruction', tdinfo[k].instruction) td.setdefault('belong_project', tdinfo[k].belong_project) td.setdefault('belong_module', tdinfo[k].belong_module) tdlist.append(td) if request.session.get('login_status'): if request.is_ajax(): td_info = json.loads(request.body.decode('utf-8')) kwargs['user'] = request.session["now_account"] kwargs['id'] = td_info.pop('id') if td_info.get('model') == 'pv': msg = add_td_pv(kwargs['id']) else: if td_info.pop('type'): msg = add_fav_data(True, **kwargs) else: msg = add_fav_data(False, **kwargs) return HttpResponse(get_ajax_msg(msg, 'ok')) else: manage_info = { 'account': request.session["now_account"], 'presentModule': presentModule[0]['module_name'], 'tdList': tdlist, 'projects': projectlist } init_filter_session(request) return render_to_response('module_td.html', manage_info) else: return HttpResponseRedirect("/qacenter/login/")
def is_prime(num): if num == 2: return True if num < 2 or num % 2 == 0: return False for n in xrange(3, int(num**0.5) + 2, 2): if num % n == 0: return False return True
def startTask(): for page in xrange(5): try: list = getDL(page + 1) print(list) for item in list: testDL(item) except: traceback.print_exc()
def _init_uniform_planes(self): """ Initialize uniform planes used to calculate the hashes if file `self.matrices_filename` exist and `self.overwrite` is selected, save the uniform planes to the specified file. if file `self.matrices_filename` exist and `self.overwrite` is not selected, load the matrix with `np.load`. if file `self.matrices_filename` does not exist and regardless of `self.overwrite`, only set `self.uniform_planes`. """ if "uniform_planes" in self.__dict__: return if self.matrices_filename: file_exist = os.path.isfile(self.matrices_filename) if file_exist and not self.overwrite: try: npzfiles = np.load(self.matrices_filename) except IOError: print("Cannot load specified file as a numpy array") raise else: npzfiles = sorted(npzfiles.items(), key=lambda x: x[0]) self.uniform_planes = [t[1] for t in npzfiles] else: self.uniform_planes = [ self._generate_uniform_planes() for _ in xrange(self.num_hashtables) ] try: np.savez_compressed(self.matrices_filename, *self.uniform_planes) except IOError: print("IOError when saving matrices to specificed path") raise else: self.uniform_planes = [ self._generate_uniform_planes() for _ in xrange(self.num_hashtables) ]
def _solveNQueens(self, row, queens): if row == self.limit: self.printBoard(queens) else: from urllib3.connectionpool import xrange for col in xrange(self.limit): if self.check(queens, row, col): queens.append([row, col]) self._solveNQueens(row + 1, queens) queens.pop()
def _vectorize(questions, answers, ctable): len_of_questions = len(questions) X = np_zeros((len_of_questions, CONFIG.max_input_len, ctable.size), dtype=np.bool) for i in xrange(len(questions)): sentence = questions.pop() for j, c in enumerate(sentence): try: X[i, j, ctable.char_indices[c]] = 1 except KeyError: pass # Padding y = np_zeros((len_of_questions, CONFIG.max_input_len, ctable.size), dtype=np.bool) for i in xrange(len(answers)): sentence = answers.pop() for j, c in enumerate(sentence): try: y[i, j, ctable.char_indices[c]] = 1 except KeyError: pass # Padding return X, y
def heap_sort(lst): def sift_down(start, end): """最大堆调整""" root = start #print "root %d start $d end %d" % (root,start,end) while True: child = 2 * root + 1 # print "child index: %d" % child #终止条件,孩子的索引值超过数组最大长度 if child > end: break # print "lst child value:%d" % lst[child] #确定最大的孩子节点的索引值 if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 #print "child+1 index: %d" % child #孩子节点最大值和棍节点交换 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] #print "lstroot %d" % lst[root],"lstchild %d" % lst[child] root = child #print "root %d" % root else: break print("-----------------创建最大堆-----------------") #创建最大堆 print(xrange((len(lst) - 2) // 2, -1, -1)) for start in xrange((len(lst) - 2) // 2, -1, -1): #print"----->loop start %d" % start sift_down(start, len(lst) - 1) print(lst) print("------------------排序过程------------------") #堆排序 for end in xrange(len(lst) - 1, 0, -1): #首尾交换 lst[0], lst[end] = lst[end], lst[0] #剩余重新堆排序 sift_down(0, end - 1) print(lst) return lst
def sieve_of_erastotenes(limit): output = [] a = [True] * limit a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: output.append(i) for n in xrange(i * i, limit, i): a[n] = False return output
def get_incident_ids(since, until, headers, ea_hun=None): id_list = [] count = get_incident_count(since, until, headers) print('Number of incidents since ', since, ' to ', until, 'is', count) get_incident_ids_url = 'https://api.pagerduty.com/incidents' payload = {'since': since, 'until': until} for ea_hun in xrange(0, count) or int(ea_hun) == count: if int(ea_hun) % 100 == 1: payload['offset'] = ea_hun r = requests.get(get_incident_ids_url, params=payload, headers=headers, stream=True) id_list = id_list + [ea_inc['id'] for ea_inc in r.json()['incidents']] return id_list
def _dfs(self, board, i, j, current_word, current_dict): current_word += board[i][j] current_dict = current_dict[board[i][j]] if end_of_word in current_dict: self.result.add(current_word) tmp, board[i][j] = board[i][j], '@' for k in xrange(4): x, y = i + dx[k], j + dy[k] if 0 <= x < self.m and 0 <= y < self.n and board[x][ y] != '@' and board[x][y] in current_dict: self._dfs(board, x, y, current_word, current_dict) board[i][j] = tmp
def __init__(self, ipAddress): #b = MyNode.b self.routingTable = [[None for x in xrange(2**b)] for x in xrange(32)] #self.leafSet = [None for x in xrange(2**(b+1))] #self.neighborhoodSet = [None for x in xrange(2**b)] #self.routingTable = [] self.downLeafSet = [] self.upLeafSet = [] self.neighborhoodSet = [] self.isNodeActive = True self.ipAddress = ipAddress self.coordinates = [random.randint(0,1000), random.randint(0,1000)] temp = str(ipAddress) temp = temp.encode('utf-8') self.nodeKey = hashlib.md5(temp).hexdigest() MyNode.id += 1 self.id = MyNode.id self.routePath = []