blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c96b9b0bff3827243173b551c767d20d7c98b942
morel00/Calculator
/cal.py
1,752
4.21875
4
#!/usr/bin/python3 # *********SUMA*********** def Suma (): Number_one = int(input("Digite el 1st no. de la Suma: ")) Number_two = int(input("Digite el 2nd no. de la Suma: ")) result = Number_one + Number_two print("El resutado es: "+ str(result)+'\n') # *********RESTAS*********** def Resta (): Number_one = int(input("Digite el 1st no. de la Resta: ")) Number_two = int(input("Digite el 2nd no. de la Resta: ")) result = Number_one - Number_two print("El resutado es: "+ str(result) + '\n') # *********DIVISION*********** def Division (): Number_one = int(input("Digite el 1st no. de la Division: ")) Number_two = int(input("Digite el 2nd no. de la Division: ")) result = Number_one / Number_two print("El resutado es: "+ str(result)+ '\n' ) # *********Multiplication*********** def Multi (): Number_one = int(input("Digite el 1st no. de la Multiplicacion: ")) Number_two = int(input("Digite el 2nd no. de la Multiplicacion: ")) result = Number_one * Number_two print("El resutado es: "+ str(result) + '\n' ) def SetUp(): print('************Calculadora********************\n') print('Seleccione su operacion con un Digito: \n') print('No. 1: Suma') print('No. 2: Resta') print('No. 3: Division') print('No. 4: Multiplicacion\n') selector = int(input('Digite su Operacion #> ')) if selector == 1: print('*****Suma***** \n') return Suma() elif selector == 2: print('*****Resta***** \n') return Resta() elif selector == 3: print('*****Division***** \n') Division() else: print('*****Multiplicacion***** \n') Multi() SetUp()
ecde9bb3582572ab14049fd828a77515ba87ce90
zdsh/leetcode
/20190131/927_Three_Equal_Parts.py
1,114
3.78125
4
""" File: 927_Three_Equal_Parts.py Date: 2019/02/18 16:26:53 """ class Solution(object): def threeEqualParts(self, A): """ :type A: List[int] :rtype: List[int] """ ret = [-1, -1] n = sum([a == 1 for a in A]) if n % 3 != 0: return ret if n == 0: return [0, len(A) - 1] p1, p2, p3, s = 0, 0, 0, 0 print n for i in range(len(A)): if A[i] == 1: s += 1 if s == n/3: p1 = i elif s == n/3 * 2: p2 = i elif s == n: p3 = i n = len(A) if n - p3 > p2 - p1 or n - p3 > p3 - p2: return ret a1 = ''.join([str(a) for a in A[0:p1 + n - p3]]) a2 = ''.join([str(a) for a in A[p1 + n - p3:p2 + n - p3]]) a3 = ''.join([str(a) for a in A[p2 + n - p3:]]) if a1[a1.index('1'):] == a2[a2.index('1'):] and a2[a2.index('1'):] == a3[a3.index('1'):]: return [p1 + n - p3 - 1, p2 + n - p3] return ret
3bef10cf6f0aebe86b9e8b6b8b37b36c1aa51154
gaurab123/DataQuest
/06_MachineLearning/03_LinearAlgebraForMachineLearning/03_MatrixAlgebra/06_MatrixInverse.py
1,367
4.25
4
# pages 25 & 26 in the hand written notes for context import numpy as np # Create a function named matrix_inverse_two() that accepts a 2 x 2 matrix, as a NumPy ndarray, and returns the matrix inverse.This function should first calculate the determinant of the matrix. # If the determinant is equal to 0, an error should be returned. # If the determinant is not equal to 0, this function should return the matrix inverse. # Calculate the inverse of matrix_a using the function you just wrote and assign the result to inverse_a. # Multiply inverse_a with matrix_a and assign the result to i_2. Display i_2 using the print() function. def matrix_inverse_two(array_22): if array_22.shape != (2,2): raise Exception('The value provided is not a 2x2 dimensional array.') a = array_22[0][0] b = array_22[0][1] c = array_22[1][0] d = array_22[1][1] determinant = (a*d) - (b*c) if determinant == 0: raise ValueError('The determinant for this 2x2 array is 0.') else: inv_det = 1/determinant left_mat = np.asarray([[d,-b], [-c,a]]) return np.dot(inv_det,left_mat) matrix_a = np.asarray([ [1.5, 3], [1, 4] ], dtype=np.float32) inverse_a = matrix_inverse_two(matrix_a) i_2 = np.dot(inverse_a,matrix_a) print(i_2)
a932f34f1cf341877d3b748c01d4bfb3aa8e44d4
shugands/AdventOfCode
/2017/06/reallocate.py
803
3.5
4
def reallocate(banks): cache = max(banks) index = banks.index(cache) banks[index] = 0 length = len(banks) while cache > 0: index += 1 index = index % length banks[index] += 1 cache -= 1 def main(): path = "2017/06/day6.txt" banks = [] with open(path, 'r') as f: for line in f: line = line.replace("\n", "") for block in line.split("\t"): banks.append(int(block)) steps = 0 seen = set() t = tuple(banks) while not t in seen: if steps >= 1000000: print("Too many steps!") break seen.add(t) reallocate(banks) t = tuple(banks) steps += 1 print("Steps: " + str(steps)) if __name__ == "__main__": main()
c87d8b77e0a4d132fc488e8b1ae83bf88f099b67
dr-mohanm/DataScience_Session4Assignment1
/Session_4_Assignment_1.py
3,114
4.40625
4
# coding: utf-8 # In[1]: # 1.1 Write a Python Program(with class concepts) to find the area of the triangle using the below formula. # area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 # Function to take the length of the sides of triangle from user should be defined in the parent class and #function to calculate the area should be defined in subclass. class Triangle: # Create parent class and assign 3 attributes to get inputs for 3 sides. class Triangle: def __init__(self, a, b, c): self.a = a self.b = b self.c = c print("Parent Class") # Create child class and call parent class using super command and create a method to calculate the area of triangle. class Triangle_Child(Triangle): def __init__(self, a, b, c): print ("Child Class") super(Triangle_Child, self).__init__(a, b, c) def area_tri(self): s=(self.a + self.b + self.c)/2 print (str(s)) return (s*(s-self.a)*(s-self.b)*(s-self.c))**0.5 # Get the inputs from user. Tri = Triangle_Child(float(input('Enter a = ')), float(input('Enter b = ')) , float(input('Enter c = '))) # Print the final result. print("Area of the triangle: " + str(Tri.area_tri())) # In[5]: # 1.2 Write a function filter_long_words() that takes a list of words and an integer n and # returns the list of words that are longer than n. # create a class and add 2 methods to get the inputs and filter the longest words. class Words_list: def __init__(self, wordlist): self.wordlist = wordlist def filter_long_words(self, n): return list(filter(lambda x:len(x) > n, self.wordlist)) # Pass the input to the class. Long_word = Words_list(["This", "is" , "the" , "data science" , "course"]) # Print the words which are greater/longer than n. print ("New List of Words is = " + str(Long_word.filter_long_words(2)) ) # In[3]: # 2.1 Write a Python program using function concept that maps list of words into a list of integers # representing the lengths of the corresponding words. # Hint:<200b> <200b>If a list [ ab,cde,erty] is passed on to the python function output should come as [2,3,4] # Here 2,3 and 4 are the lengths of the words in the list. # create a class and find the length of each word. def word_length(word_list): return list(map(lambda x: len(x), word_list)) # Pass the input to the class. word_list = ["This", "is" , "the" , "data science" , "course"] # Print the lenth of each word. print ("word lengths in array = " + str(word_length(word_list))) # In[4]: # 2.2 Write a Python function which takes a character (i.e. a string of length 1) and # returns True if it is a vowel, False otherwise # FUnction to check char is vowel and return True/False def vowel_check(char): if(char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u' or char == 'A' or char == 'E' or char == 'I' or char == 'O' or char == 'U'): return True else: return False # Pass the input char = input("Enter character: "); # Check whether the string is vowel or not and print the result. if (vowel_check(char)): print(char, "is a vowel."); else: print(char, "is not a vowel.");
0e5c19b976c378f4412d77112393ae0c1931ee49
harkevich/testgithub
/Lesson/Lesson10МетодыСтрок.py
1,622
4.21875
4
s = 'hello, world!' #-------- Метод len ----------- #print(len(s)) # подсчет всех символов в строке # -------- Метод capitalize ------------ #print(s.capitalize()) #capitalaze Переводит первый символ строки в верхний регистр, а все остальные в нижний #s2 = s.capitalize() #print(s, s2) #---------- Метод Center --------------- #print(s.center(20,',')) # Возвращает отцентрованную строку, по краям которой стоит символ fill (пробел по умолчанию) #----------- Метод Cound ---------------- #print(s.count('l', 0, 3)) # подсчитывает колл-во определенных символов в строке; Возвращает количество непересекающихся вхождений подстроки в диапазоне [начало, конец] (0 и длина строки по умолчанию) #------------ Метод find ------------- #print(s.find('l')) # Выводит первое вхожжение в строке или -1 если ошибка #------------Метод index-------- #print(s.index("o")) #Поиск подстроки в строке. Возвращает номер первого вхождения или вызывает ValueError #--------------Метод replace -------- # print(s.replace('o', 'Привет')) # замена шаблока #-------- Метод split --------- print(s.split('!')) #разюить строки по разделителю
c2e9a85d51b0e2391acc57bb14bffe7878e836d8
jmh9876/p1804_jmh
/1805/python高级/5/3-继承__init__方法.py
730
3.703125
4
class Animal(object): def __init__(self,name,color = "白色"): self.name = name self.color = color def eat(self): print("吃东西") def setColor(self,color): self.color = color def __str__(self): msg = "颜色是%s"%self.color return msg ''' 子类没有init方法 但是父类有,当实例化对象的时候 默认执行init ''' ''' 私有属性和私有方法到底能不能被继承 不能继承的话 子类怎么间接获取私有属性和私有方法 ''' class Cat(Animal): def uptree(self): print("上树") bosi = Cat("波斯猫","黑色") bosi.uptree() bosi.eat() bosi.setColor("绿色") print(bosi)
b32e33432a923dc5d297ed5e8ac96b93ffaab8ae
turkeydonkey/nzmath3
/nzmath/real.py
8,399
3.703125
4
""" real -- real numbers and the real number field. The module real provides arbitrary precision real numbers and their utilities. The functions provided are corresponding to the math standard module. """ import itertools import warnings import nzmath.arith1 as arith1 import nzmath.rational as rational import nzmath.ring as ring from nzmath.plugins import MATHMODULE as math, FLOATTYPE as Float, \ CHECK_REAL_OR_COMPLEX as check_real_or_complex class Real(ring.FieldElement): """ Real is a class of real. This class is only for consistency for other Ring object. """ convertable = (Float, int, int, rational.Rational) def __init__(self, value): """ value will be wrapped in Float. """ ring.FieldElement.__init__(self) if isinstance(value, rational.Rational): self.data = value.toFloat() else: self.data = Float(value) def __add__(self, other): if isinstance(other, Real): result = self.data + other.data elif isinstance(other, self.convertable): result = self.data + other else: return NotImplemented return self.__class__(result) def __radd__(self, other): if isinstance(other, self.convertable): result = other + self.data else: return NotImplemented return self.__class__(result) def __sub__(self, other): if isinstance(other, Real): result = self.data - other.data elif isinstance(other, self.convertable): result = self.data - other else: return NotImplemented return self.__class__(result) def __rsub__(self, other): if isinstance(other, self.convertable): result = other - self.data else: return NotImplemented return self.__class__(result) def __mul__(self, other): if isinstance(other, Real): result = self.data * other.data elif isinstance(other, self.convertable): result = self.data * other else: return NotImplemented return self.__class__(result) def __rmul__(self, other): if isinstance(other, self.convertable): result = other * self.data else: return NotImplemented return self.__class__(result) def __truediv__(self, other): if isinstance(other, Real): result = self.data / other.data elif isinstance(other, self.convertable): result = self.data / other else: return NotImplemented return self.__class__(result) __div__ = __truediv__ def __rtruediv__(self, other): if isinstance(other, self.convertable): result = other / self.data else: return NotImplemented return self.__class__(result) __rdiv__ = __rtruediv__ def __pow__(self, other): if isinstance(other, Real): result = math.pow(self.data, other.data) elif isinstance(other, self.convertable): result = math.pow(self.data, other) return result def __eq__(self, other): if isinstance(other, Real): return self.data == other.data elif isinstance(other, self.convertable): return self.data == other else: return NotImplemented def __hash__(self): return hash(self.data) def getRing(self): """ Return the real field instance. """ return theRealField class RealField(ring.Field): """ RealField is a class of the field of real numbers. The class has the single instance 'theRealField'. """ def __init__(self): ring.Field.__init__(self) self._one = Real(1) self._zero = Real(0) def __str__(self): return "R" def __repr__(self): return "%s()" % (self.__class__.__name__, ) def __contains__(self, element): if isinstance(element, (int, float, Float, Real, rational.Rational)): return True else: try: if check_real_or_complex(element): return True except TypeError: if hasattr(element, 'conjugate'): return element == element.conjugate() pass if hasattr(element, 'getRing') and element.getRing().issubring(self): return True return False def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return 2 # property one def _getOne(self): "getter for one" return self._one one = property(_getOne, None, None, "multiplicative unit.") # property zero def _getZero(self): "getter for zero" return self._zero zero = property(_getZero, None, None, "additive unit.") def issubring(self, aRing): if isinstance(aRing, RealField): return True elif self.issuperring(aRing): return False return aRing.issuperring(self) def issuperring(self, aRing): if isinstance(aRing, RealField): return True elif rational.theRationalField.issuperring(aRing): return True return aRing.issubring(self) def createElement(self, seed): return Float(seed) def getCharacteristic(self): """ The characteristic of the real field is zero. """ return 0 def log1piter(xx): " iterator for log(1+x)." d = 1 positive = True t = rational.Rational(xx) yield t while True: d += 1 positive = not positive t *= xx if positive: yield (t / d) else: yield (-t / d) def floor(x): """ floor(x) returns the integer; if x is an integer then x itself, otherwise the biggest integer less than x. """ rx = rational.Rational(x) if rx.denominator == 1: return rational.Integer(rx.numerator) return rx.numerator // rx.denominator def ceil(x): """ ceil(x) returns the integer; if x is an integer then x itself, otherwise the smallest integer greater than x. """ rx = rational.Rational(x) if rx.denominator == 1: return rational.Integer(rx.numerator) return rx.numerator // rx.denominator + 1 def tranc(x): """ tranc(x) returns the integer; if x is an integer then x itself, otherwise the nearest integer to x. If x has the fraction part 1/2, then bigger one will be chosen. """ rx = rational.Rational(x) if rx.denominator == 1: return rational.Integer(rx.numerator) return floor(x + rational.Rational(1, 2)) def fabs(x): """ returns absolute value of x. """ return abs(rational.Rational(x)) def fmod(x, y): """ returns x - n * y, where n is the quotient of x / y, rounded towards zero to an integer. """ fquot = rational.Rational(x) / y if fquot < 0: n = -floor(-fquot) else: n = floor(fquot) return x - n * y def frexp(x): """ Return a tuple (m, e) where x = m * 2 ** e, 1/2 <= abs(m) < 1 and e is an integer. This function is provided as the counter-part of math.frexp, but it might not be useful. """ if x == 0: return (rational.Rational(0), 0) m = rational.Rational(x) e = 0 if x > 0: while m >= 1: m /= 2 e += 1 while m < rational.Rational(1, 2): m *= 2 e -= 1 else: while m <= -1: m /= 2 e += 1 while m > rational.Rational(-1, 2): m *= 2 e -= 1 return (m, e) def ldexp(x, i): """ returns x * 2 ** i. """ return x * 2 ** i def EulerTransform(iterator): """ Return an iterator which yields terms of Euler transform of the given iterator. """ stock = [] b = rational.Rational(1, 2) l = -1 for term in iterator: stock.append(term) for i in range(l, -1, -1): stock[i] += stock[i+1] yield b * stock[0] b /= 2 l += 1 # constants theRealField = RealField()
c1d93bebb3b22ca6a6f14f7615f4979b18a6d627
shen-huang/selfteaching-python-camp
/exercises/1901040046/d08/mymodule/stats_word.py
1,791
3.640625
4
#将字符串s按照None的分隔切分为一个字符串组,并清洗字符串元素的标点符号,并统计不同字符是数量,最后以数量降序排列。 def stats_text_en(text): if type(text) == str:#新增类型检查语句 replace_text = text.replace(',','').replace('.','').replace('*','').replace('?','').replace('!','').replace('-','') split_text = replace_text.split() wordcount = {} for i in split_text: if i not in wordcount: wordcount[i] = 1 else: wordcount[i] += 1 wordcount = sorted(wordcount.items(),key=lambda x:x[1],reverse=True) return wordcount else: raise ValueError('it is not a str.')#如果参数错误,抛出提示。 #定义一个用来统计汉字的函数.新增list函数将中文字符串切分。暂时不引人正则函数从而用来区分中英文。 def stats_text_cn(text): if type(text) == str:#新增类型检查语句 replace_text = text.replace(',','').replace('。','').replace('*','').replace('?','').replace('!','').replace('——','') list_text = list(replace_text) wordcount = {} for i in list_text: if i not in wordcount: wordcount[i] = 1 else: wordcount[i] += 1 wordcount = sorted(wordcount.items(),key=lambda x:x[1],reverse=True) return wordcount else: raise ValueError('it is not a str.')#如果参数错误,抛出提示。 def stats_text(text):#定义函数用来统计并打印中英文字符以及对应数量。 print(stats_text_en(text)) print(stats_text_cn(text))
c295545990ac4da9ff945724d40b1f423e4c5c21
privateHmmmm/leetcode
/146-lru-cache/lru-cache.py
3,115
4.09375
4
# -*- coding:utf-8 -*- # # Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. # # # # get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. # put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. # # # Follow up: # Could you do both operations in O(1) time complexity? # # Example: # # LRUCache cache = new LRUCache( 2 /* capacity */ ); # # cache.put(1, 1); # cache.put(2, 2); # cache.get(1); // returns 1 # cache.put(3, 3); // evicts key 2 # cache.get(2); // returns -1 (not found) # cache.put(4, 4); // evicts key 1 # cache.get(1); // returns -1 (not found) # cache.get(3); // returns 3 # cache.get(4); // returns 4 # # class Node(object): def __init__(self, key, value): self.key = key self.value = value self.next = None self.pre = None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ # hashmap + double linked list self._map = {} self.head = None self.tail = None self.capacity = capacity def refreshNode(self, node): if node != self.tail: # remove from list if node == self.head: #!!!! self.head = self.head.next else: node.pre.next = node.next node.next.pre = node.pre # insert into tail self.tail.next = node node.pre = self.tail node.next = None self.tail = node return def get(self, key): """ :type key: int :rtype: int """ if key not in self._map: return -1 self.refreshNode(self._map[key]) return self._map[key].value def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if key in self._map: self._map[key].value = value self.refreshNode(self._map[key]) else: if self.capacity == 0: # remove head node del self._map[self.head.key] self.head = self.head.next self.capacity += 1 # insert into one new node new_node = Node(key, value) self._map[key] = new_node if self.head == None: # !!! self.head = new_node else: self.tail.next = new_node new_node.pre = self.tail self.tail = new_node self.capacity -=1 # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
514ec4454f96957a15a76d1076f7c3ed0d7fa36a
JacobChurch-osu/hello-world
/Scripting Projects Assignment 8 Jacob Church/Project 1 Code.py
648
4.03125
4
import math Toler = 0.000001 def newton(x): """ Returns the square root of UserNum """ Estimate = 1.0 while True: Estimate = (Estimate + x / Estimate) / 2 Diff = abs(x - Estimate ** 2) if Diff <= Toler: break return Estimate def main(): """Allows the user to obtain square roots.""" while True: x = input("Enter a positive number or press enter to quit: ") if x == "": break x = float(x) print("The programs estimate of the square root of ", x, "is ", round(newton(x),2)) print("Python's estimate: ", math.sqrt(x)) main()
c02275464ccdb87b488a6ad4d1a669e428d0b5c5
Savan777/simple-imdb-scrapper
/imdbScrape.py
1,417
3.59375
4
__author__ = 'Savan Patel' import urllib2 #need to open and see website data from bs4 import BeautifulSoup #need to parse website data #website url url = 'http://www.imdb.com/search/title?languages=%C2%B7%C2%B7%C2%B7%C2%A0Common%20Languages%C2%A0%C2%B7%C2%B7%C2%B7&release_date=2010-01-01,2017&title_type=feature&user_rating=5.7,10&sort=num_votes,desc' #opening url test_url = urllib2.urlopen(url) readHtml = test_url.read() #reading url test_url.close() #close reading bs = BeautifulSoup(readHtml,"lxml") #put the read website into BeautifulSoup #iterate through the list of movies data thats within a specific div tag with a certain class for movie in bs.find_all('div','lister-item mode-advanced'): title = movie.find_all('a',limit=2) #grab the first two a tags in all the movies data for name in title: #for each a tag grab the second a tag that contains movie name name.get_text() newName = name.get_text() #grabbing movie name from second a tag genres = movie.find('span','genre').contents[0] #find the genres from the span tag with class genre, will grab the first line of words (array) runtime = movie.find('span', 'runtime').contents[0] rating = movie.find('span', 'value').contents[0] year = movie.find('span','lister-item-year text-muted unbold').contents[0] print newName,year + ":", genres, "Run time:"+runtime, "\tRating:"+rating,"\n" #printing information scraped
d3003748f609ac9c62a6d00c3b6fafa399fb9720
torres1-23/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
806
4.46875
4
#!/usr/bin/python3 """This module defines an integer addition function "add_integer(a, b=98)" Usage: "add_integer(...)" return the addition of two arguments, equivalent to using the "+" operator in numbers. """ def add_integer(a, b=98): """Function that adds 2 integers. Args: a (int): first number to add. b (int, optional): second number to add. Raises: TypeError: if a is not integer nor float. TypeError: if b is not integer nor float. Returns: int: Addition of the two integers. """ if not isinstance(a, int) and not isinstance(a, float): raise TypeError("a must be an integer") if not isinstance(b, int) and not isinstance(b, float): raise TypeError("b must be an integer") return int(a) + int(b)
6168049840dcf14a90d10e49def2d3f62c414f95
keakaka/python_ch2.2
/comprehension.py
1,024
3.71875
4
results = [] for n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: result = n * n results.append(result) print(results) # list comprehension results = [n*n for n in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] print(results) # 문자열 리스트에서 길이가 2 이하인 문자열 List or Set strings = ['a', 'as', 'as', 'bar', 'car', 'dove', 'python'] results = [s for s in strings if len(s) <= 2] resultset = {s for s in strings if len(s) <= 2} print(results) print(resultset) # 1 ~ 100 사이의 수 중에서 짝수 리스트 results = [i for i in range(1, 100) if i&1 == 0] print(results) # 문자열 길이를 set으로 저장하기 strings = ['a', 'as', 'as', 'bar', 'car', 'dove', 'python'] strlength = {len(s) for s in strings} print(strlength) # dict comprehension strings = ['a', 'as', 'bar', 'car', 'dove', 'python'] d = {s: len(s) for s in strings} print(d) l = [n for n in range(1, 100) if '3' in str(n) and print(n, '짝') or '6' in str(n) and print(n, '짝') or '9' in str(n) and print(n, '짝')]
8c958b879d798c2784b8aafbaf2cbbe1acc34f92
bryan1292929/Table-Parsing
/src/process_data/extract/traverse_data.py
766
3.515625
4
# File: traverse_data.py # Purpose: Provides functions to traverse tables in xml files and folders. from pathlib import Path from lxml import etree # Returns a collection of xml files in a folder. def files_in_folder(folder): return Path(folder).rglob('*.xml') # Returns an iterator through tables in an xml file. def tables_in_file(file): parser = etree.HTMLParser() tree = etree.parse(file, parser) root = tree.getroot() return root.iter('table') # Returns the file type of the given file. def file_type(file): parser = etree.HTMLParser() tree = etree.parse(file, parser) root = tree.getroot() name = list(root.iter('document-name')) if len(name): return name[0].text return ""
87ff6924d5cc535fcf3791dbe0a8738f258e8d48
ysantosh/learn-ruby
/misc_program/pi1_check_div.py
314
3.703125
4
#! /usr/bin/env python # from 1..100 if number divisible by 4 and 6 print foursix # if divisible by 4 then print four # if divisible by 6 then print six for x in range (1,101): if x%4==0 and x%6==0: print "%d - foursix" %x elif x % 4 == 0: print "%d - four" %x elif x%6==0: print "%d - six" %x
6572ddc477c6242af4930b4c4c0e32c203b5d851
krenevych/algo
/source/T1_Recurence/L6.py
217
3.609375
4
n = int(input("n = ")) D2 = 5 # 1-й член послідовності D1 = 19 # 2-й член послідовності for k in range(3, n + 1): D1, D2 = 5 * D1 - 6 * D2, D1 print("D_%d = %d" % (n, D1))
bd4d82070b896f9256fbf4d04a9d41a70728f83b
ravinaNG/practice-files
/Reverse_str.py
159
3.734375
4
user = raw_input("Type any string:- ") string = "" count = -1 while(count >= -(len(user))): string = string + user[count] count = count - 1 print string
38512fa504c788c7305737c06406ec8dcec0e4de
hiyoung123/ChineseSegmentation
/src/fmm.py
871
3.609375
4
#!usr/bin/env python #-*- coding:utf-8 -*- from src.base import BaseSegment class FMMSegment(BaseSegment): def __init__(self, file: str = '../data/dict.txt'): super(FMMSegment, self).__init__() self.load_dict(file) def cut(self, sentence: str): if sentence is None or len(sentence) == 0: return [] index = 0 text_size = len(sentence) while text_size > index: word = '' for size in range(self.trie.max_word_len+index, index, -1): word = sentence[index:size] if self.trie.search(word): index = size - 1 break index = index + 1 yield word if __name__ == '__main__': text = '南京市长江大桥上的汽车' segment = FMMSegment() print(' '.join(segment.cut(text)))
1b6840af514ab11249cacd9640eb66b466f1557f
toumorokoshi/python-code-challenges
/07/28.py
892
3.90625
4
def all_sliver_users(card_names_by_person): """ given a dictionary of <string, list[string]> pairs, mapping a user to all of the card names that user owns, return a list of all users who own a card with "sliver" in the name. """ z= [] for k,v in card_names_by_person.items(): for x in v: if "sliver" in x: z.append(k) print z break return z test = { "calciumcrusader": ["flying sliver", "muscle sliver"], "toumorokoshi": ["verdant force", "beast of burden"], "chrono": ["suicide goblin", "clear sliver"], "tidus": ["pacifism", "counterspell"] } # just an fyi, a set is a data structure that is like a list, but only # allows unique values, and is order independent. assert set(all_sliver_users(test)) == set(["calciumcrusader", "chrono"]) print("it works, congrats!")
1da95b905b5c64e262675d927250286e50541c15
kdog31/eya-ai
/eya_first_run.py
774
3.578125
4
#imports import os import json #database stuff db = open("eyadb", "w") def say(saystr): os.system("say " + str(saystr)) def input(db): say("What should i call you?") name = raw_input("what should i cal you?") print("ok so your name is " + name + ", nice to meet you") say("ok so your name is " + name + ", nice to meet you") say("when were you born?") DOB_DAY = raw_input("Day: ") DOB_MONTH = raw_input("Month, in numbers: ") DOB_YEAR = raw_input("Year: ") say("ok now i know how old you are") say("what is your favorite food?") Food = raw_input("favorite food: ") say("ok thank you, i have everything i need") DOB = DOB_DAY + "/" + DOB_MONTH + "/" + DOB_YEAR db.write("hello world") db.write(name + "\n") db.write(DOB + "\n") db.write(Food) input(1)
7bb3a14d2d5fb231e85f4b4f38681e618026582c
jnau/Jnau-Sample-Scripts
/Python/Other/Hangman.py
4,243
4.25
4
#this program will allow the user to play "hangman" #these are the global variables we wil be using num_wrong = 0 question_marks = "" guess_letters = "" def get_secret_word(): #to obtain the secret word global question_marks while True: question = ("Please enter a word to be guessed\nthat does not contain ? or white space: ") secret_word = input(question).lower()#.strip() invalid_characters = [' ', '?'] #if a space or ? in word, it is invalid if not any(x in secret_word for x in invalid_characters): question_marks = "".join(len(secret_word) * "?") return secret_word # end of get_secret_word() secret_word = get_secret_word() #global variable def get_guess(): #function to obtain a valid guess global guess_letters global num_wrong global secret_word global question_marks guess = "" while True: guess = input("Please enter your next guess: ").lower().strip() invalid_characters = [' ', '?'] if any(x in guess for x in invalid_characters): continue elif len(guess) > 1: print("You can only guess a single character.") continue elif len(guess) == 0: print ("You must enter a guess.") continue elif any(x in guess for x in guess_letters): print("You already guessed the character: ", guess) continue else: guess_letters += guess break # at this point we have a valid guess # this snippet of code replaces the '?' at the correct position with the valid guess letter # first see if the guess is in the secret word if secret_word.count(guess): # if so, replace the proper question marks with the guessed letter question_marks = list(question_marks) for i in range(len(secret_word)): if secret_word[i] == guess: question_marks[i] = guess else: # if not, then the guess was wrong num_wrong = num_wrong + 1 question_marks = "".join(question_marks) return guess # end of get_guess() def display_guesses(): #display what the user has guessed so far global guess_letters sorted_letters = ", ".join(sorted(guess_letters)) print("So far you have guessed: ", sorted_letters) return # end of display_guesses() def display_marks(): #display the masked word with question marks global question_marks print(question_marks) return # end of display_marks() def display_hangman(): global num_wrong if num_wrong == 1: print(' |') elif num_wrong == 2: print(' |') print(' 0') elif num_wrong == 3: print(' |') print(' 0') print(' |') elif num_wrong == 4: print(' |') print(' 0') print('/|') elif num_wrong == 5: print(' |') print(' 0') print('/|\\') elif num_wrong == 6: print(' |') print(' 0') print('/|\\') print('/') elif num_wrong == 7: print(' |') print(' 0') print('/|\\') print('/ \\') return # end of display_hangman() def is_game_over(): global num_wrong global question_marks global secret_word global guess_letters # returns False if num_wrong == 7 or question_mark == secret_word if (num_wrong == 7): display_hangman() print("You failed to guess the secret word:", secret_word) return False elif (question_marks == secret_word): print("You correctly guessed the secret word:", secret_word) return False else: #print("game is continuing...") return True def main(): global secret_word global question_marks print(30 * "\n") print(question_marks) print("So far you have guessed:") get_guess() while is_game_over(): display_hangman() display_marks() display_guesses() get_guess() main()
88dd8ea06aa35e3af232b9a003c87bb775609382
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses08/ses08_extra.py
1,098
3.78125
4
from ses08_data_structures import Graph, Digraph, Queue, QueueNode def create_dfs_graph(): """ Initializes a test graph for DFS """ g = Graph() g.add_edge('John', 'Helena') g.add_edge('John', 'Chris') g.add_edge('Helena', 'Paul') g.add_edge('Chris', 'Paul') g.add_edge('Chris', 'Vicki') g.add_edge('Jared', 'Vicki') g.add_edge('Jared', 'Donald') g.add_edge('Jared', 'Paul') return g def dfs(graph, start): """ Depth first search on graph from node start Parameters: graph (Digraph/Graph), start: starting node in the graph Returns: prev_nodes: dictionary: key: node, value: node where this node was reached from pop_order: dictionary: key: node, value: the order in which this node was removed from the list Example use: >>> lec_graph = create_dfs_graph() >>> dfs_paths, pop_order = dfs(lec_graph, 'John') >>> abs(pop_order['Chris'] - pop_order['Helena']) > 1 True """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW
9078dd2179869a3a0e25439bc3cad7edd29914bc
biglerd7304/CTI110
/P2HW1_CelsiusConverter_DanielBigler.py
413
4.34375
4
# Celsius to Farenheit Converter # 9-4-18 # CTI-110 P2HW1 - Celsius Fahrenheit Converter # Daniel Bigler # # input is in celsius degrees_celsius = float( input('enter the temperature in Celsius: ')) # Calculate from celsius to fahrenheit degrees_fahrenheit = (degrees_celsius * 1.8) + 32 # Display the temperature in fahrenheit print('The temperature in Fahrenheit is ', format (degrees_fahrenheit))
9084d7a102ba5f8fcb335d50478eedb265358fcf
richbm10/Visualizacion-de-la-Informacion-PC3
/rewrite.py
1,178
3.515625
4
# Read World Population world_population = open('world_population.csv', 'r') lines = world_population.readlines() # Create Dictionary for Codes of Countries countries = dict() # Set the Country Code for each Country Name for line in lines: words = line.split(",") countries[words[0]] = words[1] # Delete first row del countries['name'] world_population.close() # Read Happiness (2019) happiness = open('2019.csv', 'r') lines = happiness.readlines() # Create new countries new_countries = [] # Set new countries with code for line in lines: country_name = line.split(",")[1] country_code = countries.get(country_name, None) if country_code == None: print(country_name) else: new_line = line[:-1] + "," + countries[country_name] + "\n" new_countries.append(new_line) # Write Happiness (with Code) new_file = open('happiness2.csv', 'w') header = "Overall rank,Country or region,Score,GDP per capita,Social support,Healthy life expectancy,Freedom to make life choices,Generosity,Perceptions of corruption, code\n" new_lines = [header] + new_countries new_file.writelines(new_lines)
8175f544a0329429d3738e86175f3ad9ac8d748a
unclosable/funny-project
/leetcod-problems/2add-two-numbers.py
1,575
3.8125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: reNode = l1 currentL1 = l1 lastL1 = None currentL2 = l2 flg = False while currentL1 is not None: if currentL2: add = currentL1.val + currentL2.val + (1 if flg else 0) currentL1.val = add % 10 flg = add > 9 else: break lastL1 = currentL1 currentL1 = currentL1.next currentL2 = currentL2.next if flg and currentL2: lastL1.next = currentL2 self.nodeAdd(currentL2, None, 1) elif flg and currentL1: self.nodeAdd(currentL1, None, 1) elif flg: self.nodeAdd(None, lastL1, 1) elif currentL2: lastL1.next = currentL2 return reNode def nodeAdd(self, node: ListNode, laseNode: ListNode, add): if node: add = node.val + add node.val = add % 10 if add > 9: self.nodeAdd(node.next, node, 1) else: laseNode.next = ListNode(1, None) if __name__ == "__main__": l1 = ListNode(2, next=ListNode(4, ListNode(7, None))) l2 = ListNode(5, next=ListNode(6, ListNode(4, ListNode(9, None)))) l = Solution().addTwoNumbers(l1, l2) print("---") while l: print(l.val) l = l.next
f98a65e6b1ccb923b89fcc7e1bc1fc753ac40d48
lazypanda10117/Problem-Collection
/LeetCode/540.py
2,246
3.78125
4
class Solution: LEFT = 0 RIGHT = 1 ODD = 1 EVEN = 0 def giveParity(self, num: int) -> int: return num % 2 def isMiddleSingle(self, nums: List[int]): return nums[0] != nums[1] and nums[1] != nums[2] and nums[2] != nums[0] def getDirection(self, idx: int, nums: List[int]): if self.giveParity(idx) == self.ODD: if nums[1] == nums[2]: return self.LEFT else: # This imples from previous code that nums[0] == nums[1] as we do the isSingle check before return self.RIGHT else: if nums[0] == nums[1]: return self.LEFT #because if they are different, it means the single index did not affect this else: return self.RIGHT def singleDirection(self, idx: int, nums: List[int]): if idx >= 1 and idx <= len(nums) - 2: leftIdx = (int)(idx - 1) rightIdx = (int)(idx + 2) tempNums = nums[leftIdx: rightIdx] isSingle = self.isMiddleSingle(tempNums) return (isSingle, self.LEFT) if isSingle else (isSingle, self.getDirection(idx, tempNums)) elif idx >= 1: # Should not be able to reach here unless the single element is here return (True, self.RIGHT) elif idx <= len(nums) - 2: # Should not be able to reach here unless the single element is here return (True, self.LEFT) else: raise "HOW DO YOU EVEN GET TO THIS CONDITION???" # Need to check for some edge cases (literally on the edge lol) def singleNonDuplicate(self, nums: List[int]) -> int: # binary search on list, determine direction n = len(nums) - 1 # Must be even, since number of elements is odd left = 0 right = n while left < right: idx = (int)((left + right) / 2) sd = self.singleDirection(idx, nums) if sd[0]: return nums[idx] else: if sd[1] == self.LEFT: right = idx - 1 else: left = idx + 1 return nums[left]
2e303dd5325099609ba6939f309ebdb258d7b342
tgrahamcodes/pyProj
/py.py
1,260
3.90625
4
def encrypt(): lines = [] line = '' fileName = 'test.txt' case = '' listSpecial = [] listUpper = [] # loop through lines in list # and print the entire string with open (fileName) as fh: lines = fh.read().splitlines() print (lines) # print out per letter for letter in lines: if (letter.upper()): listUpper += letter.upper() listSpecial += letter listSpecial += listSpecial[-1] return listSpecial def operation(): st = encrypt() listSpecial = [] op = 'C' aLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] if (op == 'C'): print ('Caesar Cipher:') for s in st: print (s) # print (abs(mod)) # if () > 0): # listSpecial += aLetters[mod+14] # else: listSpecial += aLetters[s+1] print (listSpecial) if (op == 'A'): for s in st: listSpecial += aLetters[13] print (listSpecial) operation()
fa6e077b39282190ca964b7319b1593c5ade2d64
adamjalred/ExampleProj
/main.py
260
4.09375
4
def multiTwoNumbers(num1, num2): num3 = num1 * num2 return num3 def addTwoNumber(num1, num2): num3 = num1 + num2 return num3 if __name__ == '__main__': answer = addTwoNumber(5, 3) answer2 = multiTwoNumbers(4, 5) print(answer) print(answer2)
e16263677af91f6e593a7d3aa59fe110de65902a
MANakib/Python-Code-sample-
/Loop.py
335
3.75
4
i = 35 Age = input("Age:") if int(Age) < 35: print ("You are too young, You must be at least 35 years old. ") else: print ( "Born in the U.S.?: Yes/No ") Answer = input() if Answer == 'Yes': print ('Years of Residency: ', int(Age)) else: x = int(Age) - i print ('Years of Residency: ', i)
b2d919a86620bc1cc0ed1c4fd16d3edd2f9c3fc3
jvanderhorst/web-335
/week-8/vanderhorst_calculator.py
219
3.859375
4
# add function def add(a, b): return a + b # subtract function def subtract(a, b): return a - b # divide function def divide(a, b): return a/b print(add(7,8)) print(subtract(17,5)) print(divide(18,3))
f94a9a725616449585524371108ef952cba14157
to-Remember/TIL
/June 4, 2021/8_변수scope.py
761
3.875
4
# 지역변수(지역구): 함수 내에서 선언. 그 함수 내에서만 사용가능 # 전역변수(전국구): 함수 밖에 선언. 이 파일 내에서 모든 함수에서 사용가능 num=10 #전역변수 def f1(): global num #전역변수로 지정 num=20#전역변수. 전역변수 값 변경 print('f1:', num) def f2(): x = 5#지역변수 num = 15 #변수 정의. 지역변수로 정의 print('f2 x:', x) print('f2 num:', num)#지역변수 def main(): print('main num:', num)#전역변수 #print('main x:', x) #다른 함수의 지역변수 사용불가 f1() f2() print('main num:', num)#전역변수 main() ''' main() 밥먹기 잠자기 운동하기 놀기 생명체크 레벨체크 메뉴 '''
24fe065d675282e5b06194d4e799de1b33dafa66
djsilenceboy/LearnTest
/Python_Test/PyCodePractice/com/djs/learn/LetterCombinationsOfAPhoneNumber.py
1,043
3.71875
4
''' @author: Du Jiang https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ ''' class Solution: __number_letter_dict = {"0": "", "1": "", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits) == 0: return [] a_list = list(Solution.__number_letter_dict[digits[0]]) if len(digits) == 1: return a_list else: return [a + b for a in a_list for b in self.letterCombinations(digits[1:])] def test(digits): solution = Solution() result = solution.letterCombinations(digits) print("result =", result) print("-" * 80) def main(): digits = "" # [] test(digits) digits = "23" # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] test(digits) print("-" * 80) if __name__ == '__main__': main()
ea3702b51fb0d33c59aeda04353c9d698a5a8a74
INKWWW/python_project
/utils/iter_next.py
2,020
4.0625
4
# 容器 '''容器是用来储存元素的一种数据结构,容器将所有数据保存在内存中,Python中典型的容器有:list,set,dict,str等等。 for … in… 这个语句其实做了两件事。第一件事是获得一个可迭代器,即调用了__iter__()函数。 第二件事是循环的过程,循环调用__next__()函数。 对于test这个类来说,它定义了__iter__和__next__函数,所以是一个可迭代的类,也可以说是一个可迭代的对象(Python中一切皆对象)。 ''' print('------容器------') class test(object): """docstring for test""" def __init__(self, data): self.data = data def __iter__(self): return self def __next__(self): if self.data > 5: raise StopIteration else: self.data += 1 return self.data for item in test(3): print(item) # 迭代器 '''含有__next__()函数的对象都是一个迭代器,所以test也可以说是一个迭代器。如果去掉__itet__()函数,test这个类也不会报错。 ''' print('------迭代器------') class test(object): """docstring for test""" def __init__(self, data): self.data = data def __next__(self): if self.data > 5: raise StopIteration else: self.data += 1 return self.data t = test(3) for i in range(3): print(t.__next__()) # 生成器 '''生成器是一种特殊的迭代器。当调用fib()函数时,生成器实例化并返回,这时并不会执行任何代码,生成器处于空闲状态,注意这里prev, curr = 0, 1并未执行。然后这个生成器被包含在list()中,list会根据传进来的参数生成一个列表,所以它对fib()对象(一切皆对象,函数也是对象)调用__next()__方法, ''' print('------生成器------') def fib(end = 1000): prev, curr=0,1 while curr < end: yield curr prev, curr = curr, curr + prev print(list(fib()))
3239bb290a89aeb6962c20565874d34e46616320
shubhpy/Python-Programs
/FinFout.py
603
3.546875
4
def retrieveFile(): try: bestStudent={} bestStudentStr= "The students ranks are as follows \n" fin = open("student.txt","r") except(IOError),e: print "File not found",e else: for line in fin: name,grade = line.split() bestStudent[grade] = name fin.close() for i in sorted(bestStudent.keys()): print bestStudent[i] + " Scored a " + i bestStudentStr += bestStudent[i]+ " scored a "+ i + "\n" print "\n" print bestStudentStr fout = open("studentrank.txt","w") fout.write(bestStudentStr) fout.close() def main(): retrieveFile() if __name__ == "__main__": main()
d088c3d5890bec181b60e28e791d190ae6615142
Yun-Su/python
/PythonApplication1/PythonApplication1/高级特性之列表生成式.py
386
3.734375
4
print([x * x for x in range(1, 11)]) print([x * x for x in range(1, 11) if x % 2 == 0]) #写列表生成式时,把要生成的元素x * x放到前面, #后面跟for循环,就可以把list创建出来, #for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方: print( [m + n for m in 'ABC' for n in 'XYZ']) #使用两层排列进行组合遍历
e98c15130c0c50a90073b2a7b87e27b0da3be825
Sachinshivamurthy/python_codes
/python/basics,datatypes-no.,string,tuple,dictionary,list,sets/function5.py
179
3.6875
4
def nsum(n): sum=0 if(n<1): return n else: for i in range(1,1+n): sum=sum+i return sum print(nsum(5))
bc2c85a29a1f37ada39ec94249f1869cda300918
serge-m/simplebbox
/simplebbox/_array_processor.py
5,335
3.65625
4
def atleast_2d(x): if x.ndim == 1: return x.reshape(1, *x.shape) return x class ArrayProcessor: def __init__(self, stack_fn): self.stack = stack_fn def x0y0wh_to_x0y0x1y1(self, x0y0wh): """ Converts a bounding box from format (min x, min y, width, height) to (min x, min y, max x, max y). In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. The function can process batch inputs. In this case representation of each bounding box must be stored as the last axis of the array. """ arr = x0y0wh res = [ arr[..., 0], arr[..., 1], arr[..., 0] + arr[..., 2], arr[..., 1] + arr[..., 3] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def x0y0x1y1_to_x0y0wh(self, x0y0x1y1): """ Converts a bounding box from format (min x, min y, max x, max y) to (min x, min y, width, height). In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. The function can process batch inputs. In this case representation of each bounding box must be stored as the last axis of the array. """ arr = x0y0x1y1 res = [ arr[..., 0], arr[..., 1], arr[..., 2] - arr[..., 0], arr[..., 3] - arr[..., 1] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def cxcywh_to_x0y0wh(self, cxcywh): """ Converts a bounding box from format (center x, center y, width, height) to (min x, min y, width, height). In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. The function can process batch inputs. In this case representation of each bounding box must be stored as the last axis of the array. """ arr = cxcywh res = [ arr[..., 0] - arr[..., 2] / 2, arr[..., 1] - arr[..., 3] / 2, arr[..., 2], arr[..., 3] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def cxcywh_to_x0y0wh_int_div(self, cxcywh): """ Converts a bounding box from format (center x, center y, width, height) to (min x, min y, width, height) using integer operations (division). In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. """ arr = cxcywh res = [ arr[..., 0] - arr[..., 2] // 2, arr[..., 1] - arr[..., 3] // 2, arr[..., 2], arr[..., 3] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def cxcywh_to_x0y0x1y1(self, cxcywh): """ Converts a bounding box from format (center x, center y, width, height) to (min x, min y, max x, max y). In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. """ arr = cxcywh x0 = arr[..., 0] - arr[..., 2] / 2 y0 = arr[..., 1] - arr[..., 3] / 2 res = [ x0, y0, x0 + arr[..., 2], y0 + arr[..., 3] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def cxcywh_to_x0y0x1y1_int_div(self, cxcywh): """ Converts a bounding box from format (center x, center y, width, height) to (min x, min y, max x, max y) using only integer division. In the coordinate system of a screen (min x, min y) corresponds to the left top corner of the box. """ arr = cxcywh x0 = arr[..., 0] - arr[..., 2] // 2 y0 = arr[..., 1] - arr[..., 3] // 2 res = [ x0, y0, x0 + arr[..., 2], y0 + arr[..., 3] ] return self.stack(res).reshape(*arr.shape[:-1], len(res)) def xyxy_abs_to_rel(self, xyxy, image_wh): """ Converts a bounding box from format (x, y, width, height) or (x, y, x, y) from absolute to relative values with respect to image width and height. Parameters ---------- image_wh : tuple of width and height of image """ x0 = xyxy[..., 0] y0 = xyxy[..., 1] x1 = xyxy[..., 2] y1 = xyxy[..., 3] w = image_wh[..., 0] h = image_wh[..., 1] return self.stack([ x0 / w, y0 / h, x1 / w, y1 / h ]) def xyxy_rel_to_abs(self, xyxy, image_wh): """ Converts a bounding box from format (x, y, width, height) or (x, y, x, y) from relative to absolute values with respect to image width and height. Parameters ---------- xyxy : tuple or list. (x, y, width, height) or (x, y, x, y). image_wh : tuple of width and height of image """ x0 = xyxy[..., 0] y0 = xyxy[..., 1] x1 = xyxy[..., 2] y1 = xyxy[..., 3] w = image_wh[..., 0] h = image_wh[..., 1] return self.stack([ x0 * w, y0 * h, x1 * w, y1 * h ])
d16fae0b18f5a7824e1b24c5846c68118868dc8f
avanover0311/Python
/pythonprojects/ForLoopBasic1.py
431
3.65625
4
#basic for count in range(0,151): print("looping -", count) # mult of 5 for num in range(5,1000000,5): print (num) # counting for num in range(1,100,1): if(num%5): print('Coding') elif (num%10): print('Coding Dojo') #whoa sum = 0 for num in range(0,500000): if(num%2 != 0): sum = sum + num print(sum) #countdown. *** for num in range(1,2018,4): print(num) #flexible *** lowNum = highNum = mult = for num in
5f50efc627190f87846cee6f01773c302b05c973
FernandoUrdapilleta/Python101
/List.py
4,265
4.28125
4
# There are four collection data types in the Python programming language: # List is a collection which is ordered and changeable. Allows duplicate members. # Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # Set is a collection which is unordered and unindexed. No duplicate members. # Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # Lists thislist = ["apple", "banana", "cherry"] # Print the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[0]) print("-------------------------------------------------------------------------------- Line 15") # Negative Indexing # Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc. thislist = ["apple", "banana", "cherry"] print(thislist[-1]) print("-------------------------------------------------------------------------------- Line 22") # Range of Indexes # You can specify a range of indexes by specifying where to start and where to end the range. # When specifying a range, the return value will be a new list with the specified items. # Return the third, fourth, and fifth item: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) print("-------------------------------------------------------------------------------- Line 31") # Note: The search will start at index 2 (included) and end at index 5 (not included). # Remember that the first item has index 0. # By leaving out the start value, the range will start at the first item: # This example returns the items from the beginning to "orange": thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4]) print("-------------------------------------------------------------------------------- Line 42") # By leaving out the end value, the range will go on to the end of the list: # This example returns the items from "cherry" and to the end: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:]) print("-------------------------------------------------------------------------------- Line 49") # Add Items # To add an item to the end of the list, use the append() method: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) print("-------------------------------------------------------------------------------- Line 57") # To add an item at the specified index, use the insert() method: # Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) print("-------------------------------------------------------------------------------- Line 65") # Remove Item # The remove() method removes the specified item: thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) print("-------------------------------------------------------------------------------- Line 73") # The pop() method removes the specified index, (or the last item if index is not specified): thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) print("-------------------------------------------------------------------------------- Line 80") # The del keyword removes the specified index: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) print("-------------------------------------------------------------------------------- Line 87") # The clear() method empties the list: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) print("-------------------------------------------------------------------------------- Line 94") # Copy a List # You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. # There are ways to make a copy, one way is to use the built-in List method copy(). thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) print("-------------------------------------------------------------------------------- Line 104") # Join two list: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)
b6443ad0a045070cddb1c824ff227fe49c9730de
hasanjafri/DailyCodingProblems
/#1320/longest_substring_distinct.py
837
3.8125
4
def longest_substring_with_k_distinct_characters(s, k): char_count = {} max_len = 0 start = 0 for end in range(len(s)): char = s[end] if char not in char_count: char_count[char] = 0 char_count[char] += 1 while len(char_count) > k: char_to_remove = s[start] char_count[char_to_remove] -= 1 if char_count[char_to_remove] == 0: del char_count[char_to_remove] start += 1 max_len = max(max_len, end - start + 1) return max_len if __name__ == "__main__": print(longest_substring_with_k_distinct_characters("araaci", 2)) # Outputs 4 print(longest_substring_with_k_distinct_characters("araaci", 1)) # Outputs 2 print(longest_substring_with_k_distinct_characters("cbbebi", 3)) # Outputs 5
73fe7a3b93ba2de72dd95713b215e977a44252fe
Sidney-kang/Unit4-06
/string.py
540
4.125
4
# Created by : Sidney Kang # Created on : 8 Nov. 2017 # Created for : ICS3UR # Daily Assignment - Unit4-06 # This program checks if 2 strings are the same def compare_strings(string_1, string_2): string_1 = string_1.upper() string_2 = string_2.upper() if string_1 == string_2: return True else: return False string_1 = raw_input("Enter any word: ") string_2 = raw_input("Enter another word: ") compare_strings(string_1, string_2) final_answer = compare_strings(string_1, string_2) print(final_answer)
d54adee2f3bdef3fb8bcf6c70ea54032bb3d4fc6
noopurkharche/dataStructuresAndAlgorithms
/wordLadder.py
720
3.78125
4
def ladderLength(beginWord, endWord, wordList): queue = [(beginWord, 1)] visited = set() while queue: word, dist = queue.pop(0) if word == endWord: return dist for i in range(len(word)): for j in 'abcdefghijklmnopqrstuvwxyz': tmp = word[:i] + j + word[i+1:] print("made word - " + tmp) if tmp not in visited and tmp in wordList: print("in Queue - " + tmp) queue.append((tmp, dist+1)) visited.add(tmp) return 0 beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] ladderLength(beginWord, endWord, wordList)
016c0e3343302f16f7c95c0a2539bd5d373ded48
Shaunwei/Leetcode-python-1
/Array/N-Queens/solveNQueens.py
2,322
3.875
4
#!/usr/bin/python """ N-Queens The n-queens puzzle is the problem of placing n queens on an nXn chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. For example, There exist two distinct solutions to the 4-queens puzzle: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] """ class Solution: # @return a list of lists of string def solveNQueens(self, n): self.res = [] self.solve(n, 0, [-1 for i in xrange(n)]) return self.res def solve(self, n, currQueenNum, board): if currQueenNum == n: oneAnswer = [ ['.' for j in xrange(n)] for i in xrange(n) ] for i in xrange(n): oneAnswer[i][board[i]] = 'Q' oneAnswer[i] = ''.join(oneAnswer[i]) self.res.append(oneAnswer) return # try to put a Queen in (currQueenNum, 0), (currQueenNum, 1), ..., (currQueenNum, n-1) for i in xrange(n): valid = True # test whether board[currQueenNum] can be i or not for k in xrange(currQueenNum): # check column if board[k] == i: valid = False; break # check dianogal if abs(board[k] - i) == currQueenNum - k: valid = False; break if valid: board[currQueenNum] = i self.solve(n, currQueenNum + 1, board) if __name__=="__main__": n = 2 # 4 print Solution().solveNQueens(n) """ The classic recursive problem. 1. Use a int vector to store the current state, A[i]=j refers that the ith row and jth column is placed a queen. 2. Valid state: not in the same column, which is A[i]!=A[current], not in the same diagonal direction: abs(A[i]-A[current]) != r-i 3. Recursion: Start: placeQueen(0,n) if current ==n then print result else for each place less than n, place queen if current state is valid, then place next queen place Queen(cur+1,n) end for end if """
103ddd98dcbf7d53c617d9cdd5843896bc2223bd
GAurelG/Udacity
/data-analyst-nanodegree/03_Projet_OpenStreetMap/Submission/Script/1_audit.py
6,438
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # In this part, we audit the street names and phones numbers. Function used to # audit both are separated, they share common parts, but for the clarity of # presentation I choose to separate them. # # Street audit: # In France, the street category name ("avenue"...) is the first word found in # the street name. We created different regular expression to audit the first # word, the last one and word that start with one or multiple spaces. # A typical street name in france could be: # Rue Marie Curie # - The first word is the street type (Avenue, Boulevard...) # - The last word would be the name of the street. # # Because street names ar often derived from well known personality, places, # flowers... we can also assess the ortograph of the last word in the street # name. # # Phone number audit: # in France phone numbers are composed of country code, one region number # and 8 digits, for example +33 1 12345678. # people often doesn't write country code (replaces by a '0'), and the can # group number by 2 or 3 starting from the end, separated by spaces, '.' # or '-'. import xml.etree.cElementTree as ET from collections import defaultdict import re data = "../Data/paris_france.osm"#sample300_paris_france.osm" first = "./1_first.txt" first_2 = "./2_first.txt" last = "./1_last.txt" last_2 = "./2_last.txt" first_word_re = re.compile(r'^\S+', re.IGNORECASE) last_word_re = re.compile(r'\S+$', re.IGNORECASE) space_start_re = re.compile(r'^\s.*', re.IGNORECASE) #only one empty tag two_frst_re = re.compile(r'^\S+\s+\S+', re.IGNORECASE) last_two_re = re.compile(r'\S+\s+\S+$', re.IGNORECASE) ####### function from the course: ####### def is_street_name(elem): return (elem.tag == "tag") and (elem.attrib['k'] == "addr:street") def print_sorted_dict(d): keys = d.keys() keys = sorted(keys)#, key=lambda s: s.lower()) for k in keys: v = d[k] print "%s: %d" % (k, v) ####### Street names Auditing function ####### ## example of regular expression used to check street names: REG1 = re.compile(r'[=\+/&<>;"\?%#$@\,\.\t\r\n]') REG2 = re.compile(r'["-]') REG3 = re.compile(r'jardins?') REG4 = re.compile(r'zones?') REG5 = re.compile(r'[\s.,_-]$') REG6 = re.compile(r' - ') REG7 = re.compile(r'epine') REG8 = re.compile(r'z ?i') REG9 = re.compile(r'rc ') REG10 = re.compile(r'^a\d?') ## One regular expression used to check names starting with "n" or "rn" ## optionnally followed by a digit. REG = re.compile(r'^r?n\d?') def find_in_name(street_name, group = "t", reg = REG): """return names matching the regular expression (reg should be a compiled regular expression). group parameters tells if we should return the group matched (=g) or the overall street name (= "t"). """ m = reg.search(street_name) if m and group == "g": return m.group() elif m and group == "t": return street_name else: return None def street_audit2(data_xml, word_n = 't'): """Takes an open file as input and print the dict listing the word found and the number of street processed""" total = 0 street_types = defaultdict(int) context = ET.iterparse(data_xml, events=('start',)) _, root = next(context) for event, element in context: if element.tag == "node" or element.tag == "way": for tag in element.iter("tag"): if is_street_name(tag): # name = tag.attrib['v'].lower() name = find_in_name(tag.attrib['v'].lower(), word_n) # name = " ".join(name1[1:]) #print name1 if name: total += 1 street_types[name] += 1 root.clear() print_sorted_dict(street_types) print total ####### phones number Auditing function ####### # regular expressions to look for 'phone' string in tags PHONE = re.compile(r'phone') # regular expression to match strange input in phone number PHONE1 = re.compile(r'[^\d\. +]') # regular expressions used in the auditing of phones numbers # see report for context in the use of theses expressions POR2 = re.compile(r'((?:\d\s?){9}$)') POR3 = re.compile(r'((?:\d\s?|\d\.){9}$)') # regular expression matching phones numbers without the # country code. It matches phone number with numbers grouped # and separated by space, '.' or '-' which correspond to the # majority of phone writting style found in France. POR4 = re.compile(r'((?:\d\s?|\d\.|\d-){9}$)') def find_phonenumb(elem, reg=POR4): """match a string against expression defining phone number variables: - elem: XML element - reg: regular expression to match phone number output: - matching string if found - False if nothing found""" n = reg.findall(elem.attrib['v']) m = reg.search(elem.attrib['v']) if n: if "-" in elem.attrib['v']: print n return n else: return False def is_phone_nb(elem, reg=PHONE): """match 'phone' in an element attrib""" m = reg.search(elem.attrib['k']) if m: return True else: return False def is_stphon(elem, reg=PHONE1): """match element different from the standard phones numbers""" m = reg.search(elem.attrib['v']) if m: return elem.attrib['v'] def phone_audit(data_xml): """audit phone number, print sorted dict of phone number matching define regular expression""" total = 0 phone_numb_tags = defaultdict(int) context = ET.iterparse(data_xml, events=('start',)) _, root = next(context) for event, element in context: if element.tag == "node" or element.tag == "way": for tag in element.iter("tag"): if is_phone_nb(tag): number = find_phonenumb(tag) strange = is_stphon(tag) if number: total += 1 #print number tags = strange #tag.attrib['k'] #print strange phone_numb_tags[tags] += 1 #total += 1 root.clear() print_sorted_dict(phone_numb_tags) print total return None if __name__ == '__main__': data_xml = open(data) #street_audit2(data_xml, "t") phone_audit(data_xml) data_xml.close()
b9f398926e39cd5ed7f04d6a759fddc0052d58bf
fredrik-k/project_euler
/p_121_130/p126.py
1,712
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' PROBLEM 126: The minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two. If we then add a second layer to this solid it would require forty-six cubes to cover every visible face, the third layer would require seventy-eight cubes, and the fourth layer would require one-hundred and eighteen cubes to cover every visible face. However, the first layer on a cuboid measuring 5 x 1 x 1 also requires twenty-two cubes; similarly the first layer on cuboids measuring 5 x 3 x 1, 7 x 2 x 1, and 11 x 1 x 1 all contain forty-six cubes. We shall define C(n) to represent the number of cuboids that contain n cubes in one of its layers. So C(22) = 2, C(46) = 4, C(78) = 5, and C(118) = 8. It turns out that 154 is the least value of n for which C(n) = 10. Find the least value of n for which C(n) = 1000. ANSWER : 18522 ''' def Cubes(x, y, z, n): return 2 * (x * y + y * z + x * z) + 4 * (x + y + z + n - 2) * (n - 1) def main(): C = {} limit = 30000 z = 1 while Cubes(z, z, z, 1) < limit: y = z while Cubes(z, y, y, 1) < limit: x = y while Cubes(z, y, x, 1) < limit: n = 1 while Cubes(z, y, x, n) < limit: c = Cubes(z, y, x, n) if c not in C: C[c] = 0 C[c] += 1 n += 1 x += 1 y += 1 z += 1 C = filter(lambda (n, count): count == 1000, list(C.iteritems())) C.sort(key=lambda (n, count): n) print "The least value of n is %d" % C[0][0] if __name__ == "__main__": main()
4ebd1b8e983020aefb6250903ec93298b0bbc9c8
jonbugge4/CSV
/sitka1.py
598
3.609375
4
import csv open_file = open("sitka_weather_07-2018_simple.csv", "r") csv_file = csv.reader(open_file, delimiter= ',') header_row = next(csv_file) print(type(header_row)) for index, column_header in enumerate(header_row): print(index, column_header) high = [] for row in csv_file: high.append(int(row[5])) print(high) import matplotlib.pyplot as plt plt.title("Daily High Temperature, July 2018", fontsize = 16) plt.xlabel("",fontsize = 12) plt.ylabel("Temperature (F)", fontsize = 12) plt.tick_params(axis='both',which = 'major', labelsize=12) plt.plot(high, c= 'red') plt.show()
64355d862201142ddcbb104a3f2dafb62777a447
sandhoefner/sandhoefner.github.io
/odds.py
487
3.703125
4
print("> Give me a number between 0 and 1") pct = input() # print("> I heard " + str(pct)) best_diff = 100 best_pair = [10,1] for i in range(1,11): for j in range(1,11): print str(i) + ".0/" + str(j) diff = abs(float(i)/j - pct) # print(str(i) + "/" + str(j) + " has diff " + str(diff)) if diff < best_diff: best_diff = diff best_pair = [i,j] print("> The nearest smallint/smallint approximation of " + str(pct) + " is " + str(best_pair[0]) + "/" + str(best_pair[1]))
077b9ff4b07ace8ecc2c416f4255999e3ab4f933
Gurgen99/python_course
/class/patker.py
1,935
3.859375
4
import math class Shape(): def __init__(self): pass def draw_me(self): raise NotImplementedError class D_2(Shape): def draw_my(self): pass def space(self): raise NotImplementedError class D_3(Shape): def draw_me(self): pass def volume(self): raise NotImplementedError class Squure(D_2): def __init__(self, a): self.a = a def draw_me(self): print("I'm a squure") def space(self): s = self.a ** 2 return s class Triangle(D_2): def __init__(self, a, h): self.a = a self.h = h def draw_me(self): print("I'm a triangle") def space(self): s = self.a * self.h / 2 return s class Rectangular(D_2): def __init__(self, a, b): self.a = a self.b = b def draw_me(self): print("i'm a rectangular") def space(self): s = self.a * self.b return s class Cone(D_3): def __init__(self,r,h): self.r = r self.h = h def draw_me(self): print("I'm a cone") def volume(self): s = (math.pi * (self.r**2) * self.h) / 3 return s class Cube(D_3): def __init__(self,a): self.a = a def draw_me(self): print("I'm a cube") def volume(self): s = self.a**3 return s class Cylinder(D_3): def __init__(self,r,h): self.r = r self.h = h def draw_me(self): print("I'm acylinder") def volume(self): s = math.pi * self.r**2 * self.h return s k1 = Squure(4) print(k1.draw_me()) print(k1.space()) k2 = Triangle(6, 7) print(k2.draw_me()) print(k2.space()) k3 = Rectangular(8, 4) print(k3.draw_me()) print(k3.space()) q1 = Cone(5,8) print(q1.draw_me()) print(q1.volume()) q2 = Cube(5) print(q2.draw_me()) print(q2.volume()) q3 = Cylinder(2,4) print(q3.draw_me()) print(q3.volume())
34521b8eda6a4172e9eae78c86a80de563f35b9f
juliarowe/Coursework
/ComputationalPhysics/IsingModel/SquareLattice.py
1,670
3.640625
4
import random import copy from Lattice import Lattice class SquareLattice(Lattice): def __init__(self, size, num_dimensions): self.size = size self.num_dimensions = num_dimensions self.data = self.generate_array(num_dimensions) # Generates the internal data structure for the square lattice def generate_array(self, num_dimensions): if num_dimensions == 1: return [self.random_spin() for x in xrange(self.size)] else: return [self.generate_array(num_dimensions - 1) for x in xrange(self.size)] def get_random_label(self): return tuple(random.randrange(self.size) for x in xrange(self.num_dimensions)) def export(self): return copy.deepcopy(self.data) # See Lattice superclass def get(self, label): ret = self.data for i in label: ret = ret[i] return ret # See Lattice superclass def set(self, label, value): arr = self.data for i in label[:-1]: arr = arr[i] arr[label[-1]] = value # Wraps a value to the other side of the grid # used to approximate an infinitely sized grid def wrap(self, number): return number % self.size # See Lattice superclass def get_neighbors(self, label): # The number of neighbors is twice the number of dimensions neighbors = [list(label) for x in xrange(2 * self.num_dimensions)] for i in xrange(self.num_dimensions): neighbors[2*i][i] = self.wrap(neighbors[2*i][i]+1) neighbors[2*i+1][i] = self.wrap(neighbors[2*i+1][i] - 1) return [tuple(x) for x in neighbors]
bf2707e997a7da003bc7dc3e7c342e8dc63fb8e4
FargoFire/LeetCode_python3
/024# Swap Nodes in Pairs.py
2,098
3.734375
4
# coding:utf-8 """ Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. 题目地址:https://leetcode.com/problems/swap-nodes-in-pairs/ Date: 2019/06/20 By: Fargo Difficulty: Medium """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # iteratively def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head second = head.next print('second', listNodeToString(second), '\n') pre = ListNode(0) while head and head.next: nxt = head.next print('nxt', listNodeToString(nxt)) head.next = nxt.next print('head', listNodeToString(head)) nxt.next = head print('nxt', listNodeToString(nxt)) pre.next = nxt print('pre', listNodeToString(pre)) head = head.next print('head', listNodeToString(head)) pre = nxt.next print('pre', listNodeToString(pre)) print('second', listNodeToString(second), '\n') out = listNodeToString(second) return out # recursively # def swapPairs(self, head): # if not head or not head.next: # return head # second = head.next # head.next = self.swapPairs(second.next) # second.next = head # return second def LlistToListNode(numbers): # Now convert that list into linked list dummyRoot = ListNode(0) ptr = dummyRoot for number in numbers: ptr.next = ListNode(number) ptr = ptr.next ptr = dummyRoot.next return ptr def listNodeToString(node): if not node: return "[]" result = "" while node: result += str(node.val) + ", " node = node.next return "[" + result[:-2] + "]" head = LlistToListNode([1,2,3,4]) print(Solution().swapPairs(head))
eda3d603e83b587a49ad477624b132876a39deb6
tangentspire/Python_Practice
/automate_the_boring_stuff_with_python/Part_1_Python_Programming_Basics/Chapter_2_Flow_Control/collatz.py
428
4.125
4
def get_number(): try: number = int(input("What number would you like to call the collatz function with? > ")) collatz(number) except ValueError: print("You have entered a non-number, please try again.") get_number() def collatz(number): if 0 == (number % 2): number = number // 2 print(number) return number elif 1 == (number % 2): number = 3 * number + 1 print(number) return number get_number()
caf725bfaa25a3cc9ed51410009b15be9199307e
TechInTech/leetcode
/3.无重复字符的最长子串.py
1,472
3.75
4
# # @lc app=leetcode.cn id=3 lang=python3 # # [3] 无重复字符的最长子串 # # https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/ # # algorithms # Medium (30.68%) # Likes: 2154 # Dislikes: 0 # Total Accepted: 174.6K # Total Submissions: 568.9K # Testcase Example: '"abcabcbb"' # # 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 # # 示例 1: # # 输入: "abcabcbb" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 # # # 示例 2: # # 输入: "bbbbb" # 输出: 1 # 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 # # # 示例 3: # # 输入: "pwwkew" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 # 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 # # # class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) < 1: return 0 if len(s) == 1: return 1 num, n = 1, len(s) for i, item1 in enumerate(s[0:n-1]): if s[i] == s[i+1]: continue item = item1 for item2 in s[i+1:n]: if item2 in item: break item += item2 if len(item) > num: num = len(item) return num
00c729747b8a5f055ec7d654506508c223693ebd
Jesta398/project
/collections'/list/ddemo3.py
654
3.515625
4
# lst=[10,20,30,40,50,60,70,80,90,100] # sum=0 # for i in lst: # sum=sum+i # print(sum) # # # or method # # lst=[10,20,30,40,50,60,70,80,90,100] # print(sum(lst)) # #max eleemnt # # lst=[10,20,30,40,50,60,70,80,90,100] # # print(max(lst)) # # lst=[10,20,30,40,50,60,70,80,90,100] # for i in lst: # # if(lst[i]<lst[i+1]): # print(lst[i+1]) # #lowest element-min # #for lenght we use -len # # lst=[10,20,30,40,50,60,70,80,90,100] # print(len(lst)) #sort # lst=[10,20,30,70,40,50,60,70,15,80,90,100,95] # print(sorted(lst)) # #descenting order sorting lst=[10,20,30,40,50,60,70,80,90,100] lst.sort(reverse=True) #descending order print(lst)
21d0afb9703a99bba599f6189b5a4e99f87d7ce2
pavanv27/MyPythonExamples
/TwoSum/1.py
579
3.515625
4
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for x in range(len(nums)-1,-1,-1): for y in range(x): if nums[x]+nums[y]==target: return [x,y] def main(): arr = [3,45,9,23,56] target = 12 # ouput expected : 9 56 45 3 23 s = Solution() print(s.twoSum(arr,target)) if __name__ == "__main__": main() # Accepted: # runtime : 388 ms # memory : 13.7mb
1883b3ed7d2bbbbc0bd73dd48ee685e0772fde62
KarimnC/EjercicioPrueba
/VelPromedio.py
327
3.78125
4
# Autor: Karimn Daniel # Calcular la vel. promedio en un viaje. tiempo = int(input("A ver prro, escribe el tiempo de viaje en horas enteras: ")) distancia = int(input("Shavo, ahora escribe la distancia del viaje en kilómetros enteros: ")) velocidad = distancia/tiempo print("A nu ma, la velocidad es: ", velocidad, "km/h")
b6a439a4ea11249f24d77160afee34e5e1c94aa1
JokerJudge/py111_lab
/Tasks/g1_merge_sort.py
2,363
3.75
4
from typing import Collection, TypeVar _Tt = TypeVar("_Tt") def sort(container: Collection[_Tt]) -> Collection[_Tt]: """ Sort input container with merge sort :param container: container of elements to be sorted :return: container sorted in ascending order """ ''' #мое пока неудавшееся решение part_list = container[0:len(container)//2] part_list_2 = container[len(container)//2:] print(part_list) print(part_list_2) #while len(part_list) > 1: ''' if len(container) <= 1: return container else: middle = len(container) // 2 # получим индекс середины print("=====") print("Common split") print("left container: ", container[:middle]) print("right container: ", container[middle:]) print("Split left container") left_container = sort(container[:middle]) # список должен быть отсортирован. Вызываем эту же функцию print("Split right container") right_container = sort(container[middle:]) # когда разделили до 1 элемента - начинаем сливать print("Merge", left_container, right_container) return merge(left_container, right_container) def merge(left_container, right_container): sorted_ = [] left_container_index = 0 right_container_index = 0 left_container_lenght = len(left_container) right_container_lenght = len(right_container) for _ in range(left_container_lenght + right_container_lenght): if (left_container_index < left_container_lenght) and (right_container_index < right_container_lenght): if left_container[left_container_index] <= right_container[right_container_index]: sorted_.append(left_container[left_container_index]) left_container_index += 1 else: sorted_.append(right_container[right_container_index]) right_container_index += 1 elif left_container_index == left_container_lenght: sorted_.append(right_container[right_container_index]) # или extend всей оставшейся части - нужно попробовать right_container_index += 1 elif right_container_index == right_container_lenght: sorted_.append(left_container[left_container_index]) left_container_index += 1 print("Merged", sorted_) return sorted_ if __name__ == "__main__": list = [6, 5, 12, 10, 9, 1] print(list) print(sort(list))
9ce12cbc0d66d593986abfd152e67031607a1ccf
matheusota/VI-and-UCT
/program.py
9,222
3.578125
4
import pdb import math from sys import argv import random ######################################################################## #find the max difference between utilities def difference(values, s): diff = 0 for (i,j) in [(i,j) for i in range(s) for j in range(s)]: if diff < abs(values[0][i][j] - values[1][i][j]): diff = abs(values[0][i][j] - values[1][i][j]) return diff ######################################################################## ######################################################################## #find expected reward of a given state using Bellman-equation #k is the value representing the action: up(0), down(1), left(2), right(3) def expectedReward(values, k, i, j): #terminal state if i == 0 and j == s - 1: return 5 else: #get the values of each adjacent cell if i != 0: up = values[0][i - 1][j] else: up = values[0][i][j] if i != s - 1: down = values[0][i + 1][j] else: down = values[0][i][j] if j != 0: left = values[0][i][j - 1] else: left = values[0][i][j] if j != s - 1: right = values[0][i][j + 1] else: right = values[0][i][j] #return according to selected action if k == 0: return -0.1 + discount * (0.85 * up + 0.05 * down + 0.05 * left + 0.05 * right) if k == 1: return -0.1 + discount * (0.05 * up + 0.85 * down + 0.05 * left + 0.05 * right) if k == 2: return -0.1 + discount * (0.05 * up + 0.05 * down + 0.85 * left + 0.05 * right) else: return -0.1 + discount * (0.05 * up + 0.05 * down + 0.05 * left + 0.85 * right) ######################################################################## ######################################################################## #print the values given by vi def printValues(values, s): for i in range(s): for j in range(s): print "%f &" % values[1][i][j], print "\\\\" ######################################################################## ######################################################################## #print the policy given by vi def printPolicy(values, s): for i in range(s): for j in range(s): #find max action value_maxAction = -9999; for k in range(4): #up if k == 0 and i != 0: aux = values[1][i - 1][j] #down elif k == 1 and i != s - 1: aux = values[1][i + 1][j] #left elif k == 2 and j != 0: aux = values[1][i][j - 1] #right elif k == 3 and j != s - 1: aux = values[1][i][j + 1] #bump wall else: aux = values[1][i][j] if aux > value_maxAction: maxAction = k value_maxAction = aux #print it if maxAction == 0: print "up & ", elif maxAction == 1: print "down & ", elif maxAction == 2: print "left & ", else: print "right & ", print "\\\\" ######################################################################## ######################################################################## #value iteration algorithm def vi(s, epsilon): global iterations #initialize values to zero values = [[[0 for i in range(1000)] for j in range(1000)] for k in range(2)] #loop until convergence while True: iterations -= 1 #copy values[1] to values[0] for (i,j) in [(i,j) for i in range(s) for j in range(s)]: values[0][i][j] = values[1][i][j] #loop through the states for (i,j) in [(i,j) for i in range(s) for j in range(s)]: #find max value values[1][i][j] = -9999 for k in range(4): aux = expectedReward(values, k, i, j) if aux > values[1][i][j]: values[1][i][j] = aux #print "***************************************\n" #printValues(values, s) #break conditions if difference(values, s) <= epsilon or iterations < 1: break return values ######################################################################## ######################################################################## #this will get a sample of executing action a at state (i, j) def newSample(i, j, a): global s k = random.uniform(0, 1) #we did not succeeded doing action a if k > 0.85: actions = [0, 1, 2, 3] #eliminate action a actions.remove(a) #select new action a = random.choice(actions) #get next state if a == 0: if i == 0: i2 = i j2 = j else: i2 = i - 1 j2 = j elif a == 1: if i == s - 1: i2 = i j2 = j else: i2 = i + 1 j2 = j elif a == 2: if j == 0: i2 = i j2 = j else: i2 = i j2 = j - 1 else: if j == s - 1: i2 = i j2 = j else: i2 = i j2 = j + 1 #return the sampled state return (i2, j2) ######################################################################## ######################################################################## #this will simulate we are "running" in the world def rollout(i, j, depth): global s global discount if depth == 0: return 0 if i == 0 and j == s - 1: return 5 else: actions = [0, 1, 2, 3] #remove bump-walls actions if i == 0: actions.remove(0) if i == s - 1: actions.remove(1) if j == 0: actions.remove(2) if j == s - 1: actions.remove(3) #select a random action a = random.choice(actions) #get a sample of the action (i2, j2) = newSample(i, j, a) #return expected reward return -0.1 + discount * rollout(i2, j2, depth - 1) ######################################################################## ######################################################################## #here is where the actual UCT algorithm happens def simulate(i, j, depth): global s global Q global N global T global exploration global discount #last node to be explored or terminal state if depth == 0: return 0 if i == 0 and j == s - 1: return 5 #state not in tree elif (i, j) not in T: for k in range(4): #initialize to zero N[(i, j, k)] = 0 Q[(i, j, k)] = 0 #add state to the tree T.add((i, j)) #return the rollout return rollout(i, j, depth) else: #get the value of N(s) n = 0 actions = [] for k in range(4): n += N[(i, j, k)] if N[(i, j, k)] == 0: actions.append(k) maxAction = 0 #remove bump-walls actions if i == 0 and 0 in actions: actions.remove(0) if i == s - 1 and 1 in actions: actions.remove(1) if j == 0 and 2 in actions: actions.remove(2) if j == s - 1 and 3 in actions: actions.remove(3) #one or more action was not previously selected if len(actions) > 0: #select randomly between them maxAction = random.choice(actions) #find the maximum action else: maxValue = -9999 for k in range(4): if N[(i, j, k)] != 0: aux = Q[(i, j, k)] + exploration * math.sqrt(math.log(n) / N[(i, j, k)]) if aux > maxValue: maxAction = k maxValue = aux #get a new sample (i2, j2) = newSample(i, j, maxAction) #compute q with the value of the new sample q = -0.1 + discount * simulate(i2, j2, depth - 1) #update N and Q N[(i, j, maxAction)] += 1 Q[(i, j, maxAction)] += (q - Q[(i, j, maxAction)])/N[(i, j, maxAction)] #return the value for this node return q ######################################################################## ######################################################################## #this function just call the simulate sequence def uct(depth, simulations): global s global Q global N global T for i in range(simulations): q = simulate(s - 1, 0, depth) #return the action with the biggest Q value maxValue = -9999 maxAction = 0 for k in [0, 3]: aux = Q[(s - 1, 0, k)] if aux > maxValue: maxAction = k maxValue = aux #return value and best action return (maxValue, maxAction) ######################################################################## ######################################################################## #here starts the execution of the program #scan arguments it = iter(range(len(argv))) alg = False discount = 1 epsilon = 0 iterations = 999999 simulations = 10000 exploration = 1 depth = 5 s = 0 #initialize some dicts and sets Q = {} N = {} T = set() for i in it: #scan type of algorithm if argv[i] == "-alg": i = next(it) if argv[i] == "vi": alg = False elif argv[i] == "uct": alg = True #scan gamma if argv[i] == "-gamma": i = next(it) discount = float(argv[i]) #scan epsilon elif argv[i] == "-epsilon": i = next(it) epsilon = float(argv[i]) #scan max number of iterations of VI elif argv[i] == "-iterations": i = next(it) iterations = int(argv[i]) #scan number of simulations of UCT elif argv[i] == "-simulations": i = next(it) simulations = int(argv[i]) #scan exploration constant of UCT elif argv[i] == "-exploration": i = next(it) exploration = int(argv[i]) #scan max depth of UCT elif argv[i] == "-depth": i = next(it) depth = int(argv[i]) #scan size of problem elif argv[i] == "-size": i = next(it) s = int(argv[i]) #run algorithms if not alg: values = vi(s, epsilon) print "Values:" printValues(values, s) print print "Policy:" printPolicy(values, s) else: print "Value:" (x, a) = uct(depth, simulations) print x print "Action:" print a ########################################################################
b352562c13ddcbad329f08f03eb0c524176e5a50
rajfal/algos
/fibonacci_last_digit0.py
1,390
4.03125
4
# Uses python3 from timeit import default_timer as timer def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_fibonacci_last_digit_itrn(n): #iterative solution #613455 #0 #get_fibonacci_last_digit_itrn(613455)(Time used: 5.10/5.00, memory used: 9363456/536870912.) # x = 0 y = z = 1 for i in range(0, n): x = y y = z z = x + y #y, z = z, x + y #print("--- i=" + str(i) + " x =" + str(x) + " y =" + str(y) + " z =" + str(z)) #p= x % 10 #print(str(p)) return x % 10 def fibonacci_last_digit(n): # return last digit of the 1st element of the tuple return fast_dbl_fib(n)[0] % 10 def fast_dbl_fib(n): if n == 0: return (0, 1) else: a, b = fast_dbl_fib((n // 2)) #a = ... F(n) #b = ... F(n+1) c = 2*b - a c = (a * c) # F(2n) d = (a*a + b*b) # F(2n + 1) if(n%2 == 0): return (c, d) else: return (d, c+d) if __name__ == '__main__': n = int(input()) #start = timer() print(fibonacci_last_digit(n)) #proc_time = timer() - start #print("fibonacci_last_digit(" + str(n) + ") took %f seconds" % proc_time)
6d30d32bf97a33f764b8050da241630bf5e2e7a5
erenkrbl/python_bites
/srednee.py
168
3.515625
4
one = input("Введите первое число ") too = input("Введите второе число ") srednee = ((int(one) + int(too)) // 2) print(srednee)
fc67206793cd483acdbb305f621ab33b8ad63083
rsp-esl/python_examples_learning
/example_set-1/script_ex-1_27.py
1,088
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## # Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB) # Date: 2017-11-17 ############################################################################## from __future__ import print_function # for Python 2.6 or higher ## Data structures, Lists numbers = [0,-1,2,-2,1,-3,3] # create a list of int numbers = sorted( numbers ) # sort the list print (numbers) # show the numbers in the (sorted) list # output: [-3, -2, -1, 0, 1, 2, 3] # create a list of positive numbers from a list positives = [ n for n in numbers if (n > 0) ] print (positives) # output: [1, 2, 3] # create a list of negative numbers from a list negatives = [ n for n in numbers if (n < 0) ] print (negatives) # output: [-3, -2, -1] squares = [ i*i for i in numbers ] print (squares) print (sum(squares)) # output: [9, 4, 1, 0, 1, 4, 9] # output: 28 ##############################################################################
4a9fda905ff636ebdaad7aed11681d5dafdfb457
shiningnight93/Baekjoon_Algorithm
/01-05-2021.py
1,944
3.515625
4
''' 01-05-2021 Baekjoon Algorithm 단계별 문제 풀이 - 3단계 언어 - Python ''' # 11021 # 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. temp = [] t = int(input()) for i in range(0, t): temp = input().split( ) a = int(temp[0]) b = int(temp[1]) print('Case #{0:d}: {1:d}'.format(i+1, a+b)) # 11022 # 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. temp = [] t = int(input()) for i in range(0, t): temp = input().split( ) a = int(temp[0]) b = int(temp[1]) print('Case #{0:d}: {1:d} + {2:d} = {3:d}'.format(i+1, a, b, a+b)) # 2438 # 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제 flag = 0 while(flag == 0): n = int(input()) if (1 <= n <= 100): flag = 1 for i in range(1, n+1): for j in range(0, i): print("*", end = '') print("") # 2439 # 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제 # 하지만, 오른쪽을 기준으로 정렬한 별을 출력하시오. flag = 0 while(flag == 0): n = int(input()) if (1 <= n <= 100): flag = 1 for i in range(1, n+1): for j in range(0, n-i): print(" ", end='') for k in range(0, i): print("*", end='') print("") # 10871 # 정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오. temp = [] flag = 0 while(flag == 0): temp = input().split( ) n = int(temp[0]) x = int(temp[1]) if (1 <= n <= 10000 and 1 <= x <= 10000): flag = 1 temp = input().split( ) for i in range(0, n): a = int(temp[i]) if a < x : print(a, end=' ')
08643d8919cab75dcd6a68709d39da0ee58f551a
elenaborisova/Python-Advanced
/10. Functions Advanced - Exercise/05_function_executor.py
332
3.828125
4
def sum_numbers(num1, num2): return num1 + num2 def multiply_numbers(num1, num2): return num1 * num2 def func_executor(*args): results = [] for arg in args: func, nums = arg results.append(func(*nums)) return results print(func_executor((sum_numbers, (1, 2)), (multiply_numbers, (2, 4))))
866cea4b528466a61b6a5054a4de7990db00cbe6
neutrons/GUI_Tools
/Logging/loggingHelpers.py
2,733
3.875
4
import os def parseLoggingConf(): """ To see this docstring: print parseLoggingConf.__doc__ This function parses a logging.conf file used in support of python logging. USER WARNING: THIS IS VERY FRAGILE CODE!!!! This function expects the logging.conf file to be in a specific format so that the arg for the RotatingFileHandler can be discovered easily. In finding this, the arg is parsed to give the path defined within the logging.conf file to place the resultant log files. The unfortunate reason for needing this parser is due to a circular dependency resulting from needing the directory path to be created before it has been created when executing: logging.config.fileConfig('logging.conf') To break this circular dependency, it is necessary to separately read and parse the logging.conf file by the main program prior to executing the logging.config.fileConfig('logging.conf') line. By doing so, the necessary path structure can be put in place prior to needing it. Sorry about this - currently don't know of a better way around this issue. """ f=open('logging.conf') #f.read() cntr=0 for line in f: if "os.path.expanduser('~')" in line: #case we found the line we're looking for - now extract path info linePath=line cntr+=1 #note that with this version of logging.conf, we expect to find two lines - second one is the one we want if cntr != 2: print "found incorrect number of entries - ambiguous result warning" #print linePath parse0=linePath.split() parse1=parse0[2].strip(',",')+')' getPath=eval(parse1) f.close() return(getPath) def checkLogDirs(baseFilename): #extract directory name for logging logDir=os.path.dirname(baseFilename) #realize that logging is supporting multiple applications each using their own subdirectory tmp=os.path.split(logDir) #split the directory into the base directory name logBaseDir=tmp[0] #and into the log directory corresponding to this application logLogDir=tmp[1] #extract the filename from the logging.conf file too logFile=os.path.basename(baseFilename) #Having the directory info, we can check if these directories exist or not. #check if the main .Logging directory exists - if not, create it createDirs=False if not os.path.exists(logBaseDir): os.mkdir(logBaseDir) #now check if the logging subdirectory for this applicaton exists, if not, create it if not os.path.exists(logDir): os.mkdir(logDir) createDirs=True return(createDirs)
d1732d71aa7d7f75c8a2160fdda01af645e56ad0
huiyi999/leetcode_python
/Valid Palindrome.py
699
3.890625
4
class Solution: def isPalindrome(self, s: str) -> bool: s2=[x.lower() for x in s if x.isalnum()] for i in range(len(s2)//2): if s2[i]!=s2[len(s2)-1-i]: return False return True def isPalindrome2(self, s: str) -> bool: s=s.lower() n=filter(str.isalnum,s) s="".join(n) if (s==s[::-1]): return True else: return False so = Solution() print(so.isPalindrome("A man, a plan, a canal: Panama")) print(so.isPalindrome("race a car")) print(so.isPalindrome("0P")) ''' Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false '''
2965bbeb4ba9fe9ebe50f6aa6b5813030e671324
reddyprasade/Natural-Language-Processing
/Sequencing/sequences.py
863
3.546875
4
# Author:Reddy prasade import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer sentences = ["I love my dog", "I love my cat", "You Love my Dog!", "Do you thing my dog is amazing" ] ## oov_token="<OOV>" this Trick used for unreconized word in Sentence tokenizer=Tokenizer(num_words=100,oov_token="<OOV>") tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index ## Sequencing - Turning sentences into data (NLP Zero to Hero - Part 2) sequences = tokenizer.texts_to_sequences(sentences) print(word_index) print(sequences) test_data = ["i really love my dog", "my dog love my manager"] test_seq = tokenizer.texts_to_sequences(test_data) print(test_seq)
42531cd111ee2157ebf4c40c7e897c4c7cf70ba9
adeebshaikh/pythontraining
/python .py
1,172
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: x=10; if(x<15): print("the number is less than 15"); # In[1]: print(3>=3) # In[8]: x=10; if(x>15): print("hello good morning"); else: print("hello good afternoon"); # In[11]: x=10 y=5 if(x<y): print(x,"is smallest number") else: print(y,"is largest number") # In[19]: x=10 y=20 z=30 if(x>y and x>z): print("x is largest") elif(y>z and y>x): print("y is largest") else: print("z is largest") # In[22]: x=10 y=10 res=x*x res1=x*y if(x==y): print(res) else: print(res1) # In[24]: x=10 if(x<0): print("nagative number") elif(x>0): print(x,"positive") elif(x==0): print("zero") # In[2]: n =1 while(n<=10): print(n) n=n+1 # In[1]: n=10 while(n>=1): print(n) n=n-1 # In[1]: x=-22 while(x>=-45): print(x) x=x-1 # In[5]: x= int(input("enter lower limit")) y= int(input("enter the upper limit")) s=0 while(x<=y): if(x%2==0): s=s+x x=x+1 print(s) # In[2]: x=int(input("enter the number")) r=0 while(x>0): r=x%10 print(r) x=x//10 # In[ ]:
887d3ac755a9777cd4feba5526b7bf0f16defd40
JoseALermaIII/python-tutorials
/pythontutorials/Udacity/CS101/Lesson 18 - How Programs Run/Q27-Lookup.py
1,121
3.5625
4
# Define a procedure, # hashtable_lookup(htable,key) # that takes two inputs, a hashtable # and a key (string), # and returns the value associated # with that key. def hashtable_lookup(htable, key): bucket = hashtable_get_bucket(htable, key) for element in bucket: if key in element[0]: return element[1] return None def hashtable_add(htable, key, value): bucket = hashtable_get_bucket(htable, key) bucket.append([key, value]) def hashtable_get_bucket(htable, keyword): return htable[hash_string(keyword, len(htable))] def hash_string(keyword, buckets): out = 0 for s in keyword: out = (out + ord(s)) % buckets return out def make_hashtable(nbuckets): table = [] for unused in range(0,nbuckets): table.append([]) return table table = [[['Ellis', 11], ['Francis', 13]], [], [['Bill', 17], ['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]] print(hashtable_lookup(table, 'Francis')) # >>> 13 print(hashtable_lookup(table, 'Louis')) # >>> 29 print(hashtable_lookup(table, 'Zoe')) # >>> 14
253dd09a821ef1c4fe5d9167ad4d3d556a7de474
bregoh/Sorting-Algorithm
/quicksort/quicksort.py
1,423
4.375
4
import math # array = array to be sorted # low = start index of the array # high = end index of the array def quicksort(array, low, high): if low < high: # return the index of the small element partition_value = partition(array, low, high) # recursive method to sort array before and after partition quicksort(array, low, partition_value - 1) quicksort(array, partition_value + 1, high) def partition(array, low, high): small_element = (low - 1) middle_value = array[high] print("new array", array) for i in range(low, high): print("array[i] is : ", array[i]) print("middle value is :", middle_value) if array[i] <= middle_value: print(array[i], " <= ", middle_value) # swap the smallest value small_element += 1 temp = array[small_element] array[small_element] = array[i] array[i] = temp print(array) # swap the element print("swaping array[", small_element + 1, "] with array[", high, "]") temp2 = array[small_element + 1] array[small_element + 1] = array[high] array[high] = temp2 print("small element is : ", small_element + 1) #print(array) return small_element + 1 array_to_be_sorted = [10, 7, 8, 9, 1, 5] length = len(array_to_be_sorted) quicksort(array_to_be_sorted, 0, length - 1) print(array_to_be_sorted)
ed424714bf5ea94607c7e959bba3896b756b6e7a
MLoopz/CodeWars
/MostSales/MostSales.py
965
3.96875
4
def top3(products, amounts, prices): listOfProducts=list() listOfAmounts=list() for i in range(0,len(products)): listOfAmounts.append([amounts[i]*prices[i],i]) listOfAmounts.sort(key = sortFirst, reverse=True) for i in range(0,len(products)): listOfProducts.append(products[listOfAmounts[i][1]]) return listOfProducts[:3] def sortFirst(val): return val[0] print(top3(["Computer", "Cell Phones", "Vacuum Cleaner"], [3,24,8], [199,299,399]))# ["Cell Phones", "Vacuum Cleaner", "Computer"] print(top3(["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"], [5, 25, 2, 7, 10, 3, 2, 24], [51, 225, 22, 47, 510, 83, 82, 124]))# ['Vacuum Cleaner', 'Gold', ' Speakers'] print(top3(["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"], [0, 12, 24, 17, 19, 23, 120, 8], [9, 24, 29, 31, 51, 8, 120, 14]))# ['Lego', 'Gold', 'Computer']
5529e5fd2a89912cf7fe41c09525e5ed4376bc73
nandoribera/PYTHON
/lista5.py
1,236
4.0625
4
#usr/bin/python3 #Eliminar una plabra de la lista #Crear lista 1 print("¿Cuantas palabras tiene la primera lista?") palabras = input() palabras = int(palabras) frase = "" frase = list(frase) x = 0 while x < palabras: print("Dime la palabra ", x + 1) palabra = input() frase.append(palabra) x = x + 1 print("La lista creada es: ", frase) #Crear lista 2 print("¿Cuantas palabras tiene la lista de palabras a eliminar?") palabras2 = input() palabras2 = int(palabras2) frase2 = "" frase2 = list(frase2) x = 0 while x < palabras2: print("Dime la palabra ", x + 1) palabra = input() frase2.append(palabra) x = x + 1 print("La lista de palabras a eliminar es: ", frase2) #Crear conjuntos para simplificar el proceso de borrado conjunto1 = set(frase) conjunto2 = set(frase2) #Con esta sentencia se pueden borrar las coincidencias de la lista1 con la lista2 conjunto3 = conjunto1 - conjunto2 #Se pasa el conjunto otra vez a tipo lista conjunto3 = list(conjunto3) #Con este if se comprueba si ha cambiado la lista1 despues de la operacion #Si cambia la longitud de la lista significa que se ha modificado if len(conjunto3) == len(conjunto1): print("No coincide ninguna palabra") print("La lista Ahora es: ", conjunto3)
08af3cf7c8d6a274eaa87fcea3ea17be899503f9
here0009/LeetCode
/Python/310_MinimumHeightTrees.py
5,720
4.34375
4
""" For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. Format The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. Example 1 : Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] 0 | 1 / \ 2 3 Output: [1] Example 2 : Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 0 1 2 \\ | / 3 | 4 | 5 Output: [3, 4] Note: According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. """ from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges): """ TLE """ def dfs(node): visited[node] = 1 res = 0 for next_node in edges_dict[node]: if not visited[next_node]: res = max(res, dfs(next_node)+1) return res edges_dict = defaultdict(list) for i, j in edges: edges_dict[i].append(j) edges_dict[j].append(i) self.min_height = n + 1 self.res = [] for i in range(n): visited = [0] * n h = dfs(i) if h == self.min_height: self.res.append(i) elif h < self.min_height: self.min_height = h self.res = [i] return self.res from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges): """ TLE """ def dfs(node): visited[node] = 1 res = 0 for next_node in edges_dict[node]: if not visited[next_node]: res = max(res, dfs(next_node)+1) if res > self.min_height: return float('inf') return res edges_dict = defaultdict(list) for i, j in edges: edges_dict[i].append(j) edges_dict[j].append(i) self.min_height = n + 1 self.res = [] for i in range(n): visited = [0] * n h = dfs(i) if h == self.min_height: self.res.append(i) elif h < self.min_height: self.min_height = h self.res = [i] return self.res from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges): def dfs(node): visited[node] = 1 res = 0 for next_node in edges_dict[node]: if not visited[next_node] and matrix[node][next_node] == 0: tmp = dfs(next_node) + 1 matrix[node][next_node] = tmp matrix[next_node][node] = tmp res = max(res, tmp) return res edges_dict = defaultdict(list) for i, j in edges: edges_dict[i].append(j) edges_dict[j].append(i) self.res = [] self.max_height = n + 1 matrix = [[0] * n for _ in range(n)] for i in range(n): visited = [0] * n dfs(i) print(i) for row in matrix: print(row) for i in range(n): tmp = max(matrix[i]) if tmp == self.max_height: self.res.append(i) elif tmp < self.max_height: self.max_height = tmp self.res = [i] return self.res from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges): edges_dict = defaultdict(set) for i, j in edges: edges_dict[i].add(j) edges_dict[j].add(i) nodes = set(range(n)) while len(nodes) > 2: leaves = set(i for i in nodes if len(edges_dict[i]) == 1) nodes -= leaves for i in leaves: for j in edges_dict[i]: edges_dict[j].remove(i) return list(nodes) # https://leetcode.com/problems/minimum-height-trees/discuss/269060/Python-Topological from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges): edges_dict = defaultdict(set) for i, j in edges: edges_dict[i].add(j) edges_dict[j].add(i) q = [i for i in range(n) if len(edges_dict[i]) < 2] next_q = [] while True: for i in q: for j in edges_dict[i]: edges_dict[j].remove(i) if len(edges_dict[j]) == 1: next_q.append(j) if not next_q: break q, next_q = next_q, [] return q S = Solution() n = 4 edges = [[1, 0], [1, 2], [1, 3]] print(S.findMinHeightTrees(n, edges)) n = 6 edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] print(S.findMinHeightTrees(n, edges))
76654c745b37420a0ca5a9fa94f2126118543e14
mblasterx/Leetcode
/p21.py
1,364
4.125
4
from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self) -> str: returnStr = 'ListNode: ' + str(self.val) while self.next: self = ListNode(self.next) returnStr += '->' + str(self.val) return returnStr class Solution: '''https://leetcode.com/problems/merge-two-sorted-lists/ ''' def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: left = ListNode() right = left while l1 and l2: if l1.val < l2.val: right.next = l1 l1 = l1.next else: right.next = l2 l2 = l2.next # update the right pointer right = right.next if l1: right.next = l1 elif l2: right.next = l2 return left.next def test(self) -> None: testCases = [ # tuples of any variables we need to test ] for (l1, l2, expectedResult) in testCases: print(l1) assert self.mergeTwoLists(l1,l2) == expectedResult, (l1, l2, expectedResult, self.mergeTwoLists(l1,l2)) print('All tests passed') def main(): s = Solution() s.test() if __name__ == '__main__': main()
f12abd1eca89231dac545ce3f2a5b24d9cb92471
cha63506/Archive-304
/Battleship/ship.py
2,970
4.0625
4
class Fleet(object): """Fleet class object, a dictionary containing name of ships, \ as keys and ship dictionaries as values. Ship dictionary \ contains co-ordinate tuple as keys and ship \ status as values.""" def __init__(self, board): self.fleet = {} self.board = board def __repr__(self): return str(self.fleet) def __str__(self): return str(self.fleet) def __getitem__(self, ship): """(str) -> str Returns the ship in the fleet of the same name.""" return self.fleet[ship] def __setitem__(self, ship, value): """(str) -> bool Creates a ship value with the key string.""" self.fleet[ship] = value def __contains__(self, ship): """(str) -> bool Returns True if the ship is in the fleet, False otherwise.""" return ship in self.fleet def is_ship_dead(self, name): """NoneType -> bool Returns True if the ship has been destroyed, False otherwise.""" if name not in self.fleet: return None ship = self.fleet[name] for item in ship: if ship[item] != "HIT" and ship[item] != "SUNK": return False for item in ship: ship[item] = "SUNK" return True def is_fleet_dead(self): """NoneType -> bool Returns True if fleet is destroyed, False otherwise.""" if self.fleet == {}: return None for ship in self.fleet: if self.is_ship_dead(ship) is False: return False return True def name_ship(self, length): """Returns the name of the ship depending on given length.""" i = 1 for ship in self.fleet: if len(self.fleet[ship]) == length: i += 1 i = str(i) if length == 2: return "DEST" + i elif length == 3: return "SUBM" + i elif length == 4: return "BATT" + i elif length == 5: return "CARR" + i return None def add_ship(self, name, x, y, length, direction): """Adds a ship with given name on given co-ordinates and direction to the fleet.""" if length == 0: return if name in self.fleet: self.fleet[name][x, y] = name elif name not in self.fleet: self.fleet[name] = {} self.fleet[name][x, y] = name self.board[x, y] = self.fleet[name][x, y] if direction == "U": return self.add_ship(name, x, y - 1, length - 1, direction) elif direction == "D": return self.add_ship(name, x, y + 1, length - 1, direction) elif direction == "L": return self.add_ship(name, x - 1, y, length - 1, direction) elif direction == "R": return self.add_ship(name, x + 1, y, length - 1, direction)
8cb410b18cda30ba1c598128ad94c7a40ef05e87
wangshihui/TensorFlow_jcaptcha
/tensorFlow-Jcaptcha/python/test.py
1,690
3.796875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- Function: 【整理】Python中:self和init__的含义与使用 Verison: 2017-10-10 ------------------------------------------------------------------------------- """ #注:此处全局的变量名,写成name,只是为了演示而用 #实际上,好的编程风格,应该写成gName之类的名字,以表示该变量是Global的变量 name ="whole global name"; class Person: name ="11" def __init__(self, newPersonName): self.name = newPersonName; #1.如果此处不写成self.name #那么此处的name,只是__init__函数中的局部临时变量name而已 #和全局中的name,没有半毛钱关系 name =newPersonName;#此处的name,只是__init__函数中的局部临时变量name而已 #此处只是为了代码演示,而使用了局部变量name, #不过需要注意的是,此处很明显,由于接下来的代码也没有利用到此处的局部变量name #则会导致:此处的name变量,实际上被浪费了,根本没有被使用 def sayYourName(self): #此处由于找不到实例中的name变量,所以会报错: #AttributeError: Person instance has no attribute 'name' print('My name is %s'%(self.name)); def selfAndInitDemo(): personInstance =Person("crifan"); personInstance.sayYourName(); ############################################################################### if __name__=="__main__": selfAndInitDemo();
3665f608624bf46e84323be1d0aad7d5fe8a5a47
TheBjorn98/nummat_p2
/temptest.py
249
3.65625
4
import numpy as np def f(x): return x[0, :]**2 + x[1, :]**3 def df(x): return np.array([x[0, :]**2, x[1, :]**2]) xs = np.array([ [0, 0.0], [1, 1], [1, 2] ]).T print(xs) print(f(xs)) print(df(xs))
3cb060b63c6c26fcd7a72ae2212a6b913cce266f
daguerre33/Ping-with-sonar-effects
/ping_with_sonar_effect.py
1,825
3.53125
4
#!/usr/bin/python3 #Ping with sonar effect. A submarine feeling under the water of net #For realistic experience, please, use headphones! import os import time from tkinter import * window = Tk() window.title("Ping with sonar effect") window.geometry("300x200+30+50") def submit(): host = host_name.get() return host label = Label(window, text="Host or IP:") label.pack(side=TOP) host_name = Entry(window, bd=5) host_name.pack() def ping(event): host = submit() try: ping_message = [] ping_message.append(os.system("ping %s -c 1" % host)) if ping_message.__contains__(512): print("Please, give a real hostname or check your internet connection!") # Ping error code 512 elif ping_message.__contains__(256): os.system("mplayer sonar_ping.mp3") #instead of mplayer, you can use any other mp3 player starting from command line print("The host seems unreachable.") # Ping error code 256 else: os.system("mplayer sonar_ping.mp3") os.system("ping %s -c 1 > ping_data.txt" % host) #if you would like to preserve the earlier data, write '>>' instead of '>' time.sleep(1) #for a longer time to catch answer, use a bigger integer than '1' os.system("mplayer sonar_ping_back.mp3") os.system("cat ping_data.txt") except: print("Something went wrong. Please, try it later.") def report(event): os.system("nano ping_data.txt") #if you like can use your favorite editor instead of nano def quit(event): window.destroy() button1 = Button(window, text="Ping", fg="black", bd=5) button1.place(x=116, y=80) button1.bind("<Button-1>", ping) button2 = Button(window, text="Report", fg="black", bd=5) button2.place(x=10, y=150) button2.bind("<Button-1>", report) button3 = Button(window, text="Quit", fg="black", bd=5) button3.place(x=210, y=150) button3.bind("<Button-1>", quit) mainloop()
ad025157acda93edfcd4ce987bb2cdfb4c3b1d78
AmanKishore/CodingChallenges
/Cracking the Coding Interview/Trees and Graphs/BSTSequences.py
1,562
4.0625
4
''' BST Sequences: Enumerate all inserrtion sequences that could have led to the given BST. ''' # BST Sequences: A binary search tree was created by traversing through an array from left to right # and inserting each element. Given a binary search tree with distinct elements, print all possible # arrays that could have led to this tree. # SOLUTION: class Node: def __init__(self, key=None): self.data = key self.left = None self.right = None def permute(permutations, options): if len(options) == 0: return permutations total_permutations = [] for i in range(len(options)): option = options[i] new_options = options[:i] + options[i+1:] if option.left: new_options.append(option.left) if option.right: new_options.append(option.right) new_permutations = [] for permutation in permutations: new_permutations.append(permutation[:]) for new_permutation in new_permutations: new_permutation.append(option.data) total_permutations.extend(permute(new_permutations, new_options)) return total_permutations def bstSequences(root): return permute([[]], [root]) def main(): node_2 = Node(2) node_1 = Node(1) node_2.left = node_1 for sequence in bstSequences(node_2): print(sequence) print("") node_3 = Node(3) node_2.right = node_3 for sequence in bstSequences(node_2): print(sequence) print("") node_5 = Node(5) node_3.right = node_5 for sequence in bstSequences(node_2): print(sequence) print("") node_0 = Node(0) node_1.left = node_0 for sequence in bstSequences(node_2): print(sequence) main()
a544e849b7214973407275a44e6c0a5415a18ad1
bpandola/advent-of-code
/2019/day_01.py
1,115
3.875
4
def calculate_fuel_for_mass(mass): return mass // 3 - 2 def calculate_fuel_for_fuel(fuel_mass): fuel_needed = 0 fuel_for_fuel = calculate_fuel_for_mass(fuel_mass) while fuel_for_fuel > 0: fuel_needed += fuel_for_fuel fuel_for_fuel = calculate_fuel_for_mass(fuel_for_fuel) return fuel_needed def calculate_fuel_required(mass): fuel_for_mass = calculate_fuel_for_mass(mass) fuel_for_fuel = calculate_fuel_for_fuel(fuel_for_mass) return fuel_for_mass + fuel_for_fuel if __name__ == '__main__': puzzle_input = [int(i) for i in open('day_01.in').read().split('\n')] # Part 1 assert calculate_fuel_for_mass(12) == 2 assert calculate_fuel_for_mass(14) == 2 assert calculate_fuel_for_mass(1969) == 654 assert calculate_fuel_for_mass(100756) == 33583 print(sum([calculate_fuel_for_mass(m) for m in puzzle_input])) # Part 2 assert calculate_fuel_required(14) == 2 assert calculate_fuel_required(1969) == 966 assert calculate_fuel_required(100756) == 50346 print(sum([calculate_fuel_required(m) for m in puzzle_input]))
98e296669408816d204ecba87a6d76ce446f1964
zyp19/leetcode1
/树/twice.平衡二叉树.py
1,294
3.828125
4
# Definition for a binary tree node. # 6.11做发现问题:左右子树的深度不超过1,为什么要求最大深度呢,我不明白!!!!原来是树的深度(高度)的定义就是树中结点的最大层数!! # 自顶向下 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True return abs(self.height(root.left)-self.height(root.right))<2 and self.isBalanced(root.left) and self.isBalanced(root.right) def height(self, root): if not root: return 0 return max(self.height(root.left),self.height(root.right))+1 # 自底向上,没有想到 class Solution: # 后序遍历模板,使用递归的方法自底向上求解,自顶而下递归,然后自底向上处理: def isBalanced(self, root: TreeNode) -> bool: return self.recur(root) != -1 def recur(self, root): if not root: return 0 left = self.recur(root.left) if left == -1: return -1 right = self.recur(root.right) if right == -1: return -1 return max(left, right) + 1 if abs(left - right) < 2 else -1
1bcd687428c5be5e835a3fb604772af2be150d0b
rpuneet/The-Game
/Maze.py
2,339
4
4
''' This class is used to store data about the maze. The matrix contains strings which refer to the image in the tile folder. ''' import pygame import json import os class Maze(): def __init__(self , matrix_data_path): ''' Initialises the maze. Loads the maze information from matrix_data_path. Parameters- (string) matrix_data_path - Location of the json file to get matrix data. ''' # Check if given path exists. if not os.path.exists(matrix_data_path): raise Exception("File does not exist : {}".format(matrix_data_path)) # 2D array containing information of each cell i.e. what image is to be drawn. with open(matrix_data_path , "r") as matrix_file: self.matrix = json.load(matrix_file) self.cell_width = 24 # Width of each cell. self.cell_height = 24 # Height of each cell. self.x_length = len(self.matrix[0]) # Number of columns. self.y_length = len(self.matrix) # Number of rows. self.images , self.positions = self.get_images_positions() def get_images_positions(self): ''' Loads all the tile images from local directory and also store all the (x,y) position for each cell. Returns- images (images of all the cells) , positions ((x,y) position of all the cells). ''' images = [[0 for i in range(self.x_length)] for j in range(self.y_length)] positions = [[0 for i in range(self.x_length)] for j in range(self.y_length)] for y in range(self.y_length): for x in range(self.x_length): if "pellet" in self.matrix[y][x]: file_name = self.matrix[y][x]+".png" else: file_name = self.matrix[y][x]+".gif" images[y][x] = pygame.image.load(os.path.join(os.getcwd() , "res" , "tiles" , file_name)).convert() positions[y][x] = [x * self.cell_width , y * self.cell_height] return images , positions def update(self , window_surface): ''' Update the screen with all the walls ''' for y in range(self.y_length): for x in range(self.x_length): window_surface.blit(self.images[y][x] , self.positions[y][x])
a672902062bff65815399258a033c9fa33345d52
LittleEndu/Codeforces
/Python/Unsorted/271a_v2.py
258
3.8125
4
# Smallest: # a=int(input())+1 # while len(set(str(a)))<4: # a+=1 # print(a) # Don't use if inside while loop.... # But, trick here was the +1 to input() so it acts as a "do while" loop b=int(input()) while 1: b+=1 if 4==len(set(str(b))):print(b);break
488404e2e9979f74c43d45a4fe9424b1f3b522c9
ZigaHocevar/ugani_stevilo
/course1.py
306
3.78125
4
num = 1 while num < 10: print(num) num = num + 1 num1 = 25 num2 = 38 num3 = 25 print(num1 == num2) print(num1 == num3) odgovor = "da" while odgovor == "da": odgovor = raw_input("Ali zelis biti v zanki? (da/ne)") while True: print("vstop v zanko") break print("nismo vec v zanki")
844bc36ac71c2f4f18e6203aa7d45b3cdb108690
jpl1991/Machine-Learning
/Python/sort2DArray2.py
482
3.765625
4
def sortMatrix(matrix): row_len = len(matrix) col_len = len(matrix[0]) #temp = [0]*(row_len*col_len) temp = [] for rows in matrix: for col in rows: temp.append(col) temp.sort() k = 0 for i in range(0, row_len): for j in range(0, col_len): matrix[i][j] = temp[k] k+=1 return matrix matrix = [[ 5, 12, 17, 21, 23], [ 1, 2, 4, 6, 8], [12, 14, 18, 19, 27], [ 3, 7, 9, 15, 25]] sorted_matrix = sortMatrix(matrix) print(sorted_matrix) print(int(3/2))
bd5c56ad04da056a964a797ce8e4f4c466a4f9fc
Zer0xPoint/LeetCode
/lib/search/binary_search.py
417
3.71875
4
def binary_search(items, start_idx, end_idx, target): while start_idx <= end_idx: mid_idx = start_idx + (end_idx - start_idx) // 2 if items[mid_idx] == target: return mid_idx elif items[mid_idx] < target: start_idx = mid_idx + 1 else: end_idx = mid_idx - 1 return -1 nums = [1, 2, 3, 4, 6] print(binary_search(nums, 0, len(nums) - 1, 5))
720b9bfb66ee3018802c41b4140769a28756332a
bobur554396/PPII2021Spring
/w3/4_Class.py
131
3.8125
4
# class class MyClass: x = 10 b = 'hello' a = MyClass() # a is object of the class print(a.x) print(a.b) a.x = 20 print(a.x)
071ff16dc734dc642a1891276b5f259acbd1fb3c
acarter881/exercismExercises
/collatz-conjecture/collatz_conjecture.py
341
3.890625
4
def collatz(n): if n % 2 == 0: return n // 2 return 3 * n + 1 def steps(number): if number < 1: raise ValueError('Can\'t use a number less than 1') iter = 0 while number != 1: iter += 1 if collatz(number) == 1: break number = collatz(number) return iter
48163fb16dbf855b626d1501e9b8c41f29133010
MaxGosselin/mpltutorial
/2-legendsTitles.py
875
3.90625
4
#%% [markdown] # # 2 - Legends titles and labels # # Following the matplotlib tutorial by sentdex. # # Link: https://www.youtube.com/watch?v=q7Bo_J8x_dw&list=PLQVvvaa0QuDfefDfXb9Yf0la1fPDKluPF #%% import matplotlib.pyplot as plt #%% # Simple plot with labels and titles x = [1,2,3] y = [5,7,4] plt.plot(x,y) plt.xlabel('Plot Number') plt.ylabel('Important Variable') #%% [markdown] # You can also add a title. #%% plt.plot(x,y) plt.xlabel('Plot Number') plt.ylabel('Important Variable') plt.title('Interesting Graph!\nCheck it out.') plt.show() #%% [markdown] # You can also add a legend if you have multiple series to plot. #%% x2, y2 = [7, 2, 4], [7, 9, 2] plt.plot(x, y, label='Series 1') plt.plot(x2, y2, label='Series 2') plt.xlabel('Plot Number') plt.ylabel('Important Variable') plt.title('Interesting Graph!\nCheck it out.') plt.legend() plt.show()
4530cc136b7609ce473ed01c6a885eef747963fa
chrimerss/FloodDetectionUsingSAR
/env/lib/python3.6/site-packages/arcgis/learn/_utils/utils.py
576
4
4
def extract_zipfile(filepath, filename, remove=False): """ Function to extract the contents of a zip file Args: filepath: absolute path to the file directory. filename: name of the zip file to be extracted. remove: default=False, removes the original zip file after extracting the contents if True """ import os, zipfile with zipfile.ZipFile(os.path.join(filepath, filename),"r") as zip_ref: zip_ref.extractall(filepath) if remove: os.remove(os.path.join(filepath, filename))
11d03787bed76c939ece41c927f6cee1a71967a7
Ricky-Millar/100-days-of-python
/etchasketchtutrle/main.py
1,818
4
4
import turtle import matplotlib.pyplot as plt import random board = turtle.Screen() board.colormode(255) width = 500 height = 400 startpos = [] turtleholder = {} board.setup(width = width,height = height) height *= 0.9 numofturtles = int(turtle.textinput('who','how many turtles?')) def randomcolor(): color = [] for i in range(3): color.append(random.randrange(0,255)) return color def create_start_pos(numofturtles): spacing = height / numofturtles+2 x = int((-width)/2) base = (-height/2) for i in range(numofturtles): y = int(base + spacing*i) startpos.append([x,y]) for i in range(numofturtles): color = randomcolor() turtleholder['competitor' + str(i)] = turtle.Turtle() turtleholder['competitor' + str(i)].shape('turtle') turtleholder['competitor' + str(i)].color(color) turtleholder['competitor' + str(i)].penup() turtleholder['competitor' + str(i)].setpos(startpos[i][0],startpos[i][1]) turtleholder['competitor' + str(i)].pendown() turtleholder['competitor' + str(i)].setheading(0) print(create_start_pos(numofturtles)) winner = 0 game = True user_bet = turtle.textinput('take your betss','WHOOO GUN WIN?') def progress_race(): global game , winner for i in range(numofturtles): turtleholder['competitor' + str(i)].forward(random.randrange(0,20)) if turtleholder['competitor' + str(i)].xcor() >= int((width/2)-20): game = False winner = i return while game == True: progress_race() WinningTurtle = winner+1 if int(user_bet) == WinningTurtle: print(f'Turtle number {WinningTurtle} won! Congratz') else: turtleholder['competitor' + str(winner)].write("you lose", True, align="left") board.exitonclick()
cafef96daeb2f6656a094cde29c2d5908403b001
Fin-M/Basic-Calculator
/Basic Calculator.py
949
4.28125
4
print("\nThis is a Basic Calculator!") first = float(input("\nWhat is your first number?: ")) second = float(input("What is your second number?: ")) operator = input("What do you want to do with the numbers (multiply, divide, add, subtract or power)?: ") if operator == "multiply": print("\nThe answer is:", first * second) elif operator == "divide": answer = first / second print("\nThe answer is:", answer) dp = round(answer, 2) print("or:", dp, "rounded to 2 decimal places.") elif operator == "add": print("\nThe answer is:", first + second) elif operator == "subtract": print("\nThe answer is:", first - second) elif operator == "power": print("\nThe answer is:", first ** second) else: print("\n[Error]") print("The number or operator you entered was incorrect. Read the instructions carefully and try again!") print("\n[Coded, edited and updated by Fin-M]\n")
18eb03a6ef45c46aa765d647f12086f51cabd29b
HappyRocky/pythonAI
/ABC/powerseries.py
330
4.0625
4
# 计算幂级数: e^x = 1 + x + x^2/2! + ... + x^n/n! (0 < x < 1, n -> 去穷大) import math x = float(input("Input x(0 < x < 1):")) N = int(input("Input N:")) result = 1 unit = 1 for i in range(1, N): unit = unit * x / i result += unit print("result:{}".format(result)) print("accurate e^x = {}".format(math.exp(x)))
3c07a20c591cf80ba8495afbb65e39c4811e84dd
daniel-reich/ubiquitous-fiesta
/K4aKGbfmzgyNNYEcM_11.py
99
3.515625
4
def is_shape_possible(n, angles): return (n-2)*180==sum(angles) and all(x<180 for x in angles)
a5ca84687e3c832d69bc70fa2537d8b6d3ce5035
aesdeef/advent-of-code-2020
/day_11/seat_part_1.py
1,566
3.921875
4
from functools import cached_property class Seat: collection = {} def __init__(self, x, y): """ Initialises the seat and adds it to the collection """ self.x = x self.y = y self.occupied = False self.occupied_new = False Seat.collection[(self.x, self.y)] = self @cached_property def adjacent(self): """ Finds all seats that are next to this seat """ seats = set() for dx in (-1, 0, 1): for dy in (-1, 0, 1): if not (dx == 0 and dy == 0): seat_x = self.x + dx seat_y = self.y + dy if (seat_x, seat_y) in Seat.collection.keys(): seats.add(Seat.collection[(seat_x, seat_y)]) return seats def get_new_state(self): """ Determines whether the seat should be occupied in the next iteration """ if not self.occupied and not any(seat.occupied for seat in self.adjacent): self.occupied_new = True elif ( self.occupied and len({seat for seat in self.adjacent if seat.occupied}) >= 4 ): self.occupied_new = False def set_new_state(self): """ Sets the new value of occupied and returns True if it's different from the current one, otherwise returns False """ if self.occupied != self.occupied_new: self.occupied = self.occupied_new return True return False
8f597486d274f380cef6e6b6b90d9e907ea713e2
reddyprasade/A-Criterion-for-Deciding-the-Number-of-Clusters-in-a-Dataset-Based-on-Data-Depth
/Elbow_Method.py
1,039
4.125
4
""" It is the most popular method for determining the optimal number of clusters. The method is based on calculating the Within-Cluster-Sum of Squared Errors (WSS) for different number of clusters (k) and selecting the k for which change in WSS first starts to diminish. The idea behind the elbow method is that the explained variation changes rapidly for a small number of clusters and then it slows down leading to an elbow formation in the curve. The elbow point is the number of clusters we can use for our clustering algorithm. """ # pip install -U yellowbrick # Elbow Method for K means # Import ElbowVisualizer from yellowbrick.cluster import KElbowVisualizer from sklearn import datasets from sklearn.cluster import KMeans iris = datasets.load_iris() cluster_df = iris.data model = KMeans() # k is range of number of clusters. visualizer = KElbowVisualizer(model, k=(2,30), timings= True) visualizer.fit(cluster_df) # Fit data to visualizer visualizer.show() # Finalize and render figure
2157648b72090b7ad9a61dbe9a22d7df9eef730e
jokly/Biometric-AccessCode
/DataHandler/Reader.py
2,003
3.515625
4
""" Module for reading input files """ import re import os def read_matrix_files(files_path, n_el, m_com): """Read files and convert to list of float matrixes """ out = [] for f_path in files_path: if os.stat(f_path).st_size != 0: out.append(read_matrix_file(f_path, n_el, m_com)) return out def read_matrix_file(file_path, n_el, m_com): """Read file and convert to float matrix[n, m] :param file_path: Path to file :type file_path: str :param n_el: Rows number :type n_el: int :param m_com: Columns number :type m_com: int :returns: list of lists of float """ with open(file_path, 'r') as fin: print(file_path) data = list(map(float, re.split('[ \n\t]+', fin.read().strip()))) return list_to_matrix(data, n_el, m_com) def list_to_matrix(input_data, n_el, m_com): """Convert list to float matrix[n, m] :param input_data: List of data :type input_data: list :param n_el: Rows number :type n_el: int :param m_com: Columns number :type m_com: int :returns: list of lists of float """ if n_el * m_com > len(input_data): raise IndexError output_matrix = [[0 for j in range(0, m_com)] for i in range(0, n_el)] for i in range(0, n_el): for j in range(0, m_com): output_matrix[i][j] = input_data[i * m_com + j] return output_matrix def read_k1(file_path): """Read k1 string from file and convert to integer list :param file_path: Path to file :type file_path: str :returns: list of int """ with open(file_path, 'r') as fin: return list(map(int, re.split('[ \n\t]+', fin.read().strip()))) def read_k2(file_path): """Read k2 string from file and convert to integer list :param file_path: Path to file :type file_path: str :returns: list of int """ with open(file_path, 'r') as fin: return list(map(int, re.split('[ \n\t]+', fin.read().strip())))
b0cbb3e8ee17a16bb117c0be8da96e2254d4e1d5
mlumsden001/University-Notes
/INFO1110/functions/max.py
176
3.53125
4
num = [1, 5, 3, 8, 9 ,12, 420] def funct(num): if len(num) > 0: return max(num) elif len(num) == 0: return None num = [] funct(num) print(funct(num))
65ef73724bd75bd6c2ebdac0cff3739ad4c2575a
Anjitha-mundanmani/ERP
/team.py
1,934
3.625
4
import employee as em teams = {} def manage_all_team_menu(): print("\t1.Create Team") print("\t2.Display Team") print("\t3.Manage Team(Particular)") print("\t4.Delete Team") print("\t5.Exit") def create_team(): team_name = input("\tEnter team name ") teams[team_name] = [] def delete_team(): team_name = input("\tEnter team name ") if team_name in teams.keys(): del teams[team_name] print("\tDeleted the team") else: print("\tWrong team name") def display_teams(): for key,value in teams.items(): name_string = "" for i in value: name_string = name_string +"|"+em.employees[i]["name"] print(f"{key} => {name_string}") def manage_team_menu(): print("\t1.Add Member") print("\t2.Delete Member") print("\t3.List Members") def manage_team(): team_name = input("\t\tEnter team name ") manage_team_menu() ch = int(input("\t\t Enter your Choice ")) if ch == 1: add_member(team_name) elif ch == 2: delete_member(team_name) elif ch == 3: list_member(team_name) else: print("\tInvalid choice") def add_member(team_name): em.display_employee() serial_no = input("\t\tEnter the serial no ofemployee ") if serial_no in em.employees.keys(): teams[team_name].append(serial_no) else: print("\t\tWrong serial No.") def list_member(team_name): name_string="" for i in teams[team_name]: name_string = name_string +"|"+i+"."+em.employees[i]["name"] print(f"{name_string}") def delete_member(team_name): list_member(team_name) serial_no = input("\t\tEnter serial no from list") if serial_no in teams[team_name]: teams[team_name].remove(serial_no) else: print("\t\tWrong serial No.") def manage_all_teams(): while True: manage_all_team_menu() ch = int(input("\tEnter your choice ")) if ch == 1: create_team() elif ch == 2: display_teams() elif ch == 3: manage_team() elif ch == 4: delete_team() elif ch == 5: break else: print("\tInvalid choice")
b4862f244015e0b36793057f1f66a41e3c2c53d2
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/omrkha003/question1.py
695
4.28125
4
# program with a recursive function to determine if a string is a palindrome # khadeejah omar # 4 May 2014 def palindrome(string) : # base case if string == "" or len(string) == 1: return ("Palindrome!") # recursive step else: if string[0] == string[-1] : return palindrome(string[1:-1]) # if the first letter and last letter of string is the same, slice those letters off and do recursive step again else : return ("Not a palindrome!") # if the first letter and last letter of the string is not the same def main() : string = input("Enter a string: \n") print(palindrome(string)) main()
b671981e4bb111d373cf91c49ddbb9ac979396dd
hutonahill/python-sjcc
/Evan Project/PythonChat.py
8,338
3.78125
4
def delete(): running = True while running == True: test = raw_input('Runing This Command Will Deleate ALL Posts, And Is Irreversible. Are You Sure You Want To Do This?(y/n): ') if test != 'n'and test != 'y': print "That Is Not A Valid Answer Please Answer 'y' Or 'n'" elif test == 'y': wPosts = open('posts.txt','w') wPosts.write('') wPosts.close() running = False elif tests == 'n': print "Program Aborted." running = False #------------------------------------------- def recall(): posts = open('posts.txt') posts = posts.read() print posts #------------------------------------------- def writePost(user,post): postFile = open('posts.txt','a') x = ' %s: %s\n' %(user,post) postFile.write(x) postFile.close() #------------------------------------------- def loginChecker(username,password): userPassword = username+':'+password userList = open('userTest.txt') userList = userList.read() if userPassword in userList: return True else: return False #------------------------------------------- def userCheck(username): #checks for a username in login if username in lit: return True else: return False #------------------------------------------- def whichUser(user): #returns the number of a user import ast x = ast.literal_eval(text) return x.index(user) #------------------------------------------- def userCount(): #returns the number of users x=True y=-1 while x==True: y+=1 raw = open("users.txt") raw = raw.read() users = raw.split(",") try: z = users[y] except IndexError: x=False if x==False: return y #------------------------------------------- def newUserCheck(username): #checks for duplicit usernames dureing regitration if username in lit: return False else: return True #------------------------------------------- def register(): ### The bulk of the following code was provided by Qi Jing with premition. Thanks. ### # Register a new user and password # The userTest.txt file must have this format for each record: user_name:password # Also the user name and password cannot contain BLANK and ":". raw = open("userTest.txt", "a+") text = raw.read().split() raw.close() user_list = [] password_list = [] new_user_flag = False # Split each element to user and password and append to the 2 lists if len(text) != 0: for item in text: user_name, password = item.split(":") user_list.append(user_name) password_list.append(password) while True: user_input = raw_input("Enter User Name ['stop' to end this program]:") if user_input.lower() == "stop": new_user_flag = False print "Program Ended" break new_user_flag = True if " " in user_input or ":" in user_input: print "Sorry, User Name cannot have BLANK or ':'. Please Re-Enter!" continue if user_input in user_list: print "The User Name You Entered already Exists. Please Try A Difrent One" continue while True: password_input1 = raw_input("Enter Password ['stop' to end this program]: ") if password_input1.lower() == "stop": new_user_flag = False print "Program Ended" break if " " in password_input1 or ":" in password_input1: print "Sorry, Password cannot have BLANK or ':'. Please Re-Enter!" continue password_input2 = raw_input("Re-enter Password: ") if password_input1 != password_input2: print "Sorry the Password You Entered Doesn't Match. Please Try Again!" continue break # We are all set and need to exit the loop break if new_user_flag == True: print "Good job. Your new user name is registered." # We need to append the new user to the file userTest.txt string = "{" + "'" + user_input+"':'"+password_input1+"'}\n" raw = open("userTest.txt", "a+") raw.write(string) raw.close() #------------------------------------------- def startProgram(): #runs the program #pre recs import ast class InputError(ValueError): pass raw = open("userTest.txt") text = raw.read() lit = text users = text.split(",") login = False print 'Welcome to Python Chat.' running = True #loop starts while running == True: running = True #request a command com = raw_input("Please Input A Command: ") com = str(com.lower()) ##test the command #login command if com == 'log in': username = raw_input("Input Your Username: ") password = raw_input('Please Enter Your Password: ') login = loginChecker(username,password) if login == True: print 'You Are Now Loged In' else: print 'an error has ocured ' print '' #Register new user command elif com == 'register': print "in register" register() print '' #running = False #help command elif com == 'help': print 'help ==> you are here. you should know what this does.' print 'log in ==> this command allows you to log in to Python Chat with an existing username and password' print 'register ==> this command allows you to create a username and password' print 'post ==> this allows you to post.' print 'recall ==> this allows you to call up old posts' print 'stop ==> this stops the program' print '' #running = False #post command elif com == 'post': if login == True: post = raw_input('Please Type Your Post(you may not include "\\n")') if '\n' in post: raise InputError('you may not user \\n') writePost(username,post) print'Post Posted' print '' #running = False else: print 'Sorry, You Must Log In To Acses This Feature' print '' #running = False #recall command elif com == 'recall': if login == True: recall() print'' #running = False else: print 'Sorry, You Must Log In To Acses This Feature' print '' #running = False elif com == 'stop': running = False print '' #delete command(admin user only) elif com == 'delete': if login == True: if username == 'Admin': delete() print '' else: print 'You Must Be The Admin To Run This Command' #running = False else: print 'Sorry, You Must Log In To Acses This Feature' print '' #check for invaliad commands else: print 'You Have Not Entered An Invalled Command. Please try Again. You May Type "help" For Help.' print '' #running = False print 'Program Has Stoped'