blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
e96d20b23237dd5ccef05aadcd70e3e818857b7d
Python
dprestsde/Web_explorator
/Explorator/ip_address.py
UTF-8
424
2.828125
3
[]
no_license
import os def get_ip_address(url): command = "host " + url process = os.popen(command) results = str(process.read()) marker = results.find('has address') + 12 print("IP Address completed!") # return results[marker:].splitlines()[0] return results[marker:].splitlines()[1] # res = res.split(":") # return res[1] #print(get_ip_address("https://www.facebook.com"))
true
5db0e10299c91d18658dda3d99e6331effaf55ef
Python
alexcrichton/wasmtime-py
/tests/test_instance.py
UTF-8
5,853
2.890625
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
import unittest from wasmtime import * class TestInstance(unittest.TestCase): def test_smoke(self): module = Module(Store(), '(module)') Instance(module, []) def test_export_func(self): module = Module(Store(), '(module (func (export "")))') instance = Instance(module, []) self.assertEqual(len(instance.exports()), 1) extern = instance.exports()[0] self.assertTrue(extern.func() is not None) self.assertTrue(extern.global_() is None) self.assertTrue(extern.memory() is None) self.assertTrue(extern.table() is None) self.assertTrue(extern.type().func_type() is not None) self.assertTrue(extern.type().global_type() is None) self.assertTrue(extern.type().memory_type() is None) self.assertTrue(extern.type().table_type() is None) func = extern.func() func.call() def test_export_global(self): module = Module( Store(), '(module (global (export "") i32 (i32.const 3)))') instance = Instance(module, []) self.assertEqual(len(instance.exports()), 1) extern = instance.exports()[0] g = extern.global_() self.assertEqual(g.get(), 3) self.assertTrue(extern.func() is None) self.assertTrue(extern.global_() is not None) self.assertTrue(extern.memory() is None) self.assertTrue(extern.table() is None) self.assertTrue(extern.type().func_type() is None) self.assertTrue(extern.type().global_type() is not None) self.assertTrue(extern.type().memory_type() is None) self.assertTrue(extern.type().table_type() is None) def test_export_memory(self): module = Module(Store(), '(module (memory (export "") 1))') instance = Instance(module, []) self.assertEqual(len(instance.exports()), 1) extern = instance.exports()[0] m = extern.memory() self.assertEqual(m.size(), 1) def test_export_table(self): module = Module(Store(), '(module (table (export "") 1 funcref))') instance = Instance(module, []) self.assertEqual(len(instance.exports()), 1) extern = instance.exports()[0] extern.table() def test_multiple_exports(self): module = Module(Store(), """ (module (func (export "a")) (func (export "b")) (global (export "c") i32 (i32.const 0)) ) """) instance = Instance(module, []) self.assertEqual(len(instance.exports()), 3) self.assertTrue(instance.exports()[0].func() is not None) self.assertTrue(instance.exports()[1].func() is not None) self.assertTrue(instance.exports()[2].global_() is not None) def test_import_func(self): module = Module(Store(), """ (module (import "" "" (func)) (start 0) ) """) hit = [] func = Func(module.store, FuncType([], []), lambda: hit.append(True)) Instance(module, [func]) self.assertTrue(len(hit) == 1) Instance(module, [func.as_extern()]) self.assertTrue(len(hit) == 2) def test_import_global(self): module = Module(Store(), """ (module (import "" "" (global (mut i32))) (func (export "") (result i32) global.get 0) (func (export "update") i32.const 5 global.set 0) ) """) g = Global(module.store, GlobalType(ValType.i32(), True), 2) instance = Instance(module, [g]) self.assertEqual(instance.exports()[0].func().call(), 2) g.set(4) self.assertEqual(instance.exports()[0].func().call(), 4) instance2 = Instance(module, [g.as_extern()]) self.assertEqual(instance.exports()[0].func().call(), 4) self.assertEqual(instance2.exports()[0].func().call(), 4) instance.exports()[1].func().call() self.assertEqual(instance.exports()[0].func().call(), 5) self.assertEqual(instance2.exports()[0].func().call(), 5) def test_import_memory(self): module = Module(Store(), """ (module (import "" "" (memory 1)) ) """) m = Memory(module.store, MemoryType(Limits(1, None))) Instance(module, [m]) Instance(module, [m.as_extern()]) def test_import_table(self): store = Store() module = Module(store, """ (module (table (export "") 1 funcref) ) """) table = Instance(module, []).exports()[0].table() module = Module(store, """ (module (import "" "" (table 1 funcref)) ) """) Instance(module, [table]) Instance(module, [table.as_extern()]) def test_invalid(self): store = Store() with self.assertRaises(TypeError): Instance(1, []) with self.assertRaises(TypeError): Instance(Module(store, '(module (import "" "" (func)))'), [1]) val = Func(store, FuncType([], []), lambda: None) module = Module(store, '(module (import "" "" (func)))') Instance(module, [val]) with self.assertRaises(RuntimeError): Instance(module, []) with self.assertRaises(RuntimeError): Instance(module, [val, val]) module = Module(store, '(module (import "" "" (global i32)))') with self.assertRaises(Trap): Instance(module, [val]) def test_start_trap(self): store = Store() module = Module(store, '(module (func unreachable) (start 0))') with self.assertRaises(Trap): Instance(module, [])
true
4ae2ecddcbf38f33676ddb1041bff527a1699b29
Python
fsbr/unh-startracker
/analysisAndPlots/astro/image/centerPixelCircle.py
UTF-8
281
2.84375
3
[]
no_license
# from PIL import Image, ImageDraw image = Image.open('figimage.jpg') draw = ImageDraw.Draw(image) # change this when the calibration vs. when you're making hte thesis figure r = 1450/2 x = 1936 y = 1296 draw.ellipse((x-r, y-r, x+r, y+r)) image.save('maxradius.png') image.show()
true
dfd6eec37a34258a95609a6b976a423d3cbf6fe4
Python
AmiteshMagar/Physics-Dept._PyTut-2
/p10.py
UTF-8
388
3.59375
4
[]
no_license
def subRout10(n,Lx,Ly): LyPrime = [] #this for us to compute the last value Lx.append(Lx[0]) Ly.append(Ly[0]) for i in range(n): calc= (Ly[i+1] - Ly[i])/(Lx[i+1] - Lx[i]) LyPrime.append(calc) Ly.pop(len(Ly)-1) return LyPrime #testing subRout10 -- works perfectly! ''' Lx =[2,5,3] Ly=[5,4,8] n=3 print(subRout10(n,Lx,Ly)) '''
true
dceafb36fc330bcce81fd8147b2d52d61ab1da9c
Python
jes5918/TIL
/Algorithm/SWEA/알고리즘응용/1251_하나로_kruskal.py
UTF-8
4,755
3.140625
3
[]
no_license
# 처음엔 다익스트라로 풀라고 생각했지만 # 다익스트라는 모든 경로를안가고 출발지부터 목적지까지 최단거리로 갈 수 있는 경우를 찾는 것이기 때문에 # # 최소신장트리 방법 사용 # 그래프의 속성을 가지고 있으며 간선에 가중치를 추가 한 그래프의 하위 개념인 트리 # 최소한의 비용으로 모든 도시를 연결하는 도로를 설계하는 문제를 풀기 적합한 알고리즘 # 간선의 가중치를 기준으로 사이클을 제거하여 필요한 정보만 가지는 방식 # 가장 작은 가중치를 가지는 트리를 만드는 알고리즘 # - 프림(Prim) 알고리즘 : 정점에 연결 된 간선의 가중치 중 가장 작은 가중치의 간선을 연결해 나가는 방식 # - 크루스칼(kruskal) 알고리즘 : 모든 간선의 가중치를 조사하고 정렬 후 순서대로 연결해 나가는 방식 # # - 최소 신장 트리에서 발생하는 사이클은 깊이 우선 탐색 방법으로 해결할 수 있지만 성능 저하 # - 분리 집합을 이용하여 해당하는 연결 되지 않은 정점을 순서대로 연결해 나가는 방식 선호 import sys sys.stdin = open('input11.txt', 'r') def find(node): if parent[node] != node: parent[node] = find(parent[node]) return parent[node] def union(node_v, node_u): root1 = find(node_v) root2 = find(node_u) if rank[root1] > rank[root2]: parent[root2] = root1 else: parent[root1] = root2 if rank[root1] == rank[root2]: rank[root2] += 1 def make_set(node): parent[node] = node rank[node] = 0 for tc in range(1, int(input().rstrip()) + 1): # 입력부분 N = int(input().rstrip()) x_point = list(map(int, input().rstrip().split())) y_point = list(map(int, input().rstrip().split())) E = float(input().rstrip()) # 섬 입력받기 arr = list(zip(x_point, y_point)) # 그래프 만들기 G = [] for i in range(N): for j in range(i + 1, N): G += [(E * ((arr[i][0] - arr[j][0]) ** 2 + (arr[i][1] - arr[j][1]) ** 2), i, j)] # 크루스칼 알고리즘 parent = dict() rank = dict() # 노드 초기화 for node in range(N): make_set(node) # 그래프 정렬 G.sort() # 유니온 과정 res = 0 for g in G: weight, node_v, node_u = g if find(node_v) != find(node_u): union(node_v, node_u) res += weight print('#{} {}'.format(tc, round(res))) # 프림알고리즘 훨씬빠름 # def hanaro(N): # check = [0xffffffffffff]*N # check[0] = 0 # visit = [0]*N # total_length = 0 # # for _ in range(N): # # 시작점 찾기 # cur = -1 # min_value = 0xffffffffffff # for i in range(N): # if visit[i]: # continue # if check[i] < min_value: # cur, min_value = i, check[i] # # visit[cur] = 1 # total_length += min_value # # for j in range(N): # if cur == j: # continue # dist_bet = (x_list[j]-x_list[cur])**2 + (y_list[j]-y_list[cur])**2 # if dist_bet < check[j]: # check[j] = dist_bet # return total_length # # # T = int(input()) # for tc in range(1,1+T): # N = int(input()) # x_list = list(map(int, input().split())) # y_list = list(map(int, input().split())) # E = float(input()) # ans = round(hanaro(N) * E) # print('#{} {}'.format(tc, ans)) # 처음 다익스트라로 잘못알고풀어 모든경로를 안찍고 거리를 꼐산 아주 틀린방법 # # def BFS(x, y): # q = deque() # q.append([x, y]) # while q: # now_dist, now = q.popleft() # for next_idx, distance in G[now]: # if dist[next_idx] > now_dist + distance: # dist[next_idx] = now_dist + distance # q.append([dist[next_idx], next_idx]) # # # for tc in range(1, int(input().rstrip())+1): # # 입력부분 # N = int(input().rstrip()) # x_point = list(map(int, input().rstrip().split())) # y_point = list(map(int, input().rstrip().split())) # E = float(input().rstrip()) # # 섬 입력받기 # arr = list(zip(x_point, y_point)) # # # 그래프 만들기 # G = [[] for _ in range(N)] # for i in range(N): # for j in range(N): # if i != j: # G[i] += [(j, int(E * ((arr[i][0] - arr[j][0]) ** 2 + (arr[i][1] - arr[j][1]) ** 2)))] # # # 거리 배열 초기화 # dist = [987654321 for _ in range(N)] # dist[0] = 0 # BFS(0, 0) # print(dist) # print('#{} {}'.format(tc, dist[N-1]))
true
799b832ff22714e93afe16514f5b6de81a0a203e
Python
kball/ambry
/ambry/geo/colormap.py
UTF-8
6,555
2.84375
3
[ "BSD-2-Clause" ]
permissive
''' Created on Mar 17, 2013 @author: eric ''' def _load_maps(): import os.path import ambry.support import csv def cmap_line(row): return { 'num': int(row['ColorNum'].strip()), 'letter': row['ColorLetter'].strip(), 'R': int(row['R'].strip()), 'G': int(row['G'].strip()), 'B': int(row['B'].strip()), } sets = {} cset = None cset_key = None scheme = None with open(os.path.join(os.path.dirname(ambry.support.__file__),'colorbrewerschemes.csv')) as f: for row in csv.DictReader(f): try: if row['SchemeType'].strip(): scheme_type = row['SchemeType'].strip() if row['ColorName'].strip(): if cset_key: sets[cset_key] = cset cset_key = (row['ColorName'].strip(), int(row['NumOfColors'].strip())) cset = { 'crit_val':row['CritVal'].strip(), 'scheme_type':scheme_type.lower(), 'n_colors':int(row['NumOfColors'].strip()), 'map' : [] } cset['map'].append(cmap_line(row)) else: cset['map'].append(cmap_line(row)) except Exception as e: print "Error in row: ", row, e.message return sets def test_colormaps(): sets = _load_maps() nums = set() for key, s in sets.items(): nums.add(s['n_colors']) print nums def get_colormaps(): """Return a dictionary of all colormaps""" return _load_maps() def get_colormap(name=None, n_colors=None, expand = None,reverse=False): """Get a colormap by name and number of colors, n_colors must be in the range of 3 to 12, inclusive expand multiplies the size of the colormap by interpolating that number of additional colors. n=1 will double the size of the map, n=2 will tripple it, etc. See http://colorbrewer2.org/ for the color browser """ cmap = get_colormaps()[(name,int(n_colors))] if expand: expand_map(cmap, expand) if reverse: cmap['map'].reverse() return cmap def interp1(value, maximum, rng): ''' Return the v/m point in the range rng''' return rng[0] + (rng[1] - rng[0])*float(value)/float(maximum) def interp3(value, maximum, s, e): from functools import partial return map(partial(interp1, value, maximum), zip(s,e)) def expand_map(cmap, n): import colorsys o = dict(cmap) o['map'] = {} omap = [] imap = cmap['map'] for j in range(len(imap)-1): omap.append(imap[j]) s = imap[j] e = imap[j+1] st = (s['R'],s['G'],s['B']) et = (e['R'],e['G'],e['B']) for i in range(1,n+1): r = interp3(i,n+1, st,et) omap.append({'R':int(r[0]),'G':int(r[1]),'B':int(r[2])}) omap.append(imap[j+1]) for i in range(len(omap)): if omap[i].get('letter'): letter = omap[i]['letter'] omap[i]['letter'] = letter+str(i+1) omap[i]['num'] = i+1 o['n_colors'] = len(omap) o['map'] = omap return o def geometric_breaks(n, min, max): """Produce breaks where each is two times larger than the previous""" n -= 1 parts = 2**n-1 step = (max - min) / parts breaks = [] x = min for i in range(n): breaks.append(x) x += step*2**i breaks.append(max) return breaks def logistic_breaks(n, min, max, reversed = False): import numpy as np ex = np.exp(-(1.0/3000.0)*np.square(np.arange(101)))[::-1] ex = ex - np.min(ex) ex = ex / np.max(ex) o = [] for v in range(n): idx = int(float(v)/float(n-1) * 100) if reversed: v = ex[100-idx] else: v = ex[idx] o.append(v*(float(max)-float(min)) + min) return o def exponential_breaks(n, avg): o = [] for i in range(-n/2,n/2): o.append(avg*(2**i+2**(i+1))/2.0) return o def write_colormap(file_name, a, map, break_scheme='even', min_val=None, max_val =None, ave_val=None): """Write a QGIS colormap file""" import numpy as np import numpy.ma as ma import math header ="# QGIS Generated Color Map Export File\nINTERPOLATION:DISCRETE\n" masked = ma.masked_equal(a, 0) min_ = np.min(masked) if not min_val else min_val max_ = np.max(a) if not max_val else max_val ave_ = masked.mean() if not ave_val else ave_val if break_scheme == 'even': max_ = max_ * 1.001 # Be sure to get all values range = min_-max_ delta = range*.001 r = np.linspace(min_-delta, max_+delta, num=map['n_colors']+1) elif break_scheme == 'jenks': from ambry.geo import jenks_breaks r = jenks_breaks(a, map['n_colors']) elif break_scheme == 'geometric': r = geometric_breaks(map['n_colors'], min_, max_) elif break_scheme == 'logistic': r = logistic_breaks(map['n_colors'], min_, max_) elif break_scheme == 'exponential': r = exponential_breaks(map['n_colors'], ave_) elif break_scheme == 'stddev': sd = np.std(a) else: raise Exception("Unknown break scheme: {}".format(break_scheme)) colors = map['map'] colors.append(None) # Causes the last item to be skipped alphas, alpha_step = np.linspace(64,255,len(colors),retstep=True) alpha = alpha_step+64 with open(file_name, 'w') as f: f.write(header) last_me = None for v,me in zip(r,colors): if me: f.write(','.join([str(v),str(me['R']), str(me['G']), str(me['B']), str(int(alpha)), me['letter'] ])) alpha += alpha_step alpha = min(alpha, 255) f.write('\n') last_me = me # Prevents 'holes' where the value is higher than the max_val if max_val: v = np.max(a) f.write(','.join([str(v),str(last_me['R']), str(last_me['G']), str(last_me['B']), str(int(alpha)), last_me['letter'] ])) f.write('\n')
true
8bc9965eae87df32297b30167570ac4585911834
Python
komo-fr/pep_map_site
/pep_map/acquirer/pep_acquirer.py
UTF-8
9,585
2.890625
3
[]
no_license
import collections from datetime import datetime import os from pathlib import Path import re from bs4 import BeautifulSoup import pandas as pd import numpy as np from .acquirer import Acquirer class PepAcquirer(Acquirer): def __init__(self, should_save_raw_data: bool= False, raw_data_out_root_path: str = 'html', make_fetch_datetime_dir: bool = True) -> None: super().__init__(should_save_raw_data, raw_data_out_root_path, make_fetch_datetime_dir) def _save_raw_data(self, html, pep_id: str, out_dir_path: str) -> None: file_name = 'pep-{}.html'.format(pep_id) path = Path(out_dir_path) / file_name self._save_html(html, path) def _extract_pep_id(self, url: str) -> str: """ URL文字列から、PEPの番号を抽出する :param url: 抽出元のURL :return: PEPの番号 () """ # TODO: どういう経緯で条件分岐が必要だったのか確認する if re.match('.+/pep-[0-9]{4}/#.+', url): return [x[len('pep-'):] for x in url.split('/') if x][ -2] # TODO: prefixの除去方法 elif re.match('.+/pep-[0-9]{4}/{0,1}', url): return [x[len('pep-'):] for x in url.split('/') if x][ -1] # TODO: prefixの除去方法 def _acquire_pep_html(self, pep_id: str, input_local_dir_path=None) -> bytes: # pep-NNNN.htmlというファイル名規則で保存されていることを前提にしている if input_local_dir_path: # ローカルのHTMLファイルから取得 path = Path(input_local_dir_path) / 'pep-{}.html'.format(pep_id) path = str(path) else: # Webから取得 base_url = 'https://www.python.org/dev/peps/pep-{}' path = base_url.format(pep_id) html = self._acquire_html(path) if self._should_save_raw_data: self._save_raw_data(html, pep_id, self._raw_data_out_dir_path) return html def _acquire_all_pep_ids(self, input_local_dir_path: str = None) -> list: # インデックスからすべてのPEPの番号を取得する pep_id = '0000' html = self._acquire_pep_html(pep_id=pep_id, input_local_dir_path=input_local_dir_path) all_pep_ids = self._scrape_linked_pep_list(html) return all_pep_ids def _scrape_linked_pep_list(self, html: bytes, allow_duplication: bool = False) -> list: """ PEP一覧のHTMLデータから、リンクされているPEPを取得する(重複がある) :param html: リンク抽出元のPEPのHTML :return: リンクされているPEPのリスト(重複あり) """ soup = BeautifulSoup(html, "lxml") a_tags = soup.find_all("a", href=re.compile("/dev/peps/pep-[0-9]{4}")) link_destination_pep_ids = [] for a_tag in a_tags: pep_url = a_tag.get("href") pep_id = self._extract_pep_id(pep_url) link_destination_pep_ids.append(pep_id) if not allow_duplication: # 重複の排除 link_destination_pep_ids = set(link_destination_pep_ids) link_destination_pep_ids = list(link_destination_pep_ids) return link_destination_pep_ids def acquire(self, input_local_dir_path: str = None, pep_ids: list = None): if input_local_dir_path: self._fetch_start_datetime = self._get_fetch_date_from_local_path( input_local_dir_path) else: self._fetch_start_datetime = datetime.now() if self._make_fetch_datetime_dir: dir_name = self.fetch_start_datetime_str self._raw_data_out_dir_path = os.path.join(self._raw_data_out_root_path, dir_name) else: self._raw_data_out_dir_path = self._raw_data_out_root_path data = self._acquire(input_local_dir_path=input_local_dir_path, pep_ids=pep_ids) self._data = data return data def _acquire(self, input_local_dir_path: str = None, pep_ids: list=None) -> dict: # pep_idsはstr型のlist(0000,0001などの文字列) if not pep_ids: pep_ids = self._acquire_all_pep_ids(input_local_dir_path=input_local_dir_path) peps_dict = {} for i, pep_id in enumerate(pep_ids): pep_dict = self._acquire_one_record(pep_id=pep_id, input_local_dir_path=input_local_dir_path) peps_dict[pep_id] = pep_dict print('[{}/{}] Completed to acquire: {}'.format(i+1, len(pep_ids), pep_id)) # TODO: logging return peps_dict def _acquire_one_record(self, pep_id: str, input_local_dir_path: str = None): html = self._acquire_pep_html(pep_id=pep_id, input_local_dir_path=input_local_dir_path) pep_dict = self._scrape(html) return pep_dict def _scrape(self, html: str) -> dict: raise NotImplementedError def _str2datetime(self, source_str: str) -> datetime: """ 文字列を日付型に変換する :param source_str: 変換前の文字列 :return: 変換後の日付型。変換に失敗したら文字列'Failed to convert'を返す """ if (source_str != source_str) or not source_str: # nullチェック # return source_str return pd.NaT converted = '' # 想定する日付書式のリスト format_list = ['%d-%b-%Y', '%d-%B-%Y', '%Y-%m-%d', '%d %b %Y', '%d %B %Y'] for format_text in format_list: try: converted = datetime.strptime(source_str, format_text) except: # TODO: ちゃんと指定する continue if not converted: # 個別対応 # 日付情報の後にコメントが入っている形式があるので、 # コメント部分をトリミングしてから日付型に変換する pattern = '^[0-9]{1,2}-[a-z,A-Z]{3}-[0-9]{4}.+$' if re.match(pattern, source_str): source_str = source_str[:len('YYYY-mm-dd') + 1] converted = datetime.strptime(source_str, '%d-%b-%Y') else: converted = 'Failed to convert' return converted class PepHeaderAcquirer(PepAcquirer): def __init__(self, should_save_raw_data: bool = False, raw_data_out_root_path: str = 'html', make_fetch_datetime_dir: bool = True) -> None: super().__init__(should_save_raw_data, raw_data_out_root_path, make_fetch_datetime_dir) self._csv_out_file_name_base = 'pep_header' def _to_dataframe(self, source_dict: dict) -> pd.DataFrame: df = super()._to_dataframe(source_dict) df = df.reset_index() df['pep_id'] = df['index'] del df['index'] df = df.set_index('pep_id') return df def _scrape(self, html: str) -> dict: """ PEPの個別ページのHTML文字列から、基本情報(Title, Createdなど)を抽出する :param html: 抽出元となるHTMLファイルの中身(文字列) :return: 抽出した基本情報の辞書 """ soup = BeautifulSoup(html, "lxml") table_tag = soup.select("table.rfc2822") if not table_tag: return {} tr_tags = table_tag[0].find_all('tr') header_dict = {} for tr_tag in tr_tags: field_name = tr_tag.find('th').text.replace(':', '') field_body = tr_tag.find('td').text.replace(':', '') header_dict[field_name] = field_body # Cratedフィールドは日付形式が揃っていないので揃える header_dict['Created_dt'] = self._str2datetime(header_dict['Created']) return header_dict class PepLinkDestinationAcquirer(PepAcquirer): def __init__(self, should_save_raw_data: bool = False, raw_data_out_root_path: str = 'html', make_fetch_datetime_dir: bool = True) -> None: super().__init__(should_save_raw_data, raw_data_out_root_path, make_fetch_datetime_dir) self._csv_out_file_name_base = 'pep_link_destination' def _to_dataframe(self, source_dict: dict) -> pd.DataFrame: df = super()._to_dataframe(source_dict) df = df.reset_index() df['link_source_pep_id'] = df['index'] del df['index'] df = df.set_index('link_source_pep_id') df = df.fillna(0) for column in df.columns: df[column] = df[column].astype(int) return df def _scrape(self, html: bytes) -> dict: """ PEP一覧のHTMLデータから、リンク数を取得する :param html: PEP一覧(PEP 0)のHTMLデータ :return: PEPごとのリンク数の辞書 """ link_destination_pep_ids = self._scrape_linked_pep_list(html, allow_duplication=True) count_dict = collections.Counter(link_destination_pep_ids) return dict(count_dict)
true
0680b00f24ecfc9ffeaa6be09e939ef62e90f70d
Python
saxenamahima/8085-emulator
/funcyions.py
UTF-8
10,550
2.53125
3
[]
no_license
import extras import registers import set_flags import validate ##################################################### # ARITHMETICS # ##################################################### def ADD(register): if not validate.validate_reg(register): print "Invalid Register: %s" % register exit(1) a = int(registers.reg["A"], 16) if register == "M": b = extras.getPair('H', 'L') if extras.chkMemory(b): b = int(registers.reg[register], 16) else: print " Invalid Memory:", b exit(1) else: b = int(registers.reg[register], 16) t = a + b a = int(extras.getLowerNibble(format(a, '0x')), 2) b = int(extras.getLowerNibble(format(b, '0x')), 2) if not validate.validate_data(t): print "\n////-----OverFlow Detected----////\n" t = format(t, "02x") t = set_flags.setCarry(t) set_flags.setFlags(a, b, t, isAbnormalFlow=True) tmp = {"A": t[1:]} else: t = format(t, "02x") tmp = {"A": t} set_flags.setFlags(a, b, t) registers.reg.update(tmp) def SUB(register): if not validate.validate_reg(register): print "Invalid Register: %s" % register exit(1) a = int(registers.reg["A"], 16) if register == "M": b = extras.getPair('H', 'L') if extras.chkMemory(b): b = int(registers.reg[register], 16) else: print " Invalid Memory:", b exit(1) else: b = int(registers.reg[register], 16) t = a - b a = int(extras.getLowerNibble(format(a, '0x')), 2) b = int(extras.getLowerNibble(format(b, '0x')), 2) if not validate.validate_data(t): print "\n////-----UnderFlow Detected----////\n" t = format(t, "02x") t = set_flags.setCarry(t) set_flags.setFlags(a, b, t, isAbnormalFlow=True) tmp = {"A": t[1:]} else: t = format(t, "02x") set_flags.setFlags(a, b, t) tmp = {"A": t} set_flags.setFlags(a, b, t) registers.reg.update(tmp) def ADI(data): a = int(registers.reg['A'], 16) b = int(data, 16) res = format((a + b), '02x') a = int(extras.getLowerNibble(format(a, '0x')), 2) b = int(extras.getLowerNibble(format(b, '0x')), 2) if validate.validate_data(int(res, 16)): registers.reg['A'] = res set_flags.setFlags(a, b, res) else: print "\n Overflow Detected ADI", data print "Register Data[A]:", registers.reg['A'] exit(1) def INR(register): if validate.validate_reg(register): if register == 'M': a = extras.getPair('H', 'L') if extras.chkMemory(a): b = int(registers.memory[a], 16) + 1 if b > 255: b = 0 registers.memory[a] = format(b, '0x') else: print "invalid memory:", a exit(1) else: b = int(registers.reg[register], 16) + 1 if b > 255: b = 0 registers.reg[register] = format(b, '0x') def DCR(register): if validate.validate_reg(register): if register == 'M': a = extras.getPair('H', 'L') if extras.chkMemory(a): b = int(registers.memory[a], 16) - 1 if b < 0: b = 255 registers.memory[a] = format(b, '0x') else: print "invalid memory:", a exit(1) else: b = int(registers.reg[register], 16) - 1 if b < 0: b = 255 registers.reg[register] = format(b, '0x') def INX(reg1): if validate.validate_reg(reg1): try: reg2 = registers.reg_pair[reg1] except: print "invalid register pair", reg1 exit(1) a = extras.getPair(reg1, reg2) a = int(a, 16) + 1 if a > 65535: a = 0 a = format(a, '04x') registers.reg[reg1] = a[:2] registers.reg[reg2] = a[2:] else: print "invalid register", reg1 exit(1) def DCX(reg1): if validate.validate_reg(reg1): try: reg2 = registers.reg_pair[reg1] except: print "invalid register pair", reg1 exit(1) a = extras.getPair(reg1, reg2) a = int(a, 16) + 1 if a < 0: a = 65535 a = format(a, '04x') registers.reg[reg1] = a[:2] registers.reg[reg2] = a[2:] else: print "invalid register", reg1 exit(1) def DAD(reg1): if validate.validate_reg(reg1): c = 0 try: reg2 = registers.reg_pair[reg1] except: print "invalid register pair", reg1 exit(1) a = int(registers.reg[reg2], 16) res = int(registers.reg['L'], 16) + a if res > 255: c = 1 res -= 256 registers.reg['L'] = format(res, '02x') a = int(registers.reg[reg1], 16) res = int(registers.reg['H'], 16) + a + c res = format(res, '02x') if not validate.validate_data(int(res, 16)): res = set_flags.setCarry(res) registers.reg['H'] = res else: print 'invalid register pair:', reg1 exit(1) def SUI(data): a = int(registers.reg['A'], 16) b = int(data, 16) res = a - b res = format(res, '02x') if not validate.validate_data(int(res, 16)): res = set_flags.setCarry(res) set_flags.setFlags(a, b, res, isAbnormalFlow=True) else: set_flags.setFlags(a, b, res) registers.reg['A'] = res ##################################################### # LOAD AND STORE # ##################################################### def MOV(reg1, reg2): if not validate.validate_reg(reg1): print "Invalid Register: %s" % reg1 exit(1) if not validate.validate_reg(reg2): print "Invalid Register: %s" % reg2 exit(1) if reg1 == 'M': a = extras.getPair('H', 'L') if extras.chkMemory(a): registers.memory[a] = registers.reg[reg2] else: print " Invalid Memory:", a elif reg2 == 'M': a = extras.getPair('H', 'L') registers.reg[reg1] = registers.memory[a] else: registers.reg[reg1] = registers.reg[reg2] def LDA(addr): data = registers.memory[addr] if validate.validate_data(int(data, 16)): registers.reg['A'] = data else: print "Data Invalid. Please Retry" def STA(addr): registers.memory[addr] = registers.reg["A"] def MVI(reg, data): if reg == 'M': a = extras.getPair('H', 'L') registers.memory[a] = data elif validate.validate_reg(reg): registers.reg[reg] = data else: print "Invalid Register" def LXI(register, data): if validate.validate_reg(register): registers.reg[register] = data[:2] if len(data[2:]) > 1: registers.reg[registers.reg_pair[register]] = data[2:] else: print "Invalid Register", register exit(1) def LHLD(addr): if extras.chkMemory(addr) and extras.chkMemory(str(int(addr) + 1)): registers.reg['L'] = registers.memory[addr] registers.reg['H'] = registers.memory[str(int(addr) + 1)] else: print "Pointing Invalid Memory:", addr def SHLD(mem): a = extras.getPair('H', 'L') registers.memory[mem] = a def XCHG(): registers.reg['D'], registers.reg['H'] = registers.reg['H'], registers.reg['D'] registers.reg['E'], registers.reg['L'] = registers.reg['L'], registers.reg['E'] def STAX(register): if validate.validate_reg(register): a = extras.getPair(register, registers.reg_pair[register]) registers.memory[a] = registers.reg['A'] else: print "Invalid Register:", register exit(1) ##################################################### # LOGICAL OPERATIONS # ##################################################### def CMP(register): if validate.validate_reg(register): a_data = int(registers.reg['A'], 16) if register == 'M': a = extras.getPair('H', 'L') if validate.validate_memory(a): a = int(registers.memory[a], 16) else: print "Invalid Memory:", a exit(1) else: a = int(registers.reg[register], 16) if a_data < a: registers.flag['CY'] = 1 elif a_data == a: registers.flag['Z'] = 1 else: registers.flag['CY'] = 0 registers.flag['Z'] = 0 else: print "Invalid Register:", registers exit(1) def CMA(): data = registers.reg['A'] registers.reg['A'] = format(255 - int(data, 16), '0x') ##################################################### # BRANCHING OPERATIONS # ##################################################### def JMP(addr): if extras.chkLable(addr): return registers.label[addr] elif extras.chkMemory(addr): return addr else: print 'pointing to invalid memory:', addr exit(1) def JC(addr): if registers.flag['CY'] == 1: return JMP(addr) else: return def JNC(addr): if registers.flag['CY'] == 0: return JMP(addr) else: return def JNZ(addr): if registers.flag['Z'] == 0: return JMP(addr) else: return def JZ(addr): if registers.flag['Z'] == 1: return JMP(addr) else: return ##################################################### # EXTRAS # ##################################################### def SET(addr, data): if validate.validate_data(int(data, 16)): registers.memory[addr] = data else: print "Data Invalid.\nPlease Enter Valid Data at Memory Location: %s" % addr exit(1)
true
ac466a13bde1493b85def1f039a1e52ea90ee003
Python
shguan10/webcam-touchscreen
/collect_data.py
UTF-8
1,513
2.5625
3
[]
no_license
import cv2 import numpy as np import pdb import common def prompted(): cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, common.MAXCOLS) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, common.MAXROWS) finger_pixels = common.sample_finger(cap) background = common.sample_background(cap) circle_position = common.generate_random_circle() cv2.namedWindow("filtered") cv2.moveWindow("filtered",common.WIN[0],common.WIN[1]) num = 0 while True: _, frame = cap.read() keypress = cv2.waitKey(1) frame = cv2.flip(frame, 1) frame = common.background_filter(frame,background) frame = common.fuzzy_mask(frame,pixels=finger_pixels) canvas = frame.copy() canvas = common.draw_circle(canvas,circle_position) cv2.imshow("filtered",canvas) if keypress == ord(" "): cv2.imwrite("data/"+str(circle_position[0])+"_"+str(circle_position[1])+".jpg",frame) circle_position = common.generate_random_circle() num+=1 print(num) elif keypress == ord("r"): circle_position = common.generate_random_circle() elif keypress == ord("q"): break cap.release() cv2.destroyAllWindows() def moused(): cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, common.MAXCOLS) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, common.MAXROWS) finger_pixels = common.sample_finger(cap) background = common.sample_background(cap) common.get_samples(cap,finger_pixels,background) cap.release() if __name__=="__main__": prompted()
true
bb1e469fcbcaccd1563f0d93862b7b0d11214b75
Python
seven320/powarun
/main/src/powarun.py
UTF-8
3,094
2.9375
3
[]
no_license
# encoding utf-8 import os, sys import datetime as dt from dotenv import load_dotenv import tweepy import get_weather class Powarun(): def __init__(self): load_dotenv(".env") auth = tweepy.OAuthHandler( consumer_key = os.environ.get("CONSUMER_KEY"), consumer_secret = os.environ.get("CONSUMER_SECRET")) auth.set_access_token( key = os.environ.get("ACCESS_TOKEN"), secret = os.environ.get("TOKEN_SECRET")) self.api = tweepy.API(auth, wait_on_rate_limit = True) JST = dt.timezone(dt.timedelta(hours=+9), "JST") self.JST = dt.datetime.now(JST) def get_tweets(self): return self.api.home_timeline(count = 10, since_id = None) def tweet(self): status = "お天気観測してるポワ" self.api.update_statue(statue = status) def change_icon(self, form): if form == "normal": image = "../../normal.png" elif form == "rainy": image = "../../rainy.png" elif form == "sunny": image = "../../sunny.png" elif form == "snowy": image = "../../snowy.png" self.api.update_profile_image(image) # def description2japanese(self, description): # trans = { # "clear sky" : "快晴", # "few clouds" : "晴れ", # "scattered clouds" : "曇り", # "broken clouds" : "曇り", # "shower rain" : "小雨", # "rain" : "雨", # "thunderstrom" : "雷雨", # "snow" : "雪", # "mist" : "霧" # } # return trans[description] def tweet_weather_forecast_morning(self, city = "kyoto"): data = get_weather.current_and_forecasts_weather_bycity(city) today_weather = {} for hourly_data in data["hourly"]: time = dt.datetime.fromtimestamp(hourly_data["dt"]) if time.day == self.JST.day: today_weather[time.hour] = hourly_data["weather"][0]["description"] """ 朝は8:00 ~ 12:00まで 夜は20:00 ~ 24:00に1時間に一回ずつ天気予報を呟く 朝は今日の天気を 夜は明日の天気を呟く """ status = "{}年{}月{}日の京都のお天気をお伝えするポワ\n".format( \ self.JST.year, \ self.JST.month, \ self.JST.day \ ) + \ "お昼頃は{}で,\n".format(today_weather[12]) + \ "その後{}となる予定ですポワ\n".format(today_weather[15]) + \ "また,夜には{}となりますポワ.".format(today_weather[18]) # 18時 self.api.update_statue(status = status) def tweet_weather_forecast_night(): pass # status = "明日の天気は" # 朝の天気 # 昼の天気 # 夜の天気 def main(): powarun = Powarun() # public_tweet = powarun.get_tweets() powarun.tweet_weather_forecast_morning() # print(public_tweet) if __name__ == "__main__": main()
true
5394e3658e9b0f0394b4d7b9a2be0a957520ed0f
Python
User9000/100python
/ex20.py
UTF-8
90
3.25
3
[]
no_license
d = {"a": 1, "b": 2,"c":3} sum=0 for keys,val in d.items(): sum= sum + val print(sum)
true
064223e30861e49d030af3fe91c06e82a8a2db6a
Python
ericjenny3623/15-112
/random/approximations.py
UTF-8
1,037
3.46875
3
[]
no_license
# sum = 0 # n = 8 # a = 0 # b = 2 # delta = (b-a)/n # precision = 6 # def f(x): # return 1 / (1 + x**6) # def printf(x): # print(round(x, precision)) # for i in range(n): # x = delta*(i+0.5) + a # y = f(x) # sum += y # printf(y) # printf(sum) # printf(sum*delta) # print("++++++++++++++++++++++") # sum = 0 # for i in range(n + 1): # if i == 0: # c = 1 # elif i == n: # c = 1 # elif i % 2 == 0: # c = 2 # else: # c = 4 # x = delta*i + a # y = f(x) # sum += y*c # printf(y) # printf(sum) # printf(sum*delta/3) # print("++++++++++++++++++++++") # sum = 0 # for i in range(n + 1): # if i == 0: # c = 1 # elif i == n: # c = 1 # else: # c = 2 # x = delta*i + a # y = f(x) # sum += y*c # printf(y) # printf(sum) # printf(sum*delta/2) h = 0.2 a = 0 b = 1 x0 = 0 y0 = 1 x = x0 y = y0 for n in range(int((b-a)/h)): dy = (x*x*y) - (y*y*0.5) y += (h*dy) x += h print(n, x, y, dy)
true
ca5e3faa1e511279bfeae6bf512616f14548099f
Python
ciabo/BinaryTrees
/RB.py
UTF-8
4,383
3.265625
3
[]
no_license
import ABR class RBNode(ABR.Node): def __init__(self,key,nil): super().__init__(key,nil) self.color = "black" def getColor(self): return self.color def setColor(self,color): self.color=color class RBTree(ABR.Tree): def __init__(self): self.nil=RBNode(None,None) self.nil.setColor("black") self.root=self.nil def setRoot(self, key): self.root = RBNode(key,self.nil) def leftRotation(self, x): y=x.getRight() x.setRight(y.getLeft()) if y.getLeft().getKey() != "nil": y.getLeft().setP(x) #Put the left subTree of y in the right subTree of x y.setP(x.getP()) #Y became the son of x parent if x.getP().getKey() == "nil": #if x is the root self.changeRoot(y) elif x == x.getP().getLeft(): x.getP().setLeft(y) else: x.getP().setRight(y) y.setLeft(x) x.setP(y) def rightRotation(self,x): y = x.getLeft() x.setLeft(y.getRight()) if y.getRight().getKey() != "nil": y.getRight().setP(x) y.setP(x.getP()) if x.getP().getKey() == "nil": self.changeRoot(y) elif x == x.getP().getLeft(): x.getP().setLeft(y) else: x.getP().setRight(y) y.setRight(x) x.setP(y) def insert(self, key): if self.root is self.nil: self.setRoot(key) self.root.setColor("red") self.fixUp(self.root) else: self.insertNode(key, self.root) def insertNode(self, key, currentNode): if key <= currentNode.getKey(): if currentNode.getLeft().getKey()!="nil": k=0 self.insertNode(key, currentNode.getLeft()) else: k=0 currentNode.setLeft(RBNode(key,self.nil)) currentNode.getLeft().setP(currentNode) currentNode.getLeft().setColor("red") self.fixUp(currentNode.getLeft()) return currentNode.getLeft() elif key > currentNode.getKey(): if currentNode.getRight().getKey() != "nil": self.insertNode(key, currentNode.getRight()) else: currentNode.setRight(RBNode(key,self.nil)) currentNode.getRight().setP(currentNode) currentNode.getRight().setColor("red") self.fixUp(currentNode.getRight()) return currentNode.getRight() def fixUp(self,z): while(z.getP().getColor()=="red"): #means that there are two red nodes in sequence if z.getP()==z.getP().getP().getLeft(): #if z's father is the left son of z's grandfather y=z.getP().getP().getRight() #y is z's uncle (the right son of z's grandfather) if y.getColor()=="red": z.getP().setColor("black") y.setColor("black") z.getP().getP().setColor("red") z=z.getP().getP() else: if z==z.getP().getRight(): z=z.getP() self.leftRotation(z) z.getP().setColor("black") z.getP().getP().setColor("red") self.rightRotation(z.getP().getP()) else: y = z.getP().getP().getLeft() if y.color == "red": z.getP().setColor("black") y.setColor("black") z.getP().getP().setColor("red") z = z.getP().getP() else: if z == z.getP().getLeft(): z = z.getP() self.rightRotation(z) z.getP().setColor("black") z.getP().getP().setColor("red") self.leftRotation(z.getP().getP()) self.root.setColor("black") def inorder(self): def _inorder(v): if v.getKey() == "nil": return if v.getLeft().getKey() != "nil": _inorder(v.getLeft()) print(v.getKey()," ",v.getColor()) if v.getRight().getKey() != "nil": _inorder(v.getRight()) _inorder(self.root)
true
0a1efdeba5d99a2462d1a5b268e3196c60ba954f
Python
tnakaicode/jburkardt-python
/sftpack/r8vec_sct.py
UTF-8
3,756
2.71875
3
[]
no_license
#! /usr/bin/env python3 # import numpy as np import matplotlib.pyplot as plt import platform import time import sys import os import math from mpl_toolkits.mplot3d import Axes3D from sys import exit sys.path.append(os.path.join("../")) from base import plot2d, plotocc from timestamp.timestamp import timestamp from i4lib.i4vec_print import i4vec_print from i4lib.i4mat_print import i4mat_print, i4mat_print_some from r8lib.r8vec_print import r8vec_print from r8lib.r8mat_print import r8mat_print, r8mat_print_some from r8lib.r8mat_write import r8mat_write from r8lib.r8vec_print_part import r8vec_print_part from r8lib.r8vec_uniform_ab import r8vec_uniform_ab def r8vec_sct(n, x): # *****************************************************************************80 # # R8VEC_SCT computes a forward or backward "slow" cosine transform of an R8VEC. # # Discussion: # # This routine is provided for illustration and testing. It is inefficient # relative to optimized routines that use fast Fourier techniques. # # Y(1) = Sum ( 1 <= J <= N ) X(J) # # For 2 <= I <= N-1: # # Y(I) = 2 * Sum ( 1 <= J <= N ) X(J) # * cos ( PI * ( I - 1 ) * ( J - 1 ) / ( N - 1 ) ) # # Y(N) = Sum ( X(1:N:2) ) - Sum ( X(2:N:2) ) # # Applying the routine twice in succession should yield the original data, # multiplied by 2 * ( N + 1 ). This is a good check for correctness # and accuracy. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 26 June 2015 # # Author: # # John Burkardt # # Parameters: # # Input, integer N, the number of data values. # # Input, real X(N), the data sequence. # # Output, real Y(N), the transformed data. # y = np.zeros(n) for i in range(0, n): y[i] = x[0] / 2.0 for j in range(1, n - 1): angle = np.pi * float((i * j) % (2 * (n - 1))) / float(n - 1) y[i] = y[i] + x[j] * np.cos(angle) j = n - 1 angle = np.pi * float((i * j) % (2 * (n - 1))) / float(n - 1) y[i] = y[i] + x[n - 1] * np.cos(angle) / 2.0 for i in range(0, n): y[i] = 2.0 * y[i] * np.sqrt(float(n) / float(n - 1)) return y def r8vec_sct_test(): # *****************************************************************************80 # # R8VEC_SCT_TEST tests R8VEC_SCT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 26 June 2015 # # Author: # # John Burkardt # n = 256 alo = 0.0 ahi = 5.0 print('') print('R8VEC_SCT_TEST') print(' Python version: %s' % (platform.python_version())) print(' R8VEC_SCT does a forward or backward slow cosine transform.') print('') print(' The number of data items is N = %d' % (n)) # # Set the data values. # seed = 123456789 c, seed = r8vec_uniform_ab(n, alo, ahi, seed) r8vec_print_part(n, c, 1, 10, ' The original data:') # # Compute the coefficients. # d = r8vec_sct(n, c) r8vec_print_part(n, d, 1, 10, ' The cosine coefficients:') # # Now compute inverse transform of coefficients. Should get back the # original data. e = r8vec_sct(n, d) for i in range(0, n): e[i] = e[i] / float(2 * n) r8vec_print_part(n, e, 1, 10, ' The retrieved data:') # # Terminate. # print('') print('R8VEC_SCT_TEST') print(' Normal end of execution.') return if (__name__ == '__main__'): from timestamp import timestamp timestamp() r8vec_sct_test() timestamp()
true
cc4df2d28ace53ef4f14ef2828e92ed061210496
Python
amomin/proje
/python/p88/solution.py
UTF-8
1,075
2.9375
3
[]
no_license
import math, sys, time import MillerTest isPrime = MillerTest.MillerRabin tic = time.clock() MIN = 2 MAX = 12201 COUNTMAX=12000 def getDivSums(n,min=2): solns = [[n,1,[n]]] if isPrime(n): return solns for i in range(min,n/2+1): if n%i==0: res = getDivSums(n/i,i) for x in res: _l=x[2]+[i] new_soln=[x[0]+i,x[1]+1,_l] if new_soln not in solns: solns.append( new_soln ) return solns solns = [0]*MIN for i in range(MIN,MAX): solns.append(False) msns=[] for i in range(MIN,MAX): x = getDivSums(i) for f in x: k=i-f[0]+f[1] if not solns[k] and k>1: solns[k]=i if k <= COUNTMAX: #print "Count solution for ",k," to be ",i if i not in msns: msns.append(i) msns.sort() k=MIN #while k<COUNTMAX: #while k<MAX: #print "f(",k,")=", solns[k] #if not solns[k]: #print "Havent solved for ",k,"yet" #k+=1 #print msns print "Of the solutions found so far, the count up to ", COUNTMAX, " is ",sum(msns) count2 = 0 for y in msns: count2+=y print "Verifying the count is ",count2 toc = time.clock() print "Time is ", toc-tic
true
7a31d67203b5102fb8e968b5a97d360cd0b6b376
Python
letouch/SDCNL
/web-scraper.py
UTF-8
4,146
2.78125
3
[]
no_license
# Web-Scraper for Reddit Data # Data used for paper and results were last scraped in September 2020. # Adapted from (https://github.com/hesamuel/goodbye_world/blob/master/code/01_Data_Collection.ipynb # data analysis imports import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # NLP Imports import nltk nltk.download('wordnet') nltk.download('stopwords') from nltk.tokenize import RegexpTokenizer from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords import re from sklearn.feature_extraction.text import CountVectorizer from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator from PIL import Image import wordninja # creating user agent headers = {"User-agent" : "randomuser"} # set user agent to reddit account username url_1 = "https://www.reddit.com/r/depression.json" res = requests.get(url_1, headers=headers) res.status_code # scraper function def reddit_scrape(url_string, number_of_scrapes, output_list): #scraped posts outputted as lists after = None for _ in range(number_of_scrapes): if _ == 0: print("SCRAPING {}\n--------------------------------------------------".format(url_string)) print("<<<SCRAPING COMMENCED>>>") print("Downloading Batch {} of {}...".format(1, number_of_scrapes)) elif (_+1) % 5 ==0: print("Downloading Batch {} of {}...".format((_ + 1), number_of_scrapes)) if after == None: params = {} else: #THIS WILL TELL THE SCRAPER TO GET THE NEXT SET AFTER REDDIT'S after CODE params = {"after": after} res = requests.get(url_string, params=params, headers=headers) if res.status_code == 200: the_json = res.json() output_list.extend(the_json["data"]["children"]) after = the_json["data"]["after"] else: print(res.status_code) break time.sleep(randint(1,6)) print("<<<SCRAPING COMPLETED>>>") print("Number of posts downloaded: {}".format(len(output_list))) print("Number of unique posts: {}".format(len(set([p["data"]["name"] for p in output_list])))) # remove any repeat posts def create_unique_list(original_scrape_list, new_list_name): data_name_list=[] for i in range(len(original_scrape_list)): if original_scrape_list[i]["data"]["name"] not in data_name_list: new_list_name.append(original_scrape_list[i]["data"]) data_name_list.append(original_scrape_list[i]["data"]["name"]) #CHECKING IF THE NEW LIST IS OF SAME LENGTH AS UNIQUE POSTS print("LIST NOW CONTAINS {} UNIQUE SCRAPED POSTS".format(len(new_list_name))) # scraping suicide_watch data suicide_data = [] reddit_scrape("https://www.reddit.com/r/SuicideWatch.json", 50, suicide_data) suicide_data_unique = [] create_unique_list(suicide_data, suicide_data_unique) # add suicide_watch to dataframe suicide_watch = pd.DataFrame(suicide_data_unique) suicide_watch["is_suicide"] = 1 suicide_watch.head() # scraping suicide_watch data depression_data = [] reddit_scrape("https://www.reddit.com/r/depression.json", 50, depression_data) depression_data_unique = [] create_unique_list(depression_data, depression_data_unique) # add suicide_watch to dataframe depression = pd.DataFrame(depression_data_unique) depression["is_suicide"] = 0 depression.head() # saving data suicide_watch.to_csv('suicide_watch.csv', index = False) depression.to_csv('depression.csv', index = False) # creating combined CSV depression = pd.read_csv('depression.csv') suicide_watch = pd.read_csv('suicide_watch.csv') dep_columns = depression[["title", "selftext", "author", "num_comments", "is_suicide","url"]] sui_columns = suicide_watch[["title", "selftext", "author", "num_comments", "is_suicide","url"]] combined_data = pd.concat([dep_columns, sui_columns],axis=0, ignore_index=True) combined_data["selftext"].fillna("emptypost",inplace=True) combined_data.head() combined_data.isnull().sum() # saving combined CSV combined_data.to_csv('suicide_vs_depression.csv', index = False)
true
17b69c73c6374633fcd6ef0b68efef0fbc0f21f1
Python
sumajali/Learning-Python-
/Interview_Programs/positive_number_or_negative_number.py
UTF-8
544
4.1875
4
[]
no_license
# Positive number or Negative number num = int(input("Enter a number to check positive or Negative:- ")) if num < 0: print("It is a Negative number") elif num == 0: print("0 is a positive number") else: print(f'{num} number is positive number') # positive or negative number using functions def positive_negative(num): if num < 0: print(f'{num} is negative number') else: print(f'{num} is positive number') num = int(input('enter a number:- ')) positive_negative(num)
true
efcfdbe3777fd2c7b86363df48f7fa643a3c8dee
Python
box-key/pyspark-project
/tests/test_dict_lookup.py
UTF-8
5,739
2.828125
3
[]
no_license
import pytest from pyspark import SparkContext from pyspark.sql import SparkSession from collections import defaultdict import csv import os import datetime as dt import re sc = SparkContext() NYC_CSCL_PATH = 'nyc_cscl.csv' root = 'data' violation_records = [os.path.join(root, 'violation_small1.csv'), os.path.join(root, 'violation_small2.csv')] VIOLATION_PATH = ','.join(violation_records) def construct_lookup(data): # data = [(PHYSICALID, L_LOW_HN, L_HIGH_HN, R_LOW_HN, R_HIGH_HN, ST_LABEL, BOROCODE_IDX, FULL_STREE)] lookup = defaultdict(list) for row in data: # format outputs id = int(row[0]) l_low = 0 if len(row[1]) == 0 else int(re.sub('-0|-', '', row[1])) l_high = 0 if len(row[2]) == 0 else int(re.sub('-0|-', '', row[2])) r_low = 0 if len(row[3]) == 0 else int(re.sub('-0|-', '', row[3])) r_high = 0 if len(row[4]) == 0 else int(re.sub('-0|-', '', row[4])) st_label = row[5].lower() borocode = int(row[6]) full_stree = row[7].lower() # add formatted elements to table lookup[(st_label, borocode)].append(((r_low, r_high), (l_low, l_high), id)) lookup[(full_stree, borocode)].append(((r_low, r_high), (l_low, l_high), id)) return lookup def format_hn(hn_record): # if a record is empty, assigns 0 if len(hn_record) == 0: return 0 # otherwise concatenate two values together # example: '187-09' = 18709 <int> # example: '187' = 187 <int> else: # format cases like `70 23` -> `70-23` hn_record = re.sub('\s', '-', hn_record) # exclude cases like `123A`, 'W', 'S', etc. try: return int(hn_record.replace('-', '')) except ValueError: return -1 # violation_record = [year, borocode, house_number, street_name] def lookup_street_segment(v_record, lookup_table): street_name = v_record[3].lower() # lower string house_number = v_record[2] # <str> borocode = v_record[1] # <int> # lookup table to get candidates hn_ranges = lookup_table[(street_name, borocode)] # if key doesn't exist, it returns empty list if len(hn_ranges) == 0: return -1 # format house number, if output is -1, returns -1 formatted_hn = format_hn(house_number) if formatted_hn == -1: return -1 # check candidate ranges, if there is a match, returns physicalID for hn_range in hn_ranges: # hn_range = ((r_low, r_high), (l_low, l_high), physicalID) ran = hn_range[formatted_hn%2] # ran = (low, high) if (ran[0] <= formatted_hn) and (formatted_hn <= ran[1]): return hn_range[2] # if there is no match, returns -1 return -1 class TestDictLookup: def test_construct_dict(self): table = sc.textFile(NYC_CSCL_PATH) header_table = table.first() # start testing res = sc.textFile(NYC_CSCL_PATH) \ .filter(lambda x: x != header_table) \ .mapPartitions(lambda x: csv.reader(x)) \ .filter(lambda x: len(x) >= 30) \ .map(lambda x: (x[0], (x[2], x[3], x[4], x[5], x[10], x[13], x[28]))) \ .reduceByKey(lambda x, y: x) \ .map(lambda x: (x[0], x[1][0], x[1][1], x[1][2], x[1][3], x[1][4], x[1][5], x[1][6])) \ .collect() assert len(res) == 119801 lookup = construct_lookup(res) assert len(lookup) == 18069 num_total = 0 for v in lookup.values(): num_total += len(v) assert num_total == 239602 LOOKUP_BCAST = sc.broadcast(lookup) assert len(LOOKUP_BCAST) == len(lookup) def test_output(self): table = sc.textFile(NYC_CSCL_PATH) header_table = table.first() # start testing res = sc.textFile(NYC_CSCL_PATH) \ .filter(lambda x: x != header_table) \ .mapPartitions(lambda x: csv.reader(x)) \ .filter(lambda x: len(x) >= 30) \ .map(lambda x: (x[0], (x[2], x[3], x[4], x[5], x[10], x[13], x[28]))) \ .reduceByKey(lambda x, y: x) \ .map(lambda x: (x[0], x[1][0], x[1][1], x[1][2], x[1][3], x[1][4], x[1][5], x[1][6])) \ .collect() assert len(res) == 119801 lookup = construct_lookup(res) print(lookup[('tides la', 5)]) print(lookup[('tides ln', 5)]) print(lookup[('roosevelt is br ped & bike path', 4)]) print(lookup[('silver ct', 5)]) print(lookup[('bluh, bluh, dummy', 1)]) def test_lookup_street_segment(self): table = sc.textFile(NYC_CSCL_PATH) header_table = table.first() # start testing res = sc.textFile(NYC_CSCL_PATH) \ .filter(lambda x: x != header_table) \ .mapPartitions(lambda x: csv.reader(x)) \ .filter(lambda x: len(x) >= 30) \ .map(lambda x: (x[0], (x[2], x[3], x[4], x[5], x[10], x[13], x[28]))) \ .reduceByKey(lambda x, y: x) \ .map(lambda x: (x[0], x[1][0], x[1][1], x[1][2], x[1][3], x[1][4], x[1][5], x[1][6])) \ .collect() assert len(res) == 119801 lookup = construct_lookup(res) print(lookup_street_segment([1, 5, '17', 'silver ct'], lookup)) print(lookup_street_segment([1, 1, '17', 'silver ct'], lookup)) print(lookup_street_segment([1, 5, '', 'silver ct'], lookup)) print(lookup_street_segment([1, 5, '59', 'silver ct'], lookup)) print(lookup_street_segment([1, 5, '18', 'silver ct'], lookup)) print(lookup_street_segment([1, 5, '21', 'silver ct'], lookup))
true
fd815447808cee8d5734076189f7b3ca0989475a
Python
gulinmerve/Ptyhon-InterviewQuestions
/1.microsoft.py
UTF-8
1,474
3.4375
3
[]
no_license
given array = 3, 10, 2, 1, 20 Output: 3 The longest increasing subsequence is 3, 10, 20 given array = 3, 2 Output: 1 The longest increasing subsequences are {3} and {2} given array = 50, 3, 10, 7, 40, 80 Output: 4 The longest increasing subsequence is {3, 7, 40, 80} given array = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] output : 6 Explanation : The sequence : [0, 2, 6, 9, 13, 15] or [0, 4, 6, 9, 11, 15] or [0, 4, 6, 9, 13, 15] data = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] from itertools import combinations res=[] for i in range(len(data),0,-1):     c = list(combinations(data,i))     for i in c:         if list(i)==sorted(i):             res=list(i)             print(list(i))             # break     if res:         break def find_longest_sub(lst): subs = [ [] for i in lst] subs[0] =[lst[0]] for i in range(1, len(lst)): for j in range(i): if (lst[i] > lst[j]) and (len(subs[j]) + 1 > len(subs[i])): subs[i] = subs[j].copy() subs[i].append(lst[i]) return len(max(subs,key=len)) def find_longest_sub2(lst):     stack = [1] * len(lst)     for i in range(1, len(lst)):         for j in range(i):             if lst[i] > lst[j]:                 stack[i] = max(stack[i], stack[j] + 1)     return max(stack)
true
b0639e9c0dc867c91e65a39b5b8e5e05da8172ea
Python
roxel/pydiary
/manage.py
UTF-8
1,479
2.53125
3
[ "MIT" ]
permissive
from app import create_app from app.database import db from flask import url_for from flask_script import Manager, Command from flask_migrate import Migrate, MigrateCommand # Creates new app compatible with production environment (built for heroku) app = create_app('config.ProductionConfig') migrate = Migrate(app, db) manager = Manager(app) class Routes(Command): """ Adds Flask-Script command listing all available routes from the app. Does not show routes requiring any parameters (e.g. needing object IDs). """ help = description = 'Lists all route rules added to the app' @staticmethod def __has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments) def run(self): links = [] for rule in app.url_map.iter_rules(): # Filter out rules we can't navigate to in a browser # and rules that require parameters if "GET" in rule.methods and Routes.__has_no_empty_params(rule): url = url_for(rule.endpoint, **(rule.defaults or {})) links.append((url, rule.endpoint)) # links is now a list of url, endpoint tuples for l in links: print(l) manager.add_command('db', MigrateCommand) manager.add_command('routes', Routes) if __name__ == '__main__': manager.run()
true
0c46cc00ffdb22290a3331c08470718ad988b991
Python
claraocarroll/plasmodiumscripts
/bamgraphing2.py
UTF-8
2,546
3.4375
3
[]
no_license
''' Created on 10 Jun 2020 @author: Clara ''' #import the module - from '/Users/Clara/anaconda2/lib/python2.7/site-packages' import pysam #import the graphing software import matplotlib matplotlib.use('Agg') #this tells matplotlib we may not necessarily have access to a screen from matplotlib import pyplot as plt #this is what we're going to use to plot #define a function that we're going to call this function twice: once for plasmodium and once for cerevisiae def getIndelFreq(fPath): #create two empty lists insertionFreq = [] delFreq = [] f = pysam.Samfile('/Users/Clara/Dropbox/barcode2little.bam','rb') #open the bam file for record in f: #uses the cigar string to calculate the number of insertions in this read numOfInsertions = sum(tup[1] for tup in record.cigartuples if tup[0] == 1) #calculates the length of the reference subsequence that this read mapped to lenOnRef = record.reference_length #add to the insertions frequency list insertionFreq.append(float(numOfInsertions) / lenOnRef) #same for deletions numOfDeletions = sum(tup[1] for tup in record.cigartuples if tup[0] == 2) #add to deletions frequency list delFreq.append(float(numOfDeletions) / lenOnRef) f.close() return insertionFreq, delFreq print(insertionFreq) #MAIN-------------------------- #call the function twice plasIns, plasDel = getIndelFreq('/Users/Clara/Dropbox/barcode2little.bam') cerevisiaeIns, cerevisiaeDel = getIndelFreq('/Users/Clara/Dropbox/cerevisiaelittle.bam') print(plasIns) #do the plotting plt.figure() #make a figure to write on #write some plots onto the figure plt.hist(plasIns, 50, alpha = 0.3, label = 'Falciparum Ins') plt.hist(plasDel, 50, alpha = 0.3, label = 'Falciparum Del') plt.hist(cerevisiaeIns, 50, alpha = 0.3, label = 'Cerevisiae Ins') plt.hist(cerevisiaeDel, 50, alpha = 0.3, label = 'Cerevisiae Del') #explaination of these plotting commands: # - we're going to make a histogram out of the list in the first argument # - the second argument specifies how many bins we want (50 in this case) # - the third argument specifies the transparency # - the fourth argument specifies the label for the plot legend #so plot housekeeping - make the legend and label the axes plt.legend(framealpha=0.3) #make it slightly transparent so it doesn't block out any of the bars plt.xlabel('InDels Per Reference Base') plt.ylabel('Count') plt.savefig('newplotOut.png') #saves the plot to a file plt.close()
true
e012fa17f16a5d4f110465e965809bb358139d9d
Python
JosuePoz/PyGamePrueba
/prueba5.py
UTF-8
1,057
3.125
3
[]
no_license
import pygame, sys, random pygame.init() size = (800, 500) # Crear ventana screen = pygame.display.set_mode(size) #Reloj clock = pygame.time.Clock() #Colores Black = ( 0, 0, 0 ) White = ( 255, 255, 255 ) Red = ( 255, 0, 0 ) Green = ( 0, 255, 0 ) Blue = ( 0, 0, 255 ) Orange = ( 250, 105, 5 ) cor_list = [] for i in range(80): x = random.randint(0,800) y = random.randint(0,500) cor_list.append([x, y]) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(White) #Incio zona de dibujo for cord in cor_list: pygame.draw.circle(screen, Red, cord, 2) if cord[1]<=500: cord[1]+=1 cord[0] += random.randint(-1,1) else: cord[0]=random.randint(0,800) cord[1]=0 #Fin hora de dibujo #Pintar pantalla pygame.display.flip() clock.tick(30)
true
5318542fb281d6a0f2b1d4479714020b318c3f59
Python
Amulya0506/Python_CS5590
/Assignments/Lab Assignment-3/Logistic_Regression.py
UTF-8
4,021
2.96875
3
[]
no_license
import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf iris = pd.read_csv('dataset.csv') iris.Species = iris.Species.replace(to_replace=['Iris-setosa', 'Iris-versicolor'], value=[0, 1]) X = iris.drop(labels=['Id', 'Species'], axis=1).values y = iris.Species.values # set seed for numpy and tensorflow # set for reproducible results seed = 5 np.random.seed(seed) tf.set_random_seed(seed) # dataset segmentation # splitting the dataset as train data and test data train_index = np.random.choice(len(X), round(len(X) * 0.8), replace=False) test_index = np.array(list(set(range(len(X))) - set(train_index))) train_X = X[train_index] train_y = y[train_index] test_X = X[test_index] test_y = y[test_index] # Define the normalized function def min_max_normalized(data): col_max = np.max(data, axis=0) col_min = np.min(data, axis=0) return np.divide(data - col_min, col_max - col_min) # Normalized processing, must be placed after the data set segmentation, # otherwise the test set will be affected by the training set train_X = min_max_normalized(train_X) test_X = min_max_normalized(test_X) # Declare the variables that need to be learned and initialization # Define placeholders X = tf.placeholder(dtype=tf.float32, shape=[None, 4]) y = tf.placeholder(dtype=tf.float32, shape=[None, 1]) # There are 4 features here, weights dimension is (4, 1) weights= tf.Variable(tf.random_normal(shape=[4, 1])) base = tf.Variable(tf.random_normal(shape=[1, 1])) init = tf.global_variables_initializer() # Declare the model you need to learn Y_prdection = tf.add(tf.matmul(X, weights), base) # Declare loss function # Use the sigmoid cross-entropy loss function, # first doing a sigmoid on the model result and then using the cross-entropy loss function loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Y_prdection, labels=y)) # Define the learning rate, batch_size etc. learning_rate = 0.3 batch_size = 50 iter_num = 250 # Define the optimizer opt = tf.train.GradientDescentOptimizer(learning_rate) # Define the goal goal = opt.minimize(loss) # Define the accuracy # The default threshold is 0.5, rounded off directly prediction = tf.round(tf.sigmoid(tf.add(tf.matmul(X, weights) , base))) # Bool into float32 type correct = tf.cast(tf.equal(prediction, y), dtype=tf.float32) # Average accuracy = tf.reduce_mean(correct) # End of the definition of the model framework # Start training model # Define the variable that stores the result loss_trace = [] train_acc = [] test_acc = [] # training model with tf.Session() as sess: # Step 7: initialize the necessary variables, in this case, w and b sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter('./graphs/logistic_reg', sess.graph) for epoch in range(iter_num): # Generate random batch index batch_index = np.random.choice(len(train_X), size=batch_size) batch_train_X = train_X[batch_index] batch_train_y = np.matrix(train_y[batch_index]).T sess.run(goal, feed_dict={X: batch_train_X, y: batch_train_y}) temp_loss = sess.run(loss, feed_dict={X: batch_train_X, y: batch_train_y}) # convert into a matrix, and the shape of the placeholder to correspond temp_train_acc = sess.run(accuracy, feed_dict={X: train_X, y: np.matrix(train_y).T}) temp_test_acc = sess.run(accuracy, feed_dict={X: test_X, y: np.matrix(test_y).T}) # recode the result loss_trace.append(temp_loss) train_acc.append(temp_train_acc) test_acc.append(temp_test_acc) # output print('epoch: {:4d} loss: {:5f} train_acc: {:5f} test_acc: {:5f}'.format(epoch + 1, temp_loss, temp_train_acc, temp_test_acc)) # Visualization of the results # accuracy plt.plot(test_acc, 'k-', label='test accuracy') plt.xlabel('epoch') plt.ylabel('accuracy') plt.title('Train and Test Accuracy') plt.legend(loc='best') plt.show()
true
f5f272c5cc1a9c410e1668fe187fab5e315ed933
Python
adri-romsor/iterative_inference_segm
/models/fcn_resunet_blocks.py
UTF-8
7,175
2.65625
3
[]
no_license
from keras.layers import (Activation, merge, Dropout, Lambda) from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import (Convolution2D, MaxPooling2D, UpSampling2D) from keras.regularizers import l2 from keras import backend as K # Return a new instance of l2 regularizer, or return None def _l2(decay): if decay is not None: return l2(decay) else: return None # Helper to build a BN -> relu -> conv block # This is an improved scheme proposed in http://arxiv.org/pdf/1603.05027v2.pdf def _bn_relu_conv(nb_filter, nb_row, nb_col, subsample=False, upsample=False, batch_norm=True, weight_decay=None): def f(input): processed = input if batch_norm: processed = BatchNormalization(mode=0, axis=1)(processed) processed = Activation('relu')(processed) stride = (1, 1) if subsample: stride = (2, 2) if upsample: processed = UpSampling2D(size=(2, 2))(processed) return Convolution2D(nb_filter=nb_filter, nb_row=nb_row, nb_col=nb_col, subsample=stride, init='he_normal', border_mode='same', W_regularizer=_l2(weight_decay))(processed) return f # Adds a shortcut between input and residual block and merges them with 'sum' def _shortcut(input, residual, subsample, upsample, weight_decay=None): # Expand channels of shortcut to match residual. # Stride appropriately to match residual (width, height) # Should be int if network architecture is correctly configured. equal_channels = residual._keras_shape[1] == input._keras_shape[1] shortcut = input # Downsample input if subsample: def downsample_output_shape(input_shape): output_shape = list(input_shape) output_shape[-2] = None if output_shape[-2]==None \ else output_shape[-2]//2 output_shape[-1] = None if output_shape[-1]==None \ else output_shape[-1]//2 return tuple(output_shape) shortcut = Lambda(lambda x: x[:,:, ::2, ::2], output_shape=downsample_output_shape)(shortcut) # Upsample input if upsample: shortcut = UpSampling2D(size=(2, 2))(shortcut) # Adjust input channels to match residual if not equal_channels: shortcut = Convolution2D(nb_filter=residual._keras_shape[1], nb_row=1, nb_col=1, init='he_normal', border_mode='valid', W_regularizer=_l2(weight_decay))(shortcut) return merge([shortcut, residual], mode='sum') # Bottleneck architecture for > 34 layer resnet. # Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf # Returns a final conv layer of nb_filter * 4 def bottleneck(nb_filter, subsample=False, upsample=False, skip=True, dropout=0., batch_norm=True, weight_decay=None): def f(input): processed = _bn_relu_conv(nb_filter, 1, 1, subsample=subsample, batch_norm=batch_norm, weight_decay=weight_decay)(input) processed = _bn_relu_conv(nb_filter, 3, 3, batch_norm=batch_norm, weight_decay=weight_decay)(processed) processed = _bn_relu_conv(nb_filter * 4, 1, 1, upsample=upsample, batch_norm=batch_norm, weight_decay=weight_decay)(processed) if dropout > 0: processed = Dropout(dropout)(processed) output = processed if skip: output = _shortcut(input, output, subsample=subsample, upsample=upsample, weight_decay=weight_decay) return output return f # Basic 3 X 3 convolution blocks. # Use for resnet with layers <= 34 # Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf def basic_block(nb_filter, subsample=False, upsample=False, skip=True, dropout=0., batch_norm=True, weight_decay=None): def f(input): processed = _bn_relu_conv(nb_filter, 3, 3, subsample=subsample, batch_norm=batch_norm, weight_decay=weight_decay)(input) if dropout > 0: processed = Dropout(dropout)(processed) processed = _bn_relu_conv(nb_filter, 3, 3, upsample=upsample, batch_norm=batch_norm, weight_decay=weight_decay)(processed) output = processed if skip: output = _shortcut(input, processed, subsample=subsample, upsample=upsample, weight_decay=weight_decay) return output return f # Builds a residual block with repeating bottleneck blocks. def residual_block(block_function, nb_filter, repetitions, skip=True, dropout=0., subsample=False, upsample=False, batch_norm=True, weight_decay=None): def f(input): for i in range(repetitions): kwargs = {'nb_filter': nb_filter, 'skip': skip, 'dropout': dropout, 'subsample': False, 'upsample': False, 'batch_norm': batch_norm, 'weight_decay': weight_decay} if i==0: kwargs['subsample'] = subsample if i==repetitions-1: kwargs['upsample'] = upsample input = block_function(**kwargs)(input) return input return f # A single basic 3x3 convolution def basic_block_mp(nb_filter, subsample=False, upsample=False, skip=True, dropout=0., batch_norm=True, weight_decay=None, return_pool=False): def f(input): processed = input if batch_norm: processed = BatchNormalization(mode=0, axis=1)(processed) processed = Activation('relu')(processed) if subsample: processed = MaxPooling2D(pool_size=(2,2))(processed) if return_pool: output_pool = processed processed = Convolution2D(nb_filter=nb_filter, nb_row=3, nb_col=3, init='he_normal', border_mode='same', W_regularizer=_l2(weight_decay))(processed) if dropout > 0: processed = Dropout(dropout)(processed) if upsample: processed = UpSampling2D(size=(2, 2))(processed) output = processed if skip: output = _shortcut(input, processed, weight_decay=weight_decay, subsample=subsample, upsample=upsample) if subsample and return_pool: return output, output_pool return output return f
true
49eb2924a4cd6751e242e7f2dbb40673b9504410
Python
BigBlackBug/csi_task
/test.py
UTF-8
1,327
2.546875
3
[]
no_license
import os import pickle from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop import constants from predictor import predictor from predictor.routes import routes from web import app class MainTestCase(AioHTTPTestCase): async def get_application(self): return app.init(routes=routes, loop=self.loop) def get_classifier(self): return pickle.load( open(os.path.join(constants.BASE_DIR, 'test_data', 'test_classifier.pickle'), 'rb')) @unittest_run_loop async def test_classifier_empty_vector(self): with self.assertRaises(ValueError): await predictor.predict([], classifier=self.get_classifier()) @unittest_run_loop async def test_classifier_none_classifier(self): with self.assertRaises(ValueError): await predictor.predict([1, 2, 3, 4], classifier=None) @unittest_run_loop async def test_classifier_no_error(self): """ I know that's a genius test, but there's nothing else we can test here. I can't test the outcomes of the method """ try: await predictor.predict([ 5.1, 3.5, 1.4, 0.2 ], classifier=self.get_classifier()) except Exception: self.fail("predictor threw an error")
true
84ba9ddb4d6b54e48006846d41f095dba1f17838
Python
kazi0/random
/random.py
UTF-8
521
4.40625
4
[]
no_license
import random print("Welcome to the Number gussing game!!") number = random.randint(1, 9) chance = 0 print("Guess a number from 1 to 9") while chance < 5: guess = int(input("Enter your guess:- ")) if(guess == number): print("You did find the number!!!") break elif(guess < number): print("Nah! It is higher number than this") else: print("Nope! It is lower number than this") chance += 1 if not(chance < 5): print("Nope")
true
d1558b9588c0892a229a78fd2c95d27d1793464e
Python
soaibsafi/project-euler-python
/023.py
UTF-8
1,992
4.0625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 16:20:15 2020 @author: Soaib """ """" Problem: A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ from math import sqrt # Get all the divisor using prime factorization def getAllDivisor(n): divisor = [1] for i in range(2,int(sqrt(n))+1): if n%i == 0: divisor.extend([i,n/i]) return list(set(divisor)) # List to store all the abandant numbers abandantNumbers = list() # Generating all the abandant numbers for i in range(12,28123): if sum(getAllDivisor(i))>i: abandantNumbers.append(i) # Let us assume all the numbers are not sum_of_abandant_numbers nonAbandantSum = [x for x in range(28123)] # Generatiing sum of two abandant numbers for i in range(len(abandantNumbers)): for j in range(i, 28123): if abandantNumbers[i] + abandantNumbers[j] < 28123: # neglecting the value which can ba written as sum of two abandant numbers nonAbandantSum[abandantNumbers[i]+abandantNumbers[j]] = 0 else: break print(sum(nonAbandantSum))
true
6e6e253afa849dd314f277a7b9dad6e4db070fba
Python
fcdmoraes/aulas_FitPart
/aula9.py
UTF-8
1,989
3.640625
4
[]
no_license
class Cavalo(object): numero = 0 def __init__(self, npatas, cor, peso): self.npatas = npatas self.cor = cor self.peso = peso # print(self) Cavalo.numero += 1 def engorda(self, dieta): print("peso antigo:", self.peso) self.peso += dieta print("peso atual:", self.peso) def __repr__(self): return "cor: {}, peso: {}".format(self.cor, self.peso) # print('numero:', Cavalo.numero) # pocoto = Cavalo(4, 'marrom', 800) # pedepano = Cavalo(4, 'branco', 850) # print('numero:', Cavalo.numero) # print(pocoto.cor) # print(pedepano.cor) # print(pocoto) # print(pedepano) # pocoto.engorda(30) # pedepano.engorda(20) # Cavalo.engorda(pedepano, 20) # pocoto.crina = 'cinza' # print(pocoto.crina) # # print(pedepano.crina) # # print(dir(pocoto)) # print(pocoto) # print(pedepano) # print(dir(Cavalo)) class Funcionario(object): numero = 0 lista = [] def __init__(self, nome, salario, idade, registro): self.nome = nome self.salario = salario self.idade = idade self.id = registro Funcionario.numero += 1 Funcionario.lista.append(self) def __repr__(self): # return "{},{},{}".format(self.nome, self.idade, self.salario) return self.nome def busca_id(registro): for objeto in Funcionario.lista: if objeto.id == registro: return objeto def busca_nome(nome): for objeto in Funcionario.lista: if objeto.nome == nome: return objeto def aumento(nome = None, registro = None, bonus = 0): if nome != None: objeto = Funcionario.busca_nome(nome) else: objeto = Funcionario.busca_id(registro) objeto.salario += bonus if __name__ == '__main__': Funcionario('Osmar', 1500, 19, 0) Funcionario('Carlos', 2200, 21, 1) Funcionario('Beatriz', 2500, 20, 2) print(Funcionario.lista) f2 = Funcionario.busca_id(2) print(f2.salario) Funcionario.aumento(nome = 'Osmar', bonus = 200) osmar = Funcionario.busca_nome('Osmar') print(osmar.salario)
true
38af4389fb481fe8cf9f9afb3c981f57fac9a92a
Python
Panda4817/Advent-of-Code-2018
/24.py
UTF-8
11,563
3.0625
3
[]
no_license
from copy import deepcopy from math import floor class Group: def __init__( self, id, amount, hit_points, attack_damage, attack_type, initiative, weaknesses=[], immunities=[], ): self.id = id self.amount = amount self.hp = hit_points self.attack_damage = attack_damage self.attack_type = attack_type self.initiative = initiative self.weaknesses = [i for i in weaknesses] self.immunities = [i for i in immunities] self.effective_power = self.amount * self.attack_damage self.been_selected = False self.selected_enemy = 0 def __str__(self) -> str: return f"""Group({self.id})units:{self.amount},hp:{self.hp},attack:{self.attack_damage},type:{self.attack_type},power:{self.effective_power},initiative:{self.initiative},weaknesses:{self.weaknesses},immunities:{self.immunities},fight:{self.been_selected},{self.selected_enemy}""" class Simulator: def __init__(self, data, boost): self.immune_system, self.infection = self.process_data(data, boost) # self.print_armies() def print_armies(self, immune=True, infection=True): if immune: for i in self.immune_system: if i.amount > 0: print(i) if infection: for j in self.infection: if j.amount > 0: print(j) def process_data(self, data, boost): # need to process data armies = data.split("\n\n") immune_system = armies[0].split("\n")[1:] infection = armies[1].split("\n")[1:] army1 = [] army2 = [] id = 1 for string in immune_system: extra_info = string.split(" (") if len(extra_info) == 2: first_part = extra_info[0].split() sections = extra_info[1].split(") ") middle_part = sections[0].split() words = ["weak", "immune"] weaknesses = [] immunities = [] current = None for w in middle_part: if w in words: current = w continue if w == "to": continue parts = w.split(",") parts = parts[0].split(";") if current == "weak": weaknesses.append(parts[0]) elif current == "immune": immunities.append(parts[0]) last_part = sections[1].split() units = int(first_part[0]) hp = int(first_part[4]) attack = int(last_part[5]) + boost attack_type = last_part[6] initiative = int(last_part[-1]) army1.append( Group( id, units, hp, attack, attack_type, initiative, weaknesses, immunities, ) ) else: parts = extra_info[0].split() units = int(parts[0]) hp = int(parts[4]) attack = int(parts[12]) + boost attack_type = parts[13] initiative = int(parts[-1]) army1.append(Group(id, units, hp, attack, attack_type, initiative)) id += 1 for string in infection: extra_info = string.split(" (") if len(extra_info) == 2: first_part = extra_info[0].split() sections = extra_info[1].split(") ") middle_part = sections[0].split() words = ["weak", "immune"] weaknesses = [] immunities = [] current = None for w in middle_part: if w in words: current = w continue if w == "to": continue parts = w.split(",") parts = parts[0].split(";") if current == "weak": weaknesses.append(parts[0]) elif current == "immune": immunities.append(parts[0]) last_part = sections[1].split() units = int(first_part[0]) hp = int(first_part[4]) attack = int(last_part[5]) attack_type = last_part[6] initiative = int(last_part[-1]) army2.append( Group( id, units, hp, attack, attack_type, initiative, weaknesses, immunities, ) ) else: parts = extra_info[0].split() units = int(parts[0]) hp = int(parts[4]) attack = int(parts[12]) attack_type = parts[13] initiative = int(parts[-1]) army2.append(Group(id, units, hp, attack, attack_type, initiative)) id += 1 return army1, army2 def target_selection(self): # target selection # order each army by effective power # then order by initiative power # print("________immune system sort__________") self.immune_system.sort(key=lambda x: x.initiative, reverse=True) self.immune_system.sort(key=lambda x: x.effective_power, reverse=True) # self.print_armies(True, False) # print("________infection sort__________") self.infection.sort(key=lambda x: x.initiative, reverse=True) self.infection.sort(key=lambda x: x.effective_power, reverse=True) # self.print_armies(False, True) # each group chooses enemy target # choose the target which will deal the most damage, accounting for weakness and immunities # if tie, order targets by largest effective power, then highest initiative, # no target is allowed if group cannot deal damage for group in self.immune_system: if group.amount <= 0: continue most_damage = 0 chosen_id = 0 for enemy in self.infection: if enemy.amount <= 0 or enemy.been_selected: continue attack = 0 if group.attack_type in enemy.immunities: attack = 0 elif group.attack_type in enemy.weaknesses: attack = group.effective_power * 2 else: attack = group.effective_power if attack > most_damage: most_damage = attack chosen_id = enemy.id group.selected_enemy = chosen_id if chosen_id > 0: for enemy in self.infection: if enemy.id == chosen_id: enemy.been_selected = True break for group in self.infection: if group.amount <= 0: continue most_damage = 0 chosen_id = 0 for enemy in self.immune_system: if enemy.amount <= 0 or enemy.been_selected: continue attack = 0 if group.attack_type in enemy.immunities: attack = 0 elif group.attack_type in enemy.weaknesses: attack = group.effective_power * 2 else: attack = group.effective_power if attack > most_damage: most_damage = attack chosen_id = enemy.id group.selected_enemy = chosen_id group.damage_to_inflict = most_damage if chosen_id > 0: for enemy in self.immune_system: if enemy.id == chosen_id: enemy.been_selected = True break # print("__________________after target selection_________________") # self.print_armies() def attack(self): # order groups by initiatives higher to lower all_groups = [] for group in self.immune_system: all_groups.append(group) for group in self.infection: all_groups.append(group) units_killed_this_round = 0 all_groups.sort(key=lambda x: x.initiative, reverse=True) # print("__________________before attack_________________") for group in all_groups: # print(group) if group.selected_enemy == 0: continue for enemy in all_groups: if enemy.id != group.selected_enemy: continue damage_to_inflict = group.effective_power if group.attack_type in enemy.weaknesses: damage_to_inflict = group.effective_power * 2 units_killed = floor(damage_to_inflict / enemy.hp) units_killed_this_round += units_killed if units_killed > enemy.amount: enemy.amount = 0 else: enemy.amount -= units_killed enemy.effective_power = enemy.amount * enemy.attack_damage if enemy.effective_power == 0: enemy.initiative = 0 enemy.been_selected = False break group.selected_enemy = 0 # print("___________________after attack_________________") # self.print_armies() return units_killed_this_round def end_war(self): number_of_immune_system = 0 number_of_infection = 0 for i in self.immune_system: if i.amount > 0: number_of_immune_system += 1 for i in self.infection: if i.amount > 0: number_of_infection += 1 if number_of_immune_system and number_of_infection > 0: return False else: return True def fight(self): while not self.end_war(): # select targets self.target_selection() # attacking units_killed = self.attack() if units_killed == 0: break def winning_units(self): total_units = 0 for i in self.immune_system: if i.amount > 0: total_units += i.amount if total_units > 0: winner = "immune system" for i in self.infection: if i.amount > 0: total_units += i.amount winner = "infection" return total_units, winner def part1(data): war = Simulator(data, 0) war.fight() return war.winning_units() def part2(data): boost = 0 while True: boost += 1 war = Simulator(data, boost) war.fight() units_left, winner = war.winning_units() if winner == "immune system": break return units_left, boost, winner
true
4e9e9a151287159092d645752a07205f5be9076e
Python
SR2k/leetcode
/first-round/536.从字符串生成二叉树.py
UTF-8
2,060
3.46875
3
[]
no_license
# # @lc app=leetcode.cn id=536 lang=python3 # # [536] 从字符串生成二叉树 # # https://leetcode-cn.com/problems/construct-binary-tree-from-string/description/ # # algorithms # Medium (53.68%) # Likes: 61 # Dislikes: 0 # Total Accepted: 2.7K # Total Submissions: 5K # Testcase Example: '"4(2(3)(1))(6(5))"' # # 你需要从一个包括括号和整数的字符串构建一棵二叉树。 # # 输入的字符串代表一棵二叉树。它包括整数和随后的 0 ,1 或 2 对括号。整数代表根的值,一对括号内表示同样结构的子树。 # # 若存在左子结点,则从左子结点开始构建。 # # # # 示例: # # 输入:"4(2(3)(1))(6(5))" # 输出:返回代表下列二叉树的根节点: # # ⁠ 4 # ⁠ / \ # ⁠ 2 6 # ⁠ / \ / # ⁠ 3 1 5 # # # # # 提示: # # # 输入字符串中只包含 '(', ')', '-' 和 '0' ~ '9'  # 空树由 "" 而非"()"表示。 # # # # # # Definition for a binary tree node. class TreeNode: def __init__(self, val = 0, left: 'TreeNode' = None, right: 'TreeNode' = None): self.val = val self.left = left self.right = right # @lc code=start from typing import Optional class Solution: def str2tree(self, s: str) -> Optional[TreeNode]: if not s: return None stack: list[TreeNode] = [] i, buffer = 0, '' while i < len(s): char = s[i] if char.isdigit() or char == '-': buffer += char elif buffer: node = TreeNode(int(buffer)) if stack: prev = stack[-1] if prev.left: prev.right = node else: prev.left = node stack.append(node) buffer = '' if char == ')': stack.pop() i += 1 if buffer: return TreeNode(int(buffer)) return stack[0] if stack else None # @lc code=end
true
e5dff5217f52d3350574152a9d6a53e5cf9f8b29
Python
mavharsha/Learn-Python-The-Hard-Way
/ex3.py
UTF-8
392
4.0625
4
[]
no_license
print "I will now count my chickens:" print "Hens", 25 +30/6 print "Roosters", 100 - 25 *3 %4 print "Now I will count the eggs:" print 3+2+1-5+4%2-1/4+6 print "Is it true that 3+2 < 5-7 ? ", 3+2 < 5-7 print "What is 3+2", 3+2 print "What is 5-7", 5-7 print "How about some more." print "Is it greater?", 5>-2 print "Is it greater or equal", 5>=-2 print "Is it less or equal?", 5<=-2
true
d4b463a892fa2b68371dcbc766470263d795dba4
Python
Success2014/Leetcode
/anagrams_2.py
UTF-8
612
3.40625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Aug 01 16:30:11 2015 @author: Neo """ class Solution: # @param {string[]} strs # @return {string[]} def anagrams(self, strs): res = [] d = {} for word in strs: word_st = ''.join(sorted(word)) if word_st in d: d[word_st].append(word) else: d[word_st] = [word] for idx, val in d.items(): if len(val) > 1: res += val return res sol = Solution() strs = ["",""] print sol.anagrams(strs)
true
29559ebae1ab5672ccbe06a3fa4e84f04e97b968
Python
shomin/dynopt_hw4
/python/ros_drc_wrapper/src/process.py
UTF-8
2,573
2.953125
3
[]
no_license
#!/usr/bin/python import os import signal from subprocess import Popen, PIPE import time import threading import Queue class Process(object): def __init__(self, cmd, stdin=False, stdout=False, stderr=False): self._stdin = self._stderr = self._stdout = None if stdin: stdin=PIPE self._stdin = Queue.Queue(0) if stdout: stdout=PIPE self._stdout = Queue.Queue(0) if stderr: stderr=PIPE self._stderr = Queue.Queue(0) self._proc = Popen(cmd, shell=False, stdin=stdin, stdout=stdout, stderr=stderr) self.threading = True threading.Thread(target=self._inThread).start() threading.Thread(target=self._outThread).start() threading.Thread(target=self._errThread).start() self.pid = self._proc.pid def kill(self): os.kill(self.pid, signal.SIGTERM) self.wait() def wait(self): self._proc.wait() self.threading = False def write(self, msg): if self._stdin: self._stdin.put(msg) def empty(self, device): if device == 'stdout' and self._stdout: return self._stdout.empty() elif device == 'stderr' and self._stderr: return self._stderr.empty() def readline(self, device, block=True, timeout=None): if device == 'stdout' and self._stdout: try: return self._stdout.get(block=block, timeout=timeout) except Queue.Empty: return None elif device == 'stderr' and self._stderr: try: return self._stderr.get(block=block, timeout=timeout) except Queue.Empty: return None def _inThread(self): while self.threading and self._stdin != None: if not self._stdin.empty(): self._proc.stdin.write(self._stdin.get()+'\n') def _outThread(self): while self.threading and self._stdout != None: data = self._proc.stdout.readline()#.strip() if data != '': self._stdout.put(data) def _errThread(self): while self.threading and self._stderr != None: data = self._proc.stderr.readline()#.strip() if data != '': self._stderr.put(data) if __name__=='__main__': proc = Process('python stressTest2.py', stdout=True) proc.wait() while not proc.empty('stdout'): print proc.readline('stdout', block=True)
true
5b9fa6589f3a9d92a8c74af08a0f715b89f9b9c1
Python
gcpreston/aoc-2020
/day15.py
UTF-8
1,376
3.796875
4
[]
no_license
from typing import Optional, List with open('input/day15.txt') as f: starting_nums = [int(n) for n in f.read().strip().split(',')] def last_time_spoken(nums: List[int], n: int) -> Optional[int]: """ Figure out the last time n appeared in nums. """ i = len(nums) - 1 for checking in reversed(nums): if checking == n: return i + 1 i -= 1 def next_num(prev_nums: List[int]) -> int: last = prev_nums[-1] t0 = last_time_spoken(prev_nums[:-1], last) if not t0: return 0 t1 = len(prev_nums) return t1 - t0 def turn_val(starting_nums: List[int], end_turn: int) -> int: turn = len(starting_nums) + 1 mem = starting_nums.copy() while turn <= end_turn: mem.append(next_num(mem)) turn += 1 return mem[-1] def turn_val_v2(starting_nums: List[int], end_turn: int) -> int: turn = len(starting_nums) + 1 last_val = 0 turn_last_seen = dict() seen = set(starting_nums) for i in range(len(starting_nums)): turn_last_seen[starting_nums[i]] = i + 1 while turn < end_turn: if last_val not in seen: next_val = 0 else: next_val = turn - turn_last_seen[last_val] seen.add(last_val) turn_last_seen[last_val] = turn last_val = next_val turn += 1 return next_val print('Part 1:', turn_val_v2(starting_nums, 2020)) print('Part 2:', turn_val_v2(starting_nums, 30000000))
true
52e2e64331f8f3c1db6ba9cc2ccf4bdef5ab238a
Python
poojasgada/HackProj
/visualizeds/BinarySearchTree/BinarySearchTreePy.py
UTF-8
1,926
4.34375
4
[]
no_license
''' Binary Search Tree Library in Python Binary Search Tree functions supported - Search for val - Print: Preorder, Postorder, Inorder - Insert - Delete - IsBST - Size - Minimum value - Maximum value ''' class Node: def __init__(self, val): self.val = val self.left = None self.right = None #BST = Binary Search Tree (Using BST henceforth to preserve my typing sanity) class BST: def __init__(self): self.root = None # Given a value, search if it is found in the BST def searchBST(self, curNode, searchVal): if not curNode: return False if curNode.val == searchVal: return True if curNode.val < searchVal: return self.searchBST(curNode.right, searchVal) else: return self.searchBST(curNode.left, searchVal) # Just print the BST in pre-order traversal def printPreorderBST(self, curNode): if curNode: print curNode.val, self.printPreorderBST(curNode.left) self.printPreorderBST(curNode.right) # Just print the BST in in-order traversal def printInorderBST(self, curNode): if curNode: self.printInorderBST(curNode.left) print curNode.val, self.printInorderBST(curNode.right) # Just print the BST in post-order traversal def printPostorderBST(self, curNode): if curNode: self.printPostorderBST(curNode.left) self.printPostorderBST(curNode.right) print curNode.val, # Get the size of a BST i-e the number of nodes in a BST def sizeBST(self, curNode): if not curNode: return 0 else: return 1 + self.sizeBST(curNode.left) + self.sizeBST(curNode.right) # Get the minimum value of BST def minValBST(self, curNode): if not curNode: return curNode if curNode.left: return self.minValBST(curNode.left) else: return curNode.val # Get the maximum value of BST def maxValBST(self, curNode): if not curNode: return curNode if curNode.right: return self.maxValBST(curNode.right) else: return curNode.val
true
4bef8c24fefd36e272819f8bb0cf6df40ddc6670
Python
phc260/leetcode
/Python/merge-intervals.py
UTF-8
678
3.3125
3
[]
no_license
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): intervals.sort(key = lambda x:x.start) ans = [] for i in intervals: if ans: n = len(ans) if ans[n-1].start<=i.start<=ans[n-1].end: ans[n-1].end = max(ans[n-1].end, i.end) else: ans.append(i) else: ans.append(i) return ans
true
63ab59a533b94846a123a75c8bedb2bc46ae7af9
Python
misaka-10032/leetcode
/coding/00231-power-of-two/solution.py
UTF-8
327
2.59375
3
[]
no_license
# encoding: utf-8 """ Created by misaka-10032 (longqic@andrew.cmu.edu). TODO: purpose """ class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ p = 1 while p <= n: if p == n: return True p <<= 1 return False
true
69ade7d45d014e2819a77ba6ccee2d699290dc75
Python
adas-eye/RosADAS
/src/lanedet/Ultra-Fast-Lane-Detection/lane_tracker.py
UTF-8
2,739
2.671875
3
[ "MIT" ]
permissive
import numpy as np from lane_obj import Lane import configs.testconfig CFG = configs.testconfig.cfg class LaneTracker: def __init__(self): self.leftlane = Lane('left') self.rightlane = Lane('right') self.detectedLeftLane = np.zeros([12,2], dtype = int) self.detectedRightLane = np.zeros([12,2], dtype = int) pass def process(self, detectedLanes): self.detectedLeftLane = np.zeros([12,2], dtype = int) self.detectedRightLane = np.zeros([12,2], dtype = int) # find candidate left right lane # sort in ascending order by the distance between x coordinate of 10th point of the lane and 1/2 image width detectedLanes.sort(key=(lambda x : abs(x[10][0] - CFG.imgWidth/2))) if len(detectedLanes) > 1: # sort first two lane sortedDetectedLane = sorted(detectedLanes[:2], key=(lambda x : x[5][0])) # self.detectedLeftLane = sortedDetectedLane[0] # self.detectedRightLane = sortedDetectedLane[1] dist = np.linalg.norm(sortedDetectedLane[0] - sortedDetectedLane[1]) print('left right detected dist:', dist) if dist < CFG.DETECTED_DIFF_THRESH: if sortedDetectedLane[0][5][0] < CFG.IMAGE_WIDTH/2: self.detectedLeftLane = sortedDetectedLane[0] else: self.detectedRightLane = sortedDetectedLane[0] else: self.detectedLeftLane = sortedDetectedLane[0] self.detectedRightLane = sortedDetectedLane[1] elif len(detectedLanes) > 0: # (detectedLeftLane = detectedLanes[0].copy()) if detectedLanes[0][0] < CFG.IMAGE_WIDTH/2 else (detectedRightLane = detectedLanes[0].copy()) if detectedLanes[0][5][0] < CFG.imgWidth/2: self.detectedLeftLane = detectedLanes[0].copy() else: self.detectedRightLane = detectedLanes[0].copy() self.leftlane.updateDetectedLane(self.detectedLeftLane) self.rightlane.updateDetectedLane(self.detectedRightLane) if not self.leftlane.isInit: self.leftlane.init() if not self.rightlane.isInit: self.rightlane.init() self.leftlane.updateLanev2() self.rightlane.updateLanev2() dist = np.linalg.norm(self.leftlane.points - self.rightlane.points) print('left right lane dist:', dist) if dist < CFG.DETECTED_DIFF_THRESH: if self.leftlane.age > self.rightlane.age: self.rightlane.reset() else: self.leftlane.reset() # self.leftlane.init() # self.rightlane.init()
true
95338952c7b73794be637ead6058c1f472bfc92a
Python
adafruit/circuitpython
/tests/basics/string_fstring.py
UTF-8
1,318
3.640625
4
[ "MIT", "GPL-1.0-or-later" ]
permissive
def f(): return 4 def g(_): return 5 def h(): return 6 print(f'no interpolation') print(f"no interpolation") print(f"""no interpolation""") x, y = 1, 2 print(f'{x}') print(f'{x:08x}') print(f'a {x} b {y} c') print(f'a {x:08x} b {y} c') print(f'a {"hello"} b') print(f'a {f() + g("foo") + h()} b') def foo(a, b): return f'{x}{y}{a}{b}' print(foo(7, 8)) # ':' character within {...} that should not be interpreted as format specifiers. print(f"a{[0,1,2][0:2]}") print(f"a{[0,15,2][0:2][-1]:04x}") # Nested '{' and '}' characters. print(f"a{ {0,1,2}}") # PEP-0498 specifies that '\\' and '#' must be disallowed explicitly, whereas # MicroPython relies on the syntax error as a result of the substitution. print(f"\\") print(f'#') try: eval("f'{\}'") except SyntaxError: print('SyntaxError') try: eval("f'{#}'") except SyntaxError: print('SyntaxError') # PEP-0498 specifies that handling of double braces '{{' or '}}' should # behave like str.format. print(f'{{}}') print(f'{{{4*10}}}', '{40}') # A single closing brace, unlike str.format should raise a syntax error. # MicroPython instead raises ValueError at runtime from the substitution. try: eval("f'{{}'") except (ValueError, SyntaxError): # MicroPython incorrectly raises ValueError here. print('SyntaxError')
true
7cd67c76c28bb9e52d5431ab13993574ac0d43ba
Python
Lyly81/InstaIRobotLinks
/getLinks.py
UTF-8
2,466
2.546875
3
[]
no_license
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By import time import random from datetime import date import database import scroll import popupFollowers """ This class is for get followers'links on the profile account. """ class GetLinks(): def __init__(self, driver): self.driver = driver self.sql_links = """ SELECT * FROM links """ self.sql_insert_link = """ INSERT INTO links (link, created_at) VALUES (%s, %s) """ """This method is for get the links of instagram account when the database is not empty. """ def getLinksFollowers(self): # Get links in database connDB = database.Database() sqll = connDB.queryFetchall(self.sql_links) data_links = list(sqll) # Put the link in list for compare list_link = [] # Get all links of database and put in the list for y in data_links: list_link.append(y[1]) for linky in data_links: # Select public account if linky[3] == 'Public': # Select link for open page web try: self.driver.get(linky[1]) except: continue time.sleep(random.uniform(2, 10)) try: # Select followers' button popupFollows = popupFollowers.PopupFollowers(self.driver) popupFollows.btnFollowers() except: err = self.driver.find_elements_by_xpath('/html/body/div/div[1]/div/div/p').text if err == 'Veuillez patienter quelques minutes avant de réessayer.': time.sleep(random.uniform(300, 600)) # Execute scroll on the followers' popup try: scrolly = scroll.Scroll(self.driver) scrolly.scrolling(70) except: continue try: a = self.driver.find_elements_by_xpath('.//div[@role="dialog"]//a[@style="width: 30px; height: 30px;"]') except: a = self.driver.find_elements_by_xpath('.//div[@role="dialog"]//a') for l in a: try: link = l.get_attribute('href') except: pass # time.sleep(random.uniform(3, 10)) if link not in list_link: data_links.append(link) # Prepare request link_dict = (link, date.today()) # Request for insert new link reqAddLink = database.Database() reqAddLink.queryInsert(self.sql_insert_link, link_dict) else: continue else: continue self.getLinksFollowers()
true
ce14a0159d8158afb44b4fd4f61dd58a34c3494c
Python
marcelogarro/challenges
/Algorithms/merge_sort.py
UTF-8
697
3.71875
4
[ "ISC", "BSD-2-Clause" ]
permissive
import unittest def merge_sort(array): if len(array) < 2: return array pivot = round(len(array)/2) left = array[:pivot] right = array[pivot:] return merge(merge_sort(left), merge_sort(right)) def merge(left, right): result = [] while left and right: if left[0] > right[0]: result.append(right.pop(0)) else: result.append(left.pop(0)) print(result + left + right) return result + left + right class TestList(unittest.TestCase): def test_right(self): self.assertEqual(merge_sort([5, 4, 3, 7, 2, 1, 10, 9, 6, 8]),[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) if __name__ == '__main__': unittest.main()
true
97b3e3660f20efa9910721c1f8ea6e3be500dfc7
Python
AdamYF/Learning-Pygame-Coding
/Chapter 7/chapter basic knowledge.py
UTF-8
1,388
3.421875
3
[]
no_license
import pygame # 使用pygame.sprite模块(主要是其中的Sprite类)对位图实现动画 # Sprite精灵包含一幅图像image和一个位置rect # 我们必须使用自己的类来扩展,从而提供一个功能完备的游戏精灵类 # 精灵序列图,包含了“贴图”或“帧”组成的行和列 # 其中的每一个都是动画序列的一帧 # 行和列的标签都是从0开始的 # 精灵族会自动调用update()方法,类似于调用draw()方法 # 我们可以自己编写独有的update()方法,但是draw()方法不会被取代 # 它向上传递到了父方法pygame.sprite.Sprite.draw() # 我们要确保的是pygame.sprite.Sprite的image属性包含的是当前帧而不是整个精灵序列图 # 由于其工作方式,精灵序列图将会作为一个独立的类变量加载,而不是直接加载到Sprite.image中 # 使用精灵组来管理精灵的更新和绘制 group = pygame.sprite.Group() group.add(sprite) # 创建组之后,可以向组容器中添加任意多个精灵以便更容易地管理,同时也减少了对全局变量的使用 # 之后,将完全使用组而不是单个的精灵来操作 # 实际情况是,并不是在一个组中包含所有的游戏精灵,而是针对每种精灵创建多个组 # 这允许了定制精灵的行为,并将其应用于精灵自己的组容器对象所管理的特定精灵类型
true
23c58744fd4f0bca4f247437f85cd4205de4b60b
Python
Mi-Przystupa/NormalizingFlowsNMT
/araNorm.py
UTF-8
4,687
3.609375
4
[ "MIT" ]
permissive
# encoding: utf-8 '''-------------------------------------------------------------------------------- Script: Normalization class Authors: Abdel-Rahim Elmadany and Muhammad Abdul-Mageed Creation date: Novamber, 2018 Last update: Jan, 2019 input: text output: normalized text ------------------------------------------------------------------------------------ Normalization functions: - Check if text contains at least one Arabic Letter, run normalizer - Normalize Alef and Yeh forms - Remove Tashkeeel (diac) from Atabic text - Reduce character repitation of > 2 characters at time - repalce links with space - Remove twitter username with the word USER - replace number with NUM - Remove non letters or digits characters such as emoticons ------------------------------------------------------------------------------------''' import sys import re #reload(sys) # Reload does the trick! #sys.setdefaultencoding('UTF8') class araNorm(): ''' araNorm is a normalizer class for n Arabic Text ''' def __init__(self): ''' List of normalized characters ''' self.normalize_chars= {u"\u0622":u"\u0627", u"\u0623":u"\u0627", u"\u0625":u"\u0627", # All Araf forms to Alaf without hamza u"\u0649":u"\u064A", #ALEF MAKSURA to YAH u"\u0629":u"\u0647" #TEH MARBUTA to HAH } ''' list of diac unicode and underscore ''' self.Tashkeel_underscore_chars= {u"\u0640":"_", u"\u064E":'a', u"\u064F":'u',u"\u0650":'i',u"\u0651":'~', u"\u0652":'o', u"\u064B":'F', u"\u064C":'N', u"\u064D":'K'} def normalizeChar(self, inputText): ''' step #2: Normalize Alef and Yeh forms ''' norm="" for char in inputText: if char in self.normalize_chars: norm = norm + self.normalize_chars[char] else: norm = norm + char return norm def remover_tashkeel(self,inputText): ''' step #3: Remove Tashkeeel (diac) from Atabic text ''' text_without_Tashkeel="" for char in inputText: if char not in self.Tashkeel_underscore_chars: text_without_Tashkeel += char return text_without_Tashkeel def reduce_characters(self, inputText): ''' step #4: Reduce character repitation of > 2 characters at time For example: the word 'cooooool' will convert to 'cool' ''' # pattern to look for three or more repetitions of any character, including # newlines. pattern = re.compile(r"(.)\1{2,}", re.DOTALL) reduced_text = pattern.sub(r"\1\1", inputText) return reduced_text def replace_links(self, inputText): ''' step #5: repalce links to LINK For example: http://too.gl/sadsad322 will replaced to LINK ''' text = re.sub('(\w+:\/\/[ ]*\S+)','+++++++++',inputText) #LINK text = re.sub('\++','URL',text) return re.sub('(URL\s*)+',' URL ',text) def replace_username(self, inputText): ''' step #5: Remove twitter username with the word USER For example: @elmadany will replaced by space ''' text = re.sub('(@[a-zA-Z0-9_]+)','USER',inputText) return re.sub('(USER\s*)+',' USER ',text) def replace_Number(self, inputText): ''' step #7: replace number with NUM For example: \d+ will replaced with NUM ''' text = re.sub('[\d\.]+','NUM',inputText) return re.sub('(NUM\s*)+',' NUM ',text) def remove_nonLetters_Digits(self, inputText): ''' step #8: Remove non letters or digits characters For example: emoticons...etc this step is very important for w2v and similar models; and dictionary ''' p1 = re.compile('[\W_\d\s]', re.IGNORECASE | re.UNICODE)#re.compile('\p{Arabic}') sent = re.sub(p1, ' ', inputText) p1 = re.compile('\s+') sent = re.sub(p1, ' ', sent) return sent def run(self, text): normtext="" text=self.normalizeChar(text) text=self.remover_tashkeel(text) text=self.reduce_characters(text) #text=self.replace_links(text) #text=self.replace_username(text) #text=self.replace_Number(text) #text=self.remove_nonLetters_Digits(text) text = re.sub('\s+',' ', text.strip()) text = re.sub('\s+$','', text.strip()) normtext = re.sub('^\s+','', text.strip()) return normtext ############################################################### ''' Please comment below lines if used it in your package This is ONLY an example of how to use ''' if __name__ == "__main__": norm = araNorm() Fwriter=open("test.norm",'w') # We used with open to reduce memory usage (as readline function) with open("test.txt",'r') as Fread: for line in Fread: cleaned_line=norm.run(line.decode('utf-8')) Fwriter.write(cleaned_line+"\n") Fwriter.close()
true
5f6f6f973514478a12e0f85391ccdcfc6592163f
Python
BenLHedgepeth/django_user_profile
/accounts/validate.py
UTF-8
1,342
3.109375
3
[]
no_license
import re from string import punctuation from django.core.exceptions import ValidationError def validate_bio(value): if len(value) < 10: raise ValidationError("Add more detail to your bio.") def validate_date(value): pattern = r'(\d{2}/d{2}/d{4})|(\d{4}-\d{2}-\d{2})|(\d{2}/d{2}/d{2})' result = re.match(pattern, str(value)) if not result: msg = "Invalid date format: MM/DD/YY; MM/DD/YYYY; YYYY-MM-DD" raise ValidationError(msg) class ValidatePasswordCharacters: def validate(self, password, user=None): password_error_msg = 'Your password must include:' regex1 = (r'\d+', ' at least one digit [0-9]') regex2 = (r'[A-Z]+', ' at least one uppercase letter [A-Z]') regex3 = (r'[a-z]+', ' at least one lowercase letter [a-z]') regex4 = (r'\W+', ' at least one special character [{punctuation}]') for pattern in (regex1, regex2, regex3, regex4): regex = re.compile(pattern[0]) result = re.search(regex, password) if not result: raise ValidationError(f'{password_error_msg}{pattern[1]}') continue return None def get_help_text(self): return """A password must at least one digit, one uppercase letter, one lowercase letter, and one special character"""
true
7c1c8527265cf308360b1256d906b3e76dcc6236
Python
uchicago-sg/caravel
/vendor/dominate/util.py
UTF-8
3,923
2.71875
3
[ "MIT" ]
permissive
''' Utility classes for creating dynamic html documents ''' __license__ = ''' This file is part of Dominate. Dominate is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dominate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Dominate. If not, see <http://www.gnu.org/licenses/>. ''' import re from .dom_tag import dom_tag try: basestring = basestring except NameError: basestring = str unichr = chr def include(f): ''' includes the contents of a file on disk. takes a filename ''' fl = open(f, 'r') data = fl.read() fl.close() return raw(data) def system(cmd, data=None): ''' pipes the output of a program ''' import subprocess s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = s.communicate(data) return out.decode('utf8') def escape(data, quote=True): # stoled from std lib cgi ''' Escapes special characters into their html entities Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. This is used to escape content that appears in the body of an HTML cocument ''' data = data.replace("&", "&amp;") # Must be done first! data = data.replace("<", "&lt;") data = data.replace(">", "&gt;") if quote: data = data.replace('"', "&quot;") return data _unescape = { 'quot': 34, 'amp': 38, 'lt': 60, 'gt': 62, 'nbsp': 32, # more here # http://www.w3.org/TR/html4/sgml/entities.html 'yuml': 255, } def unescape(data): ''' unescapes html entities. the opposite of escape. ''' cc = re.compile('&(?:(?:#(\d+))|([^;]+));') result = [] m = cc.search(data) while m: result.append(data[0:m.start()]) d = m.group(1) if d: d = int(d) result.append(unichr(d)) else: d = _unescape.get(m.group(2), ord('?')) result.append(unichr(d)) data = data[m.end():] m = cc.search(data) result.append(data) return ''.join(result) _reserved = ";/?:@&=+$, " _replace_map = dict((c, '%%%2X' % ord(c)) for c in _reserved) def url_escape(data): return ''.join(_replace_map.get(c, c) for c in data) def url_unescape(data): return re.sub('%([0-9a-fA-F]{2})', lambda m: unichr(int(m.group(1), 16)), data) class lazy(dom_tag): ''' delays function execution until rendered ''' def __new__(_cls, *args, **kwargs): ''' Need to reset this special method or else dom_tag will think it's being used as a dectorator. This means lazy() can't be used as a dectorator, but thinking about when you might want that just confuses me. ''' return object.__new__(_cls) def __init__(self, func, *args, **kwargs): super(lazy, self).__init__() self.func = func self.args = args self.kwargs = kwargs def _render(self, rendered, indent=1, inline=False): r = self.func(*self.args, **self.kwargs) rendered.append(str(r)) # TODO rename this to raw? class text(dom_tag): ''' Just a string. useful for inside context managers ''' is_pretty = False def __init__(self, _text, escape=True): super(text, self).__init__() if escape: self.text = globals()['escape'](_text) else: self.text = _text def _render(self, rendered, indent, inline): rendered.append(self.text) return rendered def raw(s): ''' Inserts a raw string into the DOM. Unsafe. ''' return text(s, escape=False)
true
77f788e0037ff73335a4f0f25181da0001a64f63
Python
feiyanshiren/myAcm
/leetcode/t000561.py
UTF-8
466
3.484375
3
[]
no_license
from typing import List class Solution: def arrayPairSum(self, nums: List[int]) -> int: nums.sort() return sum([nums[i] for i in range(0, len(nums), 2)]) s = Solution() import time t = time.time() for i in range(1000): print(s.arrayPairSum([1, 4, 3, 2])) print(s.arrayPairSum([1, 1])) print(s.arrayPairSum([-1, 3, -4,-5])) print(s.arrayPairSum([-1, -4, -6,-7])) print(s.arrayPairSum([1,2,0,-3])) print(time.time() - t)
true
937506de774b0f25a11db9f1d4c6c29ec00a861e
Python
SampathDontharaju/CloudComputing
/Hadoop-MapReduce/Twitter 5th solution/reduce2.py
UTF-8
247
2.9375
3
[]
no_license
#!/usr/bin/env python import sys import string max=0 screenName= '' for line in sys.stdin: data = line.strip('\n').split('\t') if int(data[0])> max: max= int(data[0]) screenName = data[1] print '%s\t%s' % (max,screenName)
true
72819b5773afc90f26f3a7dd019290cf95bd8c16
Python
lotcarnage/macbook_photo_organizer
/delete_duplicated_files.py
UTF-8
3,351
2.53125
3
[ "MIT" ]
permissive
import os from datetime import datetime from tqdm import tqdm import PIL.Image import PIL.ExifTags import argparse def __is_jpeg(file_path): ext = os.path.splitext(file_path)[1].lower() return ext in [".jpg", ".jpeg"] def __is_mov(file_path): ext = os.path.splitext(file_path)[1].lower() return ext in [".mov"] def __datetime_to_date_string(date): v = str(date).split() yyyymmdd = ":".join(v[0].split("-")) return " ".join([yyyymmdd, v[1]]) def __get_creation_date(file_path): if os.name == "posix": stat = os.stat(file_path) date = datetime.fromtimestamp(stat.st_birthtime) else: date = datetime.fromtimestamp(os.path.getctime(file_path)) return __datetime_to_date_string(date) def __extract_jpg_original_date(file_path): with PIL.Image.open(file_path) as jpeg_file: exif = jpeg_file._getexif() return exif[36867] def __extract_mov_original_date(file_path): from datetime import datetime as DateTime import struct ATOM_HEADER_SIZE = 8 # difference between Unix epoch and QuickTime epoch, in seconds EPOCH_ADJUSTER = 2082844800 original_date = None # search for moov item with open(file_path, "rb") as mov_file: while True: atom_header = mov_file.read(ATOM_HEADER_SIZE) #~ print('atom header:', atom_header) # debug purposes if atom_header[4:8] == b'moov': break # found else: atom_size = struct.unpack('>I', atom_header[0:4])[0] mov_file.seek(atom_size - 8, 1) # found 'moov', look for 'mvhd' and timestamps atom_header = mov_file.read(ATOM_HEADER_SIZE) if atom_header[4:8] == b'cmov': raise RuntimeError('moov atom is compressed') elif atom_header[4:8] != b'mvhd': raise RuntimeError('expected to find "mvhd" header.') else: mov_file.seek(4, 1) original_date = struct.unpack('>I', mov_file.read(4))[0] - EPOCH_ADJUSTER original_date = DateTime.fromtimestamp(original_date) if original_date.year < 1990: # invalid or censored data original_date = None if original_date is not None: original_date = __datetime_to_date_string(original_date) return original_date def __get_jpeg_creation_date(file_path): try: date = __extract_jpg_original_date(file_path) except: date = __get_creation_date(file_path) return date if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-d", "--delete_list_file_path", type=str, required=True) args = parser.parse_args() with open(args.delete_list_file_path, "rt") as list_file: lines = [line.strip().split(" // ") for line in list_file.readlines()] for line in tqdm(lines): if os.path.isfile(line[0]) and os.path.isfile(line[1]): date_lhv = __get_jpeg_creation_date(line[0]) date_rhv = __get_jpeg_creation_date(line[1]) if date_lhv is None: print(line[0]) if date_rhv is None: print(line[1]) delete_target = line[1] if date_lhv <= date_rhv else line[0] if os.path.isfile(delete_target): os.remove(delete_target) exit(0)
true
796b9ff999d977583bb193e10c2d093bfccfd498
Python
wally-wally/TIL
/02_algorithm/baekjoon/problem/1000~9999/2638.치즈/2638.py
UTF-8
1,462
2.75
3
[]
no_license
import sys sys.stdin = open('input_2638.txt', 'r') def BFS(): melting_idx = [] queue = [[0, 0]] visited = [[False] * M for _ in range(N)] while queue: pop_elem = queue.pop() for i in range(4): new_row, new_col = pop_elem[0] + dx[i], pop_elem[1] + dy[i] if 0 <= new_row < N and 0 <= new_col < M: if cheese_tray[new_row][new_col] == 0: if not visited[new_row][new_col]: queue.append([new_row, new_col]) visited[new_row][new_col] = True else: cheese_tray[new_row][new_col] += 1 if cheese_tray[new_row][new_col] >= 3: melting_idx.append((new_row, new_col)) return set(melting_idx) N, M = map(int, input().split()) cheese_tray, cheese_count = [], 0 for _ in range(N): cheese_line = list(map(int, input().split())) cheese_count += cheese_line.count(1) cheese_tray.append(cheese_line) dx, dy = (-1, 0, 1, 0), (0, 1, 0 ,-1) time = 0 while True: time += 1 melting_indexes = BFS() if cheese_count == len(melting_indexes): print(time) break for idx in range(N * M): row, col = idx // M, idx % M if (row, col) in melting_indexes: cheese_tray[row][col] = 0 elif cheese_tray[row][col] > 1: cheese_tray[row][col] = 1 cheese_count -= len(melting_indexes)
true
d6649c2a947ba87b5c69004135faa2dd0ac3cd7f
Python
mrvollger/SDA
/scripts/coverageByEnds.py
UTF-8
1,997
2.734375
3
[ "MIT" ]
permissive
#!/usr/bin/env python import argparse import os import sys import re import numpy as np import intervaltree import pandas as pd parser = argparse.ArgumentParser(description="") parser.add_argument("-a", "--reads", nargs="+", help="bed file(s) with read start and end locations" ) parser.add_argument("-b", "--regions", nargs= "+", help="bed file with regions to count within") parser.add_argument("-o", "--out", help="bed file with numebr of starts and ends in each region") args = parser.parse_args() readFiles = args.reads regionFiles = args.regions regions = {} df = None def defineRegions(): for myfile in regionFiles: f = open(myfile).readlines() for line in f: line = line.split() Chr = line[0] start = int(line[1]) end = int( line[2] ) if(Chr not in regions): regions[Chr] = intervaltree.IntervalTree() # first vlaue is number of starts in region, second is numer of ends in region regions[Chr][start:end+1] = [0,0] def increment(point, Chr, startOrEnd): for region in regions[Chr][point]: region.data[startOrEnd] += 1 def addCounts(myfile): print(myfile) f = open(myfile).readlines() for line in f: line = line.split() Chr = line[0] if(Chr not in regions): continue start = int(line[1]) end = int(line[2]) increment(start, Chr, 0) increment(end, Chr, 1) def readReads(): for myfile in readFiles: addCounts(myfile) def makeBed(): global df out = "" for key in sorted(regions): tree = regions[key] for region in sorted(tree): out += "{}\t{}\t{}\t{}\t{}\t{}\n".format(key, region.begin, region.end-1, region.data[0], region.data[1], max(region.data[0], region.data[1]) ) open(args.out, "w+").write(out) df = pd.read_csv(args.out, header=None, sep="\t") df.columns = ["chr", "start", "end", "startCount", "endCount", "maxCount"] print( df[["startCount", "endCount", "maxCount"]].describe() ) def main(): defineRegions() readReads() makeBed() main() sds = df.groupby(["chr"])["maxCount"].describe()
true
14186998277f4d64e214e1169a3e64ad7f0705ab
Python
mds2/mazegen
/ProduceMazeBook.py
UTF-8
644
3.15625
3
[ "MIT" ]
permissive
# Generates a booklet of mazes # # Run as ProduceMazeBook.py width height pages > output_file # e.g. # python ProduceMazeBook.py 18 24 10 > booklet.ps # # Prints to standard out import MazeGen import sys if __name__ == "__main__": try: (w, h) = [int(x) for x in sys.argv[1:][:2]] except: (w, h) = (18, 24) try: pages = int(sys.argv[3]) except: pages = 10 ps = MazeGen.PsGen(w, h, sys.stdout) for page in range (0, pages): gen = MazeGen.MazeGen(w, h) maze = gen.make_maze() render = MazeGen.MazeRender(maze) render.spew(ps.process) ps.finish()
true
f19a08351bc73ca0d5903bf17e164488610c47db
Python
fengyihuai/Learn_Python
/class3/turtle_hist.py
UTF-8
523
3.625
4
[]
no_license
# -*- coding: UTF-8 -*- import turtle # myTurtle = turtle.Turtle() from turtle import * def doBar(height, clr): begin_fill() color(clr) setheading(90) forward(height) right(90) forward(40) right(90) forward(height) end_fill() values = [49, 118, 201, 241, 168, 266, 221, 65, 231] colors = ["green", "blue", "red", "yellow", "orange", "purple", "black", "pink", "grey"] up() goto(-300, -200) down() idx = 0 for value in values: doBar(value, colors[idx]) idx += 1 done()
true
7a566aa70fb1e74c54bf270beb52b0a6e7ae2697
Python
vcrawford/DeviceCaching
/ContactGraph/VisualizeContactGraph.py
UTF-8
1,744
2.859375
3
[]
no_license
# Take a contact graph file and output dot file visualizing it # Call like python VisualizeContact.py contact_graph.txt output_graph.dot ... # output_graph.eps 0.01 cache_nodes.txt import sys import subprocess import xml.etree.ElementTree as et contact_data = sys.argv[1] output_file = sys.argv[2] output_file_im = sys.argv[3] min_edge_weight = float(sys.argv[4]) cache_nodes = [] # If we want to plot cache nodes # will plot the nodes for the first experiment if len(sys.argv) > 5: cache_file = sys.argv[5] tree = et.parse(cache_file) root = tree.getroot() first_experiment = root[0] for data in first_experiment: if data.tag == "cache": cache_data = data.text.split(",")[0:-1] cache_nodes = [int(x) for x in cache_data] output = open(output_file, 'w') data_in = open(contact_data, 'r') output.write("graph contact { \n") output.write("overlap = false \n") output.write("splines = true \n") output.write("node [shape=circle, label=\"\", height=0.3, style=filled, fillcolor=deepskyblue2, color=deepskyblue3] \n") output.write("edge [color=dimgray] \n") node_i = 0 for line in data_in: values = line.split() node_j = 0 for value in values: # Only need 1/2 of the contact since it is symmetric if node_i < node_j and float(value) > min_edge_weight: output.write("{} -- {} [penwidth={}]; \n".format(node_i, node_j, value)) node_j = node_j + 1 node_i = node_i + 1 # Color cache nodes for i in range(node_i): if i in cache_nodes: output.write("{} [fillcolor=pink]; \n".format(i)) else: output.write("{}; \n".format(i)) output.write("} \n") output.close() data_in.close() subprocess.call(["dot", "-Tps", output_file, "-o", output_file_im])
true
5e914d55371d3c8c2feec2e49ee45afa1ccb519d
Python
jacobwaller/beer-bot
/code/bot/controller_ws/src/controller/controller/controller_node.py
UTF-8
4,046
2.53125
3
[ "MIT" ]
permissive
from typing import final import rclpy import time from rclpy.node import Node from rclpy.duration import Duration from controller.robot_navigator import BasicNavigator, NavigationResult # Msgs from std_msgs.msg import String from std_msgs.msg import Empty from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import Twist # Services from slam_toolbox.srv import DeserializePoseGraph #`ros2 service call /slam_toolbox/deserialize_map slam_toolbox/DeserializePoseGraph {"filename: pozeywozey, match_type: 1"}` # Target Point: 4.0 1.0 # Resting point 1.0 0 # ros2 topic pub /goal_pose geometry_msgs/PoseStamped "{header: {stamp: {sec: 0}, frame_id: 'map'}, pose: {position: {x: 0.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}}" class ControllerNode(Node): ### # Makes robot go to specified [x,y] location in coords # Creates msg & publishes it to waypoint_publisher ### def goto(self, coords): goal = PoseStamped() goal.header.stamp.sec = 0 goal.header.frame_id = "map" goal.pose.position.x = coords[0] goal.pose.position.y = coords[1] goal.pose.position.z = 0.0 goal.pose.orientation.x = 0.0 goal.pose.orientation.y = 0.0 goal.pose.orientation.z = 0.0 goal.pose.orientation.w = 1.0 self.navigator.goToPose(goal) def dock(self): coords = [1.0, 0] # Go to coords self.goto(coords) # publish to dock def deliver_to(self): # Get coordinate (should be passed in function) coords = [4.0, 1.0] def __init__(self): super().__init__('controller_node') # Setup Pub/Subs/Clients for misc actions self.waypoint_publisher = self.create_publisher(PoseStamped, 'goal_pose', 2) self.undock_publisher = self.create_publisher(Empty, 'undock', 2) self.dock_publisher = self.create_publisher(Empty, 'dock', 2) self.drive_publisher = self.create_publisher(Twist, "cmd_vel", 10) # self.waypoint_subscriber = self.create_subscription() self.map_loader_client = self.create_client(DeserializePoseGraph, 'slam_toolbox/deserialize_map') # Load the map with current location being the dock location self.get_logger().info('loading map') map_loader_data = DeserializePoseGraph.Request() map_loader_data.filename = '/home/jacob/beer-bot/pozeywozey' map_loader_data.match_type = 1 future = self.map_loader_client.call_async(map_loader_data) rclpy.spin_until_future_complete(self, future) self.get_logger().info('map loaded') # Setup Nav2 Library self.navigator = BasicNavigator() initial_pose = PoseStamped() initial_pose.header.frame_id = 'map' initial_pose.header.stamp = self.navigator.get_clock().now().to_msg() initial_pose.pose.position.x = 0.0 initial_pose.pose.position.y = 0.0 initial_pose.pose.orientation.z = 0.0 initial_pose.pose.orientation.w = 0.0 # I beleive we use this because we're starting nav2 in our main launch file... # we shall see self.get_logger().info("Waiting for nav2") self.navigator.lifecycleStartup() self.get_logger().info("Done") time.sleep(5.0) # Debug, go to a predefined spot and back self.goto([4.0,1.0]) time.sleep(5.0) while not self.navigator.isNavComplete(): feedback = self.navigator.getFeedback() self.goto([1.0,0.0]) time.sleep(5.0) while not self.navigator.isNavComplete(): feedback = self.navigator.getFeedback() def main(args=None): rclpy.init(args=args) try: controller_node = ControllerNode() rclpy.spin(controller_node) finally: # controller_node.navigator.lifecycleShutdown() controller_node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
true
f9eaab083081c90eefdfa33a68e58ce1ed62e748
Python
mrelich/GalacticPlot
/tools.py
UTF-8
3,906
3.0625
3
[]
no_license
from math import pi #import ephem import numpy as np import matplotlib.pyplot as plt #------------------------------------# # Plot Galactic Coordinates #------------------------------------# def galPlot(lat, lon, origin=0, title="Galactic",projection="mollweide"): # The latitude needs to be shifted into the range # from [-180,180] degrees from [0,360) lat_shift = convertPoints(lat,origin) # Now update the lables on the x-axis to run # from 180 to -180, which is convention tick_labels = np.array([150,120,90,60,30,0,-30,-60,-90,-120,-150]) # Create the figure fig = plt.figure(figsize=(10,5)) plot = fig.add_subplot(111,projection=projection,axisbg='LightCyan') plot.set_title(title) plot.set_xticklabels(tick_labels) # Now plot the data plot.scatter(lat_shift,lon,marker="x") # Draw a grid plot.grid(True) # Plot equator eq = loadEquator() # Plot Hemisphere divide plot.plot(eq[:,0],eq[:,1],'r-') # Save the plot fig.savefig("galacticplot.png") #------------------------------------# # Plot Galactic Coordinates #------------------------------------# def eqPlot(RA, dec, origin=0, title="Equatorial",projection="mollweide"): # The right ascension needs to be shifted into the range # from [-180,180] degrees from [0,360) RA_shift = convertPoints(RA,origin) # Now update the lables on the x-axis to run # from 180 to -180, which is convention tick_labels = np.array([150,120,90,60,30,0,-30,-60,-90,-120,-150]) # Create the figure fig = plt.figure(figsize=(10,5)) plot = fig.add_subplot(111,projection=projection,axisbg='LightCyan') plot.set_title(title) plot.set_xticklabels(tick_labels) # Now plot the data plot.scatter(RA_shift,dec,marker="x") # Draw a grid plot.grid(True) # Get galactic plane points gal = loadGalactic() # Plot Hemisphere divide plot.plot(gal[:,0],gal[:,1],'r-') #------------------------------------# # Load equator for galactic plot # this is to reduce dependence on # the ephem package #------------------------------------# def loadEquator(): points = [] infile = open("equator.txt","r") for line in infile: lat = float(line.split()[0]) lon = float(line.split()[1]) points.append([lat,lon]) return np.array(points) #------------------------------------# # Load galactic plane for equatorial plot # this is to reduce dependence on # the ephem package #------------------------------------# def loadGalactic(): points = [] infile = open("galacticPlane.txt","r") for line in infile: RA = float(line.split()[0]) dec = float(line.split()[1]) points.append([RA,dec]) return np.array(points) #------------------------------------# # Convert points to [180,-180] #------------------------------------# def convertPoints(points,origin): shifted = np.remainder(points+2*pi-origin,2*pi) indices = shifted > pi shifted[indices] -= 2*pi shifted = -shifted return shifted #------------------------------------# # Get equator in galactic coords #------------------------------------# #def hemPoints(): # # dec = 0 # RA_array = np.arange(0,360) # gal_array = np.zeros((360,2)) # for RA in RA_array: # eq = ephem.Equatorial(np.radians(RA),np.radians(dec)) # ga = ephem.Galactic(eq) # gal_array[RA] = ga.get() # # return gal_array #------------------------------------# # Get equator in galactic coords #------------------------------------# #def galPoints(): # # lat = 0 # lon_array = np.arange(0,360) # eq_array = np.zeros((360,2)) # for lon in lon_array: # ga = ephem.Galactic(np.radians(lon),np.radians(lat)) # eq = ephem.Equatorial(ga) # eq_array[lon] = eq.get() # # return eq_array
true
5841d3d1544855d9aa47eebe74fd72b0eb8064dd
Python
bj1570saber/muke_Python_July
/cha_9_class/9_15_super.py
UTF-8
525
3.828125
4
[]
no_license
from human_class import Human class Student(Human): def __init__(self,school,name,age): self.school = school #Human.__init__(self,name, age)# should use super. super(Student, self).__init__(name,age) # function overriding def do_homework(self): super(Student, self).do_homework()# call parent function. print("doing_homework.") student1 = Student("Palomar", "jerry", 18) student1.do_homework()# doing_homework. # output: # Human doing homework. # doing_homework.
true
8ae742fe459d70217a921226e371e4d0551bbbc1
Python
Woohoo82/bullshit_generator
/goodidea.py
UTF-8
993
2.921875
3
[]
no_license
#!/usr/bin/python3 import random ragok = ["-ébe", "-ében", "-éből", "-én", "-ére", "-éről", "-énél", "-éhez", "-étől", "-éig", "-ének", "-ért", "-ként"] igek = list(open('dic_verb.txt')) mnevek = list(open('dic_adj.txt' )) igenevek=list(open('dic_mi.txt' )) fonevek= list(open('dic_noun.txt')) def gen_alany(): jelzo1 = random.choice(mnevek).rstrip() alany = random.choice(fonevek).rstrip() + random.choice(fonevek).rstrip() + "(k)" jelzo2 = random.choice(igenevek).rstrip() hatarozo = random.choice(fonevek).rstrip() + random.choice(ragok) return jelzo1 + " " + alany + " " + jelzo2 + " " + hatarozo def gen_allitmany(): ige_ve = random.choice(igek).rstrip() + "-ve" jelzo3 = random.choice(igenevek).rstrip() targy = random.choice(fonevek).rstrip() + "-t" ige = random.choice(igek).rstrip() return ige_ve + " " + jelzo3 + " " + targy + " " + ige + "(ik)" for x in range(5): print(gen_alany() + " " + gen_allitmany())
true
675b991dcba92eb76256f03b6ea92b7602e5c7bf
Python
ahmeeed-mohamed/myCS427project
/client2.py
UTF-8
1,135
3.171875
3
[]
no_license
import socket from cryptography.fernet import Fernet def client_program(): host = socket.gethostname() # as both code is running on same pc port = 5003 # socket server port number client_socket = socket.socket() # instantiate client_socket.connect((host, port)) # connect to the server file = open('key.key', 'rb') # Open the file as wb to read bytes key = file.read() # The key will be type bytes file.close() message = input(' -> ') # take input message = bytes(message ,'utf-8') while message.lower().strip().decode() != 'bye': f = Fernet(key) encrypted = f.encrypt(message) client_socket.send(encrypted) # send message data = client_socket.recv(1024).decode() # receive response message = bytes(data ,'utf-8') decrypted = f.decrypt(message) print('Received from server: ' + str(decrypted.decode())) # show in terminal message = input(" -> ") # again take input message = bytes(message ,'utf-8') client_socket.close() # close the connection if __name__ == '__main__': client_program()
true
715e31ab09eca0ce5a4881646c757a158631adec
Python
Honeyfy/semi-supervised-text-classification
/src/models/applying_trained_model.py
UTF-8
908
2.78125
3
[ "BSD-3-Clause" ]
permissive
import pandas as pd from src.models.text_classifier import TextClassifier def apply_trained_model(model_id, data_filename): # a function applying a trained model to a new csv file and returning a dataframe with predicted label and confidence. model_path = r'C:\develop\code\semi-supervised-text-classification\data\results\ml_model_' + str(model_id) + '.pickle' clf = TextClassifier.load(model_path) file_path = r'C:\develop\code\semi-supervised-text-classification\data' + '\\' + data_filename with open(file_path, 'r') as f: df = pd.read_csv(f) X = clf.pre_process(df, fit=False) df_pred = clf.get_prediction_df(X) df_with_prediction = pd.concat([df, df_pred], axis=1) return df_with_prediction if __name__ == '__main__': model_id = '1111' data_filename = 'enron_ml_1.csv' df_with_prediction = apply_trained_model(model_id, data_filename)
true
7ae48291d8798ffd8b9c5b57ce72008a8c77b6e4
Python
Zumbalamambo/variational-autoencoder-benchmark
/model/base.py
UTF-8
652
2.96875
3
[ "MIT" ]
permissive
from abc import abstractmethod, ABC from sklearn.metrics import log_loss, mean_squared_error class Encoder(ABC): @abstractmethod def encode(self, x): pass @abstractmethod def decode(self, encoded_x): pass def recon_error(self, x, metric='cross_entropy'): encoded_x = self.encode(x) decoded_x = self.decode(encoded_x) if metric == 'cross_entropy': error = log_loss(x, decoded_x) elif metric == 'mean_square_error': error = mean_squared_error(x, decoded_x) else: raise ValueError('%s metric is not supported' % metric) return error
true
7ddd0463ff8cbbcdc7fb0b8022fd4d31efb1a2a1
Python
LauYuLoong/python_study
/deepcopy.py
UTF-8
197
2.609375
3
[]
no_license
# -*- encoding = gbk -*- from copy import deepcopy if __name__ == '__main__': d = {'names':['Alfred','Bertrand']} c = d.copy() dc = deepcopy(d) d['names'].append('Clive') print c print dc
true
54f45f4912f2d6139ae505285b88422d98ba5cf5
Python
Aijeyomah/Budget-App
/index.py
UTF-8
1,518
3.9375
4
[]
no_license
# Budget App # Create a Budget class that can instantiate objects based on different budget categories like food, clothing, and entertainment. These objects should allow for # 1. Depositing funds to each of the categories # 2. Withdrawing funds from each category # 3. Computing category balances # 4. Transferring balance amounts between categories # Push your code to GitHub, and submit the repo link. class Budget: def __init__(self, category): self.category = category self.ledger = [] self.amount = 0 def deposit_funds(self,amount, description= 'credit'): self.ledger.append({"amount": amount, "description": description }) self.amount += amount print(self.ledger) return 'transaction completed' def check_funds(self, amount): return True if amount <= self.amount else False def withdraw_funds(self, amount, description='debit'): print('*****Withdraw amount from wallet') print('Available budgets:') for budget in self.ledger: print(budget.category) if self.check_funds(amount): self.amount -= amount self.ledger.append({"amount": -amount, "description": description }) def transfer_balance(self,amount,category): if self.check_funds(amount)==True: self.amount-=amount self.ledger.append({"amount": -amount,"description":"Transfer to "+category.category}) category.ledger.append({"amount": amount,"description": "Transfer from "+self.category}) return True else: return False
true
b1379ddd05f23aa8a45390c2059c48898b360550
Python
mangei-ux/30DaysOfPython
/Day 11/day11.py
UTF-8
990
2.6875
3
[]
no_license
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib host = "smtp.gmail.com" port = 587 username = "wsadevv@gmail.com" password = "$sec#wsabsi630" sender = username to_list = "williansantana.angola@gmail.com" # it dont render hrml email_conn = smtplib.SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username, password) # email_conn.sendmail(sender, to_list, "Howdy") # email_conn.quit() # it now renders html the_msg = MIMEMultipart("alternative") the_msg['Subject'] = "Hello there" the_msg['From'] = sender the_msg['To'] = to_list plain_txt = "Testing the message" html = """\ <html> <head></head> <body> <p>Hey!<br> Testing this email <b>message</b> Made by <a href='http://www.google.com'>Link</p> </body> <html> """ part_one = MIMEText(plain_txt, 'plain') part_two = MIMEText(html, 'html') the_msg.attach(part_one) the_msg.attach(part_two) email_conn.sendmail(sender, to_list, the_msg.as_string()) email_conn.quit() print(the_msg.as_string())
true
857d0ffa220787f163fdb17ab70b381c7ce03362
Python
rayruchira/Autoencoders-miniprojects
/CFRecSys.py
UTF-8
4,250
2.953125
3
[]
no_license
#import required libraries import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt import os #getting required files r_df = pd.read_csv('/home/ray/Projects/datasets/train_100k.csv', delimiter = ',') r=np.array(r_df, dtype=int)[:,1:] r_t_df = pd.read_csv('/home/ray/Projects/datasets/test.csv', delimiter = ',') r_t=np.array(r_t_df, dtype=int)[:,1:] #checking if it can acces files print(r_t[0]) #getting max no of movies and users nb_users = int(max(max(r[:, 0]), max(r_t[:, 0]))) nb_movies = int(max(max(r[:, 1]), max(r_t[:, 1]))) # printing the number of users and movies print(f'The number of users {nb_users}, The number of movies {nb_movies}') #Stacked Autoencoder class StackedAutoEncoder: def __init__(self,x ): super(StackedAutoEncoder, self).__init__() # getting all the functionality from the parent class self.x=x #DATA PREPROCESSING def convert_fn(self, ): converted_data = [] data=self.x for user_id in range(1, nb_users + 1): #getting all the movies ids that rated by every user movies_for_user_id = data[:, 1][data[:, 0] == user_id] # getting the movies ids that taken be the current user in the for loop rating_for_user_id = data[:, 2][data[:, 0] == user_id] ratings = np.zeros(nb_movies) # initialze all the ratings with zeros then include the rated movies ratings[movies_for_user_id - 1] = rating_for_user_id converted_data.append(list(ratings)) self.x=np.array(converted_data) #encoder layers def _encoder(self): inputs = tf.keras.layers.Input(shape=(nb_movies,)) enc1 = tf.keras.layers.Dense(30, activation='relu')(inputs) enc2= tf.keras.layers.Dense(15,activation='relu')(enc1) enc3= tf.keras.layers.Dense(10,activation='relu')(enc2) model = tf.keras.Model(inputs, enc3) self.encoder = model return model #decoder layers def _decoder(self): inputs = tf.keras.layers.Input(shape=(10,)) dec1= tf.keras.layers.Dense(15)(inputs) dec2=tf.keras.layers.Dense(30)(dec1) dec3= tf.keras.layers.Dense(nb_movies)(dec2) model = tf.keras.Model(inputs, dec3) self.decoder = model return model #autoencoder model def encoder_decoder(self): ec = self._encoder() dc = self._decoder() inputs = tf.keras.layers.Input(shape=(nb_movies,)) ec_out = ec(inputs) dc_out = dc(ec_out) model = tf.keras.Model(inputs, dc_out) self.model = model return model #training def fit(self, batch_size=32, epochs=300): #optimizer define optimizer=tf.keras.optimizers.RMSprop( learning_rate=0.01, decay=0.5) #model compilation self.model.compile(optimizer=optimizer, loss='mse',metrics=['accuracy']) log_dir = './log/' tbCallBack = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=0, write_graph=True, write_images=True) self.model.fit(self.x, self.x, epochs=epochs, batch_size=batch_size, callbacks=[tbCallBack]) #saving weights def save(self): if not os.path.exists(r'./weights'): os.mkdir(r'./weights') else: self.encoder.save(r'./weights/encoder_weightsAEM.h5') self.decoder.save(r'./weights/decoder_weightsAEM.h5') self.model.save(r'./weights/ae_weightsAEM.h5') if __name__ == '__main__': ae = StackedAutoEncoder(x=r) ae.convert_fn() print(f'\nThe dimensions of the data is {len(ae.x)} X {len(ae.x[0])}') encoder=ae.encoder_decoder() ae.fit(batch_size=32, epochs=50) ae.save() #testing ae = StackedAutoEncoder(x=r_t) ae.convert_fn() inputs=ae.x #loading weights model=tf.keras.models.load_model(r'./weights/ae_weightsAEM.h5') # Evaluate the model on the test data using `evaluate` print('\n# Evaluate on test data') results = model.evaluate(inputs, inputs, batch_size=64) print('test loss, test acc:', results)
true
26b854f9ddd0312933fcc18ee81aca7b456d35ab
Python
hchrist2010/CS-331-Introduction-to-Artificial-Intelligence
/assignment2/Players.py
UTF-8
3,451
3.203125
3
[]
no_license
''' Erich Kramer - April 2017 Apache License If using this code please cite creator. ''' class Player: def __init__(self, symbol): self.symbol = symbol # PYTHON: use obj.symbol instead def get_symbol(self): return self.symbol # parent get_move should not be called def get_move(self, board): return minimax(board, self.symbol) def minimax(board, symbol): children, moves = successor(board, symbol) results = [] for child in children: if symbol == 'X': results.append(max_value(child, symbol)) else: results.append(min_value(child, symbol)) print(results) child.display() if symbol == 'X': index = results.index(max(results)) else: index = results.index(min(results)) return moves[index] def max_value(board, symbol): if not board.has_legal_moves_remaining(symbol): return utility(board) else: v = float('-inf') children, moves = successor(board, symbol) for child in children: temp = min_value(child, 'O') if temp > v: v = temp return v def min_value(board, symbol): if not board.has_legal_moves_remaining(symbol): return utility(board) else: v = float('inf') children, moves = successor(board, symbol) for child in children: temp = max_value(child, 'X') if temp < v: v = temp return v def utility(board): p1 = 0 p2 = 0 for c in range(board.cols): for r in range(board.rows): if board.grid[c][r] == 'X': p1 += 1 elif board.grid[c][r] == 'O': p2 += 1 if c == 0 and r == 0: if board.grid[c][r] == 'X': p1 += 10 elif board.grid[c][r] == 'O': p2 += 10 if c == 0 and r == 3: if board.grid[c][r] == 'X': p1 += 10 elif board.grid[c][r] == 'O': p2 += 10 if c == 3 and r == 0: if board.grid[c][r] == 'X': p1 += 10 elif board.grid[c][r] == 'O': p2 += 10 if c == 3 and r == 3: if board.grid[c][r] == 'X': p1 += 10 elif board.grid[c][r] == 'O': p2 += 10 return p1 - p2 def successor(board, symbol): children = [] moves = [] for r in range(board.rows): for c in range(board.cols): if board.is_legal_move(c, r, symbol): child = board.cloneOBoard() child.play_move(c, r, symbol) moves.append([c, r]) children.append(child) return children, moves class HumanPlayer(Player): def __init__(self, symbol): Player.__init__(self, symbol); def clone(self): return HumanPlayer(self.symbol) # PYTHON: return tuple instead of change reference as in C++ def get_move(self, board): col = int(input("Enter col:")) row = int(input("Enter row:")) return (col, row) class MinimaxPlayer(Player): def __init__(self, symbol): Player.__init__(self, symbol); if symbol == 'X': self.oppSym = 'O' else: self.oppSym = 'X'
true
905167551ab4c53420926b8b36d34804da1ca380
Python
Aasthaengg/IBMdataset
/Python_codes/p03598/s209015805.py
UTF-8
139
2.953125
3
[]
no_license
n = int(input()) k = int(input()) array = list(map(int,input().split())) count = 0 for i in array: count += min([i,k-i]) print(count*2)
true
1ee2f219d0d16e59b7ea1ae1fdc49c51cf195110
Python
kpiyush16/learning_sequence_encoders
/utils.py
UTF-8
2,564
2.734375
3
[]
no_license
import numpy as np import calendar def JulianDate_to_MMDDYYY(y,jd): month = 1 day = 0 while jd - calendar.monthrange(y,month)[1] > 0 and month <= 12: jd = jd - calendar.monthrange(y,month)[1] month = month + 1 d = jd if jd//10 == 0: d = '0'+str(jd) return ([x+'y' for x in list(str(y))] +[str(month)+'m' if month//10==1 else '0'+str(month)+'m'] +[x+'d' for x in list(str(d))]) def get_batch(data_lst, bs, ptr): h, r, t = [], [], [] for x in data_lst[ptr:bs+ptr]: h.append(x[0]) r.append(x[1]) t.append(x[2]) return (h, r, t) # Returns a negative batch with either head or tail corruption for entire batch def get_nbatch(data_lst, bs, ptr): triples = [[],[],[]] for x in data_lst[ptr:bs+ptr]: triples[0].append(x[0]) triples[1].append(x[1]) triples[2].append(x[2]) np.random.shuffle(triples[np.random.randint(2)*2]) return(triples[0], triples[1], triples[2]) class Triple(object): def __init__(self, head, tail, relation): self.h = head self.t = tail self.r = relation # Find the rank of ground truth tail in the distance array, # If (head, num, rel) in tripleDict, # skip without counting. def argwhereTail(head, tail, rel, array, tripleDict): wrongAnswer = 0 for num in array: if num == tail: return wrongAnswer elif (head, num, rel[0]) in tripleDict: continue else: wrongAnswer += 1 return wrongAnswer def argwhereHead(head, tail, rel, array, tripleDict): wrongAnswer = 0 for num in array: if num == head: return wrongAnswer elif (num, tail, rel[0]) in tripleDict: continue else: wrongAnswer += 1 return wrongAnswer def loadTriple(inPath=None, test_data=None, vocab_r = None): tripleList = [] if test_data is not None: for x in test_data: head = x[0] tail = x[2] rel = x[1] tripleList.append(Triple(head, tail, rel)) else: with open(inPath, 'r') as fr: for line in fr: x = list(map(int, line.strip().split("\t"))) head = x[0] tail = x[2] rel = [x[1]]+[vocab_r[i] for i in JulianDate_to_MMDDYYY(2014,x[3]//24+1)] tripleList.append(Triple(head, tail, rel)) tripleDict = {} for triple in tripleList: tripleDict[(triple.h, triple.t, triple.r[0])] = True return len(tripleList), tripleList, tripleDict
true
a3e7370b45c893471d4addadca462fc9179181b1
Python
johnruiz24/covid-tracker
/data/data.py
UTF-8
7,758
2.515625
3
[]
no_license
import os import re import wget import glob import requests import numpy as np import pandas as pd from bs4 import BeautifulSoup from datetime import datetime, timedelta urls = ['https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv', 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv'] # download files for url in urls: filename = wget.download(url) conf_df = pd.read_csv('time_series_covid19_confirmed_global.csv') deaths_df = pd.read_csv('time_series_covid19_deaths_global.csv') recv_df = pd.read_csv('time_series_covid19_recovered_global.csv') #merging dataframe dates = conf_df.columns[4:] conf_df_long = conf_df.melt(id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Confirmed') deaths_df_long = deaths_df.melt(id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Deaths') recv_df_long = recv_df.melt(id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'], value_vars=dates, var_name='Date', value_name='Recovered') recv_df_long = recv_df_long[recv_df_long['Country/Region']!='Canada'] full_table = pd.merge(left=conf_df_long, right=deaths_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long']) full_table = pd.merge(left=full_table, right=recv_df_long, how='left', on=['Province/State', 'Country/Region', 'Date', 'Lat', 'Long']) #preprocessing # Convert to proper date format full_table['Date'] = pd.to_datetime(full_table['Date']) full_table['Recovered'] = full_table['Recovered'].fillna(0) full_table['Recovered'] = full_table['Recovered'].astype('int') #fixing countries names # renaming countries, regions, provinces full_table['Country/Region'] = full_table['Country/Region'].replace('Korea, South', 'South Korea') full_table.loc[full_table['Province/State']=='Greenland', 'Country/Region'] = 'Greenland' full_table['Country/Region'] = full_table['Country/Region'].replace('Mainland China', 'China') # Active Case = confirmed - deaths - recovered full_table['Active'] = full_table['Confirmed'] - full_table['Deaths'] - full_table['Recovered'] # filling missing values full_table[['Province/State']] = full_table[['Province/State']].fillna('') cols = ['Confirmed', 'Deaths', 'Recovered', 'Active'] full_table[cols] = full_table[cols].fillna(0) full_table['Recovered'] = full_table['Recovered'].astype(int) #fixing off data feb_12_conf = {'Hubei' : 34874} # function to change value def change_val(date, ref_col, val_col, dtnry): for key, val in dtnry.items(): full_table.loc[(full_table['Date']==date) & (full_table[ref_col]==key), val_col] = val # changing values change_val('2/12/20', 'Province/State', 'Confirmed', feb_12_conf) # checking values full_table[(full_table['Date']=='2/12/20') & (full_table['Province/State']=='Hubei')] # ship rows containing ships with COVID-19 reported cases ship_rows = full_table['Province/State'].str.contains('Grand Princess') | \ full_table['Province/State'].str.contains('Diamond Princess') | \ full_table['Country/Region'].str.contains('Diamond Princess') | \ full_table['Country/Region'].str.contains('MS Zaandam') ship = full_table[ship_rows] # Latest cases from the ships ship_latest = ship[ship['Date']==max(ship['Date'])] full_table = full_table[~(ship_rows)] who_region = {} # African Region AFRO afro = "Algeria, Angola, Cabo Verde, Eswatini, Sao Tome and Principe, Benin, South Sudan, Western Sahara, Congo (Brazzaville), Congo (Kinshasa), Cote d'Ivoire, Botswana, Burkina Faso, Burundi, Cameroon, Cape Verde, Central African Republic, Chad, Comoros, Ivory Coast, Democratic Republic of the Congo, Equatorial Guinea, Eritrea, Ethiopia, Gabon, Gambia, Ghana, Guinea, Guinea-Bissau, Kenya, Lesotho, Liberia, Madagascar, Malawi, Mali, Mauritania, Mauritius, Mozambique, Namibia, Niger, Nigeria, Republic of the Congo, Rwanda, São Tomé and Príncipe, Senegal, Seychelles, Sierra Leone, Somalia, South Africa, Swaziland, Togo, Uganda, Tanzania, Zambia, Zimbabwe" afro = [i.strip() for i in afro.split(',')] for i in afro: who_region[i] = 'Africa' # Region of the Americas PAHO paho = 'Antigua and Barbuda, Argentina, Bahamas, Barbados, Belize, Bolivia, Brazil, Canada, Chile, Colombia, Costa Rica, Cuba, Dominica, Dominican Republic, Ecuador, El Salvador, Grenada, Guatemala, Guyana, Haiti, Honduras, Jamaica, Mexico, Nicaragua, Panama, Paraguay, Peru, Saint Kitts and Nevis, Saint Lucia, Saint Vincent and the Grenadines, Suriname, Trinidad and Tobago, United States, US, Uruguay, Venezuela' paho = [i.strip() for i in paho.split(',')] for i in paho: who_region[i] = 'Americas' # South-East Asia Region SEARO searo = 'Bangladesh, Bhutan, North Korea, India, Indonesia, Maldives, Myanmar, Burma, Nepal, Sri Lanka, Thailand, Timor-Leste' searo = [i.strip() for i in searo.split(',')] for i in searo: who_region[i] = 'South-East Asia' # European Region EURO euro = 'Albania, Andorra, Greenland, Kosovo, Holy See, Liechtenstein, Armenia, Czechia, Austria, Azerbaijan, Belarus, Belgium, Bosnia and Herzegovina, Bulgaria, Croatia, Cyprus, Czech Republic, Denmark, Estonia, Finland, France, Georgia, Germany, Greece, Hungary, Iceland, Ireland, Israel, Italy, Kazakhstan, Kyrgyzstan, Latvia, Lithuania, Luxembourg, Malta, Monaco, Montenegro, Netherlands, North Macedonia, Norway, Poland, Portugal, Moldova, Romania, Russia, San Marino, Serbia, Slovakia, Slovenia, Spain, Sweden, Switzerland, Tajikistan, Turkey, Turkmenistan, Ukraine, United Kingdom, Uzbekistan' euro = [i.strip() for i in euro.split(',')] for i in euro: who_region[i] = 'Europe' # Eastern Mediterranean Region EMRO emro = 'Afghanistan, Bahrain, Djibouti, Egypt, Iran, Iraq, Jordan, Kuwait, Lebanon, Libya, Morocco, Oman, Pakistan, Palestine, West Bank and Gaza, Qatar, Saudi Arabia, Somalia, Sudan, Syria, Tunisia, United Arab Emirates, Yemen' emro = [i.strip() for i in emro.split(',')] for i in emro: who_region[i] = 'Eastern Mediterranean' # Western Pacific Region WPRO wpro = 'Australia, Brunei, Cambodia, China, Cook Islands, Fiji, Japan, Kiribati, Laos, Malaysia, Marshall Islands, Micronesia, Mongolia, Nauru, New Zealand, Niue, Palau, Papua New Guinea, Philippines, South Korea, Samoa, Singapore, Solomon Islands, Taiwan, Taiwan*, Tonga, Tuvalu, Vanuatu, Vietnam' wpro = [i.strip() for i in wpro.split(',')] for i in wpro: who_region[i] = 'Western Pacific' # add 'WHO Region' column full_table['WHO Region'] = full_table['Country/Region'].map(who_region) # find missing values full_table[full_table['WHO Region'].isna()]['Country/Region'].unique() # Cleaning data # fixing Country values full_table.loc[full_table['Province/State']=='Greenland', 'Country/Region'] = 'Greenland' # Active Case = confirmed - deaths - recovered full_table['Active'] = full_table['Confirmed'] - full_table['Deaths'] - full_table['Recovered'] # replacing Mainland china with just China full_table['Country/Region'] = full_table['Country/Region'].replace('Mainland China', 'China') # filling missing values full_table[['Province/State']] = full_table[['Province/State']].fillna('') full_table[['Confirmed', 'Deaths', 'Recovered', 'Active']] = full_table[['Confirmed', 'Deaths', 'Recovered', 'Active']].fillna(0) # fixing datatypes full_table['Recovered'] = full_table['Recovered'].astype(int) full_table.to_csv(os.path.join(os.getcwd(),'data/covid.csv'), index=False)
true
96b52d1170699c9e694f99a7b1633e5048fb7106
Python
INBNETWORK/crowd
/submodules/poa-token-market-net-ico/ico/sign.py
UTF-8
2,894
2.734375
3
[ "MIT", "Apache-2.0" ]
permissive
"""Sign data with Ethereum private key.""" import binascii import bitcoin from ethereum import utils from ethereum.utils import big_endian_to_int, sha3 from secp256k1 import PrivateKey def get_ethereum_address_from_private_key(private_key_seed_ascii: str) -> str: """Generate Ethereum address from a private key. https://github.com/ethereum/pyethsaletool/blob/master/pyethsaletool.py#L111 :param private_key: Any string as a seed :return: 0x prefixed hex string """ priv = utils.sha3(private_key_seed_ascii) pub = bitcoin.encode_pubkey(bitcoin.privtopub(priv), 'bin_electrum') return "0x" + binascii.hexlify(sha3(pub)[12:]).decode("ascii") def get_address_as_bytes(address: str) -> bytes: """Convert Ethereum address to byte data payload for signing.""" assert address.startswith("0x") address_bytes = binascii.unhexlify(address[2:]) return address_bytes def sign(data: bytes, private_key_seed_ascii: str, hash_function=bitcoin.bin_sha256): """Sign data using Ethereum private key. :param private_key_seed_ascii: Private key seed as ASCII string """ msghash = hash_function(data) priv = utils.sha3(private_key_seed_ascii) pub = bitcoin.privtopub(priv) # Based on ethereum/tesrt_contracts.py test_ecrecover pk = PrivateKey(priv, raw=True) signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(msghash, raw=True)) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) v = utils.safe_ord(signature[64]) + 27 r_bytes = signature[0:32] r = big_endian_to_int(r_bytes) s_bytes = signature[32:64] s = big_endian_to_int(s_bytes) # Make sure we use bytes data and zero padding stays # good across different systems r_hex = binascii.hexlify(r_bytes).decode("ascii") s_hex = binascii.hexlify(s_bytes).decode("ascii") # Convert to Etheruem address format addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) # Return various bits about signing so it's easier to debug return { "signature": signature, "v": v, "r": r, "s": s, "r_bytes": r_bytes, "s_bytes": s_bytes, "r_hex": "0x" + r_hex, "s_hex": "0x" + s_hex, "address_bitcoin": addr, "address_ethereum": get_ethereum_address_from_private_key(priv), "public_key": pub, "hash": msghash, "payload": binascii.hexlify(bytes([v] + list(r_bytes)+ list(s_bytes,))) } def verify(msghash: bytes, signature, public_key): """Verify that data has been signed with Etheruem private key. :param signature: :return: """ V = utils.safe_ord(signature[64]) + 27 R = big_endian_to_int(signature[0:32]) S = big_endian_to_int(signature[32:64]) return bitcoin.ecdsa_raw_verify(msghash, (V, R, S), public_key)
true
2b3648cc073fcf61cb83f0fe0c62d88a6e8fb48a
Python
kavanchen/Python000-class01
/Week_03/G20200389010196/second assignment/pmap.py
UTF-8
1,641
3.203125
3
[]
no_license
#扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活) import sys import subprocess import time import socket from threading import Thread def ping1(ip, n): command="ping %s -n %d"%(ip, int(n)) print(ip,("通","不通")[subprocess.call(command,stdout=open("nul","w"))]) def ping(ip, n=4): ipx = ip.split('-') ip2num = lambda x:sum([256**i*int(j) for i,j in enumerate(x.split('.')[::-1])]) num2ip = lambda x: '.'.join([str(x//(256**i)%256) for i in range(3,-1,-1)]) ip_list = [num2ip(i) for i in range(ip2num(ipx[0]),ip2num(ipx[1])+1) if not ((i+1)%256 == 0 or (i)%256 == 0)] for i in ip_list: # command="ping %s -n %d"%(i, int(n)) # print(i,("通","不通")[subprocess.call(command,stdout=open("nul","w"))]) #stdout=open("nul","w") #不显示命令执行返回的结果 th=Thread(target=ping1,args=(i, n)) th.start() def portScanner(host, port): try: s = socket.socket((AF_INET,SOCK_STREAM)) s.connect((host,port)) print('[+] %d open' % port) s.close() except: #pass print('[-] %d close' % port) t1=time.time() if len(sys.argv)!=4: print("参数输入错误!") print("运行示例:") print("py pmap.py -f ping -ip 192.168.1.1-192.168.1.100 -n 4") elif len(sys.argv)==4: print(sys.argv[0]) command_type = sys.argv[1] ip = sys.argv[2] n = sys.argv[3] if command_type == 'ping': ping(ip, n) else: for p in range(1,10000): portScanner(ip, p) t2=time.time() print("程序耗时%f秒!"%(t2-t1)) #195.091611秒
true
c03e53f3cb1cc55501f0ccabbca90dcfc111f613
Python
MaratAG/HackerRankPy
/HR_PY_Basic_Data_Types_4.py
UTF-8
873
3.953125
4
[]
no_license
# HackerRank Basic Data Types 4 Finding the percentage def problem_solution(students_and_grades): # Task function name_of_students = input().strip() if name_of_students in students_and_grades.keys(): grades_of_students = students_and_grades[name_of_students] average_mark_of_student = \ sum(grades_of_students) / len(grades_of_students) print('{:.2f}'.format(average_mark_of_student)) def main(): # Initialization N = 0 students_and_grades = {} while not 1 < N < 11: N = int(input()) for i in range(N): name_and_grades = list(input().strip().split()) name = name_and_grades[0] grades = [float(name_and_grades[i]) for i in range(1, len(name_and_grades))] students_and_grades[name] = grades problem_solution(students_and_grades) main()
true
c96fd7d7620272e20cbb35fd5b10b1f3335b3409
Python
bartlomiejlu/Python--Volcanoes-in-the-USA
/volcanoes.py
UTF-8
1,096
2.796875
3
[]
no_license
import folium import pandas data = pandas.read_csv("Volcanoes_USA.txt") lat = list(data["LAT"]) lon = list(data["LON"]) elev = list(data["ELEV"]) def color_producer(elevation): if elevation < 1000: return 'green' elif 1000 <= elevation < 3000: return 'blue' else: return 'red' map = folium.Map(location=[44.2848015,-121.8410034], zoom_start=6, tiles="openstreetmap") fg = folium.FeatureGroup(name="My Map") fgv = folium.FeatureGroup(name="Volcanoes") for lt, ln, el in zip(lat, lon, elev): fgv.add_child(folium.Marker(location=[lt, ln], popup=str(el) + " meters", icon=folium.Icon(color=color_producer(el), icon='leaf'))) fgp = folium.FeatureGroup(name="Population") fgp.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x:{'fillColor':'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <x['properties']['POP2005']>20000000 else 'red'})) map.add_child(fgv) map.add_child(fgp) map.add_child(folium.LayerControl()) map.save("Map1.html")
true
da07b090bba20917eb5e855283f514995b67b90c
Python
gkqha/leetcode_python
/codewar/4kyu/ Human readable duration format.py
UTF-8
1,342
3.375
3
[]
no_license
def format_duration(seconds): if seconds==0: return "now" year = seconds // 31536000 yearDay = seconds % 31536000 day = yearDay // 86400 dayHour = yearDay % 86400 hour = dayHour // 3600 hourMinute = dayHour % 3600 minute = hourMinute // 60 second = hourMinute % 60 res = [year, day, hour, minute, second] res[0] = yearInput(res[0]) res[1] = dayInput(res[1]) res[2] = hourInput(res[2]) res[3] = minuteInput(res[3]) res[4] = secondInput(res[4]) res = [i for i in res if i != ""] if len(res) >= 2: res[-2] = res[-2][:-1]+" and" res[-1]=res[-1][0:-1] return " ".join(res) def secondInput(s): if s == 0: return "" elif s == 1: return "1 second," else: return f"{s} seconds," def minuteInput(m): if m == 0: return "" elif m == 1: return "1 minute," else: return f"{m} minutes," def hourInput(h): if h == 0: return "" elif h == 1: return "1 hour," else: return f"{h} hours," def dayInput(d): if d == 0: return "" elif d == 1: return "1 day," else: return f"{d} days," def yearInput(y): if y == 0: return "" elif y == 1: return "1 year," else: return f"{y} years,"
true
ead0c0cc3d34b062ef3b4a13cb5c671f03047d2f
Python
Alwaysproblem/simplecode
/COPInterview/sum_subarray.py
UTF-8
1,229
2.859375
3
[]
no_license
#!/bin/python3 import math import os import random import re import sys # def subarraySum(a): # import bisect # mm,pr=0,0 # a1=[] # for i in a: # pr=(pr+i)%m # mm=max(mm,pr) # ind=bisect.bisect_left(a1,pr+1) # if(ind<len(a1)): # mm=max(mm,pr-a1[ind]+m) # bisect.insort(a1,pr) # return mm def subarraySum(a): import bisect mm,pr=0,0 a1=[] for i in a: pr = pr+i mm = mm + pr ind=bisect.bisect_left(a1,pr+1) if ind < len(a1): mm = mm + pr-a1[ind] + pr + 1 bisect.insort(a1, pr) return mm # # O(n^2) # Sum = 0 # n = len(a) # for i in range(1, n + 1): # tmpSum = sum(a[:i]) # Sum += tmpSum # for j in range(0, n - i): # tmpSum = tmpSum - a[j] + a[j + i] # Sum += tmpSum # return Sum if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') arr_count = int(input().strip()) arr = [] for _ in range(arr_count): arr_item = int(input().strip()) arr.append(arr_item) result = subarraySum(arr) print(result) # fptr.write(str(result) + '\n') # fptr.close()
true
4839463635566a8143f0a073c02d650943a31910
Python
JRLi/untitled
/GDC/aaa.py
UTF-8
2,528
2.609375
3
[]
no_license
#!/usr/bin/env python import pandas as pd import numpy as np import os ''''a = {} b = set() print(type(a), type(b)) a = {1, 3, 4} b = {1, 4 ,5} print(type(a)) print(a.union(b)) d = a.intersection(b) print(a) a.update(b) print(a) a = [1, 2, 3] a.append('5') print(a) print(b) # return None to b print('xxxxx') a = 'abcde' b = a[::-1] a = a.replace('a', 'e').replace('e', 'c').replace('c', 't') print(b) print(a) ab = [] aa = ['1','2','3','50','4'] for i in range(1,len(aa)): if int(aa[i]) - int(aa[i-1]) ==1: ab.append(aa[i]) print(ab) ''''' seq_string = 'ACTGatcgnN' seq_r_string = seq_string[::-1] complement_dict = {'a':'t','t':'a','c':'g','g':'c','A':'T','T':'A','C':'G','G':'C'} print('\t', '[INFO]',seq_r_string) seq_rc_list =[] for a in seq_r_string: seq_rc_list.append(complement_dict.get(a)) if a == 'A': seq_rc_list.append('T') elif a == 'C': seq_rc_list.append('G') elif a == 'T': seq_rc_list.append('A') elif a == 'G': seq_rc_list.append('C') elif a == 'a': seq_rc_list.append('t') else: seq_rc_list.append(a) print(seq_rc_list) #seqRC = "".join(seq_rc) seq_rc_string = '' for a in seq_rc_list: seq_rc_string += '1' print(seq_rc_string) st1 = '445\t333\tfff' lf = st1.split('\t') a, b, c = lf print(a, b, c) ''' cell_line = 'JURKAT' df1 = pd.read_table('GSE70138_Level4_ZSVCINF_n115209x22268_20151231_annotation.txt', index_col=0) print('df1_shape:', df1.shape) print('ii') ii = np.where(df1.values == cell_line)[1] print(ii) jj = np.where(df1.values == cell_line) print('jj') print(jj) ''' def openDF(in_path, direct = 'f'): fpath, fname = os.path.split(in_path) fbase, fext = os.path.splitext(fname) df = pd.read_csv(in_path, index_col=0) if fext == '.csv' else pd.read_table(in_path, index_col=0) if direct == 't': df = df.transpose() return df, fbase df1, df_base = openDF('D://Project/drs/forTest9x7.txt') avg = df1.mean() std = df1.std() minV = df1.min() maxV = df1.max() print(avg) print(std) print(minV) print(maxV) df2 = pd.DataFrame(columns=['avg', 'std', 'max', 'min']) df2['avg'] = avg df2['std'] = std df2['max'] = maxV df2['min'] = minV print(df2) df1 = pd.read_table('D://Project/drs/GDC/bb.txt', index_col=0, header=None, names=['bb']) print(df1) df2 = pd.read_table('D://Project/drs/GDC/aa.txt', index_col=0, header=None, names=['aa']) df3 = pd.DataFrame() df3['bb'] = df1['bb'] df3['aa'] = df2['aa'] #df3.rename_axis('aaaa') print(df3) print(df3.shape) print(df3.index)
true
6e563a3912819d5be887d1306f636ccf86ed05d9
Python
ddelgadoJS/KenKen
/kenken.py
UTF-8
223,254
2.515625
3
[ "MIT" ]
permissive
#José Daniel Delgado Segura #2015001500 #21-05-2015 #Programa 2 - Pasatiempo Aritmético KenKen #————————————————————————————————————————————————————————————————————————centrar————————————————————————————————————————————————————————————————————————# def centrar(ventana): #Centra la ventana que se abre. Todas las WIN la utilizan. Tomada de internet. ventana.update_idletasks() w=ventana.winfo_width() h=ventana.winfo_height() extraW=ventana.winfo_screenwidth()-w extraH=ventana.winfo_screenheight()-h ventana.geometry("%dx%d%+d%+d" % (w,h,extraW/2,extraH/2)) #——————————————————————————————————————————————————————————————————————Fin centrar——————————————————————————————————————————————————————————————————————# #——————————————————————————————————————————————————————————————————————Ventana Jugar————————————————————————————————————————————————————————————————————# def FN_WIN_jugar (): s = 0 m = 0 h = 0 WIN_menú.withdraw() WIN_configurar.withdraw() WIN_validar_completo.withdraw() global WIN_jugar global LBL_segundos global BTN_pausa global BTN_iniciar global BTN_menú_jugar global BTN_validar global BTN_reiniciar global BTN_terminar global TXT_nombre global nombre global default_horas global default_minutos global default_segundos WIN_jugar = Toplevel() LBL_segundos = Label BTN_menú_jugar = BTN_pausa = BTN_iniciar = BTN_validar = BTN_reiniciar = BTN_terminar = Button TXT_nombre = Entry nombre = StringVar() nombre.set("Nombre") WIN_jugar.protocol("WM_DELETE_WINDOW", lambda : WIN_jugar.destroy()) WIN_jugar.geometry("1000x600") WIN_jugar.title("Juego KENKEN") WIN_jugar.resizable(width = FALSE, height = FALSE) centrar (WIN_jugar) cuadrícula() TXT_nombre = Entry(WIN_jugar, textvariable = nombre, width = 20, font = ("Helvetica Neue", 15, "bold")) TXT_nombre.place(x = 760, y = 120) LBL_título = Label(WIN_jugar, text = "KenKen",font = ("Helvetica Neue", 20, "bold")).place(x = 320, y = 10) LBL_horas = Label(WIN_jugar, text = "Horas", font = ("Helvetica Neue", 13)).place(x = 768, y = 20) LBL_minutos = Label(WIN_jugar, text = "Minutos", font = ("Helvetica Neue", 13)).place(x = 825, y = 20) LBL_segundos = Label(WIN_jugar, text = "Segundos", font = ("Helvetica Neue", 13)).place(x = 891, y = 20) LBL_iniciar = Label(WIN_jugar, text = "Iniciar", font = ("Helvetica Neue", 13, "bold")).place(x = 782, y = 233) LBL_terminar = Label(WIN_jugar, text = "Terminar", font = ("Helvetica Neue", 13, "bold")).place(x = 880, y = 233) LBL_otro = Label(WIN_jugar, text = "Otro", font = ("Helvetica Neue", 13, "bold")).place(x = 787, y = 343) LBL_reiniciar = Label(WIN_jugar, text = "Reiniciar", font = ("Helvetica Neue", 13, "bold")).place(x = 886, y = 343) LBL_validar = Label(WIN_jugar, text = "Validar", font = ("Helvetica Neue", 13, "bold")) LBL_validar.place(x = 780, y = 453) LBL_top10 = Label(WIN_jugar, text = "Top 10", font = ("Helvetica Neue", 13, "bold")) LBL_top10.place(x = 889, y = 453) LBL_menú = Label(WIN_jugar, text = "Menú", font = ("Helvetica Neue", 13, "bold")) LBL_menú.place(x = 842, y = 571) BTN_iniciar = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_iniciar, height = 65, width = 65, borderwidth = 0, command = FN_iniciar) BTN_iniciar.place (x = 775, y = 165) BTN_terminar = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_terminar, height = 65, width = 65, borderwidth = 0, command = FN_terminar) BTN_terminar.place (x = 885, y = 165) BTN_otro = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_otro, height = 65, width = 65, borderwidth = 0, command = lambda : FN_otro("otro")) BTN_otro.place (x = 775, y = 275) BTN_reiniciar = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_reiniciar, height = 65, width = 65, borderwidth = 0, command = FN_reiniciar) BTN_reiniciar.place (x = 885, y = 275) BTN_validar = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_validar, height = 65, width = 65, borderwidth = 0, command = FN_validar) BTN_validar.place (x = 775, y = 385) BTN_top10 = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_top10, height = 65, width = 65, borderwidth = 0, command = WIN_top10) BTN_top10.place (x = 885, y = 385) BTN_menú_jugar = Button(WIN_jugar, image = IMG_BTN_menú, height = 65, width = 65, borderwidth = 0, command = menú_volver) BTN_menú_jugar.place (x = 832, y = 495) if validar_completo_respuesta.get() == 1: BTN_validar_completo = Button(WIN_jugar, image = IMG_BTN_WIN_validar_completo, height = 65, width = 65, borderwidth = 0, command = FN_validar_completo) BTN_validar_completo.place (x = 885, y = 385) BTN_menú_jugar.place (x = 775, y = 495) BTN_top10.place (x = 885, y = 495) LBL_validar_completo = Label(WIN_jugar, text = "Validar\ncompleto", font = ("Helvetica Neue", 13, "bold")) LBL_validar_completo.place(x = 882, y = 453) LBL_validar.place(x = 780, y = 453) LBL_top10.place(x = 889, y = 562) LBL_menú.place(x = 785, y = 562) if int(reloj_selec.get()) == 0: LBL_horas = Label(WIN_jugar, text = "Horas", font = ("Helvetica Neue", 13)).place(x = 768, y = 20) LBL_minutos = Label(WIN_jugar, text = "Minutos", font = ("Helvetica Neue", 13)).place(x = 825, y = 20) LBL_segundos = Label(WIN_jugar, text = "Segundos", font = ("Helvetica Neue", 13)).place(x = 891, y = 20) time.sleep(0.40) LBL_clock = Label(WIN_jugar, text = " "+"0"+str(h) + " " + "0"+str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) BTN_pausa = Button(WIN_jugar, height = 1, width = 5, text = "Pausa", borderwidth = 1, font = ("Helvetica Neue", 16), command = FN_pausa, state = DISABLED) BTN_pausa.place (x = 830, y = 75) elif int(reloj_selec.get()) == 2: h = int(default_horas.get()) m = int(default_minutos.get()) s = int(default_segundos.get()) default_horas.set(h) default_minutos.set(m) default_segundos.set(s) SPNBX_horas = Spinbox(WIN_jugar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 3, textvariable = default_horas, wrap = True).place(x = 775, y = 44) SPNBX_minutos = Spinbox(WIN_jugar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 59, textvariable = default_minutos, wrap = True).place(x = 840, y = 44) SPNBX_segundos = Spinbox(WIN_jugar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 59, textvariable = default_segundos, wrap = True).place(x = 915, y = 44) BTN_pausa = Button(WIN_jugar, height = 1, width = 5, text = "Pausa", borderwidth = 1, font = ("Helvetica Neue", 16), command = FN_pausa, state = DISABLED) BTN_pausa.place (x = 830, y = 75) #———————————————————————————————————————————————————————————————Clock——————————————————————————————————————————————————————————————# def FN_THRDs (): terminar = False THRD_FN_WIN_jugar = Thread (target = FN_WIN_jugar, args = ()) THRD_FN_WIN_jugar.start() def FN_iniciar (): global iniciado iniciado = True global terminar terminar = False BTN_menú_jugar.config(state = DISABLED) if nombre.get() == "Nombre" or len(nombre.get()) < 3 or len(nombre.get()) > 30: messagebox.showerror("Error en el nombre", "Debe ingresar un nombre correcto antes de iniciar (3 a 40 caracteres).") return BTN_pausa.config (state = NORMAL) BTN_iniciar.config(state = DISABLED) TXT_nombre.config(state = DISABLED) sel = nivel_selec.get() if sel == 33: lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for i in lista_btn: i.config(state = NORMAL) elif sel == 44: lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_btn: i.config(state = NORMAL) elif sel == 55: lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_btn: i.config(state = NORMAL) elif sel == 0: lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_btn: i.config(state = NORMAL) elif sel == 77: lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_btn: i.config(state = NORMAL) elif sel == 88: lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_btn: i.config(state = NORMAL) elif sel == 99: lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for i in lista_btn: i.config(state = NORMAL) if int(reloj_selec.get()) == 0: THRD_clock = Thread (target = clock, args = ()) THRD_clock.start() elif int(reloj_selec.get()) == 2: THRD_FN_timer = Thread(target = FN_timer, args = ()) THRD_FN_timer.start() def FN_pausa (): global pausa if pausa == False: pausa = True else: pausa = False def clock(): global h global m global s global clock_estado clock_estado = True if default_horas.get() == "": h = 0 if default_minutos.get() == "": m = 0 if default_segundos.get() == "": s = 0 else: h = int(default_horas.get()) m = int(default_minutos.get()) s = int(default_segundos.get()) while h <= 23: if terminar == True: LBL_clock = Label(WIN_jugar, text = " "+"0"+ "0" + " " + "0"+ "0" + " " + "0"+ "0" +" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) return if pausa == False: #Comprueba que no haya una señal de pausa. Si es False no lo hay. time.sleep(0.99) s += 1 if m == 59 and s == 60: h += 1 m = 0 s = 0 elif s == 60: m += 1 s = 0 if s < 10 and m < 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + "0"+str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s >= 10 and m < 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + "0"+str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s >= 10 and m >= 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m < 10 and h >= 10: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + "0"+str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m >= 10 and h >= 10: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m >= 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) else: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) if h == 23 and m == 59 and s == 59: break messagebox.showinfo("Fin","Fin del juego, límite de reloj alcanzado.") #—————————————————————————————————————————————————————————————Fin Clock————————————————————————————————————————————————————————————# #————————————————————————————————————————————————————————————Cuadrícula————————————————————————————————————————————————————————————# def cuadrícula(): sel = nivel_selec.get() global BTN_00 global BTN_01 global BTN_02 global BTN_03 global BTN_04 global BTN_05 global BTN_06 global BTN_07 global BTN_08 global BTN_10 global BTN_11 global BTN_12 global BTN_13 global BTN_14 global BTN_15 global BTN_16 global BTN_17 global BTN_18 global BTN_20 global BTN_21 global BTN_22 global BTN_23 global BTN_24 global BTN_25 global BTN_26 global BTN_27 global BTN_28 global BTN_30 global BTN_31 global BTN_32 global BTN_33 global BTN_34 global BTN_35 global BTN_36 global BTN_37 global BTN_38 global BTN_40 global BTN_41 global BTN_42 global BTN_43 global BTN_44 global BTN_45 global BTN_46 global BTN_47 global BTN_48 global BTN_50 global BTN_51 global BTN_52 global BTN_53 global BTN_54 global BTN_55 global BTN_56 global BTN_57 global BTN_58 global BTN_60 global BTN_61 global BTN_62 global BTN_63 global BTN_64 global BTN_65 global BTN_66 global BTN_67 global BTN_68 global BTN_70 global BTN_71 global BTN_72 global BTN_73 global BTN_74 global BTN_75 global BTN_76 global BTN_77 global BTN_78 global BTN_80 global BTN_81 global BTN_82 global BTN_83 global BTN_84 global BTN_85 global BTN_86 global BTN_87 global BTN_88 global BTN_num1 global BTN_num2 global BTN_num3 global BTN_num4 global BTN_num5 global BTN_num6 global BTN_num7 global BTN_num8 global BTN_num9 global BTN_borrar BTN_00=BTN_01=BTN_02=BTN_03=BTN_04=BTN_05=BTN_06=BTN_07=BTN_08=BTN_10=BTN_11=BTN_12=BTN_13=BTN_14=BTN_15=BTN_16=BTN_17=BTN_18=BTN_20=BTN_21=BTN_22=BTN_23=BTN_24=BTN_25=BTN_26=BTN_27=BTN_28=BTN_30=BTN_31=BTN_32=BTN_33=BTN_34=BTN_35=BTN_36=BTN_37=BTN_38=BTN_40=BTN_41=BTN_42=BTN_43=BTN_44=BTN_45=BTN_46=BTN_47=BTN_48=BTN_50=BTN_51=BTN_52=BTN_53=BTN_54=BTN_55=BTN_56=BTN_57=BTN_58 = Button BTN_60=BTN_61=BTN_62=BTN_63=BTN_64=BTN_65=BTN_66=BTN_67=BTN_68=BTN_70=BTN_71=BTN_72=BTN_73=BTN_74=BTN_75=BTN_76=BTN_77=BTN_78=BTN_80=BTN_81=BTN_82=BTN_83=BTN_84=BTN_85=BTN_86=BTN_87=BTN_88=BTN_90=BTN_91=BTN_92=BTN_93=BTN_94=BTN_95=BTN_96=BTN_97=BTN_98=BTN_num1=BTN_num2=BTN_num3=BTN_num4=BTN_num5=BTN_num6=BTN_num7=BTN_num8=BTN_num9=BTN_borrar = Button BTN_num1 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num1, borderwidth = 0, command = lambda : FN_add("1")) BTN_num2 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num2, borderwidth = 0, command = lambda : FN_add("2")) BTN_num3 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num3, borderwidth = 0, command = lambda : FN_add("3")) BTN_num4 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num4, borderwidth = 0, command = lambda : FN_add("4")) BTN_num5 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num5, borderwidth = 0, command = lambda : FN_add("5")) BTN_num6 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num6, borderwidth = 0, command = lambda : FN_add("6")) BTN_num7 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num7, borderwidth = 0, command = lambda : FN_add("7")) BTN_num8 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num8, borderwidth = 0, command = lambda : FN_add("8")) BTN_num9 = Button(WIN_jugar, height = 50, width = 50, image = IMG_BTN_num9, borderwidth = 0, command = lambda : FN_add("9")) BTN_borrar = Button(WIN_jugar, image = IMG_BTN_WIN_jugar_borrar, height = 65, width = 65, borderwidth = 0, command = FN_borrar) if sel == 33 or sel == 44 or sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: BTN_23 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("23"), state = DISABLED) BTN_23.place (x = 285, y = 164) BTN_24 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("24"), state = DISABLED) BTN_24.place (x = 345, y = 164) BTN_25 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("25"), state = DISABLED) BTN_25.place (x = 405, y = 164) BTN_33 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("33"), state = DISABLED) BTN_33.place (x = 285, y = 216) BTN_34 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("34"), state = DISABLED) BTN_34.place (x = 345, y = 216) BTN_35 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("35"), state = DISABLED) BTN_35.place (x = 405, y = 216) BTN_43 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("43"), state = DISABLED) BTN_43.place (x = 285, y = 268) BTN_44 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("44"), state = DISABLED) BTN_44.place (x = 345, y = 268) BTN_45 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("45"), state = DISABLED) BTN_45.place (x = 405, y = 268) if lado_selec.get() == 0: BTN_num1.place (x = 680, y = 30) BTN_num2.place (x = 680, y = 90) BTN_num3.place (x = 680, y = 150) BTN_borrar.place (x = 677, y = 220) else: BTN_num1.place (x = 20, y = 30) BTN_num2.place (x = 20, y = 90) BTN_num3.place (x = 20, y = 150) BTN_borrar.place (x = 17, y = 220) if sel == 44 or sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: BTN_22 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("22"), state = DISABLED) BTN_22.place (x = 225, y = 164) BTN_32 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("32"), state = DISABLED) BTN_32.place (x = 225, y = 216) BTN_42 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("42"), state = DISABLED) BTN_42.place (x = 225, y = 268) BTN_52 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("52"), state = DISABLED) BTN_52.place (x = 225, y = 320) BTN_53 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("53"), state = DISABLED) BTN_53.place (x = 285, y = 320) BTN_54 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("54"), state = DISABLED) BTN_54.place (x = 345, y = 320) BTN_55 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("55"), state = DISABLED) BTN_55.place (x = 405, y = 320) if lado_selec.get() == 0: BTN_num4.place (x = 680, y = 210) BTN_borrar.place (x = 677, y = 280) else: BTN_num4.place (x = 20, y = 210) BTN_borrar.place (x = 17, y = 280) if sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: BTN_26 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("26"), state = DISABLED) BTN_26.place (x = 465, y = 164) BTN_36 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("36"), state = DISABLED) BTN_36.place (x = 465, y = 216) BTN_46 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("46"), state = DISABLED) BTN_46.place (x = 465, y = 268) BTN_56 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("56"), state = DISABLED) BTN_56.place (x = 465, y = 320) BTN_62 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("62"), state = DISABLED) BTN_62.place (x = 225, y = 372) BTN_63 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("63"), state = DISABLED) BTN_63.place (x = 285, y = 372) BTN_64 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("64"), state = DISABLED) BTN_64.place (x = 345, y = 372) BTN_65 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("65"), state = DISABLED) BTN_65.place (x = 405, y = 372) BTN_66 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("66"), state = DISABLED) BTN_66.place (x = 465, y = 372) if lado_selec.get() == 0: BTN_num5.place (x = 680, y = 270) BTN_borrar.place (x = 677, y = 340) else: BTN_num5.place (x = 20, y = 270) BTN_borrar.place (x = 17, y = 340) if sel == 0 or sel == 77 or sel == 88 or sel == 99: BTN_11 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("11"), state = DISABLED) BTN_11.place (x = 165, y = 112) BTN_12 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("12"), state = DISABLED) BTN_12.place (x = 225, y = 112) BTN_13 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("13"), state = DISABLED) BTN_13.place (x = 285, y = 112) BTN_14 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("14"), state = DISABLED) BTN_14.place (x = 345, y = 112) BTN_15 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("15"), state = DISABLED) BTN_15.place (x = 405, y = 112) BTN_16 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("16"), state = DISABLED) BTN_16.place (x = 465, y = 112) BTN_21 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("21"), state = DISABLED) BTN_21.place (x = 165, y = 164) BTN_31 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("31"), state = DISABLED) BTN_31.place (x = 165, y = 216) BTN_41 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("41"), state = DISABLED) BTN_41.place (x = 165, y = 268) BTN_51 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("51"), state = DISABLED) BTN_51.place (x = 165, y = 320) BTN_61 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("61"), state = DISABLED) BTN_61.place (x = 165, y = 372) if lado_selec.get() == 0: BTN_num6.place (x = 680, y = 330) BTN_borrar.place (x = 677, y = 400) else: BTN_num6.place (x = 20, y = 330) BTN_borrar.place (x = 17, y = 400) if sel == 77 or sel == 88 or sel == 99: BTN_17 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("17"), state = DISABLED) BTN_17.place (x = 525, y = 112) BTN_27 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("27"), state = DISABLED) BTN_27.place (x = 525, y = 164) BTN_37 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("37"), state = DISABLED) BTN_37.place (x = 525, y = 216) BTN_47 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("47"), state = DISABLED) BTN_47.place (x = 525, y = 268) BTN_57 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("57"), state = DISABLED) BTN_57.place (x = 525, y = 320) BTN_67 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("67"), state = DISABLED) BTN_67.place (x = 525, y = 372) BTN_71 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("71"), state = DISABLED) BTN_71.place (x = 165, y = 424) BTN_72 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("72"), state = DISABLED) BTN_72.place (x = 225, y = 424) BTN_73 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("73"), state = DISABLED) BTN_73.place (x = 285, y = 424) BTN_74 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("74"), state = DISABLED) BTN_74.place (x = 345, y = 424) BTN_75 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("75"), state = DISABLED) BTN_75.place (x = 405, y = 424) BTN_76 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("76"), state = DISABLED) BTN_76.place (x = 465, y = 424) BTN_77 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("77"), state = DISABLED) BTN_77.place (x = 525, y = 424) if lado_selec.get() == 0: BTN_num7.place (x = 680, y = 390) BTN_borrar.place (x = 677, y = 460) else: BTN_num7.place (x = 20, y = 390) BTN_borrar.place (x = 17, y = 460) if sel == 88 or sel == 99: BTN_00 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("00"), state = DISABLED) BTN_00.place (x = 105, y = 60) BTN_01 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("01"), state = DISABLED) BTN_01.place (x = 165, y = 60) BTN_02 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("02"), state = DISABLED) BTN_02.place (x = 225, y = 60) BTN_03 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("03"), state = DISABLED) BTN_03.place (x = 285, y = 60) BTN_04 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("04"), state = DISABLED) BTN_04.place (x = 345, y = 60) BTN_05 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("05"), state = DISABLED) BTN_05.place (x = 405, y = 60) BTN_06 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("06"), state = DISABLED) BTN_06.place (x = 465, y = 60) BTN_07 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("07"), state = DISABLED) BTN_07.place (x = 525, y = 60) BTN_10 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("10"), state = DISABLED) BTN_10.place (x = 105, y = 112) BTN_20 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("20"), state = DISABLED) BTN_20.place (x = 105, y = 164) BTN_30 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("30"), state = DISABLED) BTN_30.place (x = 105, y = 216) BTN_40 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("40"), state = DISABLED) BTN_40.place (x = 105, y = 268) BTN_50 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("50"), state = DISABLED) BTN_50.place (x = 105, y = 320) BTN_60 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("60"), state = DISABLED) BTN_60.place (x = 105, y = 372) BTN_70 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("70"), state = DISABLED) BTN_70.place (x = 105, y = 424) if lado_selec.get() == 0: BTN_num8.place (x = 680, y = 450) BTN_borrar.place (x = 677, y = 520) else: BTN_num8.place (x = 20, y = 450) BTN_borrar.place (x = 17, y = 520) if sel == 99: BTN_08 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("08"), state = DISABLED) BTN_08.place (x = 585, y = 60) BTN_18 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("18"), state = DISABLED) BTN_18.place (x = 585, y = 112) BTN_28 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("28"), state = DISABLED) BTN_28.place (x = 585, y = 164) BTN_38 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("38"), state = DISABLED) BTN_38.place (x = 585, y = 216) BTN_48 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("48"), state = DISABLED) BTN_48.place (x = 585, y = 268) BTN_58 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("58"), state = DISABLED) BTN_58.place (x = 585, y = 320) BTN_68 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("68"), state = DISABLED) BTN_68.place (x = 585, y = 372) BTN_78 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("78"), state = DISABLED) BTN_78.place (x = 585, y = 424) BTN_80 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("80"), state = DISABLED) BTN_80.place (x = 105, y = 476) BTN_81 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("81"), state = DISABLED) BTN_81.place (x = 165, y = 476) BTN_82 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("82"), state = DISABLED) BTN_82.place (x = 225, y = 476) BTN_83 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = ("Helvetica Neue", 12, "bold"), borderwidth = 2, command = lambda : FN_BTNS("83"), state = DISABLED) BTN_83.place (x = 285, y = 476) BTN_84 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("84"), state = DISABLED) BTN_84.place (x = 345, y = 476) BTN_85 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("85"), state = DISABLED) BTN_85.place (x = 405, y = 476) BTN_86 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("86"), state = DISABLED) BTN_86.place (x = 465, y = 476) BTN_87 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("87"), state = DISABLED) BTN_87.place (x = 525, y = 476) BTN_88 = Button(WIN_jugar, height = 2, width = 5, bg = "white", font = (("Helvetica Neue", 12, "bold")), borderwidth = 2, command = lambda : FN_BTNS("88"), state = DISABLED) BTN_88.place (x = 585, y = 476) if lado_selec.get() == 0: BTN_num9.place (x = 680, y = 510) BTN_borrar.place (x = 585, y = 530) else: BTN_num9.place (x = 20, y = 510) BTN_borrar.place (x = 100, y = 530) cuadrícula_color() def FN_juegos_probables(índice, lista_completa): global elegido global juegos_probables global juego_num if juego_num == 0: juegos_probables = [] contador = 0 for i in lista_completa[índice]: juegos_probables.append(contador) contador += 1 elegido = random.choice(juegos_probables) juegos_probables.remove(elegido) elif otro_juego == True: elegido = random.choice(juegos_probables) juegos_probables.remove(elegido) return elegido def cuadrícula_color(): TXT_cuadrículas = open("kenken_juegos.dat","r") TXT_cuadrículas_read = TXT_cuadrículas.read() string = "[" lista_completa = [] lista_nivel = [] lista_juego = [] contador = 0 contador_nivel = 0 TXT_operaciones = open("Operaciones.txt","r") TXT_operaciones_leer = TXT_operaciones.read() string2 = "[" lista_completa2 = [] lista_nivel2 = [] contador_nivel2 = 0 global juego_num global lst_juego_validar global lst_validar global lst_operaciones global juego_num global últ_btn global lst_colores global otro_juego lst_colores = ["HotPink", "BlueViolet", "Sienna", "DarkGreen", "DarkMagenta", "DarkKhaki", "MediumSlateBlue", "SeaGreen", "LightSlateGrey", "Indigo", "Teal", "Olive", "LightSalmon", "Lime", "Orchid", "ForestGreen", "Gold", "MediumAquaMarine", "CadetBlue", "DarkGrey", "MediumVioletRed", "Magenta", "Plum", "Navy", "SpringGreen", "SkyBlue", "DarkOrange", "SandyBrown", "MediumBlue", "SaddleBrown", "RoyalBlue", "Tomato", "Brown", "RosyBrown", "SteelBlue", "BurlyWood", "DodgerBlue", "OrangeRed", "Khaki", "GreenYellow"] índ_color = 0 contador_lst_colores = 0 sel = nivel_selec.get() contador_for = 0 if sel == 33: índice = 0 elif sel == 44: índice = 1 elif sel == 55: índice = 2 elif sel == 0: índice = 3 elif sel == 77: índice = 4 elif sel == 88: índice = 5 elif sel == 99: índice = 6 for i in TXT_cuadrículas_read: if i != "[" and i != "]": string += i contador_control = 1 elif i == "]" and contador_control != 0: string += i lista_nivel.append(eval(string)) string = "[" contador_nivel += 1 if contador_nivel == 4: lista_completa.append(lista_nivel) lista_nivel = [] contador_nivel = 0 contador_control = 0 if juego_num == 0 or otro_juego == True: elegido = FN_juegos_probables(índice, lista_completa) lst_juego_validar = lista_completa[índice][elegido] lst_validar = [] lst_temporal = [] for r in lista_completa[índice][elegido]: for z in r: lst_temporal.append("") lst_validar.append(lst_temporal) lst_temporal = [] for y in TXT_operaciones_leer: if y != "[" and y != "]": string2 += y contador_control = 1 elif y == "]" and contador_control != 0: string2 += y lista_nivel2.append(eval(string2)) string2 = "[" contador_nivel2 += 1 if contador_nivel2 == 4: lista_completa2.append(lista_nivel2) lista_nivel2 = [] contador_nivel2 = 0 contador_control = 0 lst_operaciones = lista_completa2[índice][elegido] elif juego_num != 0 and pausa == True: FN_pausa () for j in lst_juego_validar: contador_for += 1 if len(lst_colores) - índ_color == 1: índ_color = 0 for f in j: if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(f) == p and str(f) != but_press: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = lst_colores[índ_color], relief = RAISED) if juego_num == 0 and contador_for == 1: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 elif contador_for == 1 and otro_juego == True: operaciones(str(f), lst_colores[índ_color], lst_operaciones[contador_lst_colores]) contador_lst_colores += 1 contador_for = 0 índ_color += 1 contador_lst_colores = 0 juego_num += 1 def operaciones(casilla, color, operación): sel = nivel_selec.get() #operación = "1+" if sel == 33 or sel == 44 or sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: if casilla == "23": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 165) elif casilla == "24": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 165) elif casilla == "25": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 165) elif casilla == "33": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 217) elif casilla == "34": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 217) elif casilla == "35": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 217) elif casilla == "43": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 269) elif casilla == "44": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 269) elif casilla == "45": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 269) if sel == 44 or sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: if casilla == "22": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 165) elif casilla == "32": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 217) elif casilla == "42": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 269) elif casilla == "52": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 321) elif casilla == "53": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 321) elif casilla == "54": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 321) elif casilla == "55": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 321) if sel == 55 or sel == 0 or sel == 77 or sel == 88 or sel == 99: if casilla == "26": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 165) elif casilla == "36": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 217) elif casilla == "46": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 269) elif casilla == "56": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 321) elif casilla == "62": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 373) elif casilla == "63": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 373) elif casilla == "64": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 373) elif casilla == "65": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 373) elif casilla == "66": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 373) if sel == 0 or sel == 77 or sel == 88 or sel == 99: if casilla == "11": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 113) elif casilla == "12": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 113) elif casilla == "13": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 113) elif casilla == "14": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 113) elif casilla == "15": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 113) elif casilla == "16": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 113) elif casilla == "21": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 165) elif casilla == "31": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 217) elif casilla == "41": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 269) elif casilla == "51": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 321) elif casilla == "61": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 373) if sel == 77 or sel == 88 or sel == 99: if casilla == "17": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 113) elif casilla == "27": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 165) elif casilla == "37": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 217) elif casilla == "47": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 269) elif casilla == "57": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 321) elif casilla == "67": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 373) elif casilla == "71": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 425) elif casilla == "72": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 425) elif casilla == "73": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 425) elif casilla == "74": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 425) elif casilla == "75": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 425) elif casilla == "76": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 425) elif casilla == "77": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 425) if sel == 88 or sel == 99: if casilla == "00": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 61) elif casilla == "01": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 61) elif casilla == "02": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 61) elif casilla == "03": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 61) elif casilla == "04": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 61) elif casilla == "05": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 61) elif casilla == "06": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 61) elif casilla == "07": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 61) elif casilla == "10": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 113) elif casilla == "20": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 165) elif casilla == "30": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 217) elif casilla == "40": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 269) elif casilla == "50": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 321) elif casilla == "60": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 373) elif casilla == "70": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 425) if sel == 99: if casilla == "08": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 61) elif casilla == "18": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 113) elif casilla == "28": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 165) elif casilla == "38": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 217) elif casilla == "48": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 269) elif casilla == "58": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 321) elif casilla == "68": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 373) elif casilla == "78": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 425) elif casilla == "80": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 106, y = 477) elif casilla == "81": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 166, y = 477) elif casilla == "82": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 226, y = 477) elif casilla == "83": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 286, y = 477) elif casilla == "84": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 346, y = 477) elif casilla == "85": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 406, y = 477) elif casilla == "86": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 466, y = 477) elif casilla == "87": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 526, y = 477) elif casilla == "88": LBL_operación = Label(WIN_jugar, text = operación, font = ("Helvetica Neue", 8, "bold"), bg = color, fg = "White").place(x = 586, y = 477) def validar (btn, num): global lst_validar lst_juego_validar índ_validar_lst_juego = 0 if num != "*": for i in lst_juego_validar: for j in i: if str(j) == str(btn): x = lst_juego_validar[índ_validar_lst_juego].index(j) lst_temporal_validar = lst_validar[índ_validar_lst_juego] lst_temporal_validar.insert(x, int(num)) lst_temporal_validar.pop(x + 1) return índ_validar_lst_juego += 1 else: for i in lst_juego_validar: for j in i: if str(j) == str(btn): x = lst_juego_validar[índ_validar_lst_juego].index(j) lst_temporal_validar = lst_validar[índ_validar_lst_juego] lst_temporal_validar.pop(x) lst_temporal_validar.insert(x, "") return índ_validar_lst_juego += 1 def FN_validar (): global iniciado global registrado global terminar if iniciado == False: messagebox.showerror("Error", "El juego no se ha iniciado.") return contador = 0 índ_operación = 0 lst_operación = [] r = 0 msg_error = False msg_terminar = True sel = nivel_selec.get() for i in lst_validar: #Inicia validación aritmética. contador = 0 for j in i: if j == "": contador = 1 lst_operación = [] break lst_operación.append(j) if contador == 0 and lst_operación != []: índice_validar = lst_validar[índ_operación] if lst_operaciones[índ_operación][-1] == "+": r_correcto = lst_operaciones[índ_operación][:-1] for t in lst_operación: r += t lst_operación = [] if int(r) != int(r_correcto): for j in lst_juego_validar[índ_operación]: if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True r = 0 elif lst_operaciones[índ_operación][-1] == "-": r_correcto = lst_operaciones[índ_operación][:-1] r = lst_operación[0] for t in lst_operación[1:]: r -= t lst_operación = [] if abs(r) != int(r_correcto): for j in lst_juego_validar[índ_operación]: if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True r = 0 elif lst_operaciones[índ_operación][-1] == "/": r_correcto = lst_operaciones[índ_operación][:-1] if lst_operación[0] > lst_operación[1]: r = lst_operación[0] // lst_operación[1] else: r = lst_operación[1] // lst_operación[0] lst_operación = [] if abs(r) != int(r_correcto): for j in lst_juego_validar[índ_operación]: if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True r = 0 elif lst_operaciones[índ_operación][-1] == "x": r = 1 r_correcto = lst_operaciones[índ_operación][:-1] for t in lst_operación: r = r * t lst_operación = [] if int(r) != int(r_correcto): for j in lst_juego_validar[índ_operación]: if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(j) == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True r = 0 else: lst_operación = [] contador = 0 índ_operación += 1 contador_fila = 0 lst_fila0 = ["00", "01", "02", "03", "04", "05", "06", "07", "08"] lst_fila0_validar = ["", "", "", "", "", "", "", "", ""] lst_fila1 = ["10", "11", "12", "13", "14", "15", "16", "17", "18"] lst_fila1_validar = ["", "", "", "", "", "", "", "", ""] lst_fila2 = ["20", "21", "22", "23", "24", "25", "26", "27", "28"] lst_fila2_validar = ["", "", "", "", "", "", "", "", ""] lst_fila3 = ["30", "31", "32", "33", "34", "35", "36", "37", "38"] lst_fila3_validar = ["", "", "", "", "", "", "", "", ""] lst_fila4 = ["40", "41", "42", "43", "44", "45", "46", "47", "48"] lst_fila4_validar = ["", "", "", "", "", "", "", "", ""] lst_fila5 = ["50", "51", "52", "53", "54", "55", "56", "57", "58"] lst_fila5_validar = ["", "", "", "", "", "", "", "", ""] lst_fila6 = ["60", "61", "62", "63", "64", "65", "66", "67", "68"] lst_fila6_validar = ["", "", "", "", "", "", "", "", ""] lst_fila7 = ["70", "71", "72", "73", "74", "75", "76", "77", "78"] lst_fila7_validar = ["", "", "", "", "", "", "", "", ""] lst_fila8 = ["80", "81", "82", "83", "84", "85", "86", "87", "88"] lst_fila8_validar = ["", "", "", "", "", "", "", "", ""] lst_columna0 = ["00", "10", "20", "30", "40", "50", "60", "70", "80"] lst_columna0_validar = ["", "", "", "", "", "", "", "", ""] lst_columna1 = ["01", "11", "21", "31", "41", "51", "61", "71", "81"] lst_columna1_validar = ["", "", "", "", "", "", "", "", ""] lst_columna2 = ["02", "12", "22", "32", "42", "52", "62", "72", "82"] lst_columna2_validar = ["", "", "", "", "", "", "", "", ""] lst_columna3 = ["03", "13", "23", "33", "43", "53", "63", "73", "83"] lst_columna3_validar = ["", "", "", "", "", "", "", "", ""] lst_columna4 = ["04", "14", "24", "34", "44", "54", "64", "74", "84"] lst_columna4_validar = ["", "", "", "", "", "", "", "", ""] lst_columna5 = ["05", "15", "25", "35", "45", "55", "65", "75", "85"] lst_columna5_validar = ["", "", "", "", "", "", "", "", ""] lst_columna6 = ["06", "16", "26", "36", "46", "56", "66", "76", "86"] lst_columna6_validar = ["", "", "", "", "", "", "", "", ""] lst_columna7 = ["07", "17", "27", "37", "47", "57", "67", "77", "87"] lst_columna7_validar = ["", "", "", "", "", "", "", "", ""] lst_columna8 = ["08", "18", "28", "38", "48", "58", "68", "78", "88"] lst_columna8_validar = ["", "", "", "", "", "", "", "", ""] for b in lst_juego_validar: for s in b: if sel == 33: if str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 3 x 3. if str(s) in lst_columna3: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif sel == 44: if str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 4 x 4. if str(s) in lst_columna2: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif sel == 55: if str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) elif str(s) in lst_fila6: índ_nom = lst_fila6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila6_validar.insert(índ_nom, int(elemento)) lst_fila6_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 5 x 5. if str(s) in lst_columna2: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif str(s) in lst_columna6: índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) elif sel == 0: if str(s) in lst_fila1: índ_nom = lst_fila1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila1_validar.insert(índ_nom, int(elemento)) lst_fila1_validar.pop(índ_nom + 1) elif str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) elif str(s) in lst_fila6: índ_nom = lst_fila6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila6_validar.insert(índ_nom, int(elemento)) lst_fila6_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 6 x 6. if str(s) in lst_columna1: índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) elif str(s) in lst_columna2: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif str(s) in lst_columna6: índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) elif sel == 77: if str(s) in lst_fila1: índ_nom = lst_fila1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila1_validar.insert(índ_nom, int(elemento)) lst_fila1_validar.pop(índ_nom + 1) elif str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) elif str(s) in lst_fila6: índ_nom = lst_fila6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila6_validar.insert(índ_nom, int(elemento)) lst_fila6_validar.pop(índ_nom + 1) elif str(s) in lst_fila7: índ_nom = lst_fila7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila7_validar.insert(índ_nom, int(elemento)) lst_fila7_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 7 x 7. if str(s) in lst_columna1: índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) elif str(s) in lst_columna2: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif str(s) in lst_columna6: índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) elif str(s) in lst_columna7: índ_nom = lst_columna7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna7_validar.insert(índ_nom, int(elemento)) lst_columna7_validar.pop(índ_nom + 1) elif sel == 88: if str(s) in lst_fila0: índ_nom = lst_fila0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila0_validar.insert(índ_nom, int(elemento)) lst_fila0_validar.pop(índ_nom + 1) elif str(s) in lst_fila1: índ_nom = lst_fila1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila1_validar.insert(índ_nom, int(elemento)) lst_fila1_validar.pop(índ_nom + 1) elif str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) elif str(s) in lst_fila6: índ_nom = lst_fila6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila6_validar.insert(índ_nom, int(elemento)) lst_fila6_validar.pop(índ_nom + 1) elif str(s) in lst_fila7: índ_nom = lst_fila7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila7_validar.insert(índ_nom, int(elemento)) lst_fila7_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 8 x 8. if str(s) in lst_columna0: if str(s) == "00": índ_nom = lst_columna0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna0_validar.insert(índ_nom, int(elemento)) lst_columna0_validar.pop(índ_nom + 1) else: índ_nom = lst_columna0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna0_validar.insert(índ_nom, int(elemento)) lst_columna0_validar.pop(índ_nom + 1) elif str(s) in lst_columna1: if str(s) == "01": índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) else: índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) elif str(s) in lst_columna2: if str(s) == "02": índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) else: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: if str(s) == "03": índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) else: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: if str(s) == "04": índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) else: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: if str(s) == "05": índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) else: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif str(s) in lst_columna6: if str(s) == "06": índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) else: índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) elif str(s) in lst_columna7: if str(s) == "07": índ_nom = lst_columna7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna7_validar.insert(índ_nom, int(elemento)) lst_columna7_validar.pop(índ_nom + 1) else: índ_nom = lst_columna7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna7_validar.insert(índ_nom, int(elemento)) lst_columna7_validar.pop(índ_nom + 1) elif sel == 99: if str(s) in lst_fila0: índ_nom = lst_fila0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila0_validar.insert(índ_nom, int(elemento)) lst_fila0_validar.pop(índ_nom + 1) elif str(s) in lst_fila1: índ_nom = lst_fila1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila1_validar.insert(índ_nom, int(elemento)) lst_fila1_validar.pop(índ_nom + 1) elif str(s) in lst_fila2: índ_nom = lst_fila2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila2_validar.insert(índ_nom, int(elemento)) lst_fila2_validar.pop(índ_nom + 1) elif str(s) in lst_fila3: índ_nom = lst_fila3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila3_validar.insert(índ_nom, int(elemento)) lst_fila3_validar.pop(índ_nom + 1) elif str(s) in lst_fila4: índ_nom = lst_fila4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila4_validar.insert(índ_nom, int(elemento)) lst_fila4_validar.pop(índ_nom + 1) elif str(s) in lst_fila5: índ_nom = lst_fila5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila5_validar.insert(índ_nom, int(elemento)) lst_fila5_validar.pop(índ_nom + 1) elif str(s) in lst_fila6: índ_nom = lst_fila6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila6_validar.insert(índ_nom, int(elemento)) lst_fila6_validar.pop(índ_nom + 1) elif str(s) in lst_fila7: índ_nom = lst_fila7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila7_validar.insert(índ_nom, int(elemento)) lst_fila7_validar.pop(índ_nom + 1) elif str(s) in lst_fila8: índ_nom = lst_fila8.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_fila8_validar.insert(índ_nom, int(elemento)) lst_fila8_validar.pop(índ_nom + 1) #A continuación se agregan los valores necesarios para la validación de columnas en 8 x 8. if str(s) in lst_columna0: if str(s) == "00": índ_nom = lst_columna0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna0_validar.insert(índ_nom, int(elemento)) lst_columna0_validar.pop(índ_nom + 1) else: índ_nom = lst_columna0.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna0_validar.insert(índ_nom, int(elemento)) lst_columna0_validar.pop(índ_nom + 1) elif str(s) in lst_columna1: if str(s) == "01": índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) else: índ_nom = lst_columna1.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna1_validar.insert(índ_nom, int(elemento)) lst_columna1_validar.pop(índ_nom + 1) elif str(s) in lst_columna2: if str(s) == "02": índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) else: índ_nom = lst_columna2.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna2_validar.insert(índ_nom, int(elemento)) lst_columna2_validar.pop(índ_nom + 1) elif str(s) in lst_columna3: if str(s) == "03": índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) else: índ_nom = lst_columna3.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna3_validar.insert(índ_nom, int(elemento)) lst_columna3_validar.pop(índ_nom + 1) elif str(s) in lst_columna4: if str(s) == "04": índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) else: índ_nom = lst_columna4.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna4_validar.insert(índ_nom, int(elemento)) lst_columna4_validar.pop(índ_nom + 1) elif str(s) in lst_columna5: if str(s) == "05": índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) else: índ_nom = lst_columna5.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna5_validar.insert(índ_nom, int(elemento)) lst_columna5_validar.pop(índ_nom + 1) elif str(s) in lst_columna6: if str(s) == "06": índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) else: índ_nom = lst_columna6.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna6_validar.insert(índ_nom, int(elemento)) lst_columna6_validar.pop(índ_nom + 1) elif str(s) in lst_columna7: if str(s) == "07": índ_nom = lst_columna7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna7_validar.insert(índ_nom, int(elemento)) lst_columna7_validar.pop(índ_nom + 1) else: índ_nom = lst_columna7.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna7_validar.insert(índ_nom, int(elemento)) lst_columna7_validar.pop(índ_nom + 1) elif str(s) in lst_columna8: if str(s) == "08": índ_nom = lst_columna8.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(str(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna8_validar.insert(índ_nom, int(elemento)) lst_columna8_validar.pop(índ_nom + 1) else: índ_nom = lst_columna8.index(str(s)) índ_elemento = lst_juego_validar[contador_fila].index(int(s)) elemento = lst_validar[contador_fila][índ_elemento] if elemento != "": lst_columna8_validar.insert(índ_nom, int(elemento)) lst_columna8_validar.pop(índ_nom + 1) contador_fila += 1 contador_fila = 1 contador_columna = 1 if sel == 33: for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["23","24","25"] lista_btn = [BTN_23,BTN_24,BTN_25] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["33", "34", "35"] lista_btn = [BTN_33,BTN_34,BTN_35] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["43", "44", "45"] lista_btn = [BTN_43,BTN_44,BTN_45] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 3 x 3. contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["23","33","43"] lista_btn = [BTN_23,BTN_33,BTN_43] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["24","34","44"] lista_btn = [BTN_24,BTN_34,BTN_44] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["25","35","45"] lista_btn = [BTN_25,BTN_35,BTN_45] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 44: for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["22","23","24","25"] lista_btn = [BTN_22,BTN_23,BTN_24,BTN_25] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["32","33", "34", "35"] lista_btn = [BTN_32,BTN_33,BTN_34,BTN_35] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["42","43", "44", "45"] lista_btn = [BTN_42,BTN_43,BTN_44,BTN_45] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["52","53", "54", "55"] lista_btn = [BTN_52,BTN_53,BTN_54,BTN_55] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 4 x 4. contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["22", "32", "42", "52"] lista_btn = [BTN_22,BTN_32,BTN_42, BTN_52] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["23","33","43","53"] lista_btn = [BTN_23,BTN_33,BTN_43, BTN_53] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["24","34","44","54"] lista_btn = [BTN_24,BTN_34,BTN_44, BTN_54] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["25","35","45","55"] lista_btn = [BTN_25,BTN_35,BTN_45, BTN_55] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 55: for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["22","23","24","25", "26"] lista_btn = [BTN_22,BTN_23,BTN_24,BTN_25,BTN_26] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["32","33", "34", "35", "36"] lista_btn = [BTN_32,BTN_33,BTN_34,BTN_35,BTN_36] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["42","43", "44", "45", "46"] lista_btn = [BTN_42,BTN_43,BTN_44,BTN_45,BTN_46] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["52","53", "54", "55", "56"] lista_btn = [BTN_52,BTN_53,BTN_54,BTN_55, BTN_56] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila6_validar: if q in lst_fila6_validar[contador_fila:] and q != "": índ_elemento = lst_fila6_validar.index(q) botón = lst_fila6[índ_elemento] lista_nom = ["62","63", "64", "65", "66"] lista_btn = [BTN_62,BTN_63,BTN_64,BTN_65, BTN_66] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 5 x 5. contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["22", "32", "42", "52","62"] lista_btn = [BTN_22,BTN_32,BTN_42, BTN_52, BTN_62] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["23","33","43","53", "63"] lista_btn = [BTN_23,BTN_33,BTN_43, BTN_53, BTN_63] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["24","34","44","54", "64"] lista_btn = [BTN_24,BTN_34,BTN_44, BTN_54, BTN_64] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["25","35","45","55", "65"] lista_btn = [BTN_25,BTN_35,BTN_45, BTN_55, BTN_65] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna6_validar: if q in lst_columna6_validar[contador_columna:] and q != "": índ_elemento = lst_columna6_validar.index(q) botón = lst_columna6[índ_elemento] lista_nom = ["26","36","46","56", "66"] lista_btn = [BTN_26,BTN_36,BTN_46, BTN_56, BTN_66] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 0: for q in lst_fila1_validar: if q in lst_fila1_validar[contador_fila:] and q != "": índ_elemento = lst_fila1_validar.index(q) botón = lst_fila1[índ_elemento] lista_nom = ["11","12","13","14","15", "16"] lista_btn = [BTN_22,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["21","22","23","24","25", "26"] lista_btn = [BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["31","32","33", "34", "35", "36"] lista_btn = [BTN_21,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["41","42","43", "44", "45", "46"] lista_btn = [BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["51","52","53", "54", "55", "56"] lista_btn = [BTN_51,BTN_52,BTN_53,BTN_54,BTN_55, BTN_56] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila6_validar: if q in lst_fila6_validar[contador_fila:] and q != "": índ_elemento = lst_fila6_validar.index(q) botón = lst_fila6[índ_elemento] lista_nom = ["61","62","63", "64", "65", "66"] lista_btn = [BTN_61,BTN_62,BTN_63,BTN_64,BTN_65, BTN_66] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 6 x 6. contador_columna = 1 for q in lst_columna1_validar: if q in lst_columna1_validar[contador_columna:] and q != "": índ_elemento = lst_columna1_validar.index(q) botón = lst_columna1[índ_elemento] lista_nom = ["11","21", "31", "41", "51","61"] lista_btn = [BTN_11,BTN_21,BTN_31,BTN_41, BTN_51, BTN_61] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["12","22", "32", "42", "52","62"] lista_btn = [BTN_12,BTN_22,BTN_32,BTN_42, BTN_52, BTN_62] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["13","23","33","43","53", "63"] lista_btn = [BTN_13,BTN_23,BTN_33,BTN_43, BTN_53, BTN_63] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["14","24","34","44","54", "64"] lista_btn = [BTN_14,BTN_24,BTN_34,BTN_44, BTN_54, BTN_64] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["15","25","35","45","55", "65"] lista_btn = [BTN_15,BTN_25,BTN_35,BTN_45, BTN_55, BTN_65] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna6_validar: if q in lst_columna6_validar[contador_columna:] and q != "": índ_elemento = lst_columna6_validar.index(q) botón = lst_columna6[índ_elemento] lista_nom = ["16","26","36","46","56", "66"] lista_btn = [BTN_16,BTN_26,BTN_36,BTN_46, BTN_56, BTN_66] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 77: for q in lst_fila1_validar: if q in lst_fila1_validar[contador_fila:] and q != "": índ_elemento = lst_fila1_validar.index(q) botón = lst_fila1[índ_elemento] lista_nom = ["11","12","13","14","15", "16", "17"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["21","22","23","24","25", "26","27"] lista_btn = [BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["31","32","33", "34", "35", "36", "37"] lista_btn = [BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["41","42","43", "44", "45", "46","47"] lista_btn = [BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["51","52","53", "54", "55", "56","57"] lista_btn = [BTN_51,BTN_52,BTN_53,BTN_54,BTN_55, BTN_56,BTN_57] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila6_validar: if q in lst_fila6_validar[contador_fila:] and q != "": índ_elemento = lst_fila6_validar.index(q) botón = lst_fila6[índ_elemento] lista_nom = ["61","62","63", "64", "65", "66","67"] lista_btn = [BTN_61,BTN_62,BTN_63,BTN_64,BTN_65, BTN_66,BTN_67] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila7_validar: if q in lst_fila7_validar[contador_fila:] and q != "": índ_elemento = lst_fila7_validar.index(q) botón = lst_fila7[índ_elemento] lista_nom = ["71","72","73", "74", "75", "76","77"] lista_btn = [BTN_71,BTN_72,BTN_73,BTN_74,BTN_75, BTN_76,BTN_77] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 7 x 7. contador_columna = 1 for q in lst_columna1_validar: if q in lst_columna1_validar[contador_columna:] and q != "": índ_elemento = lst_columna1_validar.index(q) botón = lst_columna1[índ_elemento] lista_nom = ["11","21", "31", "41","51","61","71"] lista_btn = [BTN_11,BTN_21,BTN_31,BTN_41, BTN_51, BTN_61,BTN_71] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["12","22", "32","42","52","62","72"] lista_btn = [BTN_12,BTN_22,BTN_32,BTN_42, BTN_52, BTN_62,BTN_72] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["13","23","33","43","53","63","73"] lista_btn = [BTN_13,BTN_23,BTN_33,BTN_43, BTN_53, BTN_63,BTN_73] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["14","24","34","44","54","64","74"] lista_btn = [BTN_14,BTN_24,BTN_34,BTN_44, BTN_54, BTN_64,BTN_74] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["15","25","35","45","55","65","75"] lista_btn = [BTN_15,BTN_25,BTN_35,BTN_45, BTN_55, BTN_65,BTN_75] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna6_validar: if q in lst_columna6_validar[contador_columna:] and q != "": índ_elemento = lst_columna6_validar.index(q) botón = lst_columna6[índ_elemento] lista_nom = ["16","26","36","46","56","66","67"] lista_btn = [BTN_16,BTN_26,BTN_36,BTN_46, BTN_56, BTN_66,BTN_76] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna7_validar: if q in lst_columna7_validar[contador_columna:] and q != "": índ_elemento = lst_columna7_validar.index(q) botón = lst_columna7[índ_elemento] lista_nom = ["17","27","37","47","57","67","77"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47, BTN_57, BTN_67,BTN_77] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 88: for q in lst_fila0_validar: if q in lst_fila0_validar[contador_fila:] and q != "": índ_elemento = lst_fila0_validar.index(q) botón = lst_fila0[índ_elemento] lista_nom = ["00","01","02","03","04","05", "06", "07"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07] for z in lista_nom: if str(botón) == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila1_validar: if q in lst_fila1_validar[contador_fila:] and q != "": índ_elemento = lst_fila1_validar.index(q) botón = lst_fila1[índ_elemento] lista_nom = ["10","11","12","13","14","15", "16", "17"] lista_btn = [BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17] for z in lista_nom: if str(botón) == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["20","21","22","23","24","25", "26","27"] lista_btn = [BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["30","31","32","33", "34", "35", "36", "37"] lista_btn = [BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["40","41","42","43", "44", "45", "46","47"] lista_btn = [BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["50","51","52","53", "54", "55", "56","57"] lista_btn = [BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55, BTN_56,BTN_57] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila6_validar: if q in lst_fila6_validar[contador_fila:] and q != "": índ_elemento = lst_fila6_validar.index(q) botón = lst_fila6[índ_elemento] lista_nom = ["60","61","62","63", "64", "65", "66","67"] lista_btn = [BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65, BTN_66,BTN_67] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila7_validar: if q in lst_fila7_validar[contador_fila:] and q != "": índ_elemento = lst_fila7_validar.index(q) botón = lst_fila7[índ_elemento] lista_nom = ["70","71","72","73", "74", "75", "76","77"] lista_btn = [BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75, BTN_76,BTN_77] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 8 x 8. contador_columna = 1 for q in lst_columna0_validar: if q in lst_columna0_validar[contador_columna:] and q != "": índ_elemento = lst_columna0_validar.index(q) botón = lst_columna0[índ_elemento] lista_nom = ["00","10","20", "30", "40","50","60","70"] lista_btn = [BTN_00,BTN_10,BTN_20,BTN_30,BTN_40, BTN_50, BTN_60,BTN_70] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna1_validar: if q in lst_columna1_validar[contador_columna:] and q != "": índ_elemento = lst_columna1_validar.index(q) botón = lst_columna1[índ_elemento] lista_nom = ["01","11","21","31", "41","51","61","71"] lista_btn = [BTN_01,BTN_11,BTN_21,BTN_31,BTN_41, BTN_51, BTN_61,BTN_71] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["02","12","22", "32","42","52","62","72"] lista_btn = [BTN_02,BTN_12,BTN_22,BTN_32,BTN_42, BTN_52, BTN_62,BTN_72] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["03","13","23","33","43","53","63","73"] lista_btn = [BTN_03,BTN_13,BTN_23,BTN_33,BTN_43, BTN_53, BTN_63,BTN_73] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["04","14","24","34","44","54","64","74"] lista_btn = [BTN_04,BTN_14,BTN_24,BTN_34,BTN_44, BTN_54, BTN_64,BTN_74] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["05","15","25","35","45","55","65","75"] lista_btn = [BTN_05,BTN_15,BTN_25,BTN_35,BTN_45, BTN_55, BTN_65,BTN_75] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna6_validar: if q in lst_columna6_validar[contador_columna:] and q != "": índ_elemento = lst_columna6_validar.index(q) botón = lst_columna6[índ_elemento] lista_nom = ["06","16","26","36","46","56","66","67"] lista_btn = [BTN_06,BTN_16,BTN_26,BTN_36,BTN_46, BTN_56, BTN_66,BTN_76] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna7_validar: if q in lst_columna7_validar[contador_columna:] and q != "": índ_elemento = lst_columna7_validar.index(q) botón = lst_columna7[índ_elemento] lista_nom = ["07","17","27","37","47","57","67","77"] lista_btn = [BTN_07,BTN_17,BTN_27,BTN_37,BTN_47, BTN_57, BTN_67,BTN_77] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 elif sel == 99: for q in lst_fila0_validar: if q in lst_fila0_validar[contador_fila:] and q != "": índ_elemento = lst_fila0_validar.index(q) botón = lst_fila0[índ_elemento] lista_nom = ["00","01","02","03","04","05", "06", "07", "08"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08] for z in lista_nom: if str(botón) == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila1_validar: if q in lst_fila1_validar[contador_fila:] and q != "": índ_elemento = lst_fila1_validar.index(q) botón = lst_fila1[índ_elemento] lista_nom = ["10","11","12","13","14","15", "16", "17", "18"] lista_btn = [BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18] for z in lista_nom: if str(botón) == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila2_validar: if q in lst_fila2_validar[contador_fila:] and q != "": índ_elemento = lst_fila2_validar.index(q) botón = lst_fila2[índ_elemento] lista_nom = ["20","21","22","23","24","25", "26","27", "28"] lista_btn = [BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila3_validar: if q in lst_fila3_validar[contador_fila:] and q != "": índ_elemento = lst_fila3_validar.index(q) botón = lst_fila3[índ_elemento] lista_nom = ["30","31","32","33", "34", "35", "36", "37", "38"] lista_btn = [BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila4_validar: if q in lst_fila4_validar[contador_fila:] and q != "": índ_elemento = lst_fila4_validar.index(q) botón = lst_fila4[índ_elemento] lista_nom = ["40","41","42","43", "44", "45", "46","47", "48"] lista_btn = [BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila5_validar: if q in lst_fila5_validar[contador_fila:] and q != "": índ_elemento = lst_fila5_validar.index(q) botón = lst_fila5[índ_elemento] lista_nom = ["50","51","52","53", "54", "55", "56","57", "58"] lista_btn = [BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55, BTN_56,BTN_57,BTN_58] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila6_validar: if q in lst_fila6_validar[contador_fila:] and q != "": índ_elemento = lst_fila6_validar.index(q) botón = lst_fila6[índ_elemento] lista_nom = ["60","61","62","63", "64", "65", "66","67", "68"] lista_btn = [BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65, BTN_66,BTN_67,BTN_68] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila7_validar: if q in lst_fila7_validar[contador_fila:] and q != "": índ_elemento = lst_fila7_validar.index(q) botón = lst_fila7[índ_elemento] lista_nom = ["70","71","72","73", "74", "75", "76","77","78"] lista_btn = [BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75, BTN_76,BTN_77,BTN_78] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 contador_fila = 1 for q in lst_fila8_validar: if q in lst_fila8_validar[contador_fila:] and q != "": índ_elemento = lst_fila8_validar.index(q) botón = lst_fila8[índ_elemento] lista_nom = ["80","81","82","83", "84", "85", "86","87","88"] lista_btn = [BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85, BTN_86,BTN_87,BTN_88] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_fila += 1 #A continuación inicia validación de columnas en 9 x 9. contador_columna = 1 for q in lst_columna0_validar: if q in lst_columna0_validar[contador_columna:] and q != "": índ_elemento = lst_columna0_validar.index(q) botón = lst_columna0[índ_elemento] lista_nom = ["00","10","20", "30", "40","50","60","70","80"] lista_btn = [BTN_00,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_80] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna1_validar: if q in lst_columna1_validar[contador_columna:] and q != "": índ_elemento = lst_columna1_validar.index(q) botón = lst_columna1[índ_elemento] lista_nom = ["01","11","21","31","41","51","61","71","81"] lista_btn = [BTN_01,BTN_11,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61,BTN_71,BTN_81] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna2_validar: if q in lst_columna2_validar[contador_columna:] and q != "": índ_elemento = lst_columna2_validar.index(q) botón = lst_columna2[índ_elemento] lista_nom = ["02","12","22", "32","42","52","62","72","82"] lista_btn = [BTN_02,BTN_12,BTN_22,BTN_32,BTN_42, BTN_52, BTN_62,BTN_72,BTN_82] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna3_validar: if q in lst_columna3_validar[contador_columna:] and q != "": índ_elemento = lst_columna3_validar.index(q) botón = lst_columna3[índ_elemento] lista_nom = ["03","13","23","33","43","53","63","73","83"] lista_btn = [BTN_03,BTN_13,BTN_23,BTN_33,BTN_43, BTN_53, BTN_63,BTN_73,BTN_83] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna4_validar: if q in lst_columna4_validar[contador_columna:] and q != "": índ_elemento = lst_columna4_validar.index(q) botón = lst_columna4[índ_elemento] lista_nom = ["04","14","24","34","44","54","64","74","84"] lista_btn = [BTN_04,BTN_14,BTN_24,BTN_34,BTN_44, BTN_54, BTN_64,BTN_74,BTN_84] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna5_validar: if q in lst_columna5_validar[contador_columna:] and q != "": índ_elemento = lst_columna5_validar.index(q) botón = lst_columna5[índ_elemento] lista_nom = ["05","15","25","35","45","55","65","75","85"] lista_btn = [BTN_05,BTN_15,BTN_25,BTN_35,BTN_45, BTN_55, BTN_65,BTN_75,BTN_85] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna6_validar: if q in lst_columna6_validar[contador_columna:] and q != "": índ_elemento = lst_columna6_validar.index(q) botón = lst_columna6[índ_elemento] lista_nom = ["06","16","26","36","46","56","66","76","86"] lista_btn = [BTN_06,BTN_16,BTN_26,BTN_36,BTN_46, BTN_56, BTN_66,BTN_76,BTN_86] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna7_validar: if q in lst_columna7_validar[contador_columna:] and q != "": índ_elemento = lst_columna7_validar.index(q) botón = lst_columna7[índ_elemento] lista_nom = ["07","17","27","37","47","57","67","77","87"] lista_btn = [BTN_07,BTN_17,BTN_27,BTN_37,BTN_47, BTN_57, BTN_67,BTN_77,BTN_87] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 contador_columna = 1 for q in lst_columna8_validar: if q in lst_columna8_validar[contador_columna:] and q != "": índ_elemento = lst_columna8_validar.index(q) botón = lst_columna8[índ_elemento] lista_nom = ["08","18","28","38","48","58","68","78","88"] lista_btn = [BTN_08,BTN_18,BTN_28,BTN_38,BTN_48, BTN_58, BTN_68,BTN_78,BTN_88] for z in lista_nom: if botón == z: índ_nom = lista_nom.index(z) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") msg_error = True contador_columna += 1 if msg_error == True and terminar == False: messagebox.showerror("Error", "Hay errores en el juego.") return for k in lst_validar: for o in k: if o == "": return False if msg_error == False and msg_terminar == True: if terminar == False: registrado = True terminar = True FN_top10(1) if sonido_selec.get() == 1: THRD_FN_sonido_aplausos = Thread (target = FN_sonido_aplausos, args = ()) THRD_FN_sonido_aplausos.start() messagebox.showinfo("Terminado", "¡Felicitaciones, juego completado!") resultado = messagebox.askquestion("Terminar", "¿Desea jugar otro KenKen del mismo nivel?") if resultado == "yes": FN_otro("validar") else: BTN_terminar.config(state = DISABLED) BTN_validar.config(state = DISABLED) BTN_menú_jugar.config(state = NORMAL) return True def FN_WIN_validar_completo (): WIN_menú.withdraw() global WIN_validar_completo WIN_validar_completo.deiconify() WIN_validar_completo.geometry("500x225") WIN_validar_completo.title("Función Extra") WIN_validar_completo.resizable(width = FALSE, height = FALSE) centrar (WIN_validar_completo) WIN_validar_completo.protocol("WM_DELETE_WINDOW", lambda : WIN_validar_completo.destroy()) global validar_completo_respuesta LBL_título = Label(WIN_validar_completo, text = "Validación completa",font = ("Helvetica Neue", 18, "bold")).place(x = 150, y = 10) LBL_validar_completo = Label(WIN_validar_completo, text = "Validar completo:", font = ("Helvetica Neue", 16, "bold")).place(x = 10, y = 60) LBL_menú = Label(WIN_validar_completo, text = "Menú", font = (("Helvetica Neue", 15))).place (x = 181, y = 191) LBL_jugar = Label(WIN_validar_completo, text = "Jugar", font = (("Helvetica Neue", 15))).place (x = 281, y = 191) BTN_menú = Button(WIN_validar_completo, image = IMG_BTN_menú, height = 65, width = 65, borderwidth = 0, command = menú_volver).place (x = 175, y = 127) BTN_jugar = Button(WIN_validar_completo, image = IMG_BTN_WIN_menú_configurar, height = 65, width = 65, borderwidth = 0, command = FN_THRDs).place (x = 275, y = 127) RDB_validar_completo = Radiobutton(WIN_validar_completo, text = "Sí", font = ("Helvetica Neue", 14), variable = validar_completo_respuesta, value = 1).place(x = 195, y = 60) RDB_validar_completo = Radiobutton(WIN_validar_completo, text = "No", font = ("Helvetica Neue", 14), variable = validar_completo_respuesta, value = 0).place(x = 195, y = 90) def FN_validar_completo (): contador = 0 contador2 = 0 índ_operación = 0 lst_operación = [] r = 0 msg_error = False msg_terminar = True sel = nivel_selec.get() if sel == 33: índice = 0 elif sel == 44: índice = 1 elif sel == 55: índice = 2 elif sel == 0: índice = 3 elif sel == 77: índice = 4 elif sel == 88: índice = 5 elif sel == 99: índice = 6 TXT_respuestas = open("Respuestas.txt","r") TXT_respuestas_read = TXT_respuestas.read() string = "[" lista_completa = [] lista_nivel = [] lista_juego = [] contador_nivel = 0 for i in TXT_respuestas_read: if i != "[" and i != "]": string += i contador_control = 1 elif i == "]" and contador_control != 0: string += i lista_nivel.append(eval(string)) string = "[" contador_nivel += 1 if contador_nivel == 4: lista_completa.append(lista_nivel) lista_nivel = [] contador_nivel = 0 contador_control = 0 global registrado global terminar for i in lst_validar: for j in i: if j == "": messagebox.showerror("Error", "Debe completar todas las casillas antes de validar completamente.") return for i in lst_validar: for j in i: if sel == 33: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for p in lista_nom: if botón == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 elif sel == 44: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 elif sel == 55: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 elif sel == 0: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 elif sel == 77: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 elif sel == 88: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 elif sel == 99: if str(j) != str(lista_completa[índice][elegido][contador][contador2]): botón = str(lst_juego_validar[contador][contador2]) lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if str(botón) == str(p): índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(bg = "Red") contador2 += 1 else: contador2 += 1 contador2 = 0 contador += 1 def FN_BTNS(button): global but_press global otro_juego but_press = button otro_juego = False lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for p in lista_nom: if button == p: índ_nom = lista_nom.index(p) elem_btn = lista_btn[índ_nom] elem_btn.config(relief = SUNKEN, bg = "DarkTurquoise") cuadrícula_color() def FN_add (add): if pausa == True: FN_pausa () global but_press a = but_press cuadrícula_color() if a == "": messagebox.showerror("Error", "Primero debe seleccionar una casilla.") return validar(a, add) sel = nivel_selec.get() if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = add, bg = "DarkTurquoise") def FN_borrar (): if pausa == True: FN_pausa () global but_press a = but_press if a == "": messagebox.showerror("Error", "Primero debe seleccionar una casilla.") return validar(a, "*") sel = nivel_selec.get() if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for i in lista_nom: if a == i: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "") def FN_sonido_aplausos(): #Reproduce el sonido de aplausos si el usuario lo seleccionó. winsound.PlaySound("SOUND_aplausos.wav", winsound.SND_FILENAME) #———————————————————————————————————————————————————————————Fin Cuadrícula—————————————————————————————————————————————————————————# #—————————————————————————————————————————————————————————————Terminar—————————————————————————————————————————————————————————————# def FN_terminar (): if iniciado == False: messagebox.showerror("Error", "El juego no se ha iniciado.") return global pausa if pausa == False: pausa = True resultado = messagebox.askquestion("Finalizar", "¿Está seguro de terminar el juego?") if resultado == "yes": global terminar terminar = True correcto = FN_validar () if correcto == True and registrado == False: resultado2 = messagebox.askquestion("Guardar", "El juego está completo y correcto. ¿Desea guardar las estadísticas del juego?") if resultado2 == "yes": FN_top10 (1) global juego_num juego_num = 0 WIN_jugar.withdraw() WIN_menú.deiconify() else: if pausa == True: pausa = False #———————————————————————————————————————————————————————————Fin Terminar———————————————————————————————————————————————————————————# #——————————————————————————————————————————————————————————————Top 10——————————————————————————————————————————————————————————————# def FN_top10 (a): #TXT_top10 = eval(open("Top10.txt", "r").read()) #Abre el archivo, lo lee y lo convierte en diccionario. sel = nivel_selec.get() if sel == 33: índice = 0 elif sel == 44: índice = 1 elif sel == 55: índice = 2 elif sel == 0: índice = 3 elif sel == 77: índice = 4 elif sel == 88: índice = 5 elif sel == 99: índice = 6 kenken_top10 = open("kenken_top10.dat","r") kenken_top10_read = kenken_top10.read() string = "" lista = [] for i in kenken_top10_read: if i != "]": string += i else: string += i if string == "]": break while string[1] == "[": string = string[1:] while string[0] != "[": string = string[1:] lista.append(eval(string)) string = "" lst_nivel = lista[índice] global h global m global s global h2 global m2 global s2 if a == 1: #¿Escribir? FN_pausa() if a == 1 and timer_estado == False and clock_estado == True: h2 = h m2 = m s2 = s elif a == 1 and timer_estado == True and clock_estado == True: h2 = (h + h2) - h2 m2 = (m + m2) - m2 s2 = (s + s2) - s2 contador = 0 agregado = 0 name = nombre.get() if h2 < 9: str_hora = "0" + str(h2) else: str_hora = str(h2) if m2 < 9: str_minuto = "0" + str(m2) else: str_minuto = str(m2) if s2 < 9: str_segundo = "0" + str(s2) else: str_segundo = str(s2) tiempo = str_hora + str_minuto + str_segundo if len(lst_nivel) < 10: if len(lst_nivel) == 0: lst_nivel.insert(contador, (name, tiempo)) else: for j in lst_nivel: if int(j[1]) > int(tiempo): lst_nivel.insert(contador, (name, tiempo)) agregado = 1 break elif int(j[1]) == int(tiempo): lst_nivel.insert(contador + 1, (name, tiempo)) agregado = 1 break contador += 1 if agregado == 0: lst_nivel.append((name, tiempo)) contador = 0 agregado = 0 else: for j in lst_nivel: if int(j[1]) > int(tiempo): lst_nivel.pop(contador) lst_nivel.insert(contador, (name, tiempo)) break elif int(j[1]) == int(tiempo): lst_nivel.insert(contador + 1, (name, tiempo)) lst_nivel.pop() agregado = 1 break contador += 1 contador = 0 kenken_top10 = open("kenken_top10.dat","w") kenken_top10.write(str(lista)) else: y = 70 pos = 1 for k in lst_nivel: name = k[0] tiempo = k[1] lbl_top10 = Label(WIN_top10, text = str(pos) + ". " + name, font = (("Helvetica Neue", 12))).place (x = 5, y = y) lbl_top10_tiempo = Label(WIN_top10, text = tiempo[:2] + " : " + tiempo[2:4] + " : " + tiempo[4:], font = (("Helvetica Neue", 12))).place (x = 416, y = y) pos += 1 y += 30 def WIN_top10 (): #WIN_jugar.withdraw() global WIN_top10 WIN_top10 = Toplevel() WIN_top10.geometry("620x370") WIN_top10.title("Top 10") WIN_top10.resizable(width = FALSE, height = FALSE) centrar (WIN_top10) WIN_top10.protocol("WM_DELETE_WINDOW", lambda : WIN_top10.destroy()) sel = nivel_selec.get() if sel == 33: top_lvl = "3 x 3" elif sel == 44: top_lvl = "4 x 4" elif sel == 55: top_lvl = "5 x 5" elif sel == 0: top_lvl = "6 x 6" elif sel == 77: top_lvl = "7 x 7" elif sel == 88: top_lvl = "8 x 8" elif sel == 99: top_lvl = "9 x 9" LBL_título = Label(WIN_top10, text = "Top 10 - " + top_lvl, font = (("Helvetica Neue", 16, "bold"))).place (x = 260, y = 10) LBL_nombre = Label(WIN_top10, text = "Nombre", font = (("Helvetica Neue", 13, "bold"))).place (x = 5, y = 40) LBL_horas = Label(WIN_top10, text = "Horas", font = (("Helvetica Neue", 13, "bold"))).place (x = 400, y = 40) LBL_minutos = Label(WIN_top10, text = "Minutos", font = (("Helvetica Neue", 13, "bold"))).place (x = 461, y = 40) LBL_segundos = Label(WIN_top10, text = "Segundos", font = (("Helvetica Neue", 13, "bold"))).place (x = 534, y = 40) FN_top10(0) #————————————————————————————————————————————————————————————Fin Top 10————————————————————————————————————————————————————————————# #————————————————————————————————————————————————————————————————————Fin Ventana Jugar——————————————————————————————————————————————————————————————————# #———————————————————————————————————————————————————————————————————Ventana Configurar——————————————————————————————————————————————————————————————————# def FN_WIN_configurar (): WIN_menú.withdraw() global WIN_configurar WIN_configurar = Toplevel() WIN_configurar.protocol("WM_DELETE_WINDOW", lambda : WIN_configurar.destroy()) WIN_configurar.geometry("600x600") WIN_configurar.title("Configurar KENKEN") WIN_configurar.resizable(width = FALSE, height = FALSE) centrar (WIN_configurar) global nivel_selec nivel_selec = IntVar() global reloj_selec reloj_selec = IntVar() global lado_selec lado_selec = IntVar() global sonido_selec sonido_selec = IntVar() BTN_menú = Button(WIN_configurar, image = IMG_BTN_menú, height = 65, width = 65, borderwidth = 0, command = menú_volver).place (x = 210, y = 500) BTN_jugar = Button(WIN_configurar, image = IMG_BTN_WIN_menú_configurar, height = 65, width = 65, borderwidth = 0, command = FN_WIN_jugar).place (x = 320, y = 500) LBL_título = Label(WIN_configurar, text = "Configuración", font = ("Helvetica Neue", 18, "bold")).place(x = 220, y = 10) LBL_nivel = Label(WIN_configurar, text = "Nivel", font = ("Helvetica Neue", 14, "bold")).place(x = 27, y = 55) LBL_reloj = Label(WIN_configurar, text = "Reloj", font = ("Helvetica Neue", 14, "bold")).place(x = 170, y = 55) LBL_panel_pos = Label(WIN_configurar, text = "Posición del panel de números y el borrador:", font = ("Helvetica Neue", 13, "bold")).place(x = 27, y = 370) LBL_sonido = Label(WIN_configurar, text = "Sonido cuando termina el juego exitosamente:", font = ("Helvetica Neue", 13, "bold")).place(x = 27, y = 440) LBL_menú = Label(WIN_configurar, text = "Menú", font = ("Helvetica Neue", 12)).place(x = 221, y = 566) LBL_jugar = Label(WIN_configurar, text = "Jugar", font = ("Helvetica Neue", 12)).place(x = 331, y = 566) RDB_nivel_3x3 = Radiobutton(WIN_configurar, text = "3 x 3", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 33).place(x = 27, y = 85) RDB_nivel_4x4 = Radiobutton(WIN_configurar, text = "4 x 4", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 44).place(x = 27, y = 115) RDB_nivel_5x5 = Radiobutton(WIN_configurar, text = "5 x 5", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 55).place(x = 27, y = 145) RDB_nivel_6x6 = Radiobutton(WIN_configurar, text = "6 x 6", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 0).place(x = 27, y = 175) RDB_nivel_7x7 = Radiobutton(WIN_configurar, text = "7 x 7", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 77).place(x = 27, y = 205) RDB_nivel_8x8 = Radiobutton(WIN_configurar, text = "8 x 8", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 88).place(x = 27, y = 235) RDB_nivel_9x9 = Radiobutton(WIN_configurar, text = "9 x 9", font = ("Helvetica Neue", 14), variable = nivel_selec, value = 99).place(x = 27, y = 265) RDB_reloj_sí = Radiobutton(WIN_configurar, text = "Sí", font = ("Helvetica Neue", 14), variable = reloj_selec, value = 0).place(x = 170, y = 85) RDB_reloj_no = Radiobutton(WIN_configurar, text = "No", font = ("Helvetica Neue", 14), variable = reloj_selec, value = 1).place(x = 170, y = 115) RDB_reloj_timer = Radiobutton(WIN_configurar, text = "Timer", font = ("Helvetica Neue", 14), variable = reloj_selec, value = 2, command = FN_timer_configurar).place(x = 170, y = 145) RDB_derecha = Radiobutton(WIN_configurar, text = "Derecha", font = ("Helvetica Neue", 14), variable = lado_selec, value = 0).place(x = 392 , y = 366) RDB_izquierda = Radiobutton(WIN_configurar, text = "Izquierda", font = ("Helvetica Neue", 14), variable = lado_selec, value = 1).place(x = 392 , y = 396) RBD_sonido_no = Radiobutton(WIN_configurar, text = "No", font = ("Helvetica Neue", 14), variable = sonido_selec, value = 0).place(x = 392 , y = 436) RBD_sonido_sí = Radiobutton(WIN_configurar, text = "Sí", font = ("Helvetica Neue", 14), variable = sonido_selec, value = 1).place(x = 392 , y = 466) def menú_volver (): #Regresar al menú principal, lo utilizan las WIN jugar, configurar, validar y ayuda. global juego_num global iniciado iniciado = False if reloj_selec.get() == 2 and juego_num == 0: if default_horas.get() == "0" and default_minutos.get() == "0" and default_segundos.get() == "0": messagebox.showerror("Error", "Si selecciona el timer los segundos, los minutos o las horas deben ser mayores a 0.") return juego_num = 0 WIN_jugar.withdraw() WIN_configurar.withdraw() WIN_validar_completo.withdraw() WIN_ayuda.withdraw() WIN_menú.deiconify() def FN_timer_configurar (): global default_horas default_horas = StringVar() global default_minutos default_minutos = StringVar() global default_segundos default_segundos = StringVar() default_horas.set("0")#Valor default de los SPNBX. default_minutos.set("0") default_segundos.set("0") LBL_horas = Label(WIN_configurar, text = "Horas", font = ("Helvetica Neue", 13)).place(x = 300, y = 55) LBL_minutos = Label(WIN_configurar, text = "Minutos", font = ("Helvetica Neue", 13)).place(x = 355, y = 55) LBL_segundos = Label(WIN_configurar, text = "Segundos", font = ("Helvetica Neue", 13)).place(x = 420, y = 55) LBL_sugeridos = Label(WIN_configurar, text = "Tiempos sugeridos:", font = ("Helvetica Neue", 13)).place(x = 300, y = 130) SPNBX_horas = Spinbox(WIN_configurar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 3, textvariable = default_horas, wrap = True).place(x = 308, y = 90) SPNBX_minutos = Spinbox(WIN_configurar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 59, textvariable = default_minutos, wrap = True).place(x = 370, y = 90) SPNBX_segundos = Spinbox(WIN_configurar, width = 2, font = ("Helvetica Neue", 12), from_ = 0, to = 59, textvariable = default_segundos, wrap = True).place(x = 440, y = 90) LBL_sugerido3x3 = Label(WIN_configurar, text = "• Para el nivel 3 x 3: 5 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 160) LBL_sugerido4x4 = Label(WIN_configurar, text = "• Para el nivel 4 x 4: 10 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 190) LBL_sugerido5x5 = Label(WIN_configurar, text = "• Para el nivel 5 x 5: 20 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 220) LBL_sugerido6x6 = Label(WIN_configurar, text = "• Para el nivel 6 x 6: 25 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 250) LBL_sugerido7x7 = Label(WIN_configurar, text = "• Para el nivel 7 x 7: 30 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 280) LBL_sugerido8x8 = Label(WIN_configurar, text = "• Para el nivel 8 x 8: 35 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 310) LBL_sugerido9x9 = Label(WIN_configurar, text = "• Para el nivel 9 x 9: 40 minutos.", font = ("Helvetica Neue", 11)).place(x = 300, y = 340) def FN_timer (): global timer_estado timer_estado = True global resultado resultado = "" global h global m global s global h2 h2 = 0 global m2 m2 = 0 global s2 s2 = 0 h = int(default_horas.get()) m = int(default_minutos.get()) s = int(default_segundos.get()) while h != 0 or m != 0 or s >= 0: if terminar == True: LBL_clock = Label(WIN_jugar, text = " "+"0"+ "0" + " " + "0"+ "0" + " " + "0"+ "0" +" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) return if pausa == False: if s < 10 and m < 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + "0"+str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s >= 10 and m < 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + "0"+str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s >= 10 and m >= 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m < 10 and h >= 10: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + "0"+str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m >= 10 and h >= 10: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) elif s < 10 and m >= 10 and h < 10: LBL_segundos = Label(WIN_jugar, text = " "+"0"+str(h) + " " + str(m) + " " + "0"+str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) else: LBL_segundos = Label(WIN_jugar, text = " "+str(h) + " " + str(m) + " " + str(s)+" ", font = ("Helvetica Neue", 16)).place(x = 774, y = 44) time.sleep(0.99) s2 += 1 if m2 == 59 and s == 60: h2 += 1 m2 = 0 s2 = 0 elif s2 == 60: m2 += 1 s2 = 0 if m > 0 and s == 0: m -= 1 s = 59 elif h > 0 and m == 0 and s == 0: h -= 1 m = 59 s = 59 elif h == 0 and m == 0 and s == 0: h = int(default_horas.get()) m = int(default_minutos.get()) s = int(default_segundos.get()) if terminar == False and iniciado == True: resultado = messagebox.askquestion("Tiempo agotado", "El timer finalizó. ¿Desea continuar?") if resultado == "yes": clock() return messagebox.showinfo("Terminado", "Juego terminado.") return s -= 1 def FN_otro (a): global juego_num global otro_juego global terminar global iniciado global but_press global h global m global s if a == "otro": if iniciado == False: messagebox.showerror("Error", "El juego no se ha iniciado.") return resultado = messagebox.askquestion("Otro juego", "¿Está seguro de terminar este juego y empezar con otro?") else: resultado = "yes" if resultado == "yes": terminar = True iniciado = False but_press = "" h = 0 m = 0 s = 0 WIN_jugar.withdraw() if len(juegos_probables) == 0: juego_num = 0 otro_juego = True FN_THRDs() def FN_reiniciar (): global terminar global iniciado global otro_juego global but_press global h global m global s if iniciado == False: messagebox.showerror("Error", "El juego no se ha iniciado.") return resultado = messagebox.askquestion("Reiniciar", "¿Está seguro de reiniciar el juego? Perderá todo el progreso.") if resultado == "yes": terminar = True iniciado = False otro_juego = False but_press = "" h = 0 m = 0 s = 0 BTN_iniciar.config(state = NORMAL) TXT_nombre.config(state = NORMAL) BTN_terminar.config(state = NORMAL) BTN_validar.config(state = NORMAL) BTN_menú_jugar.config(state = DISABLED) but_press = "" cuadrícula_color() sel = nivel_selec.get() if sel == 33: lista_nom = ["23","24","25","33","34","35","43","44","45"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 44: lista_nom = ["23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 55: lista_nom = ["26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 0: lista_nom = ["11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 77: lista_nom = ["17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 88: lista_nom = ["00","01","02","03","04","05","06","07","10","20","30","40","50","60","70","17","27","37","47","57","67","71","72","73","74","75","76","77","11","12","13","14","15","16","21","31","41","51","61","26","36","46","56","62","63","64","65","66","23","24","25","33","34","35","43","44","45","22","32","42","52","53","54","55"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_10,BTN_20,BTN_30,BTN_40,BTN_50,BTN_60,BTN_70,BTN_17,BTN_27,BTN_37,BTN_47,BTN_57,BTN_67,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_21,BTN_31,BTN_41,BTN_51,BTN_61, BTN_26,BTN_36,BTN_46,BTN_56,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_23,BTN_24,BTN_25,BTN_33,BTN_34,BTN_35,BTN_43,BTN_44,BTN_45,BTN_22,BTN_32,BTN_42,BTN_52,BTN_53,BTN_54,BTN_55] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) elif sel == 99: lista_nom = ["00","01","02","03","04","05","06","07","08","10","11","12","13","14","15","16","17","18","20","21","22","23","24","25","26","27","28","30","31","32","33","34","35","36","37","38","40","41","42","43","44","45","46","47","48","50","51","52","53","54","55","56","57","58","60","61","62","63","64","65","66","67","68","70","71","72","73","74","75","76","77","78","80","81","82","83","84","85","86","87","88"] lista_btn = [BTN_00,BTN_01,BTN_02,BTN_03,BTN_04,BTN_05,BTN_06,BTN_07,BTN_08,BTN_10,BTN_11,BTN_12,BTN_13,BTN_14,BTN_15,BTN_16,BTN_17,BTN_18,BTN_20,BTN_21,BTN_22,BTN_23,BTN_24,BTN_25,BTN_26,BTN_27,BTN_28,BTN_30,BTN_31,BTN_32,BTN_33,BTN_34,BTN_35,BTN_36,BTN_37,BTN_38,BTN_40,BTN_41,BTN_42,BTN_43,BTN_44,BTN_45,BTN_46,BTN_47,BTN_48,BTN_50,BTN_51,BTN_52,BTN_53,BTN_54,BTN_55,BTN_56,BTN_57,BTN_58,BTN_60,BTN_61,BTN_62,BTN_63,BTN_64,BTN_65,BTN_66,BTN_67,BTN_68,BTN_70,BTN_71,BTN_72,BTN_73,BTN_74,BTN_75,BTN_76,BTN_77,BTN_78,BTN_80,BTN_81,BTN_82,BTN_83,BTN_84,BTN_85,BTN_86,BTN_87,BTN_88] for i in lista_nom: índ_nom = lista_nom.index(i) elem_btn = lista_btn[índ_nom] elem_btn.config(text = "", state = DISABLED) #—————————————————————————————————————————————————————————————————Fin Ventana Configurar————————————————————————————————————————————————————————————————# #—————————————————————————————————————————————————————————————————————Ventana Ayuda—————————————————————————————————————————————————————————————————————# def FN_WIN_ayuda (): WIN_menú.withdraw() global WIN_ayuda WIN_ayuda = Toplevel() WIN_ayuda.protocol("WM_DELETE_WINDOW", lambda : WIN_ayuda.destroy()) WIN_ayuda.geometry("300x400") WIN_ayuda.title("Ayuda KENKEN") WIN_ayuda.resizable(width = FALSE, height = FALSE) centrar (WIN_ayuda) LBL_título = Label(WIN_ayuda, text = "KenKen", font = ("Helvetica Neue", 18, "bold")).place(x = 101, y = 5) LBL_función = Label(WIN_ayuda, text = "Pasatiempo Aritmético", font = ("Helvetica Neue", 14)).place(x = 51, y = 35) LBL_desarrollador = Label(WIN_ayuda, text = "Desarrollador", font = ("Helvetica Neue", 12, "underline")).place(x = 97, y = 84) LBL_autor = Label(WIN_ayuda, text = "José Daniel Delgado Segura", font = ("Helvetica Neue", 12, "bold")).place(x = 37, y = 108) LBL_correo = Label(WIN_ayuda, text = "Correo electrónico", font = ("Helvetica Neue", 12, "underline")).place(x = 80, y = 137) LBL_gmail = Label(WIN_ayuda, text = "jddsegura14@gmail.com", font = ("Helvetica Neue", 12, "bold")).place(x = 53, y = 161) LBL_fecha = Label(WIN_ayuda, text = "KenKen 1.0\n21-05-2015", font = ("Helvetica Neue", 10)).place(x = 115, y = 190) LBL_menú = Label(WIN_ayuda, text = "Menú", font = ("Helvetica Neue", 12)).place(x = 221, y = 566) BTN_menú = Button(WIN_ayuda, image = IMG_BTN_menú, height = 65, width = 65, borderwidth = 0, command = menú_volver).place (x = 70, y = 240) BTN_manual = Button(WIN_ayuda, image = IMG_BTN_WIN_ayuda_manual, height = 65, width = 65, borderwidth = 0, command = lambda : os.startfile("kenken_manual_de_usuario.pdf")).place (x = 165, y = 240) #———————————————————————————————————————————————————————————————————Fin Ventana Ayuda———————————————————————————————————————————————————————————————————# #————————————————————————————————————————————————————————————————————Programa Principal—————————————————————————————————————————————————————————————————# from tkinter import * from threading import * import os #Se utiliza en las funciones: FN_timer, clock, FN_WIN_jugar. import time #Se utiliza en las funciones: FN_timer, clock, FN_WIN_jugar. import random #Se utiliza en la función: FN_juegos_probables. import winsound #Se utiliza en la función: FN_validar. WIN_menú = Tk() WIN_menú.geometry("600x460") WIN_menú.title("KENKEN") WIN_menú.resizable(width = FALSE, height = FALSE) centrar (WIN_menú) WIN_menú.protocol("WM_DELETE_WINDOW", lambda : WIN_menú.destroy()) #-------------------Asignación Variables Programa Principal-------------------# global IMG_BTN_WIN_menú_jugar IMG_BTN_WIN_menú_jugar = PhotoImage(file = "IMG_BTN_WIN_menú_jugar.png") global IMG_BTN_WIN_menú_configurar IMG_BTN_WIN_menú_configurar = PhotoImage(file = "IMG_BTN_WIN_menú_configurar.png") global IMG_BTN_WIN_menú_config IMG_BTN_WIN_menú_config = PhotoImage(file = "IMG_BTN_WIN_menú_config.png") global IMG_BTN_WIN_menú_adici IMG_BTN_WIN_menú_adici = PhotoImage(file = "IMG_BTN_WIN_menú_adici.png") global IMG_BTN_WIN_menú_ayuda IMG_BTN_WIN_menú_ayuda = PhotoImage(file = "IMG_BTN_WIN_menú_ayuda.png") global IMG_BTN_WIN_menú_salir IMG_BTN_WIN_menú_salir = PhotoImage(file = "IMG_BTN_WIN_menú_salir.png") global IMG_BTN_menú IMG_BTN_menú = PhotoImage(file = "IMG_BTN_menú.png") global IMG_BTN_WIN_jugar_borrar IMG_BTN_WIN_jugar_borrar = PhotoImage(file = "IMG_BTN_WIN_jugar_borrar.png") global IMG_BTN_WIN_validar_completo IMG_BTN_WIN_validar_completo = PhotoImage(file = "IMG_BTN_WIN_validar_completo.png") global IMG_BTN_WIN_ayuda_manual IMG_BTN_WIN_ayuda_manual = PhotoImage(file = "IMG_BTN_WIN_ayuda_manual.png") global IMG_BTN_num1 IMG_BTN_num1 = PhotoImage(file = "BTN_num1.png") global IMG_BTN_num2 IMG_BTN_num2 = PhotoImage(file = "BTN_num2.png") global IMG_BTN_num3 IMG_BTN_num3 = PhotoImage(file = "BTN_num3.png") global IMG_BTN_num4 IMG_BTN_num4 = PhotoImage(file = "BTN_num4.png") global IMG_BTN_num5 IMG_BTN_num5 = PhotoImage(file = "BTN_num5.png") global IMG_BTN_num6 IMG_BTN_num6 = PhotoImage(file = "BTN_num6.png") global IMG_BTN_num7 IMG_BTN_num7 = PhotoImage(file = "BTN_num7.png") global IMG_BTN_num8 IMG_BTN_num8 = PhotoImage(file = "BTN_num8.png") global IMG_BTN_num9 IMG_BTN_num9 = PhotoImage(file = "BTN_num9.png") global IMG_BTN_WIN_jugar_iniciar IMG_BTN_WIN_jugar_iniciar = PhotoImage(file = "IMG_BTN_WIN_jugar_iniciar.png") global IMG_BTN_WIN_jugar_validar IMG_BTN_WIN_jugar_validar = PhotoImage(file = "IMG_BTN_WIN_jugar_validar.png") global IMG_BTN_WIN_jugar_otro IMG_BTN_WIN_jugar_otro = PhotoImage(file = "IMG_BTN_WIN_jugar_otro.png") global IMG_BTN_WIN_jugar_reiniciar IMG_BTN_WIN_jugar_reiniciar = PhotoImage(file = "IMG_BTN_WIN_jugar_reiniciar.png") global IMG_BTN_WIN_jugar_terminar IMG_BTN_WIN_jugar_terminar = PhotoImage(file = "IMG_BTN_WIN_jugar_terminar.png") global IMG_BTN_WIN_jugar_top10 IMG_BTN_WIN_jugar_top10 = PhotoImage(file = "IMG_BTN_WIN_jugar_top10.png") global pausa #Pausa de clock. pausa = False global timer_estado timer_estado = False global clock_estado clock_estado = False global registrado registrado = False global terminar terminar = False global iniciado iniciado = False global otro_juego #Si es True significa que el usuario solicitó un nuevo juego. otro_juego = False global but_press but_press = "" global últ_btn últ_btn = "" global juego_num juego_num = 0 global validar_completo #Se activa cuando el usuario selecciona que desea jugar con el validar completo. validar_completo = False #Valores por default: global nivel_selec nivel_selec = IntVar() global reloj_selec reloj_selec = IntVar() global lado_selec lado_selec = IntVar() global sonido_selec sonido_selec = IntVar() global validar_completo_respuesta validar_completo_respuesta = IntVar() global default_horas default_horas = StringVar() global default_minutos default_minutos = StringVar() global default_segundos default_segundos = StringVar() global WIN_jugar WIN_jugar = Toplevel() WIN_jugar.withdraw() global WIN_configurar WIN_configurar = Toplevel() WIN_configurar.withdraw() global WIN_validar_completo WIN_validar_completo = Toplevel() WIN_validar_completo.withdraw() global WIN_ayuda WIN_ayuda = Toplevel() WIN_ayuda.withdraw() #-----------------Fin Asignación Variables Programa Principal-----------------# LBL_título = Label(WIN_menú, text = "Menú Principal", font = (("Helvetica Neue", 22, "bold"))).place(x = 205, y = 10) LBL_jugar = Label(WIN_menú, text = "Jugar", font = (("Helvetica Neue", 16))).place (x = 77, y = 210) LBL_config = Label(WIN_menú, text = "Configurar", font = (("Helvetica Neue", 16))).place (x = 257, y = 210) LBL_adici = Label(WIN_menú, text = "Validar completo", font = (("Helvetica Neue", 16))).place (x = 416, y = 210) #Función extra LBL_ayuda = Label(WIN_menú, text = "Ayuda", font = (("Helvetica Neue", 16))).place (x = 175, y = 405) LBL_salir = Label(WIN_menú, text = "Salir", font = (("Helvetica Neue", 16))).place (x = 380, y = 405) BTN_jugar = Button(WIN_menú, image = IMG_BTN_WIN_menú_jugar, height = 130, width = 130, borderwidth = 0, command = FN_THRDs) BTN_jugar.place (x = 40, y = 75) BTN_config = Button(WIN_menú, image = IMG_BTN_WIN_menú_config, height = 130, width = 130, borderwidth = 0, command = FN_WIN_configurar) BTN_config.place (x = 240, y = 75) BTN_adici = Button(WIN_menú, image = IMG_BTN_WIN_menú_adici, height = 130, width = 130, borderwidth = 0, command = FN_WIN_validar_completo) BTN_adici.place (x = 428, y = 75) BTN_ayuda = Button(WIN_menú, image = IMG_BTN_WIN_menú_ayuda, height = 130, width = 130, borderwidth = 0, command = FN_WIN_ayuda) BTN_ayuda.place (x = 140, y = 270) BTN_salir = Button(WIN_menú, image = IMG_BTN_WIN_menú_salir, height = 130, width = 130, borderwidth = 0, command = WIN_menú.destroy) BTN_salir.place (x = 335, y = 270) WIN_menú.mainloop() #————————————————————————————————————————————————————————————————————Fin Programa Principal—————————————————————————————————————————————————————————————————#
true
3d7e2e3b0c9dabec4bb6de66d9d63f35ab1698d4
Python
marcoguastalli/my_python
/001_input-validation/file_check_test.py
UTF-8
1,966
3.03125
3
[ "MIT" ]
permissive
""" Test for the main program """ import errno import unittest from file_check import FileCheck # Test Suite in order to organize our tests by groups of functionality class FileCheckTest(unittest.TestSuite): class ParsingTests(unittest.TestCase): def test_ArgumentModelCreationOK(self): # given fc = FileCheck() # when # then self.assertIsNotNone(fc._args, "Object not initialized") self.assertTrue("file" in fc._args) def test_shouldFailWhenFileIsNone(self): # given fc = FileCheck() # when with self.assertRaises(SystemExit) as cm: fc.check_file() # then self.assertEqual(cm.exception.code, errno.EINVAL) def test_shouldFailWhenFileIsDirectory(self): # given fc = FileCheck() fc.file = "/" # when with self.assertRaises(SystemExit) as cm: fc.check_file() # then self.assertEqual(cm.exception.code, errno.EISDIR) def test_shouldFailWhenFileNotExist(self): # given fc = FileCheck() fc.file = "test_file.csv" # when with self.assertRaises(SystemExit) as cm: fc.check_file() # then self.assertEqual(cm.exception.code, errno.ENOENT) def test_shouldPassWhenCorrectFile(self): # given fc = FileCheck() fc.file = "test_ok.csv" # when # then self.assertTrue(fc.check_file()) def test_shouldFailWhenIncorrectFile(self): # given fc = FileCheck() fc.file = "test_ko.csv" # when # then self.assertFalse(fc.check_file()) if __name__ == "__main__": unittest.main(FileCheckTest) # Executing our TestSuite
true
6464a46e199a8cdb00ef1ff0c08ad818b7a7d2ce
Python
codecando-x/hands
/HierarchyAndStructure.py
UTF-8
4,757
3.21875
3
[]
no_license
import types import json class HierarchyAndStructure: __data = None __generated_object = None __quick_access_data = {} __py_code_access_keys = {} __separator = '.' __index_identifier = 'i' __type_list = [dict, list, tuple, set] __empties = {dict:'{}', list:'[]', tuple:'()', set:'{}'} __inits = {dict:{}, list:[], tuple:(), set:{}} __direct_access_templates = {dict:"{}['{}']", list:"{}[{}]", tuple:"{}[{}]", set:"{}[{}]"} __obj_chain_templates = {dict:"{}X{}", list:"{}X{}", tuple:"{}X{}", set:"{}X{}"} def __init__(self, data = None, separator: str = '.', index_identifier: str = 'i'): if data is None: return self.__data = data self.__separator = separator self.__index_identifier = index_identifier #we do this here so we do not have to do it while recursing for type_name in self.__type_list: self.__obj_chain_templates[type_name] = self.__obj_chain_templates[type_name].replace('X', self.__separator) self.__generated_object = self.__build(self.__data, types.SimpleNamespace(), 'X', 'X') # returns the python code one would use to access certain keys in the object def direct_access_keys(self, show_values: bool = False) -> str: if show_values is True: return json.dumps(self.__py_code_access_keys, indent=4) else: return json.dumps(list(self.__py_code_access_keys.keys()), indent=4) # returns key strings delimited using a dot def obj_access_keys(self, show_values: bool = False) -> str: if show_values is True: return json.dumps(self.__quick_access_data, indent=4) else: return json.dumps(list(self.__quick_access_data.keys()), indent=4) #get the value of a flattened key def get(self, key: str): if key in self.__quick_access_data: return self.__quick_access_data[key] else: raise KeyError("key: {} not found".format(key)) # return only the values def values(self): return json.dumps(list(self.__quick_access_data.values()), indent=4) def __build(self, current_obj, obj_hierarchy, direct_access_key_hierarchy: str = '', obj_chain_key_hierarchy: str = ''): current_object_type = type(current_obj) if current_object_type in self.__type_list: empty = self.__empties[current_object_type] if len(current_obj) == 0: #add key:val pair to quick_access_data for easy flat retrieval latter self.__quick_access_data[obj_chain_key_hierarchy] = empty #add key to py_code_access_keys list so we can find out key paths for development self.__py_code_access_keys[direct_access_key_hierarchy] = empty index_key = direct_access_key_hierarchy #if type(index_key) is int: if isinstance(index_key, int) or index_key.isdigit() is True: index_key = 'i' + str(index_key) setattr(obj_hierarchy, index_key, self.__inits[current_object_type]) return obj_hierarchy #this holds the keys which we will store in quick_access_data obj_chain_template = self.__obj_chain_templates[current_object_type] #this holds the keys which we will store in py_code_access_keys direct_access_template = self.__direct_access_templates[current_object_type] if current_object_type is dict: items = list(current_obj.items()) elif current_object_type in [list, tuple, set]: items = list(enumerate(current_obj)) for key, val in items: index_key = key if isinstance(index_key, int) or index_key.isdigit() is True: index_key = 'i' + str(index_key) val_type = type(val) new_direct_access_key_hierarchy = direct_access_template.format(direct_access_key_hierarchy, str(key)) new_obj_chain_key_hierarchy = obj_chain_template.format(obj_chain_key_hierarchy, str(key)) if val_type in self.__type_list: new_obj_val = self.__build(val, types.SimpleNamespace(), new_direct_access_key_hierarchy, new_obj_chain_key_hierarchy) setattr(obj_hierarchy, index_key, new_obj_val) else: new_val = str(val) if val_type is str and len(new_val) == 0: new_val = '""' self.__quick_access_data[new_obj_chain_key_hierarchy] = new_val self.__py_code_access_keys[new_direct_access_key_hierarchy] = new_val setattr(obj_hierarchy, index_key, new_val) return obj_hierarchy
true
b49ee7b28fbf3c6a707251a6f278009017cc7f29
Python
DominikVincent/eventbasedcameras
/scripts/NPtoAedat/npToAedat.py
UTF-8
9,742
2.96875
3
[]
no_license
# -*- coding: utf-8 -*- """ This module contains classes, functions and an example (main) for handling AER vision data. """ import glob #import cv2 import numpy as np import matplotlib.pyplot as plt #from win32api import GetSystemMetrics #import timer import os class Events(object): """ Temporal Difference events. data: a NumPy Record Array with the following named fields x: pixel x coordinate, unsigned 16bit int y: pixel y coordinate, unsigned 16bit int p: polarity value, boolean. False=off, True=on ts: timestamp in microseconds, unsigned 64bit int width: The width of the frame. Default = 304. height: The height of the frame. Default = 240. """ def __init__(self, num_events, width=304, height=240): """num_spikes: number of events this instance will initially contain""" self.data = np.rec.array(None, dtype=[('x', np.uint16), ('y', np.uint16), ('p', np.bool_), ('ts', np.uint64)], shape=(num_events)) self.width = width self.height = height def sort_order(self): """Generate data sorted by ascending ts Does not modify instance data Will look through the struct events, and sort all events by the field 'ts'. In other words, it will ensure events_out.ts is monotonically increasing, which is useful when combining events from multiple recordings. """ #chose mergesort because it is a stable sort, at the expense of more #memory usage events_out = np.sort(self.data, order='ts', kind='mergesort') return events_out def extract_roi(self, top_left, size, is_normalize=False): """Extract Region of Interest Does not modify instance data Generates a set of td_events which fall into a rectangular region of interest with top left corner at 'top_left' and size 'size' top_left: [x: int, y: int] size: [width, height] is_normalize: bool. If True, x and y values will be normalized to the cropped region """ min_x = top_left[0] min_y = top_left[1] max_x = size[0] + min_x max_y = size[1] + min_y extracted_data = self.data[(self.data.x >= min_x) & (self.data.x < max_x) & (self.data.y >= min_y) & (self.data.y < max_y)] if is_normalize: self.width = size[0] self.height = size[1] extracted_data = np.copy(extracted_data) extracted_data = extracted_data.view(np.recarray) extracted_data.x -= min_x extracted_data.y -= min_y return extracted_data def apply_refraction(self, us_time): """Implements a refractory period for each pixel. Does not modify instance data In other words, if an event occurs within 'us_time' microseconds of a previous event at the same pixel, then the second event is removed us_time: time in microseconds """ t0 = np.ones((self.width, self.height)) - us_time - 1 valid_indices = np.ones(len(self.data), np.bool_) #with timer.Timer() as ref_timer: i = 0 for datum in np.nditer(self.data): datum_ts = datum['ts'].item(0) datum_x = datum['x'].item(0) datum_y = datum['y'].item(0) if datum_ts - t0[datum_x, datum_y] < us_time: valid_indices[i] = 0 else: t0[datum_x, datum_y] = datum_ts i += 1 #print('Refraction took %s seconds' % ref_timer.secs return self.data[valid_indices.astype('bool')] def write_j_aerOld(self, filename, downsampled): """ writes the td events in 'td_events' to a file specified by 'filename' which is compatible with the jAER framework. To view these events in jAER, make sure to select the DAVIS640 sensor. """ import time # if downsampled: # y = 239 - self.data.y # else: # y = 479 - self.data.y y = self.data.y #y = td_events.y y_shift = 22 + 32 if downsampled: x = 319 - self.data.x else: x = 639 - self.data.x #x = self.data.x x_shift = 12 + 32 p = self.data.p p_shift = 11 + 32 ts_shift = 0 y_final = y.astype(dtype=np.uint64) << y_shift x_final = x.astype(dtype=np.uint64) << x_shift p_final = p.astype(dtype=np.uint64) << p_shift ts_final = self.data.ts.astype(dtype=np.uint64) << ts_shift vector_all = np.array(y_final + x_final + p_final + ts_final, dtype=np.uint64) aedat_file = open(filename, 'wb') version = '2.0' aedat_file.write('#!AER-DAT' + version + '\r\n') aedat_file.write('# This is a raw AE data file - do not edit\r\n') aedat_file.write \ ('# Data format is int32 address, int32 timestamp (8 bytes total), repeated for each event\r\n') aedat_file.write('# Timestamps tick is 1 us\r\n') aedat_file.write('# created ' + time.strftime("%d/%m/%Y") \ + ' ' + time.strftime("%H:%M:%S") \ + ' by the Python function "write2jAER"\r\n') aedat_file.write \ ('# This function fakes the format of DAVIS640 to allow for the full ATIS address space to be used (304x240)\r\n') ##aedat_file.write(vector_all.astype(dtype='>u8').tostring()) to_write = bytearray(vector_all[::-1]) to_write.reverse() aedat_file.write(to_write) #aedat_file.write(vector_all) #vector_all.tofile(aedat_file) aedat_file.close() def write_j_aer(self, filename): """ writes the td events in 'td_events' to a file specified by 'filename' which is compatible with the jAER framework. To view these events in jAER, make sure to select the DAVIS640 sensor. """ import time y = 479 - self.data.y #y = self.data.y #y = td_events.y y_shift = 22 + 32 x = 639 - self.data.x #x = self.data.x #print(x[x==-1]) #x = td_events.x x_shift = 12 + 32 p = self.data.p p_shift = 11 + 32 ts_shift = 0 y_final = y.astype(dtype=np.uint64) << y_shift x_final = x.astype(dtype=np.uint64) << x_shift p_final = p.astype(dtype=np.uint64) << p_shift ts_final = self.data.ts.astype(dtype=np.uint64) << ts_shift vector_all = np.array(y_final + x_final + p_final + ts_final, dtype=np.uint64) aedat_file = open(filename, 'w') print(vector_all.shape) version = '2.0' aedat_file.write('#!AER-DAT' + version + '\r\n') aedat_file.write('# This is a raw AE data file - do not edit\r\n') aedat_file.write \ ('# Data format is int32 address, int32 timestamp (8 bytes total), repeated for each event\r\n') aedat_file.write('# Timestamps tick is 1 us\r\n') aedat_file.write('# created ' + time.strftime("%d/%m/%Y") \ + ' ' + time.strftime("%H:%M:%S") \ + ' by the Python function "write2jAER"\r\n') aedat_file.write \ ('# This function fakes the format of DAVIS640 to allow for the full ATIS address space to be used (304x240)\r\n') ##aedat_file.write(vector_all.astype(dtype='>u8').tostring()) aedat_file.close() aedat_file = open(filename, 'ab') print(hex(vector_all[0])) to_write = bytearray(vector_all[::-1]) print(vector_all[:10]) print() to_write.reverse() aedat_file.write(to_write) #aedat_file.write(vector_all) #vector_all.tofile(aedat_file) aedat_file.close() def loadNParray(self, array): self.data.x = array[:, 0] self.data.y = array[:, 1] self.data.ts = array[:, 2] self.data.p = array[:, 3] def transform_all_subdirs(startpath): for root, dirs, files in os.walk(startpath, topdown=False): for file in files: if file.endswith(".npy") and "events" in file: events = np.load(os.path.join(root, file), allow_pickle = True) downsampled = "down" in file if downsampled: eventObj = Events(events.shape[0], 320, 240) else: eventObj = Events(events.shape[0], 640, 480) eventObj.loadNParray(events) eventObj.write_j_aerOld(os.path.join(root, file[:-4]+"_"+str(events.shape[0])+".aedat"), downsampled) def drawing(events, start, window = 1000): img = np.zeros((480,640)) k = 0 for event in events: if start < event[2] < start + window: k +=1 img[event[1], event[0]] +=1 print(k) plt.pcolormesh(img) plt.show() #arr = np.load("NPtoAedat/downsampled.npy", allow_pickle=True) #drawing(arr, 30000) # print(arr[:10]) # arr[arr[:,3] == -1, 3] = 0 # arr[arr[:,3] == 1, 3] = 2 # print(arr[:10]) # # arr = arr[:1] # #print(arr[:10]) # print(arr.shape) # eventClass = Events(arr.shape[0], 640, 480) # eventClass.loadNParray(arr) # eventClass.write_j_aer("test3New.aedat") # eventClass.write_j_aerOld("test3Old.aedat") # print("events:" ,arr.shape[0], " EPS: ", 1.0*arr.shape[0]/arr[-1,2]) # print("length: ", 1.0*arr[-1,2]-arr[0,2]) # print("start: ", arr[0,2], " last: ", arr[-10:,2]) path = "C:\Users\dominik\OneDrive - Technische Universität Berlin\Dokumente\degreeProject\cameraRecordings\OFRecording\\rotatingBar" # path = os.path.normpath(path) path = unicode(path, 'utf-8') transform_all_subdirs(path)
true
e6ed78af3b750ab9c78aea5680ad5008705e4686
Python
chakri1804/OpenCV_practice
/My Haarcascades/haarcascade_making.py
UTF-8
2,043
2.734375
3
[]
no_license
import cv2 import numpy as np import os ############## Making POS samples into grayscale and ############## resizing given a sample data folder list1 = os.listdir('pos') for x in list1: print(x) gray = cv2.imread('pos/arduino.png',0) resized_image = cv2.resize(gray, (46,34)) cv2.imwrite('pos/0001.png',resized_image) pass ############## ############## ############## Making NEG samples into grayscale and ############## resizing given a sample data folder list1 = os.listdir('neg') for x in list1: print(x) gray = cv2.imread('neg/'+str(x),0) resized_image = cv2.resize(gray, (200,200)) cv2.imwrite('neg/'+str(x),resized_image) pass ############## ############## ############## Removing Ugly broken useless images # def find_uglies(): # match = False # for file_type in ['neg']: # for img in os.listdir(file_type): # for ugly in os.listdir('uglies'): # try: # current_image_path = str(file_type)+'/'+str(img) # ugly = cv2.imread('uglies/'+str(ugly)) # question = cv2.imread(current_image_path) # if ugly.shape == question.shape and not(np.bitwise_xor(ugly,question).any()): # print('That is one ugly pic! Deleting!') # print(current_image_path) # os.remove(current_image_path) # except Exception as e: # print(str(e)) ############## ############## creating the coordinates file def create_pos_n_neg(): for file_type in ['pos','neg']: for img in os.listdir(file_type): if file_type == 'pos': line = file_type+'/'+img+' 1 0 0 46 33\n' with open('info.dat','a') as f: f.write(line) elif file_type == 'neg': line = file_type+'/'+img+'\n' with open('bg.txt','a') as f: f.write(line) ############## create_pos_n_neg()
true
a6af19c982fcfd8d6165b4ca2c515fa9c826a893
Python
Kylin0827/Selenium_work
/homework/task1/f2.py
UTF-8
1,149
3.21875
3
[]
no_license
from selenium import webdriver driver = webdriver.Chrome(r"d:\tools\webdrivers\chromedriver.exe") driver.get('http://www.weather.com.cn/html/province/jiangsu.shtml') ele = driver.find_element_by_id("forecastID") print(ele.text) # 再从 forecastID 元素获取所有子元素dl dls = ele.find_elements_by_tag_name('dl') # 将城市和气温信息保存到列表citys中 citys = [] for dl in dls: # print dl.get_attribute('innerHTML') name = dl.find_element_by_tag_name('dt').text # 最高最低气温位置会变,根据位置决定是span还是b ltemp = dl.find_element_by_tag_name('span').text ltemp = int(ltemp.replace('℃','')) print(name, ltemp) citys.append((name, ltemp)) lowest = None lowestCitys = [] # 温度最低城市列表 for one in citys: curcity = one[0] ltemp = one[1] # 发现气温更低的城市 if lowest==None or ltemp<lowest: lowest = ltemp lowestCitys = [curcity] # 温度和当前最低相同,加入列表 elif ltemp ==lowest: lowestCitys.append(curcity) print('温度最低为%s℃, 城市有%s' % (lowest, ' '.join(lowestCitys)))
true
0a2e47ea25839128b2c390fd2129574da86fef4f
Python
jonasfsilva/jaeger-between-microservices-example
/phoenix/app/models.py
UTF-8
1,043
2.765625
3
[]
no_license
import re from flask_restplus import Namespace, fields def validate_payload(payload): pattern_int = re.compile(r"(0|-?[1-9][0-9]*)") telefone = payload.get('telefone') if not telefone.isdigit(): return { "message": "The phone number is not a integer" }, 400 class UserModel: users_schema = Namespace('users', description='Users', validate=True) model = users_schema.model('users', { "nome": fields.String(required=True, description=(u'Descricao')), "email": fields.String(required=True, description=(u'Email')), "telefone": fields.String(required=True, description=(u'Telefone')), "pais": fields.String(required=False, description=(u'Pais')), "cidade": fields.String(required=False, description=(u'Cidade')), "endereco": fields.String(required=False, description=(u'Endereco')), "senha": fields.String(required=True, description=(u'Senha')), "verificado": fields.Boolean(required=True, description=(u'Verificado')), })
true
e63e13d6888a93999ad0c8b625f9972a445c29c2
Python
iccank05/Facjrul-Ichsan_praktikum-kelas-dan-objek
/luasdankelilinglingkaran.py
UTF-8
1,319
3.640625
4
[]
no_license
class KelilingLingkaran(object) : def __init__ (self, r, p) : self.jarijari = r self.phi = p def hitungKeliling (self) : return 2 * self.phi * self.jarijari def cetakData (self) : print ("jari-jari\t: ", self.jarijari) print ("phi\t: ", self.phi) def cetakKeliling (self) : print ("Keliling\ t= ", self.hitungKeliling()) def main(): KLingkaran1 = KelilingLingkaran (45,3.14) print ("objek Lingkaran1") KLingkaran1.cetakData () KLingkaran1.cetakKeliling () KLingkaran2 = KelilingLingkaran (49,22/7) print ("\nobjek Lingkaran2") KLingkaran2.cetakData () KLingkaran2.cetakKeliling () if __name__ == "__main__": main () class LuasLingkaran(object) : def __init__(self, r, p) : self.jarijari = r self.phi = p def hitungLuas (self) : return self.phi * self.jarijari * self.jarijari def cetakData (self) : print ("jari-jari\t:", self.jarijari) print ("phi\t: ", self.phi) def cetakLuas (self) : print ("luas\t= ", self.hitungLuas()) def main(): LLingkaran1 = LuasLingkaran(17,3.14) print ("objek Lingkaran") LLingkaran1.cetakData () LLingkaran1.cetakLuas () LLingkaran2 = LuasLingkaran(31,22/7) print("\nobjek Lingkaran2") LLingkaran2.cetakData () LLingkaran2.cetakLuas () if __name__ == "__main__": main ()
true
674c75815f9880671e0a2d096d392985eb2d77f9
Python
jiffy1065/crh
/car_battery_charge.py
UTF-8
2,372
4.28125
4
[]
no_license
# NEW!为子类添加新的属性和方法 class Car(): def __init__(self, year, brand, type): self.year = year self.brand = brand self.type = type self.mile = 1000 self.petro = 80 def car_name(self): car_name = 'My car is ' + str(self.year) + ' ' + self.brand + ' ' + self.type + '.' return car_name def update_mile(self, mile_reading): self.mile += mile_reading def car_miles(self): car_miles = "The car's updated miles are " + str(self.mile) + 'km.' return car_miles def fill_petro(self, petro_reading): if petro_reading < self.petro: petro_reading = self.petro print('需要加油!') else: print('暂时不需要加油!') class Battery(): def __init__(self, battery_original_volume=5000): self.battery_original_volume = battery_original_volume def used_battery(self, reading_volume): if reading_volume < self.battery_original_volume: print('需要换电池!') else: print("电池条件良好!") class Charge(): def __init__(self, safe_battery_percentage=0.3): self.safe_battery_percentage = safe_battery_percentage def battery_reading(self, reading_percentage): if self.safe_battery_percentage < reading_percentage: self.safe_battery_percentage = reading_percentage print('电量' + str(reading_percentage * 100) + '%充足!可以行驶!') else: print('电量过低,请充电!') class Electric_car(Car): def __init__(self, year, brand, type): # super() 是一个特殊函数,帮助Python将父类和子类关联起来,调用Electric_car 的父类的方法__init__() super().__init__(year, brand, type) self.battery = Battery() self.charge = Charge() # 对父类没用的方法,如果调用则剔除! def fill_petro(self): print('电车不需要加油!') # 注意写法! my_e_car = Electric_car(2020, 'BYD', '秦') my_e_car.update_mile(1000) print(my_e_car.car_name() + '\n' + my_e_car.car_miles()) # 注意写法! my_e_car.battery.used_battery(6000) my_e_car.charge.battery_reading(0.4) my_e_car.fill_petro() print('\n')
true
78a689c6ad5d4fe63e55549303d075d32873e5f4
Python
daniel-reich/ubiquitous-fiesta
/N7zMhraJLCEMsmeTW_9.py
UTF-8
167
2.828125
3
[]
no_license
def min_swaps(st): l = len(st) t1, t2 = '01', '10' s = sum(st[x]!= t1[x%2] for x in range(l)) s2 = sum(st[x]!= t2[x%2] for x in range(l)) return min(s,s2)
true
e9e63c91e78a468ea3e0245d4a2bac2de0f2425e
Python
zemiret/AGHtochess
/mechanics/model/UnitFactory.py
UTF-8
642
2.8125
3
[]
no_license
from statistics import mean from typing import Any, Dict from model.Param import Param from model.Unit import Unit class UnitFactory: params: Dict[str, Any] def __init__(self, **params: Any): self.params = params def create(self, *, round: int) -> Unit: attrs = {} uniforms = [] for name, v in self.params.items(): if isinstance(v, Param): x, attrs[name] = v.sample(round=round) uniforms.append(x) else: attrs[name] = v price = int((1 + mean(uniforms)) * 100 * round) return Unit(**attrs, price=price)
true
c63249b87c69114089c1ea02eafbd19d3606bfea
Python
Rollingkeyboard/pyscripts
/csvTovcf.py
UTF-8
1,053
2.875
3
[]
no_license
#!/usr/bin/env python csvFile = input('please input csv file:') vcfTemp = input('please input the place you want to store vcf file.e.g /path/to/filename.vcf:') vcfFile = open(vcfTemp,'w') t = open(csvFile,'r') csvTitle = t.readline().split(',') vcfTitle = [] n = 0 for i in csvTitle: vcfTitle.append(input('please input {} convert to[tel,address,name],enter to ignore:'.format(csvTitle[n]))) n = n + 1 t.seek(0) counts = len(t.readlines()) t.seek(1) f = 0 while f != counts: csvls = t.readline().split(',') #print(csvls) vcfFile.write('BEGIN:VCARD'+'\n') vcfFile.write('VERSION:3.0'+'\n') for i in vcfTitle: if i =='': pass elif i.upper()=='TEL': vcfFile.write('TEL;CELL'+':'+csvls[vcfTitle.index(i)]+'\n') elif i.upper()=='ADDRESS': vcfFile.write('ADR'+':'+csvls[vcfTitle.index(i)]+'\n') elif i.upper()=='NAME': vcfFile.write('FN'+':'+csvls[vcfTitle.index(i)]+'\n') vcfFile.write('END:VCARD'+'\n') f = f + 1 t.close() vcfFile.close()
true
4a9c302d2070e0cce9b944ec72c6ad2485cd6bfe
Python
venelink/lxmls-toolkit
/lxmls/deep_learning/utils.py
UTF-8
4,534
2.90625
3
[ "MIT" ]
permissive
import numpy as np # # UTILITIES # def logsumexp(a, axis=None, keepdims=False): """ This is an improvement over the original logsumexp of scipy/maxentropy/maxentutils.py that allows specifying an axis to sum It also allows keepdims=True. """ if axis is None: a = np.asarray(a) a_max = a.max() return a_max + np.log(np.exp(a-a_max).sum()) else: a_max = np.amax(a, axis=axis, keepdims=keepdims) return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims)) def index2onehot(index, N): """ Transforms index to one-hot representation, for example Input: e.g. index = [1, 2, 0], N = 4 Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]] """ L = index.shape[0] onehot = np.zeros((L, N)) for l in np.arange(L): onehot[l, index[l]] = 1 return onehot def glorot_weight_init(shape, activation_function, random_seed=None): """Layer weight initialization after Xavier Glorot et. al""" if random_seed is None: random_seed = np.random.RandomState(1234) # Weights are uniform distributed with span depending on input and output # sizes num_inputs, num_outputs = shape weight = random_seed.uniform( low=-np.sqrt(6. / (num_inputs + num_outputs)), high=np.sqrt(6. / (num_inputs + num_outputs)), size=(num_outputs, num_inputs) ) # Scaling factor depending on non-linearity if activation_function == 'sigmoid': weight *= 4 elif activation_function == 'softmax': weight *= 4 return weight # # Model and Data # class AmazonData(object): """ Template """ def __init__(self, **config): # Data-sets self.datasets = { 'train': { 'input': config['corpus'].train_X, 'output': config['corpus'].train_y[:, 0] }, # 'dev': (config['corpus'].dev_X, config['corpus'].dev_y[:, 0]), 'test': { 'input': config['corpus'].test_X, 'output': config['corpus'].test_y[:, 0] } } # Config self.config = config # Number of samples self.nr_samples = { sset: content['output'].shape[0] for sset, content in self.datasets.items() } def size(self, set_name): return self.nr_samples[set_name] def batches(self, set_name, batch_size=None): dset = self.datasets[set_name] nr_examples = self.nr_samples[set_name] if batch_size is None: nr_batch = 1 batch_size = nr_examples else: nr_batch = int(np.ceil(nr_examples*1./batch_size)) data = [] for batch_n in range(nr_batch): # Colect data for this batch data_batch = {} for side in ['input', 'output']: data_batch[side] = dset[side][ batch_n * batch_size:(batch_n + 1) * batch_size ] data.append(data_batch) return DataIterator(data, nr_samples=self.nr_samples[set_name]) class DataIterator(object): """ Basic data iterator """ def __init__(self, data, nr_samples): self.data = data self.nr_samples = nr_samples def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] class Model(object): def __init__(self, **config): self.initialized = False def initialize_features(self, *args): self.initialized = True raise NotImplementedError( "Need to implement initialize_features method" ) def get_features(self, input=None, output=None): """ Default feature extraction is do nothing """ return {'input': input, 'output': output} def predict(self, *args): raise NotImplementedError("Need to implement predict method") def update(self, *args): # This needs to return at least {'cost' : 0} raise NotImplementedError("Need to implement update method") return {'cost': None} def set(self, **kwargs): raise NotImplementedError("Need to implement set method") def get(self, name): raise NotImplementedError("Need to implement get method") def save(self): raise NotImplementedError("Need to implement save method") def load(self, model_folder): raise NotImplementedError("Need to implement load method")
true
f76ecf851ebe91a867dd62da7f0f386f874a6a04
Python
jhfwb/Web-spiders
/clientScrapySystem/webScrapySystem/GYS_pySpiders/check/single_check.py
UTF-8
3,470
2.609375
3
[]
no_license
import re import requests import os.path from bs4 import BeautifulSoup class WebPageCheck: def __init__(self, start_url_selector='', start_url_re_rule='', cacheDirPath='', header={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" }): if cacheDirPath!='': cacheDirPath=cacheDirPath+'/' if(start_url_re_rule!=''): fileName_re_rule = cacheDirPath + "check-" + start_url_re_rule.replace('/', '').replace('\\', '').replace( '.', '').replace(':', '') + '.html' if os.path.isfile(fileName_re_rule): with open(fileName_re_rule, 'r', encoding='utf-8', newline="") as fp: fileTest2 = ''.join(fp.readlines()) fp.close() else: resp = requests.get(start_url_re_rule, headers=header) fileTest2 = resp.text # 将其保存起来。并进行慢慢进行检测。 with open(fileName_re_rule, 'w', encoding='utf-8', newline="") as fp: fp.write(resp.text) fp.close() soup2 = BeautifulSoup(fileTest2, "html.parser") self.testHtml_selector = soup2 #提取出所有的href hrefs=re.findall(r'href=\"(.*?)\"',str(soup2)) self.hrefs=hrefs if (start_url_selector != ''): fileName_selector = cacheDirPath + "check-" + start_url_selector.replace('/', '').replace('\\', '').replace( '.', '').replace(':', '') + '.html' if os.path.isfile(fileName_selector): with open(fileName_selector, 'r', encoding='utf-8', newline="") as fp: fileTest = ''.join(fp.readlines()) fp.close() else: resp = requests.get(start_url_selector, headers=header) fileTest = resp.text # 将其保存起来。并进行慢慢进行检测。 with open(fileName_selector, 'w', encoding='utf-8', newline="") as fp: fp.write(resp.text) fp.close() soup = BeautifulSoup(fileTest, "html.parser") self.testHtml_selector = soup def check_re_url(self,rules=[]): results={} losehrefs=[] for r in rules: results.setdefault(r,[]) for href in self.hrefs: for rule in rules: try: result=re.fullmatch(rule,href).string results[rule].append(result) except: losehrefs.append(href) results.setdefault('losehrefs',losehrefs) return results def check_selector(self,cssStr): try: return self.testHtml_selector.select(cssStr)[0] except: print("该css有误") return None if __name__ == '__main__': #写上测试的名称 webPageCheck=WebPageCheck(start_url_selector="https://www.11467.com/jinan/co/159221.htm",start_url_re_rule="https://b2b.11467.com/search/-540a88c55e26-pn8.htm",cacheDirPath='ache') a=webPageCheck.check_selector("#contact > div > dl > dd:nth-child(6)") b = webPageCheck.check_re_url(['.*//b2b\.11467\.com/search/-540a88c55e26-pn[\d+]+\.htm','(.+(www.11467.com)/\w+/)(co/)?\d+(\.htm)$']) print(b)
true
0882b5a16a0a73678b9716fc43127bd55ab41aa4
Python
Severoth/pygame-qix
/Enemy.py
UTF-8
325
2.5625
3
[]
no_license
from utils import reach_wall import pygame # Constants SCREEN_HEIGHT = 380 SCREEN_WIDTH = 400 SIZE = 5 RED = (255, 0, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) class Enemy(pygame.sprite.Sprite): def __init__(self): self.width = SIZE self.height = SIZE self.cell = (0, 0)
true
f3b0beb523fbb5b9bfea7274b22164a111eea2e2
Python
TaoHuang13/DeepRL
/02.DDQN/Train.py
UTF-8
1,574
2.734375
3
[ "MIT" ]
permissive
import gym import matplotlib.pyplot as plt import argparse import copy import Agent def reward_func(env, x, x_dot, theta, theta_dot): r1 = (env.x_threshold - abs(x))/env.x_threshold - 0.5 r2 = (env.theta_threshold_radians - abs(theta)) / env.theta_threshold_radians - 0.5 reward = r1 + r2 return reward def main(): agent = Agent.DDQNAgent(env=ENV) env = gym.make(ENV) #env = env.unwrapped reward_list = [] #plt.ion() fig, ax = plt.subplots() for i in range(EPISODES): state = env.reset() ep_reward = 0 while True: #env.render() action = agent.choose_action(state) next_state, reward, done, info = env.step(action) if ENV == 'CartPole-v0': x, x_dot, theta, theta_dot = next_state reward = reward_func(env, x, x_dot, theta, theta_dot) agent.store_transition(state, action, reward, next_state) ep_reward += reward if agent.buffer.check(): agent.learn() if done: print("Episode: {}, reward is {}".format(i, round(ep_reward, 3))) break state = next_state r = copy.copy(reward) reward_list.append(r) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--env', type=str, default='CartPole-v0') parser.add_argument('--episodes', type=int, default=400) args = parser.parse_args() ENV = args.env EPISODES = args.episodes main()
true
678b87da777df7605a9df92e865aaacd28a917f2
Python
dhealy05/TimeStamp
/scripts/analyze_volatility.py
UTF-8
3,886
2.859375
3
[]
no_license
# # # # # # # # # # # # I M P O R T S # # # # # # # # # # # # from __future__ import division import sys # for command line arguments import os # for manipulating files and folders import argparse # for command line arguments import pandas as pd import numpy as np import matplotlib.pyplot as plt ############### ####metrics#### ############### def get_metrics(moving_wallets, prices): moving_wallets, prices = equal_lengths(moving_wallets, prices) drawdown = get_max_drawdown(moving_wallets) price_drawdown = get_max_drawdown(get_market_returns(prices)) relative_drawdown = drawdown/price_drawdown beta = get_beta(moving_wallets, prices) deviation, rv = get_relative_volatility(moving_wallets, prices) sharpe = get_ratio(moving_wallets, prices) print("Beta: " + str(beta)) print("Max Drawdown: " + str(drawdown)) print("Relative Drawdown: " + str(relative_drawdown)) print("Sharpe Ratio: " + str(sharpe)) print("Relative Volatilty: " + str(rv)) return [sharpe, drawdown, relative_drawdown, deviation, rv, beta] def get_relative_volatility(moving_wallets, prices): market = get_market_returns(prices) market_variance = np.std(market) index_variance = np.std(moving_wallets) #plt.plot(market, label='Market Returns') #plt.plot(moving_wallets, label='Algo Returns') #plt.xlabel('2/11/2019 - 1/15/2020') #plt.ylabel('Returns') #plt.title('Algo vs Market') #plt.legend() #plt.show() print(market_variance) print(index_variance) relative_volatility = index_variance/market_variance return index_variance, relative_volatility def get_ratio(moving_wallets, prices): moving_wallets[:] = [moving_wallet - 100 for moving_wallet in moving_wallets] stddev = np.std(moving_wallets) sharpe_ratio = moving_wallets[len(moving_wallets)-1] / stddev return sharpe_ratio def get_max_drawdown(moving_wallets): drawdown = 0 i = np.argmax(np.maximum.accumulate(moving_wallets) - moving_wallets) # end of the period if len(moving_wallets[:i]) > 0: j = np.argmax(moving_wallets[:i]) # start of period drawdown = (moving_wallets[j] - moving_wallets[i]) / moving_wallets[j] return np.round(drawdown*100, 2) def get_beta(moving_wallets, prices): #stddev = np.std(moving_wallets) #print(stddev) market_returns, relative_performances = [], [] for i in range(0, len(prices) - 1, 1): #returns: #market = (prices[i] / prices[0]) - 1.0 #relative_performance = (moving_wallets[i] / 100) - 1.0 #performance and relative performance #market = (prices[i] / prices[0]) #relative_performance = ((moving_wallets[i] / 100) / market) #excess performance market = (prices[i] / prices[0]) relative_performance = ((moving_wallets[i] / 100) - market) market_returns.append(market) relative_performances.append(relative_performance) #print(market_returns[len(market_returns)-1]) #print(relative_performances[len(relative_performances)-1]) covariance = np.cov(market_returns, relative_performances, bias=True)[0][1] #covariance = np.cov(market_returns, relative_performances)[0][1] market_variance = np.var(market_returns) beta = covariance / market_variance #print(covariance) #print(market_variance) #print(beta) return beta def get_market_returns(prices): market_returns = [] for i in range(0, len(prices) - 1, 1): market = (prices[i] / prices[0]) * 100 market_returns.append(market) return market_returns def equal_lengths(moving_wallets, prices): if len(moving_wallets) > len(prices): moving_wallets = moving_wallets[0:len(prices)] else: prices = prices[0:len(moving_wallets)] return moving_wallets, prices
true
91405c6f19115562cc87e6d82986825b28d95fcf
Python
KuroKousuii/Codeforces
/Python/800 - III/1191A.py
UTF-8
165
3.359375
3
[]
no_license
x = int(input()) check = x % 4 if check == 0: print(f'{1} A') elif check == 1: print(f'{0} A') elif check == 2: print(f'{1} B') else: print(f'{2} A')
true
fe1308c7b19fb0c88d15cc3b194eee7c69e48b7b
Python
thitimon171143/MyPython
/midterm 2562-1/important02.py
UTF-8
155
3.34375
3
[]
no_license
s = 0 n = 0 t = float(input()) while t >= 0 : t = float(input()) s += t n += 1 if n == 0 : print('No Data') else: print('avg =',(s/n))
true
d726e7a6d51432d517babaa0a80161763e97e968
Python
MuSaCN/PythonLearning
/Learning_Quant/python金融大数据挖掘与分析全流程详解/第14章源代码汇总/14.4.1 xlwings库的基本用法.py
UTF-8
1,045
3.46875
3
[]
no_license
# ============================================================================= # 14.4.1 Python创建Excel基础 by 王宇韬 # ============================================================================= import xlwings as xw import matplotlib.pyplot as plt import pandas as pd # 新建一个Excel文件,并设置为不可见 app = xw.App(visible=True,add_book=False) wb = app.books.open("华小智.xlsx") wb = app.books.add() # wb就是新建的工作簿 wb = app.books[0] # 创建新工作表 sht = wb.sheets.add() sht = wb.sheets[0] # 将A1单元格改为华小智 sht.range('A1','A4').value = '23' # 导入表格 df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) sht.range('A2').value = df # 生成图片 fig = plt.figure() x = [1, 2, 3] y = [2, 4, 6] plt.plot(x, y) # 将产生的图片导入到Excel当中 sht.pictures.add(fig, name='图片1', update=True, left=500) # 保存生成的Excel文件 wb.save('华小智.xlsx') wb.close() # 退出工作簿 app.quit() # 退出程序 print('生成Excel文件成功')
true
9726c8e61f6d02bd046b6145979bdbaff878608c
Python
jdgreen/Project-Euler
/solutions/src/python/euler018.py
UTF-8
919
3.140625
3
[]
no_license
#dynamic program to find highest path through a tree data file def best_path1(file): i = 0 #read in data points for line in reversed(list(open(file))): row = map(int,line.rstrip().split(" ")) #print row m = 0 for element in range(len(row)): if i == 0: i = 1 break elif sum[element] > sum[element+1]: row[element] += sum[element] else: row[element] += sum[element+1] sum = row print line return sum[0] def best_path(file): i = 0 #read in data points with open(file) as data: for line in reversed(list(data)): row = map(int,line.strip().split()) m = 0 for element in range(len(row)): if i == 0: i = 1 break elif sum[element] > sum[element+1]: row[element] += sum[element] else: row[element] += sum[element+1] sum = row return sum[0] print best_path("/home/jonathan/Documents/computing/project_euler/data/euler018.data")
true
fe6946a7118db2ecff88c19f18712f18a0217f1e
Python
jankidepala/machine-learning-IOT
/Tensor-flow/HelloWorld.py
UTF-8
329
2.75
3
[]
no_license
import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') tf.contrib.data.Dataset.from_tensor_slices dataset1 = tf.contrib.data.Dataset.from_tensor_slices(tf.random_uniform([4, 20])) print(dataset1.output_types) # ==> "tf.float32" print(dataset1.output_shapes) # ==> "(10,)" sess = tf.Session() print(sess.run(hello))
true
bfe7b44337e9990395f818dd50824fe7c9e8c1a5
Python
mpettersson/PythonReview
/questions/math/is_prime.py
UTF-8
1,374
4.125
4
[]
no_license
""" IS PRIME (CHECK FOR PRIMALITY) Is a number prime? Remember: A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is NOT prime is called a composite number. """ import math # Naive Solution: Check every num from 2 to num - 1 to see if it evenly divides the num. def is_prime_naive(num): if num < 2: return False i = 2 while i < num: if num % i == 0: return False i += 1 return True # Check every num from 2 to math.sqrt(num) to see if it num % i is zero. def is_prime(num): if num < 2: return False i = 2 while i <= math.sqrt(num): if num % i == 0: return False i += 1 return True def is_prime_optimized(num): if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i = i + 6 return True nums = [-10, 0, 1, 2, 3, 4, 100, 113] [print(f"is_prime_naive({n}): {is_prime_naive(n)}") for n in nums] print() [print(f"is_prime({n}): {is_prime(n)}") for n in nums] print() [print(f"is_prime_optimized({n}): {is_prime_optimized(n)}") for n in nums]
true
c81a0e0a8a92a34d4813c4309e41be694927f379
Python
srinivas1746/Object-Trackers
/people_counter.py
UTF-8
1,179
2.84375
3
[]
no_license
import cv2 import imutils from time import sleep # Initializing the HOG person # detector hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # Reading the Image # image = cv2.imread('/home/srinu/Desktop/test.jpeg') cam = cv2.VideoCapture("/home/srinu/Downloads/People counting.mp4") currentframe = 0 while (True): # reading from frame ret, image = cam.read() # Resizing the Image image = imutils.resize(image, width=min(400, image.shape[1])) # Detecting all the regions in the # Image that has a pedestrians inside it (regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(4, 4), scale=1.05) # Drawing the regions in the Image for (x, y, w, h) in regions: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) print(len(regions)) # Showing the output Image if(len(regions)>0): cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows()
true
18c9c74ae072d802940f2a35cb7181e032dabe64
Python
SoundaryaAdaikkalavan/Guvi-Beginners
/insert_max.py
UTF-8
298
2.828125
3
[]
no_license
n,m=map(int,input().split())#input c=list(map(int,input().split()))#list1 a=list(map(int,input().split()))#list2 b=list(map(int,input().split()))#list3 d=0 for i in range(0,len(b)): a.append(b[i]) if d==0: print(max(a),end="") d+=1 else: print("",max(a),end="")
true