blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2b1722cd1358365072b4c647ebd0a44b9c083d8c
Signa-ling/Competitive-Programming-Solution
/AtCoder/ABC/ABC162/ABC162_B.py
158
3.703125
4
n = int(input()) ans = 0 for i in range(1, n+1): if i%3==0 and i%5==0: continue elif i%3==0: continue elif i%5==0: continue ans+=i print(ans)
e7a2610c5c3e66e5a151b584434e03c3f4a1b41b
DataEdgeSystems/Project
/Python/Scripts/inhml.py
492
3.8125
4
class A: def __init__(self): print 'init obj of A class' def disp(self): print 'disp in A class' class B(A): def __init__(self): A.__init__(self) print 'init obj of B class' def disp(self): A.disp(self) print 'disp in B class' class C(B): def __init__(self): B.__init__(self) print 'init obj of C class' def disp(self): B.disp(self) print 'disp in C class' c=C() c.disp()
31f292621af342d500fb51a1c00b309fe3da9520
gianbianchi/Uniso
/Ago-24-2021/Python/ex007.py
142
3.984375
4
tempC = float(input("Qual a temperatura em Celsius? ")) tempF = (9*tempC + 160)/5 print("A temperatura em Fahrenheit é: {}".format(tempF))
b4092ba066dc962b651545199df76f7fa7edee78
Bibin22/pythonpgms
/Tutorials/Class Prgms/static and instance variable.py
229
3.828125
4
class Car: wheels = 4 def __init__(self): self.car ="BMW" self.mil =12 c1 = Car() c2 = Car() c1.car = "Audi" c1.mil = 19 Car.wheels = 17 print(c1.car, c1.mil, Car.wheels) print(c2.car, c2.mil, Car.wheels)
5a2c863cd177dc3a305fee96c3bc8e3c879524cf
Technicoryx/python_strings_inbuilt_functions
/string_04.py
382
3.96875
4
"""Below Python Programme demonstrate casefold functions in a string""" string = "PYTHON IS AWESOME" # print lowercase string print("Lowercase string:", string.casefold()) firstString = "der Fluß" secondString = "der Fluss" # ß is equivalent to ss if firstString.casefold() == secondString.casefold(): print('The strings are equal.') else: print('The strings are not equal.')
047e4393383bfaea72753cf1e4208c797a951301
RonnyJiang/Python_PyCharm
/MapReduce/mapreduceTest.py
1,888
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @desc:mapreduce的练习题 @author: Ronny @contact: set@aliyun.com @site: www.lemon.pub @software: PyCharm @since:python 3.5.2(32bit) on 2016/11/9.0:59 """ '''练习①:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。''' # 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: def normalize(name): return str(name).lower().capitalize() L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) '''练习②:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:''' # -*- coding: utf-8 -*- from functools import reduce def prod(L): def multiple(x,y): return x*y return reduce(multiple,L) print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) print(3*5*7*9) #945 一致 print(pow(2,3)) '''练习③:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:''' # 此题有待完善 from functools import reduce print(float("30")) def str2float(s): if type(eval(s))==float: if '.' in s: if s.endswith('.'): return int(s[:len(s)-1]) * 1.0 n = s.find('.') return reduce(lambda x, y: x + y, [reduce(lambda x, y: x * 10 + y, map(int, s[:n])), reduce(lambda x, y: x * 10 + y, map(int, s[n + 1:])) / pow(10, len( s) - n - 1)]) else: return int(s) elif s.isdigit(): return int(s)*1.0 else: raise TypeError("bad parameters type") print(str2float('123854562314.0001')) print(str2float('30.')) print(str2float('39')) #这个还有问题 # print(str2float("-10.15")) 负的浮点数还没考虑
90de1d12dbabb014edb77b66c42c23848dac38ec
BitorqubitT/ADT
/Hashtable/DoublyLinkedList.py
1,713
3.734375
4
class DoublyLinkedListNode: def __init__(self, searchKey, newItem): self.searchKey = searchKey self.data = self.searchKey, newItem self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None # no need for tail as always the next pointer of last object will remain as none self.size = 0 def insertNode(self, searchKey=None, newItem=None): node = DoublyLinkedListNode(searchKey, newItem) # make new node node.next = self.head if self.head is not None: self.head.prev = node self.head = node node.prev = self.head def searchList(self, searchKey): p = self.head while p is not None: if p.data is not None: if p.data[0] == searchKey: return p.data, p if p.next is not None: p = p.next else: return False def deleteNode(self, searchKey): p = self.searchList(searchKey) if p is None: return False elif p is not False: p = self.searchList(searchKey)[1] if p.prev is not None and p != self.head: p.prev.next = p.next else: self.head = p.next if p.next is not None: p.next.prev = p.prev return True else: return False def getList(self): node = self.head i = [] while node: if node.data is not None: i.append(node.data) node = node.next return i def get_top(self): return self.head
ef451fb13f42559b46be5b8fd01fda0bd0365953
andyd0/foobar
/level_3/fuel_injection_perfection.py
970
3.75
4
# Fuel Injection Perfection def solution(n): # Python will convert n to bignum if necessary so 309 digits should # be fine n = int(n) count = 0 while n > 1: # Last bit of a binary number indicates whether the number is odd # if the last bit is 1, it's odd. n & to 1 will lead to either 1 or 0 if n & 1 == 1: # if odd, +/- is based on whether the number is a multiple of 4 # to ensure the subsequent number is still even and then on the even # path. 3 is a special case as we always want to choose 2 to avoid # the aditional step if n != 3 and ((n + 1) % 4 == 0): n += 1 else: n -= 1 else: # shifting the binary number by 1 to the right divides by 2. n >>= 1 count += 1 return count assert solution('3') == 2 assert solution('15') == 5 assert solution('4') == 2 assert solution('16') == 4 assert solution('17') == 5 assert solution('18') == 5 assert solution('19') == 6
be87d7d6412dc1a7f596ddfc948bc92202c31a18
andresnunes/Projetos_Python
/Projetos_Python/Exercicios-Livro-PythonForEverybody/6Ex5.py
390
4.53125
5
''' Exercise 5: Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number. ''' str = 'X-DSPAM-Confidence:0.8475' start = str.find(":") num = float(str[start + 1:]) print(num)
ccc9971579e361226403e3d74ae7ae88ad202601
viverbungag/Codewars
/Integers-Recreation One.py
430
3.609375
4
def list_squared(m, n): # your code ans = [] for x in range(m, n): div = 0 for y in range(1, int((x**0.5)+1)): if x % y == 0: if(x / y == y): div += (y**2) else: div += (y**2) + ((x/y)**2) if (int(div**0.5) - (div**0.5)) == 0: ans.append([x, int(div)]) return ans print (list_squared(1, 250))
9699225c8d0681ae1fbf50a9e87a299407f5ed0f
lishuchen/Algorithms
/lintcode/132_Word_Search_II.py
1,521
3.859375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- class TrieNode: def __init__(self): self.dct = dict() self.is_end = False class Solution: # @param board, a list of lists of 1 length string # @param words: A list of string # @return: A list of string def wordSearchII(self, board, words): # write your code here if not board or not words: return [] # build trie self.root = TrieNode() for word in words: self.build_trie(word) self.board = board self.rows = len(board) self.cols = len(board[0]) self.visit = [[False] * self.cols for _ in range(self.rows)] self.rsl = set() for i in range(self.rows): for j in range(self.cols): self.search(i, j, self.root, "") return list(self.rsl) def search(self, i, j, node, word): if node.is_end: self.rsl.add(word) if -1 < i < self.rows and -1 < j < self.cols and self.visit[i][j] == False: self.visit[i][j] = True ch = self.board[i][j] if ch in node.dct: offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)] for x, y in offsets: self.search(i + x, j + y, node.dct[ch], word + ch) self.visit[i][j] = False def build_trie(self, word): node = self.root for ch in word: node = node.dct.setdefault(ch, TrieNode()) node.is_end = True
af16f54c735cff24631d45c8e0ced7de7e40aefe
marcobakos/python-by-examples
/zipfile/zip.py
1,518
3.90625
4
#!/usr/bin/python # # Copyright (C) 2014 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program 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 General Public License for more details. import os import zipfile try: import zlib comp = zipfile.ZIP_DEFLATED except: comp = zipfile.ZIP_STORED from argparse import ArgumentParser def zip(zipname, file_to_compress): zp = zipfile.ZipFile(zipname, mode="w", compression=comp ) for f in file_to_compress: if not os.path.exists(f): print("Cannot find %s, continuing.." % f) continue zp.write(f) zp.close() print("Done, created %s" % zipname) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--file', help="file(s) to zip", required=True, nargs='+' ) parser.add_argument('--zipname', help="name of zip", required=True, nargs=1 ) args = parser.parse_args() zip( zipname=args.zipname[0], file_to_compress=args.file )
5c24ab5e11286fd383c14b872451d6bcbc5924f4
anirudhjayaraman/Project-Euler-Solutions
/euler13.py
400
3.59375
4
# Read the problem matrix into an array in python filename = 'euler13.txt' with open(filename, "r") as ins: array = [] for line in ins: array.append(line) # Convert the array into an array of integers newArray = [] for i in array: newArray.append(int(i)) # Sum up the array and print the first 10 numbers of the sum as a string arraySum = sum(newArray) print str(arraySum)[:10]
f5dfb150280ea6ccbfd0cf5c69b0a0784b8c724d
WilliamHdz/Tareas_Proyectos
/PYTHON/P07.py
1,478
3.640625
4
flag = True while flag == True: archivo = open("Salida_P07.txt","a") print("") print("####################################################################") print("# 1. CALCULAR EL FACTORIAL DE UN NÚMERO DIVISIBLE ENTRE 7 ---- (f) #") print("# 2. HISTORIAL ----------------------------------------------- (h) #") print("# 3. SALIR --------------------------------------------------- (s) #") print("####################################################################") print("") opt = input("INGRESE LA OPCIÓN QUE DESEA EJECUTAR: ") print("") if opt == "f": fact = int(1) num = int(input("INGRESE UN NÚMERO DIVISIBLE ENTRE 7: ")) if (num%7) == 0: for i in range(1,num+1): fact *= i print("EL FACTORIAL DE",num,"ES:",fact) archivo.write('EL FACTORIAL DE %s'%num+' ES: %s'%fact+'\n') archivo.close() else: print("¡ERROR! EL NÚMERO",num,"NO ES DIVISIBLE ENTRE 7.") archivo.write('EL NÚMERO %s'%num+' NO ES DIVISIBLE ENTRE 7.\n') archivo.close() elif opt == "h": archivo = open("Salida_P07.txt","r") historial = archivo.read() archivo.close() print(historial) elif opt == "s": flag = False else: print("######################################") print("# USTED NO INGRESO UNA OPCIÓN VALIDA #") print("######################################") print("") print("####################################") print("# GRACIAS POR UTILIZAR EL PROGRAMA #") print("####################################")
e3c398cd033c81858e227d1f2e296cff1e87385e
rohitr84/project-euler-py
/python/src/Set_1_to_25/Problem_25.py
1,164
4.0625
4
#!/usr/bin/python # # Problem 25 # # Find the first term in the Fibonacci sequence to # contain 1000 digits. import unittest class Test_Problem_25(unittest.TestCase): def test_first_fibonacci_with_2_digits(self): """ """ self.assertEqual(7, first_term_in_fibonacci_sequence_with_n_digits(2)) def test_first_fibonacci_with_3_digits(self): """ """ self.assertEqual(12, first_term_in_fibonacci_sequence_with_n_digits(3)) def first_term_in_fibonacci_sequence_with_n_digits(n_digits): """ Computes fibonacci numbers, tracking term count until number exceeds 10^(n-1) digits. """ # Initializations term = 2 previous = 1 current = 1 # Compute fibonacci numbers until current exceeds 10^(n-1) while current < pow(10, n_digits - 1): # Update fibonacci numbers current += previous previous = current - previous # Increment term count term += 1 return term if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Test_Problem_25) unittest.TextTestRunner(verbosity=2).run(suite) target = 1000 print "First Fibonacci to contain 1000 digits:", \ first_term_in_fibonacci_sequence_with_n_digits(target)
6c99da2077daba547994e87adf5b6f31fd33c96c
mplanchard/recipes
/python/decorators/decorator_with_or_without_args.py
4,023
4.3125
4
""" The following illustrates the flow of execution for a flexible decorator that be called either be called, with/without arguments, e.g. ``@decorate()`` or ``@decorate('foo')``, or used as a raw decorator, e.g. ``@decorate``. Rather than ``callable()``, if you expect a callable object might be passed to your decorator, you can also use ``inspect.isfunction(arg) or inspect.ismethod(arg)``. """ from inspect import isfunction, ismethod class decorate: def __init__(self, *args, **kwargs): """__init__ is always called at decoration time If the decorator is called with parens, ``__init__()`` is called with the arguments passed to the decorator. If the decorator is raw, ``__init__()`` is called with one argument, which is the decorated function. Note that because of this, you may only have ONE specified positional argument, which is understood to either be the decorated function or something else. Other arguments must be kwargs. """ print('__init__({})'.format(locals())) self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): """__call__ is either called at decoration time or at runtime If the decorator is specified with parens, as a call, ``__call__()`` is called upon decoration and should return a wrapped function. In this case, only one argument is passed to ``__call__()`, which is the decorated function. If the decorator is raw, with no parens, ``__call__()`` will be called when the funcion is called, and acts as the function wrapper. In this case, the arguments to ``__call__()`` are the arguments passed to the function. """ print('__call__({})'.format(locals())) if len(self.args) == 1 and callable(self.args[0]) and not self.kwargs: print('__call__ acting as func wrapper') func = self.args[0] self._pre() ret = func(*args, **kwargs) self._post() return ret elif len(args) == 1 and callable(args[0]) and not kwargs: print('__call__ returning a wrapped func') func = args[0] def func_wrapper(*args, **kwargs): """This wrapper will replace the decorated function As such, it should be sure to call the decorated function. The arguments to this wrapper are the arguments passed to the function. """ print('func_wrapper({})'.format(locals())) self._pre() ret = func(*args, **kwargs) self._post() return ret return func_wrapper else: raise RuntimeError('Problem with call signature') def _pre(self): print('_pre function') def _post(self): print('_post function') # print('pre-decoration with args') # # # @decorate() # def func_with_dec_args(*args): # print('func_with_dec_args({})'.format(args)) # return 'foo' # # # print('post-decoration with args') # # # print('pre-decoration no args') # # @decorate # def func_with_no_dec_args(*args): # print('func_with_no_dec_args({})'.format(args)) # return 'bar' # # # print('post-decoration no args') # # # ret = func_with_dec_args('a', 'b') # print(ret) # # ret = func_with_no_dec_args('c', 'd') # print(ret) class SomeClass: @decorate() def meth_with_dec_args(self, *args): print('meth_with_dec_args({})'.format(args)) return 'args' # @decorate # def meth_with_no_dec_args(self, *args): # print('meth_with_no_dec_args({})'.format(args)) # return 'no_args' print('pre-instantiation') c = SomeClass() print('post-instantiation') print(c.meth_with_dec_args('a', 'b')) # print(c.meth_with_no_dec_args('c', 'd'))
f90804b775b25e02452dff247c1cb0a602766e46
harrylewis/exercism
/python/parallel-letter-frequency/parallel_letter_frequency.py
290
3.75
4
def calculate(text_input): counts = {} for group in text_input: for char in group.lower(): if char.isalpha(): if char in counts: counts[char] += 1 else: counts[char] = 1 return counts
6a7b344ed8a41007e35b51362660805bf9554d63
largomst/HackerRank-Algorithms
/Implementation/Kangaroo.py
392
3.53125
4
x1, v1, x2, v2 = input().strip().split(' ') x1, v1, x2, v2 = int(x1), int(v1), int(x2), int(v2) result = 'NO' if x1 < x2 and v1 > v2: while x1 < x2: x1 += v1 x2 += v2 if x1 == x2: result = 'YES' elif x1 > x2 and v1 < v2: while x1 > x2: x1 += v1 x2 += v2 if x1 == x2: result = 'YES' else: pass print(result)
947ef339489ddfb6ba1234af8ee4874152f6a89c
lbenet/ValidiPy
/src/python/jet.py
2,761
3.78125
4
# -*- coding:utf-8 -*- """The x in the argument of functions is actually an object which is itself a derivative pair""" import numpy as math # NB import numpy as np class Jet: """Multidim jet""" def __init__(self, valor, deriv=0.0): self.valor = valor self.deriv = deriv def __add__(self, otro): if not isinstance(otro, Jet): otro = Jet(otro) return Jet(self.valor+otro.valor, self.deriv+otro.deriv) def __radd__(self, otro): return self+otro def __sub__(self, otro): if not isinstance(otro, Jet): otro = Jet(otro) return Jet(self.valor-otro.valor, self.deriv-otro.deriv) def __neg__(self, otro): return Jet(-self.valor, -self.otro) def __rsub__(self, otro): return (self - otro).neg() def __pow__(self, n): if not isinstance(n, int): raise ValueError("Powers not implemented for non-integers") return Jet(self.valor**n, n*self.valor**(n-1) * self.deriv) def __repr__(self): return "Jet({}, {})".format(self.valor, self.deriv) def __mul__(self, otro): if not isinstance(otro, Jet): otro = Jet(otro) return Jet(self.valor*otro.valor, self.valor*otro.deriv + self.deriv*otro.valor) def __rmul__(self, otro): return self*otro def __div__(self, otro): if not isinstance(otro, Jet): otro = Jet(otro) ratio = self.valor / otro.valor return Jet(ratio, (self.deriv - ratio * otro.deriv) / otro.valor) def __rdiv__(self, otro): if not isinstance(otro, Jet): otro = Jet(otro) return (otro / self) def sin(self): return Jet(sin(self.valor), cos(self.valor) * self.deriv) def cos(self): return Jet(cos(self.valor), -sin(self.valor) * self.deriv) def exp(self): value = math.exp(self.valor) return Jet(value, value*self.deriv) # def __getitem__(self, n): # if n==0: # return self.valor # elif n==1: # return self.deriv # raise ValueError("Item number must be 0 or 1; was given %d" % n) def tuple(self): return (self.valor, self.deriv) def derivar(f, a): """Calcular el jet (valor y derivada) de la funcion f(x) en el punto x=a""" x = Jet(a, np.ones_like(a)) result = f(x) return result.tuple() def sin(x): #print "Trying sin of ", x try: return x.sin() except: return math.sin(x) def cos(x): try: return x.cos() except: return math.cos(x) def exp(x): try: return x.exp() except: return math.exp(x)
797055c6a2c9c69f477a6cfe78c4a25074068dec
abhianshi/Natural-Language-Processing
/Dependency Parser/Dependency_Parser.py
11,823
3.65625
4
# Natural Language Processing # Assignment - 1 # Creator : Abhianshu Singla # NID : ab808557 # Used Atom for writing python Script # Python version - 3.5.2 # While running, it takes two inputs - the file paths of source file and target file # import statements import sys # Reading the arguments from the terminal and open the source file. # Returns the source string. def readInput(): print("\n\nInput Sentence:") input_words = [] input_tags = [] source_file = open(str(sys.argv[1]), "r") source_string = str(source_file.read()) sequence = source_string.split("\n") for i in range(len(sequence)): print(sequence[i], end = " ") if(len(sequence[i]) > 0): word,tag = sequence[i].split("/") input_words.append(word) input_tags.append(tag) else: # Deleting the empty new line character del sequence[len(sequence) - 1] return sequence, input_words, input_tags def corpusData(): # Corpus File path # corpus_file = open("/Users/abhianshusingla/Downloads/CAP6640-prog3-distro/wsj-clean.txt") corpus_file = open("./wsj-clean.txt") #corpus_file = open("/Users/abhianshusingla/Documents/NLP/new_corpus.txt") corpus_string = str(corpus_file.read()) # Data Structures to corpus data corpus_dictionary = {} token_list = [] tag_list = [] # Parameters for counting the relevant data in corpus sentence_count = 0 rightArc_count = 0 leftArc_count = 0 root_arc_count = 0 # Temporary Variables temp_list = [] # Reading the corpus file line by line sentences = corpus_string.split("\n") for k in range(len(sentences)): # Tokenize every word in a sentence words = [] temp_words1 = sentences[k].split("\t") for j in range(len(temp_words1)): temp_words2 = temp_words1[j].split(" ") words.extend(temp_words2) # End of Sentence if(len(words) < 2): # countingArcs(corpus_dictionary, temp_list, root_arc_count, rightArc_count, leftArc_count) # Counting the arcs in a sentence for i in range(len(temp_list)): if(temp_list[i][3] == 0): root_arc_count += 1 elif(temp_list[i][0] > temp_list[i][3]): rightArc_count += 1 tag1 = temp_list[i][2] tag2 = temp_list[temp_list[i][3] - 1][2] key = (tag1, tag2, 'R') if(key in corpus_dictionary): corpus_dictionary[key] += 1 else: corpus_dictionary[key] = 1 elif(temp_list[i][0] < temp_list[i][3]): leftArc_count += 1 tag1 = temp_list[i][2] tag2 = temp_list[temp_list[i][3] - 1][2] key = (tag1, tag2, 'L') if(key in corpus_dictionary): corpus_dictionary[key] += 1 else: corpus_dictionary[key] = 1 sentence_count += 1 temp_list = [] elif(len(temp_list) != 0 and int(words[0]) == 1): # countingArcs(corpus_dictionary, temp_list, root_arc_count, rightArc_count, leftArc_count) # Counting the arcs in a sentence for i in range(len(temp_list)): if(temp_list[i][3] == 0): root_arc_count += 1 elif(temp_list[i][0] > temp_list[i][3]): rightArc_count += 1 tag1 = temp_list[i][2] tag2 = temp_list[temp_list[i][3] - 1][2] key = (tag1, tag2, 'R') if(key in corpus_dictionary): corpus_dictionary[key] += 1 else: corpus_dictionary[key] = 1 elif(temp_list[i][0] < temp_list[i][3]): leftArc_count += 1 tag1 = temp_list[i][2] tag2 = temp_list[temp_list[i][3] - 1][2] key = (tag1, tag2, 'L') if(key in corpus_dictionary): corpus_dictionary[key] += 1 else: corpus_dictionary[key] = 1 sentence_count += 1 temp_list = [] token_list.append(words[1]) tag_list.append(words[2]) words[0] = int(words[0]) words[3] = int(words[3]) temp_list.append(words) else: # Continuation of a sentence token_list.append(words[1]) tag_list.append(words[2]) words[0] = int(words[0]) words[3] = int(words[3]) temp_list.append(words) tag_list = list(set(tag_list)) tag_list.sort() # Printing corpus data print("\nCorpus Statistics:\n") print(" # sentences : ", sentence_count) print(" # tokens : ", len(token_list)) print(" # POS tags : ", len(tag_list)) print(" # Left-Arcs : ", leftArc_count) print(" # Right-Arcs : ", rightArc_count) print(" # Root-Arcs : ", root_arc_count) return corpus_dictionary, tag_list def printArcs(corpus_dictionary, tag_list): print("\n\nLeft Arc Array Nonzero Counts:") for i in range(len(tag_list)): print('\n{: <4}'.format(tag_list[i]), " : ", end = "") for j in range(len(tag_list)): key = (tag_list[i], tag_list[j], 'L') if(key in corpus_dictionary): #print("[", '{: <4}'.format(tag_list[j]), ",", '{: <4}'.format(corpus_dictionary[key]), "]", end = " ") print("[", tag_list[j], ",", corpus_dictionary[key], "]", end = " ") print("\n\n\nRight Arc Array Nonzero Counts:") for i in range(len(tag_list)): print('\n{: <4}'.format(tag_list[i]), " : ", end = "") for j in range(len(tag_list)): key = (tag_list[i], tag_list[j], 'R') if(key in corpus_dictionary): #print("[", '{: <4}'.format(tag_list[j]), ",", '{: <4}'.format(corpus_dictionary[key]), "]", end = " ") print("[", tag_list[j], ",", corpus_dictionary[key], "]", end = " ") print("\n\n\nArc Confusion Array:") confusion_arc_count = 0 for i in range(len(tag_list)): print('\n{: <4}'.format(tag_list[i]), " : ", end = "") for j in range(len(tag_list)): key1 = (tag_list[i], tag_list[j], 'L') key2 = (tag_list[i], tag_list[j], 'R') if(key1 in corpus_dictionary and key2 in corpus_dictionary): #print("[", '{: <4}'.format(tag_list[j]), ",", '{: <4}'.format(corpus_dictionary[key]), "]", end = " ") print("[", tag_list[j], ",", corpus_dictionary[key1], ",", corpus_dictionary[key2], "]", end = " ") confusion_arc_count += 1 print("\n\n Number of confusing arcs = ", confusion_arc_count) # The oracle performs two functions. # 1. It determines whether a particular transition is permitted for two given words. # 2. When multiple transitions are permitted for two given words, # it determines which of all possible transitions should be taken by the parser. def oracle(corpus_dictionary, tag1, tag2, size_stack, size_buffer): if(size_buffer == 0 and size_stack == 1): print('No Action') # Empty stack or 1 element stack without considering root if(tag1 == '' or tag2 == ''): return 'SHIFT' # Special Oracle Rules if(tag1[0] == 'V' and (tag2[0] == '.' or tag2[0] == 'R')): # Rule 1 - If the first character of the tag for the i-th element is "V" (tag1) and # the first character of the tag for the j-th element (tag2) is either "." or "R", # then your oracle should return "Right-Arc" as the action for the parser to take return 'Right-Arc' elif(size_stack > 2 and (tag1[0] == 'I' and tag2[0] == '.')): # Rule 2 - If the current size of the stack is greater than two (not including the ROOT node) and # the first character of the tag of the i-th element (tag1) is either "I" and tag2 starts with ".", # then the oracle should return "SWAP" for the parser action return 'SWAP' elif(size_buffer != 0 and (tag1[0] == 'V' or tag1[0] == 'I')): # Rule 3 - If the buffer is non-empty and # the first character of the tag for the i-th element (tag1) is either "V" or "I" and # the first character of the tag for the j-th element (tag2) is either "D", "I", "J", "P", or "R", # then the oracle should return "SHIFT" for the parser action. if(tag2[0] == 'D' or tag2[0] == 'I' or tag2[0] == 'J' or tag2[0] == 'P' or tag2[0] == 'R'): return 'SHIFT' key1 = (tag1, tag2, 'L') key2 = (tag1, tag2, 'R') if(key1 in corpus_dictionary and key2 in corpus_dictionary): # Confusion Arcs if(corpus_dictionary[key1] > corpus_dictionary[key2]): return 'Left-Arc' else: return 'Right-Arc' elif(key1 in corpus_dictionary): return 'Left-Arc' elif(key2 in corpus_dictionary): return 'Right-Arc' else: return 'SHIFT' # Printing the stack_ def printStack(stack_): print("[", end = "") for i in range(len(stack_)): if(i > 0): print(",", end = "") print(stack_[i], end = "") print("]", end = "") #Printing the buffer_ def printBuffer(buffer_): print("[", end = "") for i in range(len(buffer_)): if(i > 0): print(",", end = "") print(buffer_[i], end = "") print("]", end = "") # Transition-based Dependency Parser def parser(sequence, input_words,input_tags,corpus_dictionary): # Using list as a stack stack_ = [] # Using list as a buffer buffer_ = sequence[:] i = 1 while(True): size_stack = len(stack_) size_buffer = len(buffer_) tag1 = '' tag2 = '' val1 = '' val2 = '' if(size_buffer == 0 and size_stack == 1): printStack(stack_) printBuffer(buffer_) print("ROOT", "-->", stack_.pop()) break; printStack(stack_) printBuffer(buffer_) if(size_stack >= 2): val2 = stack_.pop() val1 = stack_.pop() tag2 = val2.split('/')[1] tag1 = val1.split('/')[1] action = oracle(corpus_dictionary, tag1, tag2, size_stack, size_buffer) if(action == 'SHIFT'): print("SHIFT") if(val1 != '' and val2 != ''): stack_.append(val1) stack_.append(val2) if(len(buffer_) != 0): stack_.append(buffer_[0]) del buffer_[0] else: print("This parser doesn't support all sentences and ending the program here.") break; elif(action == 'SWAP'): buffer_.insert(0,val1) stack_.append(val2) print("SWAP") elif(action == 'Left-Arc'): print("Left-Arc:", val1, "<--", val2) stack_.append(val2) elif(action == 'Right-Arc'): print("Right-Arc:", val1, "-->", val2) stack_.append(val1) # Printing header of the program output print("") print("University of Central Florida") print("CAP6640 Spring 2018 - Dr. Glinos") print("Dependency Parser by Abhianshu Singla") corpus_dictionary, tag_list = corpusData() printArcs(corpus_dictionary, tag_list) sequence, input_words, input_tags = readInput() print("\n\n\nParsing Actions and Transitions:\n") parser(sequence, input_words,input_tags,corpus_dictionary)
6e3e08affb4abb1d38f8bfecfe9668c8cdad0965
komiamiko/fc-ezalia
/src/algorithm.py
2,026
4.125
4
""" Pure algorithms, not specific to an application. """ class UnionFind(object): """ Union-find data structure, also known as disjoint set. Only works on a range of integers [0, n). All operations are permitted to mutate the underlying list. """ def __init__(self, n): """ Make a union-find data structure that starts with the integers [0, n) each as a singleton set. """ self.leaders = list(range(n)) def test(self, i, j): """ Are these values in the same set? """ leaders = self.leaders it = [] jt = [] while leaders[i] != i: it.append(i) i = leaders[i] while leaders[j] != j: jt.append(j) j = leaders[j] for k in it: leaders[k] = i for k in jt: leaders[k] = j return i == j def join(self, i, j): """ Join the sets containing these values. """ leaders = self.leaders it = [] while leaders[i] != i: it.append(i) i = leaders[i] while leaders[j] != j: it.append(j) j = leaders[j] it.append(j) for k in it: leaders[k] = i def test_and_join(self, i, j): """ Join the sets containing these values (if they are different). Returns true if they were already in the same set, otherwise false. Functionally equivalent to: flag = uf.test(i, j) uf.join(i, j) return flag ... but this operation can be optimized somewhat if they are fused. """ leaders = self.leaders it = [] while leaders[i] != i: it.append(i) i = leaders[i] while leaders[j] != j: it.append(j) j = leaders[j] result = i == j it.append(j) for k in it: leaders[k] = i return result
2a69963a7baff5c6eb2b28fc1ea72b4cfbf4efa7
sgriffith3/PythonBasics7-22-19
/in.py
269
4.09375
4
#!/usr/bin/env python3 import pdb my_text = "I want to ride a donkey down the Grand Canyon trails" count = 0 pdb.set_trace() if "an" in my_text: print("There is an 'an' in your text") for letter in my_text: if "a" == letter: count += 1 print(count)
7c23acba0ea89e261f74000124675e267a122a89
sunnnwo86/Python_test
/lambda.py
446
3.953125
4
power = lambda x : x*x under_3 = lambda x: x<3 list_input_a = [1,2,3,4,5] output_a = map(power,list_input_a) print("#map함수의 실행결과 ") print("map(power, list_input_a):", output_a) print("map(power, list_input_a):", list(output_a)) print() output_b = filter(under_3, list_input_a) print("#filter() 함수의 실행 결과") print("filter(under_3, list_input_b):" , output_b) print("filter(under_3, list_input_b):" , list(output_b))
69076e3d2a44c7c36affc5fdb3d83e0d514f4dec
shhuan/algorithms
/leetcode/easy/Longest_Common_Prefix.py
1,150
3.5
4
# -*- coding: utf-8 -*- """ created by huash at 2015-04-12 18:31 Write a function to find the longest common prefix string amongst an array of strings. """ __author__ = 'huash' import sys import os class Solution: # @return a string def longestCommonPrefix(self, strs): # 44ms if not strs: return '' if len(strs) == 1: return strs[0] for i in range(len(strs[0])): ch = strs[0][i] for s in strs[1:]: if i >= len(s) or ch != s[i]: return strs[0][:i] return strs[0] def longestCommonPrefix2(self, strs): # 64m return strs[0][:max(filter(lambda i: i == 0 or len(set([s[:i] for s in strs])) == 1, [i for i in range(max(min([len(s) for s in strs])+1, 1))]))] if strs else '' s = Solution() print(s.longestCommonPrefix(['12123333', '1212', '1212x2q', '1212e21', '1212de21e12', '1212dwqdq', '1212dqdw'])) print(s.longestCommonPrefix(['111122'])) print(s.longestCommonPrefix(["a", "b"])) print(s.longestCommonPrefix([""])) print(s.longestCommonPrefix(["a"])) print(s.longestCommonPrefix([]))
c4e817f17416a7f0417c53f512d9b146509895f6
cherryzoe/Leetcode
/621. Task Scheduler.py
2,503
3.90625
4
# Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. # However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. # You need to return the least number of intervals the CPU will take to finish all the given tasks. # Example 1: # Input: tasks = ["A","A","A","B","B","B"], n = 2 # Output: 8 # Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. # Note: # The number of tasks is in the range [1, 10000]. # The integer n is in the range [0, 100]. # 前半部分都是一样的,求出最多的次数mx,还有同时出现mx次的不同任务的个数mxCnt。 # 这个解法的思想是先算出所有空出来的位置,然后计算出所有需要填入的task的个数,如果超出了空位的个数,就需要最后再补上相应的个数。 # 注意这里如果有多个任务出现次数相同,那么将其整体放一起,就像上面的第二个例子中的CE一样,那么此时每个part中的空位个数就是n - (mxCnt - 1), # 那么空位的总数就是part的总数乘以每个part中空位的个数了,那么我们此时除去已经放入part中的,还剩下的task的个数就是task的总个数减去mx * mxCnt, # 然后此时和之前求出的空位数相比较,如果空位数要大于剩余的task数,那么则说明还需补充多余的空位,否则就直接返回task的总数即可, # 参见代码如下: # 举例: AAAABBBBCCD, n=2 # ABC ABC ABD AB(Mcnt) # 单位长度(n+1) * (3-1)个单位 + Mcnt(最多元素个数) # 取A到A为一个单位, 每个单位长度为N+1, 一共有count(A)-1个单位, 最后加上最多元素个数,如果A,B个数均为最大, Mcnt=2 # task_cnt = {A:4, B:4, C:2, D:1}.values = {3,3,2,1} # max_cnt = 3 得到最多元素的个数, # Mcnt = 2 此处有两个最大值A, B class Solution(object): def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ task_cnt = collections.Counter(tasks).values() max_cnt = max(task_cnt) Mcnt = task_cnt.count(max_cnt) return max( ((max_cnt - 1) * (n + 1) + Mcnt), len(tasks))
d2aa2bd7b0faa2b94bead3686848c6202102a553
aishahanif666/Working_with_Conditionals
/Even or odd.py
371
4.25
4
print("IDENTIFY EVEN OR ODD NUMBER:\n") a = int(input("Enter number: ")) if (a%2 == 0): print("It's an even number!") else: print("This number is odd!") print("\nIDENTIFY POSITIVE OR NEGATIVE NUMBER:\n") b = int(input("Enter number: ")) if (b<0): print("Neagative number") elif (a>0): print("Positive number") else: print("Zero")
4092fee6ace4f471f78828c2031084f8eda865cd
wowalid/doku-solver
/input.py
1,113
3.71875
4
size = int(input("Size (or sudoku)?")) blocks = [] cells = [] if size == 'sudoku': print "Awaiting sudoku set values..." while True: b = [] v = raw_input("Value?") if v == "": break b.append("%s=" % (v,)) c_str = raw_input("Cell?") if c_str == "": break c = tuple(int(i) for i in c_str.split(',')) if c in cells: print "WTF?" continue b.append(c) cells.append(c) blocks.append(b) else: print "Awaiting mathdoku conditions and blocks..." max_cells = size**2 while len(cells)<max_cells: b = [] blocks.append(b) cond = raw_input("Condition?") b.append(cond) while True: c_str = raw_input("Cell?") if c_str == "": break c = tuple(int(i) for i in c_str.split(',')) if c in cells: print "WTF?" continue b.append(c) cells.append(c) name = raw_input("Name?") print """add(%s, %s, *%s)""" % (repr(name), repr(size), repr(blocks))
da27b5818c5b913bb5fb7efc8e0c4f35af052665
bbog/Project-Euler-Problems
/3/solve.py
681
4
4
''' URL: http://projecteuler.net/problem=3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' def getLargestPrimeFactor(number): # first version was slow as hell, so... let's cheat a little : D # credits: http://primes.utm.edu/lists/small/100000.txt for line in reversed(open('primes.txt').readlines()): line = line.rstrip() line = ' '.join(line.split()) if line: for prime in line.split(' '): if number % int(prime) == 0: return prime return 1 def main(): # test # print getLargestPrimeFactor(13195) print getLargestPrimeFactor(600851475143) if __name__ == '__main__': main()
77abf8589d92ca2d99ea1cf8566b9c686e2398d9
akaraboyun/Python-Examples
/kuvvet.py
122
3.78125
4
a = int(input("a: ")) b = int(input("b: ")) toplam = 1 for i in range(b): toplam *= a print("Sonuç:",toplam)
19cef77cf7d5bee183d14d79beaa1d5234d6dac5
sebas494/Proyecto-final
/proyecto.py
30,851
3.546875
4
print("Parqueadero pontificia universidad javeriana cali\n" ) def opcion_1 (opciones1): import json archivo = open("usuarios.json", "r+", encoding = "utf-8") usuariosJson = json.load(archivo) #archivo2=open("Pisos.json", "r+", encoding = "utf-8") #PisosJson = json.load(archivo2) archivo3=open("Pisos_ocupados.json", "r+", encoding = "utf-8") PisosJson_ocupados = json.load(archivo3) while opciones1!=-1: opciones=eval(input("¿Que desea hacer?\n1)Permitir el ingreso de vehiculos\n2)Registrar un vehiculo\n3)Retirar un vehiculo del estacionamiento\n4)Generear un conjunto de estadisticas para la Oficina de Servicios Generales de la Universidad\n\n Escriba aqui el numero dependiendo de la opcion= ")) #Si el usuario marca la opcion 1 del menu. if opciones==1: #Ingresa el numero de la placa placa=input("Ingrese el numero de la placa: ") numero_comprobante=0 for piso in PisosJson_ocupados: w=PisosJson_ocupados[piso] for parqueaderos in w: for parqueadero in parqueaderos: if parqueadero[1]!=0: if parqueadero[1][0]==placa: numero_comprobante+=1 if numero_comprobante==1: return opcion_1(eval(input("Ya tienes un vehiculo en el parqueadero, no puedes ingresar mas\nIngresa 1 para volver al menu principal: "))) else: def buscar_placa (usuariosJson, placa): for buscar_placa in usuariosJson["usuarios"]: for buscar_listas in usuariosJson: if buscar_placa[3]==placa: return True buscar_placa(usuariosJson,placa) fila=0 columna=0 nombre="" tipo_usuario_parquear="" if buscar_placa(usuariosJson,placa)==True: print("¡Bienvenido Javeriano, ya estas registrado en nuestra base de datos!") for buscar in range (len(usuariosJson["usuarios"])): for encontrar_elemento in range (6): if usuariosJson["usuarios"][buscar][encontrar_elemento]==placa: fila=buscar columna=encontrar_elemento break if(usuariosJson["usuarios"][fila][4])=="Discapacitado": tipo_vehiculo=4 elif(usuariosJson["usuarios"][fila][4])=="Motocicleta": tipo_vehiculo=3 elif(usuariosJson["usuarios"][fila][4])=="Automóvil Eléctrico": tipo_vehiculo=2 elif(usuariosJson["usuarios"][fila][4])=="Automóvil": tipo_vehiculo=1 elif(usuariosJson["usuarios"][fila][2])=="Personal Administrativo": tipo_usuario_parquear="Personal Administrativo" elif(usuariosJson["usuarios"][fila][2])=="Profesor": tipo_usuario_parquear="Profesor" elif(usuariosJson["usuarios"][fila][2])=="Estudiante": tipo_usuario_parquear="Estudiante" else: print("\nSeras catalogado como visitante y tendras un pago diario, ya que esta placa no esta registrada en la base de datos.\n") identificacion=eval(input("Ingrese su numero de identificacion: ")) tipo_vehiculo=eval(input("¿Que tipo de vehiculo es?\n1)Automovil\n2)Automovil electrico\n3)Motocicleta\n4)Discapacitado\nEscriba de acuerdo a la letra asignada en las opciones: ")) nombre_vehiculo="" if tipo_vehiculo==1: nombre_vehiculo="Automovil" elif tipo_vehiculo==2: nombre_vehiculo="Automovil electrico" elif tipo_vehiculo==3: nombre_vehiculo="Motocicleta" elif tipo_vehiculo==4: nombre_vehiculo="Discapacitado" variable_nombre=nombre_vehiculo tipo_usuario_parquear="Visitante" #Se evalua piso por piso el numero total de estacionamientos disponibles de acuerdo al tipo de vehiculo ingresado res=0 for cada_piso in PisosJson_ocupados: llave_piso=PisosJson_ocupados[cada_piso] for lista_parqueadero in llave_piso: for espacios in lista_parqueadero: if tipo_vehiculo==1: if espacios[0]==1: res+=1 elif tipo_vehiculo==2: if espacios[0]==1 or 2: res+=1 elif tipo_vehiculo==3: if espacios[0]==3: res+=1 elif tipo_vehiculo==4: if espacios[0]==1 or 4: res+=1 #Se valida que hayan parqueaderos disponibles para el tipo de vehiculo ademas que el usuario selecciona el piso que desea visualizar. if res>0: print("\nEl numero total para de parqueaderos disponibles para el tipo vehiculo que se quiere ingresar es de :"+str(res)) seleccione_piso=eval(input("\nIngrese el numero de piso que quiere visualizar.\n Piso #1:(1)\nPiso #2:(2)\nPiso #3:(3)\nPiso #4:(4)\nPiso #5:(5)\nPiso #6:(6)\nIngrese aqui el numero del piso: ")) print("\nLas posiciones llenas o no disponibles estan marcadas con (X) y las vacias y disponibles con (0).\n") seleccionado="" if seleccione_piso==1: seleccionado="Piso1" elif seleccione_piso==2: seleccionado="Piso2" elif seleccione_piso==3: seleccionado="Piso3" elif seleccione_piso==4: seleccionado="Piso4" elif seleccione_piso==5: seleccionado="Piso5" elif seleccione_piso==6: seleccionado="Piso6" if seleccione_piso<=5: if tipo_vehiculo==1: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(10): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==2: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(10): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1 or 2: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==3: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(10): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==3: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==4: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(10): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1 or 4: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" else: if tipo_vehiculo==1: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(5): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==2: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(5): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1 or 2: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==3: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(5): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==3: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" if tipo_vehiculo==4: a="" print("Piso #"+str(seleccione_piso)+"\n") for ver in range(5): for mejor in range(10): if PisosJson_ocupados[seleccionado][ver][mejor][0]==1 or 4: a+=str(0) +"\t" else: a+="x" +"\t" print(a) a="" def posicion_parqueo(b): while b!=0: print("\n¿En que posicion desea parquear su vehiculo?\n") ingrese_fila=eval(input("Ingrese el numero de la fila: ")) ingres_columna=eval(input("Ingrese columna: ")) if PisosJson_ocupados[seleccionado][ingrese_fila][ingres_columna][0]==tipo_vehiculo: print("¡Efectivamente esta desocupado para este tipo de vehiculo!") parquear_usuario=[placa,variable_nombre,tipo_usuario_parquear,"Diario"] PisosJson_ocupados[seleccionado][ingrese_fila][ingres_columna][1]=parquear_usuario with open("Pisos_ocupados.json", "w",encoding = "utf-8") as archivo_introducir: json.dump(PisosJson_ocupados,archivo_introducir, indent=4, ensure_ascii=False) archivo_introducir.close break else: return posicion_parqueo (eval(input("\nEste puesto no le sirve para su tipo de vehiculo\n\nIngrese el numero (2) para volver a escoger un puesto en el mimsmo piso:\nIngrese (0) para volver al menu principal:\n\nDigite su opcion:"))) b=1 posicion_parqueo(b) else: print("No hay parqueaderos disponibles para este tipo de vehiculo.") #Se ingresa el tipo de pago print("\n¡Su vehiculo se ha registrado con exito!.\n") opciones1=eval(input("Ingrese el numero 1 para volver al menu principal: ")) if opciones==2: nombres_registro=str(input("Ingrese su nombre y apellido: ")) identificacion_registro=eval(input("Ingrese su numero de identificacion: ")) for buscar in usuariosJson["usuarios"]: if buscar[1]==identificacion_registro: print("Este usuario ya esta registrado") return opcion_1 (eval(input("Escriba el numero 2 para volver al menu principal= "))) Tipo_usuario=eval(input("¿Que tipo de usuario eres?\n1)Estudiante(1)\n2)Profesor(2)\n3)Personal administrativo(3)\nIngrese el numero segun corresponda: ")) placa_registro=input("Ingrese el numero de placa del vehiculo: ") tipo_vehiculo_registro=eval(input("¿Que tipo de vehiculo es?\n1)Automovil\n2)Automovil electrico\n3)Motocicleta\n4)Discapacitado\nEscriba de acuerdo a la letra asignada en las opciones: ")) nombre_vehiculo="" if tipo_vehiculo_registro==1: nombre_vehiculo="Automovil" elif tipo_vehiculo_registro==2: nombre_vehiculo="Automovil electrico" elif tipo_vehiculo_registro==3: nombre_vehiculo="Motocicleta" elif tipo_vehiculo_registro==4: nombre_vehiculo="Discapacitado" variable_nombre=nombre_vehiculo plan_pago=eval( input("Ingrese el tipo de pago\n1)Diario\n2)Mensualidad\nIngrese el numero segun corresponda: ")) usuario_nuevo_registro=[nombres_registro,identificacion_registro,Tipo_usuario,placa_registro,nombre_vehiculo,plan_pago] with open("usuarios.json", "w",encoding = "utf-8") as archivo: json.dump(usuario_nuevo_registro, archivo, indent=4, ensure_ascii=False) archivo.close print("\n¡Se te registro exitosamente!\n") #Si el usuario marca la opcion 2 del menu. def opcion_2(num): archivo3=open("Pisos_ocupados.json", "r+", encoding = "utf-8") PisosJson_ocupados = json.load(archivo3) archivo1=open("Pisos.json", "r+", encoding = "utf-8") PisosJson = json.load(archivo1) if opciones==3: opcion_2_0=0 while opcion_2_0 !=1: fila_hallar=0 columna_hallar=0 piso=0 pasar=False placa_retirar=input("Ingrese el numero de la placa del vehiculo que desea retirar: ") for buscar_pisos in range (6): for buscar_listas in range(10): for buscar_elementos in range(10): if buscar_pisos==1: if PisosJson_ocupados["Piso1"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso1"][buscar_listas][buscar_elementos][1][0]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break elif buscar_pisos==2: if PisosJson_ocupados["Piso2"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso2"][buscar_listas][buscar_elementos][1][0]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break elif buscar_pisos==3: if PisosJson_ocupados["Piso3"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso3"][buscar_listas][buscar_elementos][1][0]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break elif buscar_pisos==4: if PisosJson_ocupados["Piso4"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso4"][buscar_listas][buscar_elementos][1][1]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break elif buscar_pisos==5: if PisosJson_ocupados["Piso5"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso5"][buscar_listas][buscar_elementos][1][0]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break elif buscar_pisos==6: for buscar_listas in range(5): for buscar_elementos in range(10): if PisosJson_ocupados["Piso6"][buscar_listas][buscar_elementos][1]!=0: if PisosJson_ocupados["Piso6"][buscar_listas][buscar_elementos][1][0]==placa_retirar: piso=buscar_pisos fila_hallar=buscar_listas columna_hallar=buscar_elementos pasar=True break if pasar==True: print("El vehiculo con esta placa se encuentra en el parqueadero.") tiempo=eval(input("Ingrese el numero de horas que permanecio el vehiculo en el parqueadero: ")) pago_total=0 fila_hallar_usuarios=0 for buscar in range (len(usuariosJson["usuarios"])): for encontrar_elemento in range (6): if usuariosJson["usuarios"][buscar][encontrar_elemento]==placa_retirar: fila_hallar_usuarios=buscar break def retirar(usuariosJson,tiempo,fila_hallar_usuarios): nombre="" if usuariosJson["usuarios"][fila_hallar_usuarios][5]=="Diario" and usuariosJson["usuarios"][fila_hallar_usuarios][2]=="Personal Administrativo": return(tiempo*1500) elif usuariosJson["usuarios"][fila_hallar_usuarios][5]=="Diario" and usuariosJson["usuarios"][fila_hallar_usuarios][2]=="Profesor": return(tiempo*2000) elif usuariosJson["usuarios"][fila_hallar_usuarios][5]=="Diario" and usuariosJson["usuarios"][fila_hallar_usuarios][2]=="Estudiante": return(tiempo*1000) else: if usuariosJson["usuarios"][fila_hallar_usuarios][5]=="Mensualidad": return 0 retirar(usuariosJson,tiempo,fila_hallar_usuarios) pago_total=(retirar(usuariosJson,tiempo,fila_hallar_usuarios)) seleccionado="" if piso==1: seleccionado="Piso1" elif piso==2: seleccionado="Piso2" elif piso==3: seleccionado="Piso3" elif piso==4: seleccionado="Piso4" elif piso==5: seleccionado="Piso5" elif piso==6: seleccionado="Piso6" if PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]!=0: PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]=0 if PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]!=0: PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]=0 if PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]!=0: PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]=0 if PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]!=0: PisosJson_ocupados[seleccionado][fila_hallar][columna_hallar][1]=0 with open("Pisos_ocupados.json", "w",encoding = "utf-8") as volver_numero: json.dump(PisosJson_ocupados,volver_numero, indent=4, ensure_ascii=False) volver_numero.close else: print("El vehiculo con esta placa NO se encuentra en el parqueadero.") return opcion_2 (eval(input("Ingrese 2 para ingresar otro placa de vehiculo: "))) if pago_total>0: print("El valor total a pagar es de $"+str(pago_total)) print("\n¡Muchas gracias por usar nuestros servicios!\n") return opcion_1 (eval(input("Escriba el numero 2 para volver al menu principal= "))) else: print("No debes realizar ningun pago ya que tienes paga la mensualidad.") print("\n¡Muchas gracias por usar nuestros servicios!\n") return opcion_1 (eval(input("Escriba el numero 2 para volver al menu principal= "))) num=0 opcion_2(num) if opciones==4: Opciones4_1=eval(input("¿Que reporte desea generar?\n1)Reporte con la cantidad de vehículos estacionados según el tipo de usuario\n2)Reporte de cantidad de vehículos estacionados según el tipo de vehículo.\n3)Reporte que indique el porcentaje de ocupación del parqueadero\nDigite el numero segun la opcion")) personal_administrativo=0 profesor=0 estudiante=0 visitante=0 motocicleta=0 automovil=0 Automovil_electrico=0 discapacitado=0 piso1=0 piso2=0 piso3=0 piso4=0 piso5=0 piso6=0 ocuapcion_total=0 for pisos in PisosJson_ocupados: variable=PisosJson_ocupados[pisos] for parqueaderos in variable: for parqueadero in parqueaderos: if parqueadero[1]!=0: ocuapcion_total+=1 if pisos=="Piso1": piso1+=1 elif pisos=="Piso2": piso2+=1 elif pisos=="Piso3": piso3+=1 elif pisos=="Piso4": piso4+=1 elif pisos=="Piso5": piso5+=1 elif pisos=="Piso6": piso6+=1 if parqueadero[0]==1: automovil+=1 elif parqueadero[0]==2: Automovil_electrico+=1 elif parqueadero[0]==3: motocicleta+=1 elif parqueadero[0]==4: discapacitado+=1 if parqueadero[1][1]=="Estudiante": estudiante+=1 elif parqueadero[1][1]=="Profesor": profesor+=1 elif parqueadero[1][1]=="Personal Administrativo": personal_administrativo+=1 elif parqueadero[1][1]=="Visitante": visitante+=1 PisosJson_ocupados.close() PocupacionGlobal=(ocuapcion_total/550)*100#calculo del porcentaje de ocupación global PocupacionP1=(piso1/100)*100#calculo del porcentaje de ocupación del piso 1 PocupacionP2=(piso2/100)*100#calculo del porcentaje de ocupación del piso 2 PocupacionP3=(piso3/100)*100#calculo del porcentaje de ocupación del piso 3 PocupacionP4=(piso4/100)*100#calculo del porcentaje de ocupación del piso 4 PocupacionP5=(piso5/100)*100#calculo del porcentaje de ocupación del piso 5 PocupacionP6=(piso6/50)*100#calculo del porcentaje de ocupación del piso 6 if Opciones4_1==1: with open ("Estadisticas_del_parqueadero.txt","w") as archivo:#se crea el archivo de texto del reporte 1 archivo.write("La cantidad de vehiculos de usuarios profesores es: "+str(profesor)+"\n") archivo.write("La cantidad de vehiculos de usuarios estudiantes es: "+str(estudiante)+"\n") archivo.write("La cantidad de vehiculos de usuarios personal administrativo es: "+str(personal_administrativo)+"\n") archivo.write("La cantidad de vehiculos de usuarios visitantes es: "+str(visitante)+"\n") archivo.close() print("\n¡Estadisticas generadas!\n\n") elif Opciones4_1==2: with open ("Estadisticas_del_parqueadero.txt","w") as archivo:#se crea el archivo de texto del reporte 2 archivo.write("La cantidad de vehiculos del tipo automovil es: "+str(automovil)+"\n") archivo.write("La cantidad de vehiculos del tipo automovil eléctrico es: "+str(Automovil_electrico)+"\n") archivo.write("La cantidad de vehiculos del tipo motocicleta es: "+str(motocicleta)+"\n") archivo.write("La cantidad de vehiculos del tipo discapacitado es: "+str(discapacitado)+"\n") archivo.close() print("\n¡Estadisticas generadas!\n\n") elif Opciones4_1==3: with open ("Estadisticas_del_parqueadero.txt","w") as archivo:#se crea el archivo de texto del reporte 3 archivo.write("El porcentaje de ocupación del parqueadero es del: "+str(PocupacionGlobal)+"%.\n") archivo.write("El porcentaje de ocupación del piso 1 es de: "+str(PocupacionP1)+"%.\n") archivo.write("El porcentaje de ocupación del piso 2 es de: "+str(PocupacionP2)+"%.\n") archivo.write("El porcentaje de ocupación del piso 3 es de: "+str(PocupacionP3)+"%.\n") archivo.write("El porcentaje de ocupación del piso 4 es de: "+str(PocupacionP4)+"%.\n") archivo.write("El porcentaje de ocupación del piso 5 es de: "+str(PocupacionP5)+"%.\n") archivo.write("El porcentaje de ocupación del piso 6 es de: "+str(PocupacionP6)+"%.\n") archivo.close() print("\n¡Estadisticas generadas!\n\n") opciones1=0 opcion_1(opciones1)
614964298088ee50bc7b88e2c4e03eb8c86b009e
TakanoriHasebe/DeepLearning
/ManufactureDeepLearning/temp/make-affine.py
1,207
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 23 11:12:48 2017 @author: Takanori """ """ Affine """ import numpy as np X = np.random.rand(1, 2) # print(X.shape) # print(X) W = np.random.rand(2, 3) B = np.random.rand(1, 3) # print(W.shape) Y = np.dot(X, W) + B # print(Y.shape) print(Y) class Affine: def __init__(self, W, b): self.W =W self.b = b self.x = None self.original_x_shape = None # 重み・バイアスパラメータの微分 self.dW = None self.db = None def forward(self, x): # テンソル対応 self.original_x_shape = x.shape x = x.reshape(x.shape[0], -1) self.x = x out = np.dot(self.x, self.W) + self.b return out def backward(self, dout): dx = np.dot(dout, self.W.T) self.dW = np.dot(self.x.T, dout) self.db = np.sum(dout, axis=0) dx = dx.reshape(*self.original_x_shape) # 入力データの形状に戻す(テンソル対応) return dx affine = Affine(W, B) out = affine.forward(X) print('out:'+str(out)) dout = affine.backward(out) print('dout:'+str(dout))
18834a2e10d205704950357c3c21369fb4589cb4
JediChou/jedichou-study-algo
/onlinejudge/leetcode/quiz00258/quiz00258-a1.py
1,118
3.71875
4
import unittest class Solution: def addDigits(self, num: int) -> int: if num < 10: return num return self.addDigits(sum([int(d) for d in str(num)])) class Quiz00258(unittest.TestCase): def test_Less10(self): answer = Solution() self.assertEqual(answer.addDigits(1), 1) self.assertEqual(answer.addDigits(2), 2) self.assertEqual(answer.addDigits(3), 3) self.assertEqual(answer.addDigits(4), 4) self.assertEqual(answer.addDigits(5), 5) self.assertEqual(answer.addDigits(6), 6) self.assertEqual(answer.addDigits(7), 7) self.assertEqual(answer.addDigits(8), 8) self.assertEqual(answer.addDigits(9), 9) def test_Less20AndGreatThan20(self): answer = Solution() self.assertEqual(answer.addDigits(10), 1) def test_LeetcodeSample(self): answer = Solution() self.assertEqual(answer.addDigits(38), 2) self.assertEqual(answer.addDigits(39), 3) self.assertEqual(answer.addDigits(123), 6) if __name__ == "__main__": unittest.main()
26b2d57d398cb9d5a43e895dd47a514771436838
mjutzi/TikzTuringSimulator
/core/tape_expansion.py
1,269
3.6875
4
import collections def left_of_expandable(index, list, placeholder=None): new_index = index - 1 while new_index < 0: list.insert(0, placeholder) new_index += 1 return new_index def left_of_unexpandable(index, list, placeholder=None): new_index = index - 1 if new_index < 0: raise ValueError('Index out of left range.') return new_index def right_of_expandable(index, list, placeholder=None): new_index = index + 1 while new_index >= len(list): list.append(placeholder) return new_index def right_of_unexpandable(index, list, placeholder=None): new_index = index + 1 if new_index >= len(list): raise ValueError('Index out of right range.') return new_index ExpansionStrategy = collections.namedtuple('ExpansionStrategy', 'move_left_op move_right_op') EXPAND_ALL = ExpansionStrategy(move_left_op=left_of_expandable, move_right_op=right_of_expandable) EXPAND_NONE = ExpansionStrategy(move_left_op=left_of_unexpandable, move_right_op=right_of_unexpandable) EXPAND_LEFT_ONLY = ExpansionStrategy(move_left_op=left_of_expandable, move_right_op=right_of_unexpandable) EXPAND_RIGHT_ONLY = ExpansionStrategy(move_left_op=left_of_unexpandable, move_right_op=right_of_expandable)
fa6d1859bebff07e7952f42094d753e19911d730
daniel-reich/ubiquitous-fiesta
/LanWAvTtQetP5xyDu_6.py
294
3.53125
4
def coins_div(lst): if sum(lst)%3: return False dtbs = {(0,0,0)} #set of possible distributions with inital subset of coins coor = [0,1,2] for cn in lst: dtbs = dtbs.union({tuple(d[i]+cn*(i==j) for i in coor) for j in coor for d in dtbs}) m=sum(lst)//3 return (m,m,m) in dtbs
d6cacc7a88a1248cd03c84274d2c5b706b36b7f6
Cactiw/Dark-Desire-Order-Bot
/castle_files/libs/message_group.py
1,599
3.71875
4
""" Здесь находятся классы и методы для работы с группами сообщений - сообщения, которые должны быть отправлены строго в определённом порядке, но асинхронно """ from threading import Lock, RLock from multiprocessing import Queue from queue import Empty lock = Lock() message_groups = {} message_groups_locks = {} groups_need_to_be_sent = Queue() class MessageInQueue: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class MessageGroup: def __init__(self, created_id): with lock: group_id_list = list(message_groups) if not group_id_list: self.id = 0 else: self.id = group_id_list[-1] + 1 message_groups.update({self.id: self}) self.messages = [] self.created_id = created_id self_lock = RLock() message_groups_locks.update({self.id: self_lock}) self.busy = False def add_message(self, message): self_lock = message_groups_locks.get(self.id) with self_lock: self.messages.append(message) def get_message(self): if not self.messages: return 1 message = self.messages[0] self.messages.pop(0) return message def send_group(self): self.messages.append(None) groups_need_to_be_sent.put(self) message_groups.pop(self.id) def is_empty(self): return not self.messages
f94f5f952c32bf0416089d2bdba644df2b5e69b3
moonlightshadow123/leetcode_solutions
/string/125-Valid-Palindrome/high_low.py
911
3.65625
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ def isAlpha(char): if ord(char) >= ord('A') and ord(char) <= ord('Z'): return True elif ord(char) >= ord('a') and ord(char) <= ord('z'): return True elif ord(char) >= ord('0') and ord(char) <= ord('9'): return True return False n = len(s); if n == 0: return True s = s.lower() start = 0; end = n-1 while start < end: if not isAlpha(s[start]): start += 1 continue if not isAlpha(s[end]): end -= 1 continue if s[start] != s[end]: print start,end return False start += 1; end -= 1 return True
f279f64bd84040a8165edc3d50f435e0211f4c1e
zebasare/Ejercicio_Clases_y_Objetos
/main.py
1,376
3.96875
4
import math class Punto: def __init__(self,x=0,y=0): self.x=x self.y=y def __str__(self): return f"Punto ubicado en {self.x,self.y}" def cuadrante(self): if self.x>0 and self.y>0: print("El punto esta en el primer cuadrante") elif self.x<0 and self.y>0: print("El punto esta en el segundo cuadrante") elif self.x<0 and self.y<0: print("El punto se encuentra en el tercer cuadrante") elif self.x>0 and self.y<0: print("El punto se encuatra en el cuarto cuadrante") else: print("El punto se encuentra en el origen") def vector(self,p): vectX=(p.x-self.x) vectY=(p.y-self.y) print(f"Vector resultante : {vectX,vectY}") def distancia(self,p): dist=math.sqrt( (p.x-self.x)**2 + (p.y-self.y)**2) print(f"Distancia del vector generado : ",dist) class Rectangulo: def __init__(self,inicial=Punto(0,0),final=Punto(0,0)): self.inicial=inicial self.final=final def base_altura_area(self): base=self.final.x-self.inicial.x altura=self.final.y-self.inicial.y print("Base :",base) print("Altura: ",altura) print("Area: ", base * altura) unpunto=Punto() otropunto=Punto(2,3) unpunto.cuadrante() unpunto.vector(otropunto) unpunto.distancia(otropunto) rect=Rectangulo(unpunto,otropunto) rect.base_altura_area()
001fc09cc6409080a6b0cdd303ab999581b0bed4
elcarmen/PythonLearning
/[3] BasicLogIn.py
331
3.6875
4
username = "User1211" # I'll upgrade username and password as a data folder password = "vexy1189" userlogin = input("Username: ") userpassword = input("Password: ") if(username == userlogin) and (userpassword == password): print("successful") else: print(''' Wrong username or password You can sign up ''')
e6eeb8243f29630ff4562e3ee2fa5b2ad0e4c8ce
Xuyuanp/LeetCode
/python/climbingStairs.py
764
4.0625
4
#! /usr/bin/env python class Solution: # @param n, an integer # @return aan integer def climbStairs(self, n): if n < 3: return n steps = [0 for i in range(n + 1)] steps[1] = 1 steps[2] = 2 i = 3 while i <= n: steps[i] = steps[i - 1] + steps[i - 2] i += 1 return steps[n] if __name__ == "__main__": print Solution().climbStairs(0) print Solution().climbStairs(1) print Solution().climbStairs(2) print Solution().climbStairs(3) print Solution().climbStairs(4) print Solution().climbStairs(5) print Solution().climbStairs(6) print Solution().climbStairs(7) print Solution().climbStairs(8) print Solution().climbStairs(9)
485f22853438b8a36d2f9aba2805c445746b05e5
DarioBernardo/hackerrank_exercises
/arrays/merge_two_arrays.py
658
4.09375
4
from typing import List def merge(nums1: List[int], nums2: List[int]) -> None: """ Do not return anything, modify nums1 in-place instead. """ n2_pointer = len(nums2)-1 n1_pointer = len(nums1)-1-len(nums2) current_pos = len(nums1)-1 while current_pos >= 0: num1_val = nums1[n1_pointer] if n1_pointer < 0 or n2_pointer >= 0 and num1_val < nums2[n2_pointer]: nums1[current_pos] = nums2[n2_pointer] n2_pointer -= 1 else: nums1[current_pos] = num1_val n1_pointer -= 1 current_pos -= 1 n1 = [1, 2, 3, 0, 0, 0] n2 = [2, 5, 6] merge(n1, n2) print(n1)
6bdefad690a3328dbd624923ba387c6243170b8d
talk2mat2/newpyrepo
/pygame.py
2,772
4
4
# pygame, this is modified number guessing game written in python def Easy(): # function for easy game max_trial = 6 answer = 5 guess_count = 0 guess = None print('level 1 (easy mode)') while guess != answer and guess_count < max_trial: try: print(f'you have {max_trial - guess_count} guess left') guess = int(input('guess a number between 1-10: ')) except ValueError: print('please enter a valid number between 1-10 and try again!') break guess_count += 1 if guess != answer: print('wrong answer') if guess_count == max_trial: print('Game Over') else: print('you got it right') def Medium(): # function for medium game max_trial = 4 answer = 15 guess_count = 0 guess = None print('level 2 (Medium mode)') while guess != answer and guess_count < max_trial: try: print(f'you have {max_trial - guess_count} guess left') guess = int(input('guess a number between 1-20: ')) except ValueError: print('please enter a valid number between 1-20 and try again!') break guess_count += 1 if guess != answer: print('wrong answer') if guess_count == max_trial: print('Game Over') else: print('you got it right') def Hard(): # function for hard game max_trial = 3 answer = 48 guess_count = 0 guess = None print('level 3 (hard mode)') while guess != answer and guess_count < max_trial: try: print(f'you have {max_trial - guess_count} guess left') guess = int(input('guess a number between 1-50: ')) except ValueError: print('please enter a valid number between 1-50 and try again!') break guess_count += 1 if guess != answer: print('wrong answer') if guess_count == max_trial: print('Game Over') else: print('you got it right') levels = {1: Easy, 2: Medium, 3: Hard} # dictionary containing key value pairs of game functions levels #game_selector = '' try: game_selector = input( 'welcome to the number guessing game\n the ' 'levels are \n 1.Easy \n 2.Medium\n 3.Hard\n' 'please choose a game level(1,2 or 3):- ') game_list = levels.get(int(game_selector)) # # instance of game level function from the dictionary selector game_list() # galling the game function except: print('please enter a valid selection 1,2 or 3 and try again')
c9637c7e63795840497ee23040436b2df824d197
onlyrobot/Tool
/code/maze_generation_prim_algorithm.py
2,586
3.734375
4
# maze generate with prim algorithm import random import turtle VISITED = 1 PATH = 1 ROW, COL = 30, 30 DIRS = [(-1, 0), (0, 1), (1, 0), (0, -1)] maze = [[[0, 0, 0, 0, 0] for i in range(COL)] for i in range(ROW)] START, END = (0, 0), (ROW - 1, COL - 1) que = [START] def cross_border(cell): return cell[0] < 0 or cell[0] >= ROW or cell[1] < 0 or cell[1] >= COL def visited(cell): return maze[cell[0]][cell[1]][4] == 1 def fill_rectangle(x, y, width, height): turtle.penup() turtle.goto(x, y) # turtle.pendown() turtle.begin_fill() turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.end_fill() def draw_maze(): CELL_SIZE = 10 BORDER_SIZE = 2 turtle.setup(ROW * CELL_SIZE, COL * CELL_SIZE) turtle.hideturtle() turtle.speed(0) turtle.pensize(0) for i in range(ROW): for j in range(COL): x = -ROW * CELL_SIZE / 2 + j * CELL_SIZE y = COL * CELL_SIZE / 2 - i * CELL_SIZE width, height = CELL_SIZE, CELL_SIZE if maze[i][j][0] != PATH: fill_rectangle(x - BORDER_SIZE, y, CELL_SIZE + 2 * BORDER_SIZE, BORDER_SIZE) if maze[i][j][1] != PATH: fill_rectangle(x + CELL_SIZE - BORDER_SIZE, y + BORDER_SIZE, BORDER_SIZE, CELL_SIZE + 2 * BORDER_SIZE) if maze[i][j][2] != PATH: fill_rectangle(x - BORDER_SIZE, y - CELL_SIZE + BORDER_SIZE, CELL_SIZE + 2 * BORDER_SIZE, BORDER_SIZE) if maze[i][j][3] != PATH: fill_rectangle(x, y + BORDER_SIZE, BORDER_SIZE, CELL_SIZE + 2 * BORDER_SIZE) turtle.done() return 0 def print_maze(): return 0 if __name__ == '__main__': while que: r, c = que.pop(random.randint(0, len(que) - 1)) maze[r][c][4] = VISITED dirs = [] for dir in DIRS: # four direction cell = (r + dir[0], c + dir[1]) if not cross_border(cell): if visited(cell): dirs.append(dir) elif maze[cell[0]][cell[1]][4] == 0: que.append(cell) maze[cell[0]][cell[1]][4] = 2 if dirs: dir = random.choice(dirs) index = DIRS.index(dir) maze[r][c][index] = PATH maze[r + dir[0]][c + dir[1]][index + 2 if index < 2 else index - 2] = PATH maze[START[0]][START[1]][3] = 1 # entrance maze[END[0]][END[1]][2] = 1 # exit draw_maze()
dc3c7e0b4e1be22a84496d46f3de5528f428fc0a
cmgrier/BeachBotsMQP
/base_bot/src/base_bot/MeshAnalyzer.py
17,441
3.578125
4
#!/usr/bin/env python3 import pyzed.sl as sl import time import rospy import math from support.Constants import * # works with the given mesh data to produce useful information class MeshAnalyzer: def __init__(self, mesh): self.mesh = mesh """ VERTICES """ # returns the lowest vertices that fall within the given range def get_lowest_vertices(self, vertices, range): lowest = self.get_lowest_vertex(vertices) lowest_vertices = [] for vertex in vertices: if vertex[2] < lowest[2] + range: lowest_vertices.append(vertex) return lowest_vertices # returns the lowest vertex in the given vertices list def get_lowest_vertex(self, vertices): lowest = vertices[0] for vertex in vertices: if vertex[2] < lowest[2]: lowest = vertex return lowest # sort the given list of vertices by z def sort_by_height(self, vertices): sorted(vertices, key=lambda x: x[2]) return vertices # returns the avg height (z) of the given vertices def get_avg_height(self, vertices): length = len(vertices) height_sum = 0 for vertex in vertices: height_sum += vertex[2] return height_sum / length # makes a vector from the two given vertices from the first to the second def make_vector(self, vertex1, vertex2): vector = [0, 0, 0] vector[0] = vertex2[0] - vertex1[0] vector[1] = vertex2[1] - vertex1[1] vector[2] = vertex2[2] - vertex1[2] return vector # finds the vertices that exist within the center of the vertices list within given radius def center_vertices(self, vertices, radius): center_vertices = [] y_bounds = self.get_bounds(vertices, 1) x_bounds = self.get_bounds(vertices, 0) x_center = (x_bounds[1] - x_bounds[0]) / 2 + x_bounds[0] y_center = (y_bounds[1] - y_bounds[0]) / 2 + y_bounds[0] print("X_bounds:") print(x_bounds) print("Y_bounds:") print(y_bounds) for vertex in vertices: if x_center - radius < vertex[0] < x_center + radius and y_center - radius < vertex[1] < y_center + radius: center_vertices.append(vertex) return center_vertices # finds the limits of the given vertices in given dimension (0, 1, or 2 representing x, y, and z respectively) def get_bounds(self, vertices, dimension): first_vertex = vertices[0] bounds = [first_vertex[dimension], first_vertex[dimension]] for vertex in vertices: if vertex[dimension] < bounds[0]: bounds[0] = vertex[dimension] elif vertex[dimension] > bounds[1]: bounds[1] = vertex[dimension] return bounds # returns the middle half of the vertices list def get_median_vertices(self, vertices): length = len(vertices) median_vertices = [] for i in range(length): if length / 4 < i < length * .75: median_vertices.append(vertices[i]) return median_vertices """ TRIANGLES """ # finds a surface that can be traversed by the robot def find_traversable_surface(self): triangles = self.mesh.triangles level_triangles = self.get_level_triangles(triangles) # returns all triangles that are level enough to be driven across def get_level_triangles(self, triangles): level_triangles = [] for triangle in triangles: if self.is_triangle_traversable_by_angle(triangle): level_triangles.append(triangle) return level_triangles # returns the normal of the triangle (the unit vector pointing perpendicular to the triangle) def get_triangle_normal(self, triangle): # each point in the given triangle (the triangle holds indexes of vertexes, not vertexes themselves) p1 = self.mesh.vertices[int(triangle[0]) - 1] p2 = self.mesh.vertices[int(triangle[1]) - 1] p3 = self.mesh.vertices[int(triangle[2]) - 1] # vector 1 is from point 1 to 2 u = self.make_vector(p1, p2) # vector 2 is from point 1 to 3 v = self.make_vector(p1, p3) normal = [0, 0, 0] normal[0] = u[1] * v[2] - v[1] * u[2] normal[1] = -1 * (u[0] * v[2] - v[0] * u[2]) normal[2] = u[0] * v[1] - v[0] * u[1] length = math.sqrt(math.pow(normal[0], 2) + math.pow(normal[1], 2) + math.pow(normal[2], 2)) return [normal[0] / length, normal[1] / length, normal[2] / length] # returns true if the given triangle's normal z length is greater than a threshold value def is_triangle_traversable_by_z_length(self, triangle): normal = self.get_triangle_normal(triangle) return normal[2] > TRIANGLE_NORMAL_Z_TRAVERSABLE # returns the radian angle between two vectors def angle_between_vectors(self, v1, v2): dot = float(v1[0]) * float(v2[0]) + float(v1[1]) * float(v2[1]) + float(v1[2]) * float(v2[2]) lv1 = math.sqrt(float(math.pow(v1[0], 2) + math.pow(v1[1], 2) + math.pow(v1[2], 2))) lv2 = math.sqrt(float(math.pow(v2[0], 2) + math.pow(v2[1], 2) + math.pow(v2[2], 2))) x = dot / (lv1 * lv2) return math.acos(x) # returns True if the difference between triangles normal angle and a vertical line is within a threshold def is_triangle_traversable_by_angle(self, triangle): normal = self.get_triangle_normal(triangle) vertical = [0.0, 0.0, 1.0] angle = self.angle_between_vectors(vertical, normal) #print("normal: " + str(normal) + " vertical: " + str(vertical)) #print("angle: " + str(angle)) return math.fabs(angle) < TRIANGLE_NORMAL_ANGLE_TRAVERSABLE # returns the centroid [x, y, z] of the given triangle def get_centroid(self, triangle): v1 = self.mesh.vertices[int(triangle[0]) - 1] v2 = self.mesh.vertices[int(triangle[1]) - 1] v3 = self.mesh.vertices[int(triangle[2]) - 1] x = (v1[0] + v2[0] + v3[0]) / 3.0 y = (v1[1] + v2[1] + v3[1]) / 3.0 z = (v1[2] + v2[2] + v3[2]) / 3.0 return [x, y, z] # returns True if given point is within the triangle def is_point_in_triangle(self, point, triangle): p1 = self.mesh.vertices[int(triangle[0]) - 1] p2 = self.mesh.vertices[int(triangle[1]) - 1] p3 = self.mesh.vertices[int(triangle[2]) - 1] if point[0] > p1[0] and point[0] > p2[0] and point[0] > p3[0]: return False if point[0] < p1[0] and point[0] < p2[0] and point[0] < p3[0]: return False if point[1] > p1[1] and point[1] > p2[1] and point[1] > p3[1]: return False if point[1] < p1[1] and point[1] < p2[1] and point[1] < p3[1]: return False A = self.area_of_triangle(p1, p2, p3) t0 = self.area_of_triangle(point, p1, p2) t1 = self.area_of_triangle(point, p2, p3) t2 = self.area_of_triangle(point, p1, p3) difference_in_area = math.fabs(A - t0 - t1 - t2) return difference_in_area < 0.0005 # returns True if given point is within triangle created by the 3 given points, p1, p2, and p3 def is_point_in_triangle_simple(self, point, p1, p2, p3): """ if (point[0] > p1[0] and point[0] > p2[0] and point[0] > p3[0]) or \ (point[0] < p1[0] and point[0] < p2[0] and point[0] < p3[0]) or \ (point[1] > p1[1] and point[1] > p2[1] and point[1] > p3[1]) or \ (point[1] < p1[1] and point[1] < p2[1] and point[1] < p3[1]): return False """ if point[0] > p1[0] and point[0] > p2[0] and point[0] > p3[0]: print("above x") return False if point[0] < p1[0] and point[0] < p2[0] and point[0] < p3[0]: print("below x") return False if point[1] > p1[1] and point[1] > p2[1] and point[1] > p3[1]: print("above y") return False if point[1] < p1[1] and point[1] < p2[1] and point[1] < p3[1]: print("below y") return False A = self.area_of_triangle(p1, p2, p3) t0 = self.area_of_triangle(point, p1, p2) t1 = self.area_of_triangle(point, p2, p3) t2 = self.area_of_triangle(point, p1, p3) difference_in_area = math.fabs(A - t0 - t1 - t2) return difference_in_area < 0.0005 # returns the area of the triangle created by the three given points def area_of_triangle(self, p1, p2, p3): return math.fabs( (p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])) / 2 ) # returns the triangle that contains the given point, p. Otherwise returns [-1, -1, -1] def get_triangle_from_point(self, p, triangles): #print("triangle for " + str(p) + "...") for triangle in triangles: if self.is_point_in_triangle(p, triangle): return triangle return [-1, -1, -1] """ ZONES """ # returns all triangles in self.mesh.triangles that are in the given zone index def get_triangles_in_zone(self, zone): triangles_in_zone = [] for triangle in self.mesh.triangles: point = self.get_centroid(triangle) if self.is_point_in_zone(zone, point): triangles_in_zone.append(triangle) return triangles_in_zone # returns True if the given point is in the given zone index def is_point_in_zone(self, zone, point): top_left = zone.corners[0] top_right = zone.corners[1] bottom_right = zone.corners[2] bottom_left = zone.corners[3] top = math.sqrt(math.pow(top_left[0] - top_right[0], 2) + math.pow(top_left[1] - top_right[1], 2)) side = math.sqrt(math.pow(top_left[0] - bottom_left[0], 2) + math.pow(top_left[1] - bottom_left[1], 2)) area = top * side # area of 4 triangles t0 = .5 * (point[0] * (top_left[1] - top_right[1]) + top_left[0] * (top_right[1] - point[1]) + top_right[0] * (point[1] - top_left[1])) t1 = .5 * (point[0] * (top_right[1] - bottom_right[1]) + top_right[0] * (bottom_right[1] - point[1]) + bottom_right[0] * (point[1] - top_right[1])) t2 = .5 * (point[0] * (bottom_right[1] - bottom_left[1]) + bottom_right[0] * (bottom_left[1] - point[1]) + bottom_left[0] * (point[1] - bottom_right[1])) t3 = .5 * (point[0] * (bottom_left[1] - top_left[1]) + bottom_left[0] * (top_left[1] - point[1]) + top_left[0] * (point[1] - bottom_left[1])) sum_of_triangles = math.fabs(t0) + math.fabs(t1) + math.fabs(t2) + math.fabs(t3) difference_in_area = math.fabs(sum_of_triangles - area) return difference_in_area < 0.05 # returns the traversable triangles from self.mesh.triangles that are in the given zone index def get_traversable_mesh_in_zone(self, zone): potential_triangles = self.get_triangles_in_zone(zone) traversable_triangles = [] for triangle in potential_triangles: if self.is_triangle_traversable_by_angle(triangle): traversable_triangles.append(triangle) return traversable_triangles # this is an old method DO NOT USE def make_occupancy_grid(self, area_corners): tl = area_corners[0] tr = area_corners[1] OG = [] dx = tr[0] - tl[0] dy = tr[1] - tl[1] yi = 0 traversable_triangles = [] if DEBUG: print("filtering triangles") for triangle in self.mesh.triangles: if self.is_triangle_traversable_by_angle(triangle): traversable_triangles.append(triangle) if DEBUG: print("Number of triangles: " + str(len(self.mesh.triangles)) + " Number of TT: " + str(len(traversable_triangles))) print("number of filtered triangles " + str(len(self.mesh.triangles) - len(traversable_triangles))) while yi < OG_WIDTH: xi = 0 while xi < OG_WIDTH: x = tl[0] + xi * dx / (OG_WIDTH - 1) y = tl[1] + yi * dy / (OG_WIDTH - 1) t = self.get_triangle_from_point([x, y], traversable_triangles) if t[0] == -1 and t[1] == -1 and t[2] == -1: if DEBUG: print("triangle not found") OG.append(-1) else: if DEBUG: print("triangle is traversable") OG.append(self.get_triangle_normal(t)[2]) xi += 1 yi += 1 return OG # makes an OG from the given zones and area_corners def make_occupancy_grid_in_front(self, visible_zones, area_corners): zone_triangles = dict() for zone in visible_zones: zone_triangles[zone.id] = [] for triangle in self.mesh.triangles: if self.is_triangle_traversable_by_angle(triangle): centroid = self.get_centroid(triangle) for zone in visible_zones: if self.is_point_in_zone(zone, centroid): triangles = zone_triangles[zone.id] triangles.append(triangle) zone_triangles[zone.id] = triangles break if DEBUG: for zone in visible_zones: print("triangles in zone " + str(zone.id) + ": " + str(len(zone_triangles[zone.id]))) tl = area_corners[0] tr = area_corners[1] br = area_corners[2] OG = [] dx = tr[0] - tl[0] dy = tr[1] - br[1] total_not_found = 0 total_no_zone = 0 total_found = 0 yi = 0 while yi < OG_WIDTH: xi = 0 while xi < OG_WIDTH: x = tl[0] + xi * dx / (OG_WIDTH - 1) y = tl[1] - yi * dy / (OG_WIDTH - 1) zone_id = -1 for zone in visible_zones: if self.is_point_in_zone(zone, [x, y]): zone_id = zone.id break if zone_id == -1: total_no_zone += 1 OG.append(-1) else: t = self.get_triangle_from_point([x, y], zone_triangles[zone_id]) if t[0] == -1 and t[1] == -1 and t[2] == -1: total_not_found += 1 OG.append(-1) else: total_found += 1 OG.append(self.get_triangle_normal(t)[2]) xi += 1 yi += 1 if DEBUG: print("total triangles not found: " + str(total_not_found) + " total no zones: " + str(total_no_zone) + " total found: " + str(total_found)) return OG # makes an OG from the given zones and area_corners def make_occupancy_grid_bl(self, visible_zones, area_corners): zone_triangles = dict() for zone in visible_zones: zone_triangles[zone.id] = [] for triangle in self.mesh.triangles: if self.is_triangle_traversable_by_angle(triangle): centroid = self.get_centroid(triangle) for zone in visible_zones: if self.is_point_in_zone(zone, centroid): triangles = zone_triangles[zone.id] triangles.append(triangle) zone_triangles[zone.id] = triangles break if DEBUG: for zone in visible_zones: print("triangles in zone " + str(zone.id) + ": " + str(len(zone_triangles[zone.id]))) tl = area_corners[0] tr = area_corners[1] br = area_corners[2] bl = area_corners[3] OG = [] dx = tr[0] - tl[0] dy = tr[1] - br[1] total_not_found = 0 total_no_zone = 0 total_found = 0 yi = 0 while yi < OG_WIDTH: xi = 0 while xi < OG_WIDTH: x = bl[0] + xi * dx / (OG_WIDTH - 1) y = bl[1] + yi * dy / (OG_WIDTH - 1) zone_id = -1 for zone in visible_zones: if self.is_point_in_zone(zone, [x, y]): zone_id = zone.id break if zone_id == -1: total_no_zone += 1 OG.append(-1) else: t = self.get_triangle_from_point([x, y], zone_triangles[zone_id]) if t[0] == -1 and t[1] == -1 and t[2] == -1: total_not_found += 1 OG.append(-1) else: total_found += 1 OG.append(self.get_triangle_normal(t)[2]) xi += 1 yi += 1 if DEBUG: print("total triangles not found: " + str(total_not_found) + " total no zones: " + str(total_no_zone) + " total found: " + str(total_found)) return OG
1663ed2b9c40a347ca117ae87bfbb658a9a08ed1
jaewie/algorithms
/python/tests/collection/test_dynamic_array.py
2,245
3.515625
4
import unittest from collection.dynamic_array import DynamicArray class TestDynamicArray(unittest.TestCase): def setUp(self): self.arr = DynamicArray() def test_constructor(self): self.assertTrue(self.arr.is_empty()) self.assertEquals(0, len(self.arr)) def test_one_append(self): element = 1 self.arr.append(element) self.assertFalse(self.arr.is_empty()) self.assertEquals(1, len(self.arr)) def test_multiple_appendes(self): elements = range(100) for element in elements: self.arr.append(element) self.assertFalse(self.arr.is_empty()) self.assertEquals(len(elements), len(self.arr)) def test_one_pop(self): element = 1 self.arr.append(element) self.assertEquals(element, self.arr.pop()) self.assertTrue(self.arr.is_empty()) self.assertEquals(0, len(self.arr)) def test_multiple_pops(self): elements = range(100) for element in elements: self.arr.append(element) for element in reversed(elements): self.assertEquals(element, self.arr.pop()) self.assertTrue(self.arr.is_empty()) self.assertEquals(0, len(self.arr)) def test_pop_empty(self): self.assertRaises(IndexError, self.arr.pop) def test_pop_too_many(self): self.arr.append(1) self.arr.pop() self.assertRaises(IndexError, self.arr.pop) def test_find_empty(self): self.assertEquals(-1, self.arr.find(900)) def test_get_empty(self): self.assertRaises(IndexError, self.arr.__getitem__, 30) def test_get_not_empty(self): element = 900 self.arr.append(element) self.assertEquals(element, self.arr[0]) def test_set_empty(self): self.assertRaises(IndexError, self.arr.__setitem__, 0, 30) def test_set_not_empty(self): self.arr.append(900) self.arr[0] = 0 self.assertEquals(0, self.arr[0]) def test_find_empty(self): lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] for e in lst: self.arr.append(e) for i, e in enumerate(lst): self.assertEquals(i, self.arr.find(e))
bad38b18f34faa65be3cbba18753b7897f6ca479
denysdenys77/battle_simulator
/helpers/geometric_average_helper.py
369
3.75
4
from typing import List class GeometricHelper: @staticmethod def get_geometric_average(items: List[float]) -> float: """Returns geometric average of int items in list.""" multiply = 1 n = len(items) for i in items: multiply = multiply * i geometric_mean = multiply ** 1 / n return geometric_mean
d0e08a188e2d65352349ceb1742a3966eabde253
caihedongorder/PythonEx
/PythonApplication1/PythonApplication1/module1.py
302
3.578125
4
import PythonApplication1 import os c = PythonApplication1.test(); c.a = 100 c.b = 101 class test1(PythonApplication1.test): def __init__(self): self.c = 100 return super(test1, self).__init__() d = test1() d.a = 100 d.b = 100 d.c = 10 print("a:{c.a},b:{c.b}".format(c = c))
7bbd51b638b1c274950e9c6f56302c73e2dcfd17
reinaldoboas/Curso_em_Video_Python
/Mundo_1/desafio017.py
643
4.125
4
### Curso em Vídeo - Exercicio: desafio017.py ### Link: https://www.youtube.com/watch?v=vmPW9iWsYkY&list=PLvE-ZAFRgX8hnECDn1v9HNTI71veL3oW0&index=26 ### Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, ### calcule e mostre o comprimento da hipotenusa. # Importando o módulo da biblioteca math from math import hypot co = float(input("Digite o Cateto Oposto: ")) ca = float(input("Digite o Cateto Adjacente: ")) # Realizando o calculo matematico hipotenusa = hypot(co, ca) print(f"O Cateto Oposto {co} e o Cateto Adjacente {ca} têm o comprimento da Hipotenusa: {hipotenusa}.")
bb94f37015b85fe0c8d6cacf93161bf67a37765d
wh2353/Rosalind_Solutions_in_Python
/Bioinformatics Textbook Track/BA9J/BA9J_Smart_way.py
708
3.9375
4
''' Smart Way of implementing BWT reversal: instead of indexing letters from first and last column, let first column equal to range(len(seq)), then sorted alphabetically based on the letters in the input seq, the index and the content of the first column can be served as the previous first and last column ''' def burrows_wheeler_reverse(seq): out_seq = '' idx = 0 first_col = sorted(range(len(seq)), key= lambda i: seq[i]) while len(out_seq) < len(seq): out_seq += seq[first_col[idx]] idx = first_col[idx] return out_seq[1:] + out_seq[0] if __name__ == "__main__": seq = open("rosalind_ba9j.txt","r").read().rstrip() print burrows_wheeler_reverse(seq)
226d147fbc1b0edd56290c0c326eaff12d457647
JamesHeal/PAT-AdvancedLevel-for-Zhejiang-University
/Advanced/1001.py
676
4.0625
4
#coding:utf-8 #次方的表示方法 lower_margin = -10 ** 6 upper_margin = 10 ** 6 if __name__ == '__main__': #split()是用来识别空格 #直接input()输入的是class类型 a, b = input().split() A = int(a) B = int(b) if type(A) is not int: print('the type of "a" is wrong') elif type(B) is not int: print('the type of "b" is wrong') elif A < lower_margin or A > upper_margin: print('"a" is out of range') elif B < lower_margin or A > upper_margin: print('"b" is out of range') else: c = A + B #format()的用法,‘:’后接的是format处理的方式 print("{:,}".format(c))
f363cfbe640b304c6119945a210c1ae277fb833e
tong-zeng/collocations
/mutual_info/ngrams.py
415
3.515625
4
#!/usr/bin/env python import sys if not len(sys.argv)==2: raise "expected NGRAM_LENGTH" ngram_len = int(sys.argv[1]) for line in sys.stdin: tokens = line.strip().split() if ngram_len == 1: for token in tokens: print token else: if len(tokens) < ngram_len: continue for i in range(0,len(tokens)-ngram_len+1): print "\t".join(tokens[i:i+ngram_len])
d034203626132935911e15ea07363877d4ce20b6
adrian-chen/ai3202
/Assignment3/aStar.py
7,458
3.84375
4
import argparse import math WIDTH = 10 HEIGHT = 8 def read_graph(f, g, height): # Read file, then create nodes in graph g for each entry in the matrix list_index = 0 # We read from top to bottom y = height-1 for line in f: if line: # Keeps track of x coordinate (read in order) x = 0 # Split on space to get each entry vals = str.split(line) for v in vals: n = Node(v) n.set_loc(x,y) g.add_to_data(n, list_index) x += 1 y -= 1 list_index += 1 class Graph: def __init__(self, width, height): self.width = width self.height = height self.data = [] # 2d array of Nodes for i in range(0, height): self.data.append([]) def add_to_data(self, node, x): self.data[x].append(node) def print_graph(self): for i in range(0, self.height): line = "" for j in range(0, self.width): line += str(self.data[i][j].val) + " " print line def get(self, x, y): # Get node at given location, or if it doesn't exist return None if x < 0 or y < 0: return None else: for l in self.data: for n in l: if n.x is x and n.y is y: return n def setup_edges_node(self, node): # For any given node, return all adjacent nodes that are valid adjacent=[] x = node.x y = node.y # All possible adjacent nodes down_left = self.get(x-1,y-1) down = self.get(x,y-1) down_right = self.get(x+1,y-1) right = self.get(x+1,y) up_right = self.get(x+1,y+1) up = self.get(x,y+1) up_left = self.get(x-1,y+1) left = self.get(x-1, y) for node in [down_left, down, down_right, right, up_right, up, up_left, left]: # Don't count as adjacent if it's a wall if node is not None and node.val is not 2: # Set costs (diag different) additional_cost = 0 if node in [down_left, down_right, up_left, up_right]: additional_cost = 14 else: additional_cost = 10 # We have extra cost if space is a mountain if node.val is 1: additional_cost += 10 adjacent.append([node,additional_cost]) return adjacent def setup_edges(self,x,y): # Wraps setup_edges_node if we only have the grid location node = self.get(x,y) return setup_edges_node(node) class Node: def __init__(self, val): self.val = int(val) # Add these t simplify self.x = 0 self.y = 0 self.parent = None # Cost so far self.g = 0 # Cost of heuristic self.h = 0 # Sum total cost self.cost = 0 def set_loc(self, x, y): # Set x and y coords for a node self.x = x self.y = y class aStar: # The maximum number to follow when printing path, in case we have a loop MAX_PATH_LENGTH = 100 def __init__(self, start, end, g, heuristic): self.path = [] self.start = start self.end = end self.chosen_heuristic = heuristic self.g = g # Track locations evaluated for assignment - begin at 1 for start node self.locations_evaluated = 1 def heuristic(self, n): # Dispatches to correct heurstic function if self.chosen_heuristic == "manhattan": return self.manhattan(n) elif self.chosen_heuristic =="diagonal": return self.diagonal(n) else: raise Exception('Invalid choice of heuristic') def manhattan(self, n): return 10 * abs(n.x - self.end.x) + 10 * abs(n.y-self.end.y) def diagonal(self, n): dx = abs(n.x - self.end.x) dy = abs(n.y - self.end.y) return 10 * (dx + dy) + (14 - 20) * min(dx, dy) def update_node(self, node, parent, move_cost): # Update information for a given node - specifically cost and parent node.parent = parent # Update actual distance node.g = move_cost + parent.g # Update heuristic node.h = self.heuristic(node) # Set final cost node.cost = node.g + node.h def search(self): # Run actual search algorithm # Begin at start node open = [self.start] closed = [] while len(open) > 0: # Grab minimum cost node out of list node = min(open, key=lambda n: n.cost) open.remove(node) if node is not self.end: # If we haven't found the end closed.append(node) # Add adjacent edges for (adj, move_cost) in self.g.setup_edges_node(node): # As long as it is not already finished if adj not in closed: if adj in open: # Check if current path is better than previously found path if adj.g > (node.g + move_cost): self.update_node(adj, node, move_cost) else: # Otherwise give it info for the first time and add it to open self.update_node(adj, node, move_cost) open.append(adj) self.locations_evaluated = self.locations_evaluated + 1 else: self.print_output() break def print_output(self): # Print assignment specified output path = self.get_path(self.end) print """ =====================================A* Search====================================== Successfully finished pathfinding using A* search with the %s heuristic. The final cost of the path was %d. The number of locations traveled was %d. The optimal path was: %s ==================================================================================== """ % (self.chosen_heuristic, self.end.cost, self.locations_evaluated, path) def get_path(self, node): # Get path to a given node from the start node path = [] cursor = node # Maximum just in case for i in range(0,self.MAX_PATH_LENGTH): if cursor: path.append((cursor.x, cursor.y)) cursor = cursor.parent # We want it in reverse order return path[::-1] if __name__ == "__main__": # Command line parser parser = argparse.ArgumentParser() parser.add_argument("input_file", help="The name of the file to treat as the search space") parser.add_argument("heuristic", help="Name of search heuristic to use in A* search", choices=("manhattan", "diagonal"), default="manhattan") args = parser.parse_args() # open file f = open(args.input_file, 'r'); g = Graph(WIDTH, HEIGHT) # Read the graph from txt read_graph(f, g, HEIGHT) # Create and perform A* search search = aStar(g.get(0,0), g.get(WIDTH-1,HEIGHT-1), g, args.heuristic) search.search()
68ef0a2d78b65a9a6a12cff39fd399bdb74c5d10
rcarasek/Aprendendo-Python
/fibonacci.py
286
4.03125
4
def fibonacci(num): a = 0 sequencia = [0, 1] while a < num-1: print(sequencia) proximo = sequencia[a] + sequencia[a + 1] sequencia.append(proximo) a = a + 1 return sequencia x = input('Quantos itens?') x = int(x) fibonacci(x) print(x)
db1e37012d7afb3ebf52f36cbabf9b1fb72d5166
ChrisVelasco0312/misionTicUTP_class
/Ciclo_1_fundamentos/Unidad_4/Clase_11/orden_superior.py
265
3.546875
4
# función map numeros = [num for num in range(1, 101)] doble = list( map(lambda numero: numero * 2, numeros) ) # print(numeros) # print(doble) # función filter filtrada = list(filter(lambda numero: numero > 20 and numero < 55, numeros)) print(filtrada)
c871bdc5156d0647f58c33b0224585edbf77e96f
MARGARITADO/Mision_04
/Software.py
1,438
4.125
4
#Autor: Martha Margarita Dorantes Cordero #Calcular total de paquetes def calcularTotal(numPaquetes) : #Función que realiza la operación requerida para calcular el total a pagar con el descuento aplicable. total = (numPaquetes * 2300) - calcularDescuento(numPaquetes) return total def calcularDescuento(numPaquetes) : #Función que realiza la operación requerida para calcular el descuento aplicable con base en el número de paquetes. total = numPaquetes * 2300 descuento = 0 if(numPaquetes < 10) : return descuento elif(numPaquetes < 20) : descuento = total * 0.15 return descuento elif(numPaquetes < 50) : descuento = total * 0.22 return descuento elif(numPaquetes < 100) : descuento = total * 0.35 return descuento else : descuento = total * 0.42 return descuento def main() : #Función principal que solictia el número de paquetes de software vendidos y llama a las funciones #previamente descritas para calcular el descuento y el total a pagar después del descuento. numPaquetes = int(input("\n Ingrese el número de paquetes vendidos: ")) if(numPaquetes <= 0) : print('\n ERROR. El número de paquetes debe ser un entero positivo. GRACIAS.') else : print('\n Subtotal: $%.2f'%(numPaquetes * 2300)) print(' Descuento: $%.2f'%(calcularDescuento(numPaquetes))) print(' -----------------------') print(' Total a pagar: $%.2f'%(calcularTotal(numPaquetes))) main()
6976e016fa332643ea0b9b3996e6d66ab3ad5a93
AiZhanghan/Algorithms-Fourth-Edition
/code/chapter1/Queue.py
1,335
4.15625
4
from collections import deque class Queue: """基于collections.deque""" def __init__(self): """创建空队列""" self.queue = deque() def enqueue(self, item): """添加一个元素 Args: item: Item """ self.queue.append(item) def dequeue(self): """删除最早添加的元素 Return: Item """ return self.queue.popleft() def __len__(self): """队列中的元素数量 Return: int """ return len(self.queue) def __iter__(self): """返回一个迭代器""" # 记录迭代位置, 从0开始 self.position = 0 return self def __next__(self): """返回迭代器下一个指向的值""" if self.position < len(self.queue): item = self.queue[self.position] self.position += 1 return item else: raise StopIteration if __name__ == "__main__": q = Queue() while True: item = input() if item == "q": break elif q and item == "-": print(q.dequeue()) else: q.enqueue(item) print("(%d left in queue)" % len(q)) for item in q: print(item)
17d0a5b8659c4812b6819b533792dba9c15b4537
kyclark/tiny_python_projects
/16_scrambler/solution.py
1,989
4
4
#!/usr/bin/env python3 """Scramble the letters of words""" import argparse import os import re import random # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Scramble the letters of words', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='text', help='Input text or file') parser.add_argument('-s', '--seed', help='Random seed', metavar='seed', type=int, default=None) args = parser.parse_args() if os.path.isfile(args.text): args.text = open(args.text).read().rstrip() return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) splitter = re.compile("([a-zA-Z](?:[a-zA-Z']*[a-zA-Z])?)") for line in args.text.splitlines(): print(''.join(map(scramble, splitter.split(line)))) # -------------------------------------------------- def scramble(word): """For words over 3 characters, shuffle the letters in the middle""" if len(word) > 3 and re.match(r'\w+', word): middle = list(word[1:-1]) random.shuffle(middle) word = word[0] + ''.join(middle) + word[-1] return word # -------------------------------------------------- def test_scramble(): """Test scramble""" state = random.getstate() random.seed(1) assert scramble("a") == "a" assert scramble("ab") == "ab" assert scramble("abc") == "abc" assert scramble("abcd") == "acbd" assert scramble("abcde") == "acbde" assert scramble("abcdef") == "aecbdf" assert scramble("abcde'f") == "abcd'ef" random.setstate(state) # -------------------------------------------------- if __name__ == '__main__': main()
3ca37d98a5ffa754fd7596b065d870729f279849
juniweb/TIL
/Python/PythonForBeginners_Microsoft/exm_errorHandling.py
418
3.890625
4
# Syntax error # if x == y # print('x is equals y') # Runtime error x = 42 y = 0 try: print(x / y) except ZeroDivisionError as e: # Optionally, log e something print('Sorry, something went wrong') except: print('Something really went wrong') finally: print('This always runs on success or failure') # Logic error x1 = 206 y1 = 42 if x1 < y1: print(str(x) + ' is greater then ' + str(y))
0661f17891131140f4a1c28fe5f95454e43ab28c
Aniketthani/Python-Tkinter-Tutorial-With-Begginer-Level-Projects
/2buttons.py
441
4.03125
4
from tkinter import * root=Tk() # function for button onclick def click(): label=Label(root,text="You clicked Me") label.pack() #Creating a Button mybutton=Button(root,text="Click Me" , pady="50", padx="100" , command=click,fg="blue", bg="orange") # for disabling a button disabled_button=Button(root,text="This is a Disabled Button",state="disabled") #showing it on screen mybutton.pack() disabled_button.pack() root.mainloop()
5f1352fcf465f30756428c561d6297753dc7c573
kevin-d-mcewan/ClassExamples
/Chap10_OOP/PropertiesForDataAccess.py
1,478
3.53125
4
#PropertiesForDataAccess.py from timewithproperties import Time """ Create a TIME obj. TIME's __init__ method has HOUR, MIN and SECOND params, each w/default value of 0.""" # Here, specify the HR and MIN-SEC def to 0: wake_up = Time(hour=6, minute=30) print(wake_up) print('----------------------------------------------') print(wake_up.__repr__) # Print using __repr__ method print(wake_up.__str__) # Print using __str__ method print('----------------------------------------------') print(str(wake_up)) # RightWay print using __str__ print(repr(wake_up)) # RightWay Print using __repr__ method print('----------------------------------------------') # GETTING AN ATTR VIA A PROPERTY print("wake_up.hour = ", wake_up.hour) # OR print("wake_up.hour = " + str(wake_up.hour)) print('---------------------------------------------') """ SETTING THE TIME """ wake_up.set_time(hour = 7, minute = 40) print(wake_up) print('OR...') print(repr(wake_up)) print('------------------------------------------------') # SETTING AN ATTR VIA A PROPERTY wake_up.hour = 8 print(wake_up) print('OR...') print(repr(wake_up)) print('===============================================') ''' ATTEMPTING TO SET AN INVALID VALUE''' # wake_up.hour = 100 print(wake_up) print('-------------------------------') wake_up = Time(hour=7, minute=23, second=14) print(str(wake_up.hour)) print(wake_up.hour) print('-----------------------------------')
15295a4207c183b64d1ae77ae39a78ac3d1b254a
qamarilyas/Demo
/stringValidator.py
198
3.546875
4
str='aB2' print(any(i.isalnum() for i in str)) print(any(i.isalpha() for i in str)) print(any(i.isdecimal() for i in str)) print(any(i.islower() for i in str)) print(any(i.upper() for i in str))
176892211bfb33f2bd057831bcb4322871ce7df3
diego-mr/FATEC-MECATRONICA-0791821037-DIEGO
/LTP1-2020-2/PRATICA03/exercicio02.py
290
4.1875
4
#Escreva um programa permita o usuário informa uma temperatura em graus Celsius e converta ela para graus Fahrenheit valor_celsius = float(input('inserir o valor do grau em celsius:')) valor_Fahrenheit = 1.8 * valor_celsius + 32 print('valor convertido em Fahrenheit', valor_Fahrenheit)
d41f4d9fa1171a9d1ddfd2e917252b623776a633
vaishaliyosini/Python_Concepts
/16.list_compr.py
1,077
4.03125
4
nums = [1, 2, 3, 4, 5, 6, 7] # traditional for loop l = [] for n in nums: l.append(n) print(l) # prints '[1, 2, 3, 4, 5, 6, 7]' # meet list comprehension l = [n for n in nums] print(l) # prints '[1, 2, 3, 4, 5, 6, 7]' # get square of each number l = [n*n for n in nums] print(l) # prints '[1, 4, 9, 16, 25, 36, 49]' # same thing achieved using 'map' + 'lambda' # 'map' means running everything in the list for a certain function # 'lambda' means an anonymous function l = map(lambda n: n*n, nums) for x in l: print(x) # prints # 1 # 4 # 9 # 16 # 25 # 36 # 49 # using 'if' in list comprehension l = [n for n in nums if n%2 == 0] print(l) # prints '[2, 4, 6]' # returning tuples with two for loops in list comprehension l = [] for letter in "ab": for num in range(2): l.append((letter, num)) print(l) # prints '[('a', 0), ('a', 1), ('b', 0), ('b', 1)]' # same thing using list comp l = [(letter, num) for letter in "ab" for num in range(2)] print(l) # prints '[('a', 0), ('a', 1), ('b', 0), ('b', 1)]
c0d0f5b167152b9baf5e6de66ad8d95da3bf800b
AdityaShidlyali/Python
/Learn_Python/Chapter_5/4_delete_data_in_lists.py
453
4.25
4
# to delete the data in the list there are two methods # 1st is based on the index number and 2nd one is based on the element specified # 1st method list_1 = ["apple", "mango", "chickoo", "banana", "grapes"] del list_1[2] print(list_1) list_1.pop(2) # 2 here is the index number of the list print(list_1) # without mentioning the index number the pop() method deletes the element from the last index # 2nd method list_1.remove("grapes") print(list_1)
46f649da5b853ccf866699a617adaa5028ad314a
antoinemadec/test
/python/programming_exercises/q4/q4.py
626
4.34375
4
#!/usr/bin/env python3 print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') Answer:""") foo = input("Enter comma separated list: ") l = foo.split(',') print(l) print(tuple(l))
4227366a6b9d50aa3811051b2807878882ceb324
hanyinggg/python
/Scripts/sort/Quicksort.py
700
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri May 11 14:56:12 2018 @author: hand """ import random def QuickSort(myList,left,right): if left >= right: return myList low = left high =right base = myList[left] while left < right: while (left < right) and (myList[right]>=base): right -=1 myList[left] = myList[right] while (left < right) and (myList[left]<=base): left +=1 myList[right] = myList[left] myList[right] = base QuickSort(myList, low, left-1) QuickSort(myList, left+1, high) return myList myList =[random.randint(1,10000) for i in range(500)] QuickSort(myList,0,len(myList)-1) print(myList)
dfff61fc16a06bcb1032efc1348431a3176dae01
Anshul-GH/freelance_projects
/category_linkedin_learning/python_advanced_skills/Ex_Files_Learning_Python_Upd/Exercise Files/Ch2/loops_start.py
286
3.90625
4
# # Example file for working with loops # def main(): x = 0 # define a while loop # define a for loop # use a for loop over a collection # use the break and continue statements #using the enumerate() function to get index if __name__ == "__main__": main()
387008a77142bbd385a7f2e84a89118b013babce
NemesLaszlo/Pac-Man_MQTT
/player.py
4,266
3.828125
4
import pygame from settings import * vec = pygame.math.Vector2 class Player: """ Player class with the methods and parameters. """ def __init__(self, app, position): """ Constructor of the Player, with the parameters. """ self.app = app self.grid_position = position # position is a player start position from player init self.pix_position = self.get_pix_position() self.starting_position = [position.x, position.y] self.direction = vec(1, 0) self.speed = 2 self.current_score = 0 self.stored_direction = None self.able_to_move = True self.lives = 1 def update(self): """ Player move check and update to work correctly. """ if self.able_to_move: self.pix_position += self.direction * self.speed if self.move_next_position(): if self.stored_direction is not None: self.direction = self.stored_direction self.able_to_move = self.can_move() # following the player circle on grid - tracking the movement self.grid_position[0] = (self.pix_position[0] - TOP_BOTTOM_BUFFER + self.app.cell_width // 2) // self.app.cell_width + 1 self.grid_position[1] = (self.pix_position[1] - TOP_BOTTOM_BUFFER + self.app.cell_height // 2) // self.app.cell_height + 1 # check the actual grid position, and if there it has a coin, the player "eat" that if self.on_coin(): self.eat_coin() def draw(self): """ Drawing the player circle and the the informations about the player lives count. """ # player circle pygame.draw.circle(self.app.screen, PLAYER_COLOR, (int(self.pix_position.x), int(self.pix_position.y)), self.app.cell_width // 2 - 2) # drawing player lives for x in range(self.lives): pygame.draw.circle(self.app.screen, PLAYER_COLOR, (30 + 20 * x, HEIGHT - 15), 7) # player position on grid for following # pygame.draw.rect(self.app.screen, RED, # (self.grid_position[0] * self.app.cell_width + TOP_BOTTOM_BUFFER // 2, # self.grid_position[1] * self.app.cell_height + TOP_BOTTOM_BUFFER // 2, self.app.cell_width, self.app.cell_height), 1) def get_pix_position(self): # player circle position on the grid map return vec((self.grid_position[0] * self.app.cell_width) + TOP_BOTTOM_BUFFER // 2 + self.app.cell_width // 2, (self.grid_position[1] * self.app.cell_height) + TOP_BOTTOM_BUFFER // 2 + self.app.cell_height // 2) # by read keyboard movement at this moment def move(self, vector_dir): """ By read keyboard movement at this moment. "Special moving with direction storing and moving" """ self.stored_direction = vector_dir # move next position check def move_next_position(self): """ Moving to the next position checker. """ if int(self.pix_position.x + TOP_BOTTOM_BUFFER // 2) % self.app.cell_width == 0: if self.direction == vec(1, 0) or self.direction == vec(-1, 0) or self.direction == vec(0, 0): return True if int(self.pix_position.y + TOP_BOTTOM_BUFFER // 2) % self.app.cell_height == 0: if self.direction == vec(0, 1) or self.direction == vec(0, -1) or self.direction == vec(0, 0): return True # check the wall, and we can move there or not def can_move(self): """ Check the wall, can we move there or not. """ for wall in self.app.walls: if vec(self.grid_position + self.direction) == wall: return False return True def on_coin(self): """ Check the player position on a grid, is there a coin or there is no coin there. """ if self.grid_position in self.app.coins and self.move_next_position(): return True return False def eat_coin(self): """ Coin "eating" and score increase. """ self.app.coins.remove(self.grid_position) self.current_score += 1
dd83631940854cc85b251751b52690413e884126
CharlotteKuang/algorithm
/LeetCode/160.IntersectionOfTwoLinkedLists/Solution.py
1,198
3.875
4
import pdb # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not headA or not headB: return None p = headA while p.next: p = p.next mark = p #make a cycled list mark.next = headA rst = None p1 = headB p2 = headB while p1 and p2: p1 = p1.next p2 = p2.next if p2: p2 = p2.next if p1 == p2: break pdb.set_trace() if p1 and p2 and p1 == p2: p1 = headB while p1 != p2: p1 = p1.next p2 = p2.next rst = p1 #unmake the cycle mark.next = None return rst if __name__ == '__main__': headA = ListNode(1) headA.next = ListNode(2) headA.next.next = ListNode(3) headA.next.next.next = ListNode(4) tmp = headA.next.next.next.next = ListNode(5) headB = ListNode(6) headB.next = ListNode(7) headB.next.next = tmp tmp.next = ListNode(8) sol = Solution() rst = sol.getIntersectionNode(headA, headB) print rst.val headC = ListNode(2) headC.next = ListNode(3) headD = ListNode(5) sol.getIntersectionNode(headC, headD)
8d20b56da4ddf5efcec6b365dc2384d9bf5bb94c
MdouglasJCU/Sandbox
/count_vowels.py
206
4.0625
4
name = input("Pleas enter your name") vowel_count = 0 for i in name: if i in "aeiouAEIOU": vowel_count += 1 print("Out of {} letters, {} has {} vowels".format(len(name), name, vowel_count))
702a45cf96e966ac87a806ee7f570b7fdeec24f6
omar-ouhibi/gomycodeedition
/q3.py
102
4.21875
4
#Q3 n = int(input("type a number")) if n%2 != 0: print('its odd') else: print('its even')
04ce7cd8efae424721f61b6fd365510a684cedd5
JulyKikuAkita/PythonPrac
/cs15211/ValidateIPAddress.py
4,981
3.90625
4
__source__ = 'https://github.com/kamyu104/LeetCode/blob/master/Python/validate-ip-address.py' # Time: O(1) # Space: O(1) # # Description: 468. Validate IP Address # # Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. # # IPv4 addresses are canonically represented in dot-decimal notation, # which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; # # Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid. # # IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. # The groups are separated by colons (":"). # For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. # Also, we could omit some leading zeros among four hexadecimal digits # and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 # is also a valid IPv6 address(Omit leading zeros and using upper cases). # # However, we don't replace a consecutive group of zero value with a single empty group # using two consecutive colons (::) to pursue simplicity. # For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. # # Besides, extra leading zeros in the IPv6 is also invalid. # For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid. # # Note: You may assume there is no extra space or special characters in the input string. # # Example 1: # Input: "172.16.254.1" # # Output: "IPv4" # # Explanation: This is a valid IPv4 address, return "IPv4". # Example 2: # Input: "2001:0db8:85a3:0:0:8A2E:0370:7334" # # Output: "IPv6" # # Explanation: This is a valid IPv6 address, return "IPv6". # Example 3: # Input: "256.256.256.256" # # Output: "Neither" # # Explanation: This is neither a IPv4 address nor a IPv6 address. # Hide Company Tags Twitter # Hide Tags String import unittest # 20ms 100% class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ blocks = IP.split('.') if len(blocks) == 4: for i in xrange(len(blocks)): if not blocks[i].isdigit() or not 0 <= int(blocks[i]) < 256 or \ (blocks[i][0] == '0' and len(blocks[i]) > 1): return "Neither" return "IPv4" blocks = IP.split(':') if len(blocks) == 8: for i in xrange(len(blocks)): if not (1 <= len(blocks[i]) <= 4) or \ not all(c in string.hexdigits for c in blocks[i]): return "Neither" return "IPv6" return "Neither" class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' #Thought: 1. Regex: # 10ms 14.19% class Solution { public String validIPAddress(String IP) { if(IP.matches("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"))return "IPv4"; if(IP.matches("(([0-9a-fA-F]{1,4}):){7}([0-9a-fA-F]{1,4})"))return "IPv6"; return "Neither"; } } 2. # 6ms 45.16% class Solution { public String validIPAddress(String IP) { if (isValidIPv4(IP)) return "IPv4"; else if (isValidIPv6(IP)) return "IPv6"; else return "Neither"; } public boolean isValidIPv4(String ip) { if (ip.length()<7) return false; if (ip.charAt(0)=='.') return false; if (ip.charAt(ip.length()-1)=='.') return false; String[] tokens = ip.split("\\."); if (tokens.length!=4) return false; for(String token:tokens) { if (!isValidIPv4Token(token)) return false; } return true; } public boolean isValidIPv4Token(String token) { if (token.startsWith("0") && token.length()>1) return false; try { int parsedInt = Integer.parseInt(token); if (parsedInt<0 || parsedInt>255) return false; if (parsedInt==0 && token.charAt(0)!='0') return false; } catch(NumberFormatException nfe) { return false; } return true; } public boolean isValidIPv6(String ip) { if (ip.length()<15) return false; if (ip.charAt(0)==':') return false; if (ip.charAt(ip.length()-1)==':') return false; String[] tokens = ip.split(":"); if (tokens.length!=8) return false; for(String token: tokens) { if (!isValidIPv6Token(token)) return false; } return true; } public boolean isValidIPv6Token(String token) { if (token.length()>4 || token.length()==0) return false; char[] chars = token.toCharArray(); for(char c:chars) { boolean isDigit = c>=48 && c<=57; boolean isUppercaseAF = c>=65 && c<=70; boolean isLowerCaseAF = c>=97 && c<=102; if (!(isDigit || isUppercaseAF || isLowerCaseAF)) return false; } return true; } } '''
1cfd30d9f890543a32273605ad31e2530aa7ffe9
BrianArmstrong/Dojo_Assignments
/Python/Python Fundamentals/Multiples_Sum_Average.py
401
4.21875
4
#Multiples Part 1 (prints all of the numbers from 1 to 1000) for x in range(1,1001): print x #Multiples Part 2 (prints all of the multiples of 5 from 5 to 1000) for x in range(5,1001,5): print x #Sum list (sums up all of the list) a = [1,2,5,10,255,3] print sum(a) #Average List (take the sum of the list and divide it by the length to get the average) a = [1,2,5,10,255,3] print sum(a)/len(a)
72034559c29386d6a036948c6495ceaa5a03f641
doug460/AI-1-Spring2018
/HW1/breadthFirst.py
5,101
3.84375
4
''' Created on Feb 6, 2018 This is the breadth first search program for AI 1 The first two arguments are the main parts of this program the goal and the initial state @author: dabrown ''' import numpy as np from inputs import goal, initialState # number of nodes expanded expanded = 0 # this function turns the character array into an easily printed string # input: # character array # output: # string def getString(array): # string to hold chars string = "" # get the character and index in the array for indx, char in enumerate(array): # append to string holder string += char return string # test if the state is a solution # input: # Array # Output: # boolean def testGoal(array): return np.array_equal(array,goal) # test history # if node exists in history, return true # else false # input: # node # history # output # boolean def testHistory(node, history): for array in history: if(np.array_equal(node,array)): return(True) return(False) # expand a node excluding previous states # input: # node array # frontier list # history of expanded nodes list # output: # updated frontier # updated history def expandNode(node, frontier, history): # get index of where the blank space is at array = node.array index = np.where(array=='*')[0][0] # holds the node to be added to the list # check above empty if(index - 3 >= 0): # switch positions nextNode = np.copy(array) nextNode[index] = node.array[index - 3] nextNode[index - 3] = '*' # add to frontier if not already explored if(not testHistory(nextNode, history)): frontier.append(NewNode(nextNode,node)) history.append(nextNode) print('added: %s' % (getString(nextNode))) # check below empty if(index + 3 <= 8): # switch positions nextNode = np.copy(node.array) nextNode[index] = node.array[index + 3] nextNode[index + 3] = '*' # add to frontier if not already explored if(not testHistory(nextNode, history)): frontier.append(NewNode(nextNode,node)) history.append(nextNode) print('added: %s' % (getString(nextNode))) # check left empty if(index != 0 and index != 3 and index != 6): # switch positions nextNode = np.copy(node.array) nextNode[index] = node.array[index - 1] nextNode[index - 1] = '*' # add to frontier if not already explored if(not testHistory(nextNode, history)): frontier.append(NewNode(nextNode,node)) history.append(nextNode) print('added: %s' % (getString(nextNode))) # check right empty if(index != 2 and index != 5 and index != 8): # switch positions nextNode = np.copy(node.array) nextNode[index] = node.array[index + 1] nextNode[index + 1] = '*' # add to frontier if not already explored if(not testHistory(nextNode, history)): frontier.append(NewNode(nextNode,node)) history.append(nextNode) print('added: %s' % (getString(nextNode))) return(frontier, history) class NewNode: def __init__(self,array,parent): self.array = array self.parent = parent if __name__ == '__main__': pass print('BREADTH FIRST SEARCH') print('Goal: %s' % (getString(goal))) # state is the state that will be acted upon state = np.copy(initialState) print('Init: %s' % (getString(initialState))) # create a list of nodes with the initial node as the first element frontier = [] frontier.append(NewNode(state,None)) print('added: %s' % (getString(state))) # history of nodes that have been in frontier history = [] # loop through the frontier while(frontier): # pop out first node node = frontier.pop(0) expanded += 1 print('popped: %s' %( getString(node.array))) # add node to history history.append(node.array) # test if success if(testGoal(node.array)): print('Reached successful node!') break; # expand node frontier, history = expandNode(node, frontier, history) # print info print('Number of nodes in fringe: %d' % ( len(frontier))) print('Number of nodes expanded: %d' % ( expanded)) # path to solve problem (reverse order) path = [] path.append(node) # get path while(node.parent != None): node = node.parent path.append(node) # print out path print('\nThe solution path is:') while(path): print(getString(path.pop(-1).array))
513415b5161b0dabfcf1389e9af0733685158c20
htingwang/HandsOnAlgoDS
/LeetCode/0289.Game-Of-Life/Game-Of-Life.py
1,243
3.578125
4
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead. """ for i in range(len(board)): for j in range(len(board[0])): neighbors = 0; for x in range(3): for y in range(3): if i-1+x >= 0 and i-1+x < len(board) and j-1+y >= 0 and j-1+y < len(board[0]) and board[i-1+x][j-1+y] > 0: neighbors += 1; #print [i, j, x, y, i-1+x, j-1+y, neighbors] if board[i][j] == 1: board[i][j] = neighbors; else: board[i][j] = -neighbors; #print board for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 1 or board[i][j] == 2: board[i][j] = 0; elif board[i][j] == 3 or board[i][j] == 4: board[i][j] = 1; elif board[i][j] > 4: board[i][j] = 0; elif board[i][j] == -3: board[i][j] = 1; elif board[i][j] < 0: board[i][j] = 0;
8d614a7e9ccf369aca75b0dbd477af75424b6302
mathvolcano/leetcode
/1133_largestUniqueNumber.py
387
3.609375
4
""" 1133. Largest Unique Number https://leetcode.com/problems/largest-unique-number/ """ class Solution: def largestUniqueNumber(self, A: List[int]) -> int: # O(n) because we have to count every element from collections import Counter counts = Counter(A) keys = [x for x in counts if counts[x] == 1] return -1 if len(keys) == 0 else max(keys)
1e32c37427cacfe51c24eeb9928fde3bd64b0d1b
vivekpabani/CodeEval
/easy/delta times/delta_times.py
1,317
3.6875
4
#!/usr/bin/env python """ Problem Definition : """ __author__ = 'vivek' import sys def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: data = [[int(j) for j in i.split(':')] for i in test.strip().split()] date1, date2 = data[0], data[1] if date1[0] != date2[0]: if date1[0] < date2[0]: date1, date2 = date2, date1 elif date1[1] != date2[1]: if date1[1] < date2[1]: date1, date2 = date2, date1 else: if date1[2] < date2[2]: date1, date2 = date2, date1 hour, minute, sec = 0, 0, 0 sec_diff = date1[2] - date2[2] if sec_diff < 0: sec_diff += 60 minute -= 1 sec += sec_diff if sec < 10: sec = '0' + str(sec) minute_diff = date1[1] - date2[1] if minute_diff < 0: minute_diff += 60 hour -= 1 minute += minute_diff hour += (date1[0] - date2[0]) if sec < 10: sec = '0' + str(sec) if minute < 10: minute = '0' + str(minute) if hour < 10: hour = '0' + str(hour) print str(hour) + ':' + str(minute) + ':' + str(sec) if __name__ == '__main__': main()
0c6f6284a29aee805c872c55e12fa3b5f1e54f4b
anantpanthri/PythonSelfPractice
/FlowerSquare.py
1,890
4.03125
4
import turtle #this function will draw a flower in a window def draw_flower(sonu): sonu.shape("turtle") sonu.color("red") sonu.speed(0) for i in range(1, 40): sonu.forward(50) sonu.left(60) sonu.forward(50) sonu.left(120) sonu.forward(50) sonu.left(60) sonu.forward(50) sonu.right(10) sonu.right(60) sonu.color("black") sonu.forward(200) sonu.left(120) #leaf begins sonu.color("green") sonu.forward(50) sonu.left(60) sonu.forward(50) sonu.left(120) sonu.forward(50) sonu.left(60) sonu.forward(50) sonu.left(150) sonu.forward(90) sonu.left(160) sonu.forward(58) sonu.left(50) sonu.color("black") sonu.forward(100) sonu.right(90) sonu.forward(100) sonu.left(180) sonu.forward(200) sonu.left(90) sonu.forward(500) sonu.left(90) sonu.forward(200) sonu.left(90) sonu.forward(500) sonu.left(90) #this function will draw a square def draw_square(sonu): sonu.shape("turtle") sonu.speed(0) sonu.color("black") k=0 for i in range(1,250): if k<4: sonu.forward(100) sonu.right(90) k+=1 else: sonu.right(10) k=0 def draw_triangle(tom): for i in range(1,4): tom.forward(100) tom.left(120) def draw_art(): window= turtle.Screen() window.bgcolor("white") sonu = turtle.Turtle() draw_flower(sonu) # draw_square(sonu) ''' hanu = turtle.Turtle() hanu.shape("arrow") hanu.color("black") window.bgcolor("yellow") hanu.circle(100) window.bgcolor("grey") tom = turtle.Turtle() draw_triangle(tom)''' window.exitonclick() draw_art()
c8a5cfaaf3336648608e1ed376056f2e23e963a7
W1nU/algorithm
/first/10216.py
855
3.5
4
# 09 32 import sys input = sys.stdin.readline import math def union(a, b): root_a = find(a) root_b = find(b) if root_a != root_b: sets[root_a] = root_b def find(a): parent = sets[a] if parent == a: return parent else: root = find(parent) sets[parent] = root return root T = int(input()) for _ in range(T): N = int(input()) sets = [n for n in range(N)] bases = [list(map(int, input().split())) for _ in range(N)] ret = 0 for i in range(N): x, y, r = bases[i] for j in range(i, N): x2, y2, r2 = bases[j] distance = math.sqrt((x2 - x) ** 2 + (y2 - y) ** 2) if distance <= r + r2: union(i, j) for i in range(N): if i == sets[i]: ret += 1 print(ret)
638707311ff0585391ed836895e58391260feb2f
daniel-reich/turbo-robot
/zqr6f8dRD84K8Lvzk_4.py
1,771
4.09375
4
""" As stated on the [On-Line Encyclopedia of Integer Sequences](https://oeis.org/A003215): > The hexagonal lattice is the familiar 2-dimensional lattice in which each > point has 6 neighbors. A **centered hexagonal number** is a centered figurate number that represents a hexagon with a dot in the center and all other dots surrounding the center dot in a hexagonal lattice. At the end of that web page the following illustration is shown: Illustration of initial terms: . . o o o o . o o o o o o o o . o o o o o o o o o o o o . o o o o o o o o o o o o o o o o . o o o o o o o o o o o o . o o o o o o o o . o o o o . . 1 7 19 37 . Write a function that takes an integer `n` and returns `"Invalid"` if `n` is not a **centered hexagonal number** or its illustration as a multiline rectangular string otherwise. ### Examples hex_lattice(1) ➞ " o " # o hex_lattice(7) ➞ " o o \n o o o \n o o " # o o # o o o # o o hex_lattice(19) ➞ " o o o \n o o o o \n o o o o o \n o o o o \n o o o " # o o o # o o o o # o o o o o # o o o o # o o o hex_lattice(21) ➞ "Invalid" ### Notes N/A """ def hex_lattice(n): ans='' p=(3+(12*n-3)**.5)/6 if not p.is_integer(): return 'Invalid' rows=0;ds=-1;dc=1;cc=int(p)-1;sc=int(p) while rows<2*int(p)-1: ans+=' '*sc+'o '*cc+'o'+' '*sc+'\n' sc+=ds cc+=dc rows+=1 if sc==1: ds=1 dc=-1 return ans[:-1]
98ef87e8cd1db024cb0808e0dd7df7c907caf346
bluestreakxmu/PythonExercises
/FlashCardChallenge/quizzer.py
1,352
3.65625
4
import random from sys import argv import os def read_flashcard_file(filename): """Get the questions from a fixed flash card file""" filepath = "cardrepository/" + filename if not os.path.isfile(filepath): print("Not a valid file name!!") exit() flash_card_dict = {} with open(filepath) as file: while True: line = file.readline().replace("\n", "") if 0 == len(line): break keyvalue = line.split(",") flash_card_dict[keyvalue[0]] = keyvalue[1] return flash_card_dict def select_questions_randomly(flash_car_dict): while True: flash_card_key = random.choice(list(flash_card_dict.keys())) answer = input("{}? ".format(flash_card_key)) if "exit" == answer.lower(): print("Goodbye") exit() elif answer.lower() == flash_card_dict[flash_card_key].lower(): print("Correct! Nice job.") else: print("Incorrect. The correct answer is {}.".format(flash_card_dict[flash_card_key])) def get_filename(): if 2 != len(argv): print("Please input a quiz questions file name!") exit() return argv[1] # Run the script filename = get_filename() flash_card_dict = read_flashcard_file(filename) select_questions_randomly(flash_card_dict)
1d7806ed27c2eac22564b98d9703df9ff593fcf9
purusottam234/Python-Class
/Day 5/exercise.py
678
4.21875
4
# 1. Show that a what occurs if ...elif statement specifies an else before the last elif. grade = 80 if grade >= 90: print("A") elif grade >= 80: print("B") else: print("fail") elif grade >= 70: print("c") # 2. program to implement the if statement grade = 10 if grade >= 40: print("pass") 3. program to implement the if else statement age = 20 if age >= 20: print("they are ready to marriage") else: print("you belong to young") 4. program to implement the if ..elif statement age = int(input("Enter your age:")) if age >= 13: print("teen") elif age >= 20: print('young') elif age >= 50: print('ols') else: print("child")
496eeac3476016bed3676193b1b50101d7d2a3cf
oxanastarazhok/Hometask
/Text_split/Text_split.py
300
3.859375
4
message = ("How are you? Eh, ok. Low or Lower? Ohh.") def find_secret_message(message): secret_message = "" for letter in message: if letter.isupper(): secret_message += letter return secret_message print find_secret_message("How are you? Eh, ok. Low or Lower? Ohh.")
8a6edd829a049a3aef09b16227f4fcd2931874ab
uma-c/CodingProblemSolving
/trees/BST/inorder_successor.py
1,493
3.765625
4
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def nextLowestNode(node: 'TreeNode'): while node.left: node = node.left return node def inorderSuccessor(root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': def _inorderSuccessor(node, stack_of_parents): if node.val < p.val: stack_of_parents.append(node) return _inorderSuccessor(node.right, stack_of_parents) elif node.val > p.val: stack_of_parents.append(node) return _inorderSuccessor(node.left, stack_of_parents) else: if node.right: return nextLowestNode(root.right) else: if stack_of_parents: parent = stack_of_parents[-1] if parent.left == node: return parent else: n = node found = False while stack_of_parents: parent = stack_of_parents.pop() if n != parent.right: found = True break n = parent if found: return nextLowestNode(parent.right) return None return _inorderSuccessor(root, [])
d1a5950862f2bd38af9e15a24ef21717992a5629
Yang-Hyeon-Seo/1stSemester
/python/coffeeMachine_v2.py
2,128
4.25
4
cup={} menu={'Americano':1800, 'Cafe latte':2200, 'Cafe Mocha': 2800} money=0 sum=0 def print_menu(): print(' '+'='*5+'Sookmyung Cafe'+'='*5) print("""1. Select coffee menu 2. Check your order 3. Pay total price 4. Get change""") def print_coffeeMenu(): print('[Cafe Menu]') for coffee,won in menu.items(): print(' '+coffee+' '+str(won)+'won') def select_menu(): while True: coffee=input('Select Menu : ') if coffee not in menu.keys(): print('You selected wrong menu..') continue many=int(input('How many cups ? ')) if coffee in cup.keys(): cup[coffee] += many else: cup[coffee] = many break def check_order(): for coffee, many in cup.items(): print(coffee, '\t', many,'cups') def calculate_price(): global sum global money sum=0 for coffee in cup.keys(): sum += cup[coffee]*menu[coffee] print('TotalPrice :',sum) while True: money=int(input('Pay money : ')) if sum > money: print('Too small..\n') else: break def get_change(): change= money - sum print('Your change is',change,'won') print('='*30) change_5000=change//5000 change=change%5000 change_1000=change//1000 change=change%1000 change_500=change//500 change=change%500 change_100=change//100 print('5000 won :',change_5000) print('1000 won :',change_1000) print('500 won :',change_500) print('100 won :',change_100) while True: print_menu() print() choose=int(input('Choose : ')) if choose == 1: print() print_coffeeMenu() print('\n') select_menu() elif choose == 2: check_order() elif choose == 3: calculate_price() elif choose == 4: get_change() print('\nThank you for using our machine') break
d60f2d3f02370be8ea0f3f6792f300ad17843d47
blackbat13/Algorithms-Python
/fractals/binary_tree.py
427
3.90625
4
import turtle def binary_tree(rank: int, length: float) -> None: turtle.forward(length) if rank > 0: turtle.left(45) binary_tree(rank - 1, length / 2) turtle.right(90) binary_tree(rank - 1, length / 2) turtle.left(45) turtle.back(length) turtle.speed(0) turtle.penup() turtle.left(90) turtle.back(350) turtle.pendown() turtle.pensize(3) binary_tree(5, 400) turtle.done()
eb023916054af3c231d5345da95813ef938365e3
mishu-mnp/Calculator
/calculator.py
4,282
3.90625
4
# ****::Calculator Application::***** from tkinter import * from tkinter.font import Font from tkinter import messagebox root = Tk() root.title("Calculator") s = StringVar() entry = Entry(root, textvariable=s, width=40, justify=RIGHT,) entry.place(x=30, y=10) history_label = Label(root, text="History: ", relief=SUNKEN, anchor=W, height=5, width=30, bg='white') history_label.pack(side=BOTTOM, fill=X) # *** ::Functions:: *** def number_1(): entry.insert(INSERT,"1") def number_2(): entry.insert(INSERT,"2") def number_3(): entry.insert(INSERT,"3") def number_4(): entry.insert(INSERT,"4") def number_5(): entry.insert(INSERT,"5") def number_6(): entry.insert(INSERT,"6") def number_7(): entry.insert(INSERT,"7") def number_8(): entry.insert(INSERT,"8") def number_9(): entry.insert(INSERT,"9") def number_0(): entry.insert(INSERT,"0") def operator_sum(): entry.insert(INSERT,"+") def operator_sub(): entry.insert(INSERT,"-") def operator_multi(): entry.insert(INSERT,"*") def operator_div(): entry.insert(INSERT,"/") def operator_mod(): entry.insert(INSERT,"%") def operator_dot(): entry.insert(INSERT,".") def number_del(): length = len(entry.get()) entry.delete(length - 1, None) def number_clear(): entry.delete(0, END) history = [] def operator_equal(): content = entry.get() result = str(eval(content)) entry.delete(0, "end") entry.insert(INSERT, result) history.append(content) history.reverse() history_label.configure(text="History: " + " | ".join(history[0:4])) def exit_window(): mssg = messagebox.askquestion(title="Exit", message="Do you really want to exit?") if mssg == "yes": root.quit() # *** ::Buttons:: *** button_1 = Button(root, text="1", width=6, command=number_1) button_1.place(x=30, y=80) button_2 = Button(root, text="2", width=6, command=number_2) button_2.place(x=90, y=80) button_3 = Button(root, text="3", width=6, command=number_3) button_3.place(x=150, y=80) button_4 = Button(root, text="4", width=6, command=number_4) button_4.place(x=30, y=130) button_5 = Button(root, text="5", width=6, command=number_5) button_5.place(x=90, y=130) button_6 = Button(root, text="6", width=6, command=number_6) button_6.place(x=150, y=130) button_7 = Button(root, text="7", width=6, command=number_7) button_7.place(x=30, y=180) button_8 = Button(root, text="8", width=6, command=number_8) button_8.place(x=90, y=180) button_9 = Button(root, text="9", width=6, command=number_9) button_9.place(x=150, y=180) button_zero = Button(root, text="0", width=6, command=number_0) button_zero.place(x=90, y=230) # *** ::Operator Buttons:: *** button_div = Button(root,text="/", width=7, command=operator_div) button_div.place(x=210, y=80) button_multi = Button(root,text="*", width=7, command=operator_multi) button_multi.place(x=210, y=130) button_sub = Button(root,text="-", width=7, command=operator_sub) button_sub.place(x=210, y=180) button_sum = Button(root,text="+", width=7, command=operator_sum) button_sum.place(x=210, y=230) button_mod = Button(root,text="%", width=6, command=operator_mod) button_mod.place(x=30, y=230) button_clear = Button(root,text="C", width=7, font="times 10 bold", command=number_clear) button_clear.place(x=210, y=40) button_del = Button(root,text="del", width=6, font="times 10 bold", command=number_del) button_del.place(x=150, y=40) button_dot = Button(root,text=".", width=6, command=operator_dot) button_dot.place(x=150, y=230) button_equal = Button(root,text="=", width=6, command=operator_equal) button_equal.place(x=90, y=40) button_exit = Button(root,text="Exit", width=8, command=exit_window, bd=5, bg="yellow", fg="blue") button_exit.place(x=110, y=280) # to make our window not resizeable root.resizable(False, False) # fixing the shape of our Calculator window root.geometry("300x400+100+100") # using this so that after running code our Calculator window remains on the screen # otherwise it will get closed automatically root.mainloop()
673094c9153453c0bd63bb50dd8df7f44cf0cfe0
nischalshrestha/automatic_wat_discovery
/Notebooks/py/bhavul93/tackle-titanic-with-tensorflow-for-beginners/tackle-titanic-with-tensorflow-for-beginners.py
21,870
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # Tackling Titanic with basic Tensorflow # # In this notebook, we're going to explore the data a bit, and try basic pandas and tensorflow to get the job done. It is meant for beginners, and should help those who're just getting started with kaggle and/or tensorflow. # # **What you can learn from it :** # - How to read the data and do basic preprocessing required to use neural networks # - Design a 2 layer Neural Network model yourself using tensorflow instead of using in built DNN classifier # # # **What is NOT covered in this tutorial :** # - Data visualization with lot of graphs and their observations # - Comparison of different classifiers for the problem # # I'm myself trying to improve everyday. This is my first Kernel at Kaggle. Your feedback would be very appreciative. # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory import os print(os.listdir("../input")) # Any results you write to the current directory are saved as output. # # Read Data # # Here's what we'll do # - Read data into csv files (train and test) # - Print out a small summary of the data # - Combine them into one dataset if we require later on # - Find out how many examples of each class exist in the training data (check if skewed or not) # - Find out how many features have null values # - Fix null values for numerical features # - Fix null values with some values for categorical features # ## Read data into csv files # In[ ]: # Read data into csv files train_df = pd.read_csv("../input/train.csv") test_df = pd.read_csv("../input/test.csv") print("train_df shape : ",train_df.shape) print("test_df shape : ",test_df.shape) # ## Print out summary of data # In[ ]: # Print small summary print("A look at training data:") train_df.head() # In[ ]: print("A look at testing data:") test_df.head() # > ***Obvious observation - 'Survived' column is missing in test_df*** # ## Find out how many examples of each class in training data # In[ ]: train_df.groupby('Survived')['PassengerId'].count() # **Observations** : # 1. 549+342 = 891. So no data in the training data is missing its class # 2. It's not such a skewed dataset # ## How many features have null values # In[ ]: # What any does is return whether any element in a particular axis is true or not. So, it works for us in this case. For each column, it checks if any column has a NaN value or not. train_df.isnull().any() # **Age**, **Cabin** and **Embarked** are the only ones having NaN values. We gotta fix them. # In[ ]: # How many NaN values of Age in train_df? train_df['Age'].isnull().sum() # In[ ]: # For Cabin train_df['Cabin'].isnull().sum() # In[ ]: # For Embarked train_df['Embarked'].isnull().sum() # ## Fixing null / NaN values for each column one by one # ### For embarked # In[ ]: train_df.groupby('Embarked')['PassengerId'].count() # We observed earlier that only 2 entries have NaN for Embarked. And here, we see there are only 3 possible values of Embarked - C, Q and S. Out of which, S has the most number. So, let's just assign the missing ones to S. # In[ ]: train_df['Embarked'] = train_df['Embarked'].fillna('S') # Now, let's check again.... # In[ ]: train_df.groupby('Embarked')['PassengerId'].count() # Perfect. # ### For Age # In[ ]: train_df.groupby('Age')['PassengerId'].count() # So, the first thing to note is, thie Age can be in decimals! So, it's more of a continuous variable than discrete one. # I think it would make sense to fix the missing ones by filling them with the mean? # In[ ]: train_df['Age'].mean() # In[ ]: train_df['Age'] = train_df['Age'].fillna(train_df['Age'].mean()) # Now, let's check how many missing values remain. # In[ ]: train_df['Age'].isnull().sum() # Perfect. # ### For Cabin # In[ ]: train_df.groupby('Cabin')['PassengerId'].count() # Okay, So : # - This can be alphanumeric # - 147 different vaulues exist for Cabin # - None of them seem to be far far greater in number than others # - A lot of values are actually missing - 687! # # So, let's do one thing - Add a new 'Cabin' value as 'UNKNOWN' and fill the data with that # In[ ]: train_df['Cabin'] = train_df['Cabin'].fillna('UNKNOWN') # Check how many NaN now # In[ ]: train_df['Cabin'].isnull().sum() # Perfect. # ### All NaN values fixed # In[ ]: # What any does is return whether any element in a particular axis is true or not. So, it works for us in this case. For each column, it checks if any column has a NaN value or not. train_df.isnull().any() # ## Helper Methods we learnt from above # # We'll use these for testing dataset, and maybe in future as well. # In[ ]: def get_num_of_NaN_rows(df): return df.isnull().sum() def fill_NaN_values_for_numerical_column(df, colname): df[colname] = df[colname].fillna(df[colname].mean()) return df def fill_NaN_values_for_categorical_column(df, colname, value): df[colname] = df[colname].fillna(value) return df # In[ ]: # Let's test them on test data (which still might have missing rows!) num_of_NaN_rows_of_test_set = get_num_of_NaN_rows(test_df) print("num_of_NaN_rows_of_test_set : ",num_of_NaN_rows_of_test_set) # One chapter done. # # Preprocessing Data # # - Convert Categorical values to numerical ones # - Divide train_df into train_df_X and train_df_y # - One hot values # ### Convert Categorical values to numerical ones # **1. Find which columns are categorical** # # Ref : https://stackoverflow.com/questions/29803093/check-which-columns-in-dataframe-are-categorical/29803290#29803290 # In[ ]: all_cols = train_df.columns # In[ ]: numeric_cols = train_df._get_numeric_data().columns # In[ ]: categorical_cols = set(all_cols) - set(numeric_cols) categorical_cols # In[ ]: # Let's make a helper method from this now. def find_categorical_columns(df): all_cols = df.columns numeric_cols = df._get_numeric_data().columns return set(all_cols) - set(numeric_cols) # **2. Convert to numerical ones using get_dummies of Pandas** # # Ref : http://fastml.com/converting-categorical-data-into-numbers-with-pandas-and-scikit-learn/ # In[ ]: # First, let's backup our train_df and test_df till now train_df_backup_filledna_still_having_categorical_data = train_df train_df_backup_filledna_still_having_categorical_data.head() # In[ ]: # Now, let's convert it. train_df_dummies = pd.get_dummies(train_df, columns=categorical_cols) train_df_dummies.shape # In[ ]: # However, backup's shape is still train_df_backup_filledna_still_having_categorical_data.shape # In[ ]: # Let's check out data once train_df_dummies.head() # In[ ]: train_df.shape # ### Another way to convert Categorical columns data into numerical is assigning them integers # Ref : https://stackoverflow.com/questions/42215354/pandas-get-mapping-of-categories-to-integer-value # In[ ]: # 2nd way to convert is having integers represent different values of each categorical column train_df_numerical = train_df.copy() for col in categorical_cols: train_df_numerical[col] = train_df_numerical[col].astype('category') train_df_numerical[col] = train_df_numerical[col].cat.codes train_df_numerical.shape # In[ ]: train_df_numerical.head() # In[ ]: # Let's make helper function here also def convert_categorical_column_to_integer_values(df): df_numerical = df.copy() for col in find_categorical_columns(df): df_numerical[col] = df_numerical[col].astype('category') df_numerical[col] = df_numerical[col].cat.codes return df_numerical # *Perfect*. # # Now, we have all of these available for our use : # # * **train_df** : original training dataset (891,12) # * **train_df_dummies** : training dataset with dummies (891, 1732) # * **train_df_numerical** : training dataset with integers for categorical attributes (891,12) # # Running a model in Tensorflow # # This will again involve a set of steps # - Get data converted to numpy arrays so tensorflow can read them # - Write tensorflow model # - Run a session of tensorflow model and check accuracy on training data set # # Try the above for both train_df_dummies and train_df_numerical # In[ ]: # import tensorflow stuff... import tensorflow as tf # In[ ]: # Dividing data between X and Y # Ref : https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-column-in-pandas train_df_dummies_Y = train_df_dummies['Survived'] # Don't worry. drop does not change the existing dataframe unless inplace=True is passed. train_df_dummies_X = train_df_dummies.drop('Survived', axis=1) train_df_numerical_X = train_df_numerical.drop('Survived', axis=1) train_df_numerical_Y = train_df_numerical['Survived'] print("train_df_numerical_X shape : ",train_df_numerical_X.shape) print("train_df_numerical_Y shape : ",train_df_numerical_Y.shape) print("train_df_dummies_X shape : ",train_df_dummies_X.shape) print("train_df_dummies_Y shape : ",train_df_dummies_Y.shape) # ### Converting to numpy arrays so tensorflow variables can pick it up # In[ ]: trainX_num = train_df_numerical_X.as_matrix() trainY_num = train_df_numerical_Y.as_matrix() trainX_dummies = train_df_dummies_X.as_matrix() trainY_dummies = train_df_dummies_Y.as_matrix() print("trainX_num.shape = ",trainX_num.shape) print("trainY_num.shape = ",trainY_num.shape) print("trainX_dummies.shape = ",trainX_dummies.shape) print("trainY_dummies.shape = ",trainY_dummies.shape) # In[ ]: # Reshaping the rank 1 arrays formed to proper 2 dimensions trainY_num = trainY_num[:,np.newaxis] trainY_dummies = trainY_dummies[:,np.newaxis] print("trainX_num.shape = ",trainX_num.shape) print("trainY_num.shape = ",trainY_num.shape) print("trainX_dummies.shape = ",trainX_dummies.shape) print("trainY_dummies.shape = ",trainY_dummies.shape) # ### Tensorflow Model # # Now, let's build our model. # We could use existing DNN classifier. But instead, we're gonna build this one with calculations ourselves. # 2 layers. Hence, W1, b1, W2, b2 as parameters representing weights and biases to layer 1 and layer 2 respectively. # # We'll use RELU as our activation function for first layer. Why? Because it performs better in general. # And sigmoid for the 2nd layer. Since output is going to be a binary classification, it makes sense to use sigmoid. # In[ ]: ### Tensorflow model def model(learning_rate, X_arg, Y_arg, num_of_epochs): # 1. Placeholders to hold data X = tf.placeholder(tf.float32, [11,None]) Y = tf.placeholder(tf.float32, [1, None]) # 2. Model. 2 layers NN. So, W1, b1, W2, b2. # This is basically coding forward propagation formulaes W1 = tf.Variable(tf.random_normal((20,11))) b1 = tf.Variable(tf.zeros((20,1))) Z1 = tf.matmul(W1,X) + b1 # This is also called logits in tensorflow terms A1 = tf.nn.relu(Z1) W2 = tf.Variable(tf.random_normal((1, 20))) b2 = tf.Variable(tf.zeros((1,1))) Z2 = tf.matmul(W2,A1) + b2 A2 = tf.nn.sigmoid(Z2) # 3. Calculate cost cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=Z2, labels=Y) cost_mean = tf.reduce_mean(cost) # 4. Optimizer (Gradient Descent / AdamOptimizer ) - Using this line, tensorflow automatically does backpropagation optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost_mean) # 5. initialize variabls session = tf.Session() tf.set_random_seed(1) init = tf.global_variables_initializer() session.run(init) # 6. Actual loop where learning happens for i in range(num_of_epochs): _, cost_mean_val = session.run([optimizer, cost_mean], feed_dict={X:X_arg, Y:Y_arg}) if i % 100 == 0: print("i : ",i,", cost : ",cost_mean_val) return session.run([W1,b1,W2,b2,A2,Y],feed_dict={X:X_arg, Y:Y_arg}) # In[ ]: W1_tr,b1_tr,W2_tr,b2_tr,A2,Y = model(0.01, trainX_num.T, trainY_num.T, 3000) # In[ ]: # Validating that our formulaes were correct by checking shapes of ouput prediction A2.shape # In[ ]: Y.shape # In[ ]: # Let's see the predictions variable A2[:,0:5] # **As we see, our predictions array isn't 0s or 1s. So, we must convert it to 0s / 1s. ** # In[ ]: A2_bool = A2 > 0.5 Y_prediction_training = A2_bool.astype(int) Y_int = Y.astype(int) # In[ ]: Y_int # In[ ]: Y_prediction_training # In[ ]: accuracy = (Y_prediction_training == Y_int).mean() accuracy # ### Awesome # # 81.48% accuracy isn't bad on training dataset. That too, with just 3000 epochs! # # People got near 85% with 40000 epochs. So, it's fine. This is good enough. # # In[ ]: # First, let's list our helper functions we could make from logic used above. def convert_sigmoid_output_to_boolean_array(array, threshold): array = array > threshold return array def convert_boolean_array_to_binary_array(array): array_binary = array.astype(int) return array_binary # * **Let's try now with dummies (one-hot vectors) data.** # # This is the time. Let's generalize the model we wrote above to take more arguments and not be specific to shapes of our X or Y. # Also, let's now print the training accuracy in the model itself with the cost at each 100th epoch! # In[ ]: ### Tensorflow model def model_generic(learning_rate, X_arg, Y_arg, num_of_epochs, hidden_units, threshold): # 1. Placeholders to hold data X = tf.placeholder(tf.float32, [X_arg.shape[0],None]) Y = tf.placeholder(tf.float32, [1, None]) # 2. Model. 2 layers NN. So, W1, b1, W2, b2. # This is basically coding forward propagation formulaes W1 = tf.Variable(tf.random_normal((hidden_units,X_arg.shape[0]))) b1 = tf.Variable(tf.zeros((hidden_units,1))) Z1 = tf.matmul(W1,X) + b1 A1 = tf.nn.relu(Z1) W2 = tf.Variable(tf.random_normal((1, hidden_units))) b2 = tf.Variable(tf.zeros((1,1))) Z2 = tf.matmul(W2,A1) + b2 A2 = tf.nn.sigmoid(Z2) # 3. Calculate cost cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=Z2, labels=Y) cost_mean = tf.reduce_mean(cost) # 4. Optimizer (Gradient Descent / AdamOptimizer ) - Using this line, tensorflow automatically does backpropagation optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost_mean) # 5. Accuracy methods predicted_class = tf.greater(A2,threshold) prediction_arr = tf.equal(predicted_class, tf.equal(Y,1.0)) accuracy = tf.reduce_mean(tf.cast(prediction_arr, tf.float32)) # 5. initialize variabls session = tf.Session() tf.set_random_seed(1) init = tf.global_variables_initializer() session.run(init) # 6. Actual loop where learning happens for i in range(num_of_epochs): _, cost_mean_val, accuracy_val = session.run([optimizer, cost_mean, accuracy], feed_dict={X:X_arg, Y:Y_arg}) if i % 100 == 0: print("i:",i,", cost : ",cost_mean_val,", training accuracy : ",accuracy_val) return session.run([W1,b1,W2,b2,A2,Y,accuracy],feed_dict={X:X_arg, Y:Y_arg}) # In[ ]: W1_dum,b1_dum,W2_dum,b2_dum,A2_dummies,Y_dummies,training_accuracy_val = model_generic(0.005, trainX_num.T, trainY_num.T, 3000, 100,0.5) # In[ ]: training_accuracy_val # So, for when we use dummies data, accuracy goes up and down, and after 3000 epochs is somewhere near 85.52%. This is good only! # # Prediction on Test Data # # Let's use 'numerical' vector data only now. # - Converting test data in the same form # - Pass it through the network to get the value of A2 # - Concatenate this with the data and write that into csv # - Submit the csv # In[ ]: test_df # In[ ]: test_df.isnull().any() # In[ ]: test_df['Age'] = test_df['Age'].fillna(test_df['Age'].mean()) test_df['Fare'] = test_df['Fare'].fillna(test_df['Fare'].mean()) test_df['Cabin'] = test_df['Cabin'].fillna('UNKNOWN') # In[ ]: test_df.isnull().any() # In[ ]: # Converting to numerical data test_df_numerical = test_df.copy() for col in categorical_cols: test_df_numerical[col] = test_df_numerical[col].astype('category') test_df_numerical[col] = test_df_numerical[col].cat.codes test_df_numerical.shape # In[ ]: test_df_numerical.head() # In[ ]: import math # Ref : https://stackoverflow.com/questions/32109319/how-to-implement-the-relu-function-in-numpy # Ref : https://stackoverflow.com/questions/3985619/how-to-calculate-a-logistic-sigmoid-function-in-python def predict(W1,b1,W2,b2,X): Z1 = np.dot(W1,X) + b1 A1 = np.maximum(Z1, 0, Z1) Z2 = np.dot(W2,A1) + b2 A2 = 1 / (1 + np.exp(-Z2)) return A2 # In[ ]: # Let's predict X_test = test_df_numerical.as_matrix() X_test.shape # In[ ]: W1_tr.shape # In[ ]: W2_tr.shape # In[ ]: final_prediction = predict(W1_tr,b1_tr,W2_tr,b2_tr,X_test.T) # In[ ]: final_prediction_int = final_prediction > 0.5 final_prediction_int = final_prediction_int.astype(int) final_prediction_int.shape # In[ ]: final_survived_df = pd.DataFrame(data=final_prediction_int.T, columns=['Survived']) final_survived_df # In[ ]: test_df['PassengerId'] # In[ ]: final_df = pd.concat([test_df['PassengerId'], final_survived_df], axis=1) final_df # In[ ]: # Exporting to a csv file final_df.to_csv("output-prediction.csv", index=False) # # One function to sum the whole notebook # # Now that we've reached here, we would want to execute the same notebook for different values of hyperparameters - to see how well our ouput csv file does on the leaderboard, and if we can improve our position. # For this, I've tried to utilize the helper functions we kept writing above and made one method which does everything from loading data, to fixing null values, to evaluating the model and then predicting and outputing a csv file. # Ultimately, you could just call this method with a range of hyperparameters, and let it do its magic. I'm gonna do the same on a # In[ ]: # helper exercise which does the whole thing for any training dataframe given def execute_steps_for_titanic(columns_to_use, output_file_name, learning_rate=0.01, num_of_epochs=3000, hidden_units=50, threshold_for_output=0.5, ): # read data training_df_orig = pd.read_csv("../input/train.csv") testing_df_orig = pd.read_csv("../input/test.csv") # get X and Y separated train_df_Y = training_df_orig['Survived'] train_df_X = training_df_orig[columns_to_use] test_df_X = testing_df_orig[columns_to_use] # fix missing data categorical_columns = find_categorical_columns(train_df_X) replace_values_dict = {'Embarked':'S', 'Cabin':'UNKNOWN'} for col in columns_to_use: num_of_NaN_rows = get_num_of_NaN_rows(train_df_X)[col] num_of_NaN_rows_test = get_num_of_NaN_rows(test_df_X)[col] if(num_of_NaN_rows > 0): print("Filling NaN values for column:",col) if col not in categorical_columns: train_df_X[col] = train_df_X[col].fillna(train_df_X[col].mean()) else: train_df_X[col] = train_df_X[col].fillna(replace_values_dict[col]) if(num_of_NaN_rows_test > 0): print("Filling NaN values for column:",col," in test data") if col not in categorical_columns: test_df_X[col] = test_df_X[col].fillna(test_df_X[col].mean()) else: test_df_X[col] = test_df_X[col].fillna(replace_values_dict[col]) print("Fixed NaN values in training and testing data.") # convert categorical to numerical data train_df_X_num = convert_categorical_column_to_integer_values(train_df_X) test_df_X_num = convert_categorical_column_to_integer_values(test_df_X) # Get numpy arrays for this data train_X = train_df_X_num.as_matrix() test_X = test_df_X_num.as_matrix() train_Y = train_df_Y.as_matrix() # fix rank-1 array created train_Y = train_Y[:,np.newaxis] # call model and get values W1,b1,W2,b2,A2,Y,final_tr_accuracy = model_generic(learning_rate, train_X.T, train_Y.T, num_of_epochs, hidden_units, threshold_for_output) print("Final training accuracy : ",final_tr_accuracy) # get prediction and save it to output file prediction = predict(W1,b1,W2,b2,test_X.T) # if prediction value > threshold, then set as True, else as False prediction = prediction > threshold_for_output # Convert the True/False array to a 0 , 1 array prediction = prediction.astype(int) # Convert back to dataframe and give the column name as 'Survived' prediction_df = pd.DataFrame(data=prediction.T, columns=['Survived']) # Make a final data frame of the required output and output to csv final_df = pd.concat([testing_df_orig['PassengerId'], prediction_df], axis=1) final_df.to_csv(output_file_name+"_tr_acc_"+"{0:.2f}".format(final_tr_accuracy)+"_prediction.csv", index=False) print("Done.") # In[ ]: # Let's try this once? # All this while, we kept including Name and PassengerId as 2 important columns however in real life, they actually don't really matter in deciding whether a person would live or not. # So, now let's check without them. columns_to_use = ['Pclass','Sex','Age','SibSp','Parch','Ticket','Fare','Cabin','Embarked'] execute_steps_for_titanic(columns_to_use, "bhavul", learning_rate=0.005, num_of_epochs=5000, hidden_units=30, threshold_for_output=0.5) # In[ ]:
17c565e75aa127c584eb2c4e282d86971a4d92e1
isutare412/python-cookbook
/02_Strings_and_Text/09_normalizing_unicode_text_to_a_standard_representation.py
781
3.515625
4
import unicodedata s1 = 'Spicy Jalape\u00f1o' s2 = 'Spicy Jalapen\u0303o' print(s1) print(s2) print(s1 == s2) # NFC normalization ('C'omposed) t1 = unicodedata.normalize('NFC', s1) t2 = unicodedata.normalize('NFC', s2) print(ascii(t1)) print(ascii(t2)) print(t1 == t2) # NFC normalization ('D'ecomposed) t1 = unicodedata.normalize('NFD', s1) t2 = unicodedata.normalize('NFD', s2) print(ascii(t1)) print(ascii(t2)) print(t1 == t2) # NFKC, NFKD normalization s3 = '\ufb01' print(s3) print(unicodedata.normalize('NFC', s3)) print(unicodedata.normalize('NFD', s3)) print(unicodedata.normalize('NFKC', s3)) print(unicodedata.normalize('NFKD', s3)) # removing diacritical marks t1 = unicodedata.normalize('NFD', s1) print(''.join(c for c in t1 if not unicodedata.combining(c)))
093336a2a4ac0534f7789e2a9bdc4b5bfd7251df
PederBG/sorting_algorithms
/BucketSort.py
963
4.03125
4
""" Works good if the element values in the list is evenly distributed. Argument m is the value of the biggest element in the list. Works by calculating an index from each of the elements and putting it in the right "bucket". Then sort each bucket and collapse the sub lists. RUNTIME: Best: Ω(n + k), Average: Θ(n + k), Worst: O(n^2), where k is number of buckets. """ from algoritmer.InsertionSort import InsertionSort def BucketSort(A, m): B = [[] for i in range(len(A))] # Makes an empty list of lists for j in range(0, len(A)): # Populate the new list index = (A[j] * len(A)) // (m + 1) B[index].append(A[j]) for k in range(0, len(A)): # Sort each list InsertionSort(B[k]) return sum(B, []) # Collapsing the sub lists (clever short method) # -------------------------------------------------------- A = [102, 32, 476, 468, 954, 200, 754, 333, 654, 1000] A_sorted = BucketSort(A, 1000) print(A_sorted)
463bfc909a069f5a5f650803401dd7df4efa5bca
Introduction-to-Programming-OSOWSKI/2-3-comparisons-BradyDuPaul2023
/main.py
627
3.8125
4
#WRITE YOUR CODE IN THIS FILE def greaterThan(x, y): if x > y: return True else: return False print(greaterThan(1, 10)) def lessThan(x, y): if x < y: return True else: return False print(lessThan(17, 14)) def equalTo(x, y): if x == y: return True else: return False print(equalTo(110, 11)) def greaterOrEqual(x, y): if x >= y: return True else: return False print(greaterOrEqual(12, 13)) def lessOrEqual(x, y): if x <= y: return True else: return False print(lessOrEqual(4, 2))
c14e38b014120a712ad0e97adb0ac26588db7ab2
jeykarlokes/complete-reference-to-python3-programs
/python/functions.py
5,928
3.9375
4
# #functions # def printoddoreven(num): # for n in num: # if n%2!=0: # return True # return False # print(printoddoreven([12])) # # default paarameters # # (A,B) IS THE paarameters # # (11,12) IS THE ARGUMENT # def add(a,b): # return a+b # def sub(a,b): # return a-b # def common(a,b,func = add): # return(func(a,b)) # print(common(11,12,sub)) # # KEYWORD argument --> we are explicity passing the arguments with = asignment # def add(a,b): # return a+b # def sub(a,b): # return a-b # def common(a,b,func = add): # return(func(a,b)) # print(common(b=11,a=121,func=sub)) # # scope # total =0 # def mm(): # print(total) # total = 1 + 2 # return total # print(mm()) # # global # total =0 # def mm(): # global total # total +=1 # return total # print(mm()) # #nonlocal # def mm(): # """hello this is simple nonlocal variable it is used to access the variables which are local and within function of function itself-------""" # total =0 # total +=1 # print(total) # def mn(): # nonlocal total # total +=2 # print(total) # print(mm()) # print(mm.__doc__) # #args in function collects and returns as a tuple # def sum(*args): # total =0 # for num in args: # total+=num # return total # print(sum(1,2,3,4,5)) # def identify_words(*words): # if "lokesh" in words and "jeykar" in words: # return "lokesh jeykar is present in the words" # return "no lokesh jeykar is present" # print(identify_words("lokesh","hello","jeykar"))#present # print(identify_words("lokesh","hello","jeykar "))#not present # # kwargs collects and returns as a dictionary # def colours(**colors): # print(colors) # if "lokesh" in colors and colors["lokesh"] == "white": # return "lokesh likes white colour" # elif "lokesh" in colors: # print("lokesh is there but not white ") # return "nothing is there" # print(colours(lokesh = "white",akshaya = "green")) # print(colours(lokesh = "red")) # print(colours(aks = "redd")) # #parameter ordering *args takes arguments until it reaches the keyword argument # # 1. parameter # # 2. *args # # 3. default parameter # # 4. **kwargs # def parameter_ordering(a,b,*args,ball = "pen",**kwargs): # return [a,b,args,ball,kwargs] # print(parameter_ordering(1,2,33,44,55,566,"kumar" , first_name= "lokesh",last_name="jeykar")) # #list and tuple unpacking # #means that it takes that entire list or tuple and pass it as argument (every number in the list or tuple is passed as each) # def numbers(*nums): # print(nums) # intial = 0 # for numb in nums: # intial += numb # return intial # number = [1,2,3,4,5,6,7,8,9,11] # number1 = (1,2,3,4,5,6,7,8,9,11) # print(numbers(*number1)) # print(numbers(*number)) # #dictionary unpacking # print("dictionary unpacking!!") # def addition(a,b,c,**kwargs): # print(kwargs) # print(a,b,c) # return a+b+c # add_num = dict(a=1,b=2,c=33, aa = 11 ,dog = "barks") # print(addition(**add_num)) # #lambdas similar to a function it is a online expression # def add(a,v):return a + v # print(add(1,22)) # # the above in lambdas # addition = lambda a,b : a+b-2*12 # print(addition(11,14)) # #map which accepts two args one is function and other is iterable thing (list,string,dict,tuple ) # num = [1,2,3,4,5] # double = map(lambda x:x*2,num) # print(list(double)) # # print(double) # names = [dict(one ="harish ",two ="vikash",three="motta",four= "maddu")] # caps_names = list(map(lambda name : name["one"] ,names)) # print(str(caps_names)) #filter it is similar to map it checks the condition within the lamda chats = [{"username":"lokesh","status":["i'm okk"]}, {"username":"vel","status":[]}, {"username":"yeshwant","status":["ya good"]}, {"username":"kumar","status":[]}, ] print("extract not active users using filters") filter_chats = list(filter(lambda c : c["status"]==[],chats)) print((filter_chats)) s = list(map(filter(lambda x : if x <=9 ,for x in range(3))) # #map and filter # chats = [{"username":"lokesh","status":["i'm okk"]}, # {"username":"vel","status":[]}, # {"username":"yeshwant","status":["ya good"]}, # {"username":"kumar","status":[]}, # ] # print("extract non active users and upper it with map and filter") # filter_chats = list(filter(lambda c : c["status"]==[],chats)) maps = list(map(lambda user:user["username"].upper(),filter_chats)) print(maps) # print("more simpleer ways,,,,,,,,,,,") # filter_maps = list(map(lambda user:user["username"].upper(),filter(lambda u :u["status"]==[],chats))) # print(filter_maps) # #same example extracting inactive users using list comprehension # print("extracting inactive users using list comprehension") # inactive_users = [user["username"].upper() + " is inactive " for user in chats if not user["status"]] # print(inactive_users) # print("##########") # new_names = ["tvs_star_city","bajaj_pulsar","honda_shine"] # new_names1 = (list(map(lambda name :name.upper(),filter(lambda x : len(x)<15 ,new_names)))) # print(new_names1) # #all checks all the args are truthy or false # nums = [1,2,4,6,8,10] # alls = all([print(num) for num in nums if num%2==0]) # print(alls) # names = ["Tvs","Tata","Techmahindra","Twoys"] # print(all([name[0]=="T" for name in names ])) # print("all in dict ") # family = dict(father ="jai",mother = "jayanthi",son="lokesh",daughter = "akshaya") # print(all({fam["father"] + "is there" for fam in family if fam["father"]=="j"})) # # #any if any of the values is truthy it returns true # # print("any") # # nums = [1,2,3,4,11] # # print(any([num for num in nums if num%3==2]))
ee72e60f8511a099f1776a8baffe1f3d0c6ac6f7
soundestmammal/machineLearning
/py_docs_lessons/python-pb/state.py
655
3.8125
4
#Suppose we want to model a bank account with support for deposit #and withdraw operations. One way to do that is by using global st #ate as shown in the following balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance-= amount return balance class BankAccount: def __init__(self): self.balance -= amount return self.balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance robert = BankAccount() vincent = BankAccount() robert.deposit(100) robert.withdraw(50)
4cb4afdb4f0085c3d53cebc1eca9815f4a7c3bfb
thinkreed/pyf
/ud036/unit2/2_27.py
585
3.546875
4
import os from string import digits def rename_files_in_dir(): files_list = os.listdir(r'/Users/thinkreed/Downloads/prank') print(files_list) current_path = os.getcwd() os.chdir(r'/Users/thinkreed/Downloads/prank') remove_digits = str.maketrans('', '', digits) for file_name in files_list: os.rename(file_name, file_name.translate(remove_digits)) os.chdir(current_path) def test(): rename_files_in_dir() test_str = '2353587jjjjh4455' remove_digits = str.maketrans('', '', digits) print(test_str.translate(remove_digits)) test()
7dc676b20dcde0038483663c23c76a680bc448b6
wenjiaaa/Leetcode
/P0001_P0500/0852-peak-index-in-a-mountain-array.py
1,684
4.03125
4
""" https://leetcode.com/problems/peak-index-in-a-mountain-array/ 852. Peak Index in a Mountain Array Easy 918 1325 Add to List Share Let's call an array arr a mountain if the following properties hold: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... arr[i-1] < arr[i] arr[i] > arr[i+1] > ... > arr[arr.length - 1] Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. Example 1: Input: arr = [0,1,0] Output: 1 Example 2: Input: arr = [0,2,1,0] Output: 1 """ class Solution(object): def peakIndexInMountainArray(self, arr): """ :type arr: List[int] :rtype: int """ """ ## O(n) for i in range(len(arr)): if i == 0 and arr[i] >= arr[i + 1]: return 0 elif i == len(arr) - 1 and arr[i] >= arr[i - 1]: return len(arr) - 1 elif arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]: return i """ # O(n^2) if arr[0] >= arr[1]: return 0 if arr[-1] >= arr[-2]: return len(arr) - 1 left, right = 0, len(arr)-1 while (left <= right): mid = (left + right) // 2 if arr[mid] >= arr[mid-1] and arr[mid] >= arr[mid+1]: return mid elif arr[mid] <= arr[mid+1]: left = mid + 1 elif arr[mid] <= arr[mid-1]: right = mid - 1 return mid S = Solution() arr = [3, 4, 5, 1] print(S.peakIndexInMountainArray(arr))
a90374f96d86dcbf6744b200a776f2ec40f722ad
tinkle1129/Leetcode_Solution
/Math/43. Multiply Strings.py
1,066
3.75
4
# - * - coding:utf8 - * - - ########################################### # Author: Tinkle # E-mail: shutingnupt@gmail.com # Name: Multiply Strings.py # Creation Time: 2018/3/22 ########################################### class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ s1,s2 = len(num1),len(num2) ret = [0] * (s1+s2) for i in range(s1): for j in range(s2): ret[i+j+1]+=int(num1[i])*int(num2[j]) flag = 0 ans = '' for i in range(s1+s2-1,-1,-1): ret[i] = ret[i]+flag flag = ret[i]/10 ret[i] = ret[i]%10 ans = str(ret[i])+ans if flag: ans = str(flag)+ans pos = True a = '' for i in range(len(ans)): if ans[i]=='0' and pos: pass else: pos = False a += ans[i] return a if len(a) else '0' S = Solution() print S.multiply('9','9')
0a2cee99bc2e4e06a00be96ee57f7446a50fc57a
gary-gggggg/gary
/1-mouth01/day09/exe06.py
230
3.578125
4
"""实际参数 形式参数""" def func01(p1, p2, p3): print(p1) print(p2) print(p3) dict01 = {"p3": 20, "p1": 50, "p2": 35} func01(**dict01) def func02(**kwargs): print(kwargs) func02(p1=88,p3=456,pp=1256)
257b8f83c5b5e616e2d74a83fdde65c2015af179
JRobayo99/Talleres-de-algotimos
/Taller de Estructuras de Control Selectivas/Ejercicio_2.py
316
3.5
4
salrim=int(input("Ingrese el monto del salario mesual:")) if (salrim<=900000): satlr = salrim*0.15 ttst = satlr+salrim print("El salario neto es de : " "{:.0f}".format(ttst)) elif(salrim> 900000): satlr = salrim*0.12 ttst = salrim+satlr print("El salario neto es de : " "{:.0f}".format(ttst))
68602a52b8d9856ea6c2c0bbdef61344bbf686d2
yurifarias/CursoEmVideoPython
/ex023.py
295
3.78125
4
número = int(input('Digite um número de 1 a 9999: ')) uni = número // 1 % 10 dez = número // 10 % 10 cen = número // 100 % 10 mil = número // 1000 % 10 print('Unidades: {}'.format(uni)) print('Dezenas: {}'.format(dez)) print('Centenas: {}'.format(cen)) print('Milhares: {}'.format(mil))
3cf4e6918f3ed9c105ed397c1e6975ce89d24f86
mpenkov/crackingthecodinginterview
/chapter1/problem6.py
808
4.0625
4
# # Given an image represented by an N*N matrix, write a method to rotate the # image by 90 degrees. Can you do this in place? # def swap(m, x1, y1, x2, y2): m[x1][y1], m[x2][y2] = m[x2][y2], m[x1][y1] def transpose(m): N = len(m) for i in xrange(N): for j in xrange(i + 1, N): swap(m, i, j, j, i) return m # return makes chaining functions easier def flip_horiz(m): N = len(m) for i in xrange(N): for j in xrange(N / 2): swap(m, i, N - 1 - j, i, j) return m def flip_vert(m): N = len(m) for i in xrange(N / 2): for j in xrange(N): swap(m, i, j, N - i - 1, j) return m def rotate_clockwise(m): return transpose(flip_vert(m)) def rotate_anticlockwise(m): return transpose(flip_horiz(m))
466622f128194101691bb1a3d11623356560025c
xy008areshsu/Leetcode_complete
/python_version/longest_substring_with_at_most_two_distinct_chars.py
2,663
3.78125
4
""" Given a string, find the length of the longest substring T that contains at most 2 distinct characters. T is "ece" which its length is 3. """ #idea : maintain a h_map, keys are each char, and vals are lists of indices of each char, each val is a sorted list, since the index goes from 0 to len(s) - 1 # scan the string, if the char already in h_map, append the index of that char to the value list. # else, if len(h_map) still less than 2, add this char into the h_map # else, find the minimum index and remove it from the value list. If any value list is empty, then delete the corresponding key. Repeat this until the length of # h_map is less than 2. # update the longest length at each step of the for loop import collections class Solution: # @param s, a string # @return an integer def lengthOfLongestSubstringTwoDistinct(self, s): # More practice, if s is None: return 0 if len(s) == 0 or len(s) == 1 or len(s) == 2: return len(s) h_map = {} longest_len = 0 for i, c in enumerate(s): if c in h_map: h_map[c].append(i) else: if len(h_map) < 2: h_map[c] = collections.deque() h_map[c].append(i) else: while len(h_map) >= 2: c_min, indices = min(h_map.items(), key = lambda x:x[1][0]) # list of index are sorted lists h_map[c_min].popleft() if len(h_map[c_min]) == 0: del h_map[c_min] h_map[c] = collections.deque() h_map[c].append(i) c_min, i_min = min(h_map.items(), key = lambda x : x[1][0]) c_max, i_max = max(h_map.items(), key = lambda x : x[1][-1]) i_min = i_min[0] i_max = i_max[-1] if i_max - i_min + 1 > longest_len: longest_len = i_max - i_min + 1 c_min, i_min = min(h_map.items(), key = lambda x : x[1][0]) c_max, i_max = max(h_map.items(), key = lambda x : x[1][-1]) i_min = i_min[0] i_max = i_max[-1] if i_max - i_min + 1> longest_len: longest_len = i_max - i_min + 1 return longest_len if __name__ == '__main__': sol = Solution() print(sol.lengthOfLongestSubstringTwoDistinct('cdaba')) print(sol.lengthOfLongestSubstringTwoDistinct('ccaabbb')) print(sol.lengthOfLongestSubstringTwoDistinct('abadc')) print(sol.lengthOfLongestSubstringTwoDistinct('aac')) print(sol.lengthOfLongestSubstringTwoDistinct('abacd'))