blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ee0ca87dc7393247fc507193b6ef22c4c97c1293
MeitarEitan/Devops0803
/9.py
343
3.796875
4
def saveNames(): inputUser = input("Enter your name:") myNewFile = open("names.txt", "a") myNewFile.write(inputUser + "\n") myNewFile.close() def printNames(): file = open("names.txt", "r") for name in file.readlines(): print(name, end=" ") file.close() saveNames() saveNames() saveNames() printNames()
17c0945cae7677615b0f2b181b12505ebfadb0fd
varunpsr/python-ds
/binary-search-tree.py
2,061
4.0625
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): if self is not None: return f"{self.value}" else: return "None" class BinarySearchTree: def __init__(self): self.root = None def add_node(self, node): print(f"Adding node: {node}\n") if self.root is None: self.root = node print(f"Added root node: {self.root}") else: current_node = self.root while True: if node.value < current_node.value: if current_node.left is None: current_node.left = node print(f"Adding {node} to left of {current_node}") break current_node = current_node.left else: if current_node.right is None: current_node.right = node print(f"Adding {node} to right of {current_node}") break current_node = current_node.right def print_preorder(self, node): if node is not None: print(node) self.print_preorder(node.left) self.print_preorder(node.right) def print_postorder(self, node): if node is not None: self.print_postorder(node.left) self.print_postorder(node.right) print(node) def print_inorder(self, node): if node is not None: self.print_inorder(node.left) print(node) self.print_inorder(node.right) root = Node(7) two = Node(2) five = Node(5) nine = Node(9) eleven = Node(11) bst = BinarySearchTree() bst.add_node(root) bst.add_node(two) bst.add_node(five) bst.add_node(nine) bst.add_node(eleven) bst.print_preorder(bst.root) bst.print_inorder(bst.root) bst.print_postorder(bst.root)
6e49ad323b536ee1e669d1ce643959b66da67823
python-fisika-uin/Fundamental
/fundamental001.py
1,367
3.8125
4
# Sintaks Sekuensial print('Hello World!') nama = 'Eko S.W' usia = 40 Usia = 50 #ini berbeda dengan usia (huruf kecil) print(nama, 'Usia=', usia) # Sintaks bercabang if usia <= 40: print('Masih muda') print('Usia belajar') print('Usia mencari jatidiri') else: print('Tak muda lagi') print('Banyakin tobat') print('Pikir anak cucu') #sintaksis perulangan jumlah_anak = 2 for iterasi in range(1, jumlah_anak+1): print('Halo anak ke', iterasi) # contoh lain: menghitung 1+2+3+4+5 = 15 jumlah_bilangan = 5 total_penjumlahan = 0 for bilangan in range(1, jumlah_bilangan+3): total_penjumlahan = total_penjumlahan + bilangan print('Hasil penjumlahan', total_penjumlahan) # cara membaca baris ke 27 """ 1. total_penjumlahan = 0 + 1 = 1 2. total_penjumlahan = 1 + 2 = 3 3. total_penjumlahan = 3 + 3 = 6 4. total_penjumlahan = 6 + 4 = 10 5. total_penjumlahan = 10 + 5 = 15 6. total_penjumlahan = 15 + 6 = 21 7. total_penjumlahan = 21 + 7 = 28 """ #tipe data array uang_untuk_anak = [] #tipe data array uang_untuk_anak.append(10000) uang_untuk_anak.append(5000) uang_untuk_anak.append(50000) # berapa rata2 uang untuk tiap anak? jumlah_total_uang = 0 for uang in uang_untuk_anak: jumlah_total_uang = jumlah_total_uang + uang print('Jumlah total uang', jumlah_total_uang) rata_rata_uang = jumlah_total_uang / 3 print('Rata-rata uang', rata_rata_uang)
bc8744b8265be788f974f5bd0a5c9b24f26da35d
xinzheshen/py3-practice
/src/cookbook/09_yuanbiancheng/decoretor0.py
735
3.546875
4
import time from functools import wraps def timethis(func): ''' Decorator that reports the execution time. ''' # 注意加不加@wraps的区别 @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrapper @timethis def hello(msg: str): """ print the message after sleep 2s """ time.sleep(2) print(msg) hello("decoretor") print(hello.__name__) print(hello.__doc__) print(hello.__module__) print(hello.__annotations__) print(hello.__wrapped__("hi")) from inspect import signature # 打印参数签名信息 print(signature(hello))
03175236c641b680cf7e47e78e13c6f3bece9a72
Aptegit/Assignment1
/new_testcode.py
751
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: obill =float(input('How much is your original bill? ')) #input string # In[2]: print(type(obill)) #to check the data type of variable # In[3]: tip = int(input('What percentage is your tip?')) #input string # In[4]: print(type(tip)) #to check the data type of variable # In[5]: f1 = obill*tip #calculating percentage using standard percentage formula ftip= float("{:.2f}".format(f1/100)) print (ftip) print('Your tip based on ' + str(tip) + ' % is ' + str(ftip) + ' $ . ') # In[6]: fbill = obill + ftip #adding tip percent value to the original bill #print(type(obill)) #print(type(ftip)) print('Your total bill is : ' + str(fbill) + ' $ . ')
f7202c99351112f2da3783118059f6d02c040d1d
jameswong95/ICT1008
/block_stack.py
1,341
3.890625
4
class Stack: top = -1 def __init__(self): self.top = -1 # this stack is implemented with Python list (array) self.data = [] def size(self): return len(self.data) def push(self, value): # increment the size of data using append() self.data.append(value) self.top += 1 def pop(self): self.top -= 1 return self.data.pop() def isEmpty(self): size = self.size() if size == 0: return True else: return False def peek(self): if not self.isEmpty(): return self.data[self.size()-1] else: return False def peekAt(self, pos): return self.data[pos] def copyTo(self): stack = Stack() for ele in self.data: stack.push(ele) return stack def toString(self): string1 = "" size = len(self.data) if size > 0: for i in reversed(xrange(size)): string1 += str(self.data[i]) elif size is 0: string1 += " " return string1 def printStack(self): print self.data def contains(self, value): for i in range(len(self.data)): if self.data[i] is value: return i return -1
8e803130fffcc7f8139e4125c2e1fa451becba71
binjun/LeetCode
/longestpalindromicsubstring.py
1,196
4.0625
4
# -*- coding: utf-8 -*- """ Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example2: Input: "cbbd" Output: "bb" """ import unittest class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ ret = "" length = len(s) if length <= 1: return ret for i in range(length, 1, -1): for j in range(length - i + 1): substring = s[j:i+j] #print "substring = %s" % substring if substring == substring[::-1]: ret = substring break else: continue break return ret solution = Solution() class myUnittest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testcase1(self): self.assertEqual(solution.longestPalindrome("babad"), "bab") def testcase2(self): self.assertEqual(solution.longestPalindrome("cbbd"), "bb") unittest.main()
2512fbd72639a9c9d35adad3ddbb2c4e9b032ace
shivam-72/simple-python
/PYTHON FUN/lovecalculator.py
798
3.890625
4
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") name1.lower() name2.lower() name3 = name1+name2 T = name3.count("t") R = name3.count("r") U = name3.count("u") E = name3.count("e") total = str(T+R+U+E) L = name3.count("l") O = name3.count("o") V = name3.count("v") E = name3.count("e") total2 = str(L+O+V+E) total3 = total+total2 value = int(total3) if value >= 0 and value <= 25: print(f'your score is {total3}, you are decent couple') elif value > 25 and value <= 50: print(f'your score is {total3}, you are alright together') elif value > 50 and value <= 75: print(f'youour score is {total3}, you love is unconditional') else: print(f' your score is {total3}, purest form of love')
e547651f91838d65f910be328522ef1e196652a4
salemmp/memorize-words
/words.py
1,626
3.71875
4
import os import sys import time lista = {"hello":"hola", "word":"palabra", "phone":"celular", "hand":"mano", "how":"como", "people":"gente", "leave":"salir", "key":"tecla", "understand":"entender", "can":"poder", "we":"nosotros", "he":"el", "she":"ella", "low":"bajo", "high":"alto", "someone":"alguien", "head":"cabeza", "table":"mesa", "room":"cuarto", "bathroom":"baño"} #contador aciertos = 0 #obtenemos llaves llaves = lista.keys() ################################################# for x in llaves: valor = lista.get(x) respuesta = input (x +" is? ") if respuesta == valor: print("correcto!!!") aciertos = aciertos + 1 time.sleep(1) os.system("cls") else: print("incorrecto") time.sleep(0.3) os.system("cls") ################################################################## if (aciertos >= 1) and (aciertos <5): print(str(aciertos)+ '/20') salida = input("Mal , sigue estudiando") if (aciertos >=5) and (aciertos<10): print(str(aciertos)+ '/20') salida = input("puedes mejorar") if aciertos >=10 and aciertos <15: print(str(aciertos)+ '/20') salida = input("intermedio.. nada mal") if aciertos >=15 and aciertos <20: print(str(aciertos)+ '/20') salida = input("muy bien ! sigue asi") if aciertos == 20: print(str(aciertos)+ '/20') salida = input("Excelente!! ")
a383e4a8701f7c9ab85f7295dc309bb4609902f9
lianhuo-yiyu/python-study
/study9 str/main.py
464
4.09375
4
#str的驻留机制 指相同的字符串只会占据一个内存空间,一个字符串只被创建一次,之后新的变量是获得之前的字符串的地址 a = 'python' b = "python" c = """python""" print(id(a)) print(id(b)) print(id(c)) s1 = '' s2 = '' print(s1 == s2) print(s1 is s2) print(id(s1)) print(id(s2)) #理论上有特殊字符串不驻留,下面这个cmd不驻留,pycharm进行了优化 z1 = 'a%' z2 = 'a%' print(id(z1)) print(id(z2))
94c2379bf1ab91f31e7fcb57dee06b37b00d3a14
lianhuo-yiyu/python-study
/study6 dict/main.py
824
4.09375
4
#字典 { } 可变序列 dict 以键值对的方式存储数据 {name : hhh}:前面的叫键,:后面的叫值 字典是无序的序列 字典存储是key时经过hash计算 #字典的键key不允许重复,只有值可以重复,后面的键值会覆盖相同的键名 列表可以按照自己的想法找地方插入元素,dict不行,它是无序的 字典空间换时间,内存浪费大 zidian = {'name' : 'python' , "nianling" : 24} print(zidian) c = dict(name = 'python', nian = 100) print(type(c)) print(c) #字典中的值获取 print(zidian['nianling']) #print(zidian['nian']) print(c.get('nian')) print(c.get('nianling')) print(c.get('nianling', 'bucunzai')) #可以让返回的none值变成不存在 #列表可以按位置插入 lst =[5,6,9,7,5,0,5] lst.insert(1, -1) print(lst)
1f5f1540137ef46b49d62027955fa15f46dc14e1
lianhuo-yiyu/python-study
/STUDY10 函数/递归函数.py
393
3.875
4
# Python 学习 1 # 2020/11/28 17:12 #递归函数 一个函数调用自己 #递归用来计算阶乘 def fac(n): if n ==1: return 1 else: return n *fac(n - 1) print(fac(6)) def text(n): for i in range(1,n): if i == 1 : print('1') elif i == 2 : print('1','1') elif i != 1 and i !=2 : print(555 + i) print(text(5))
5cd01bde10307074f0c003b09c034b799fb36965
lianhuo-yiyu/python-study
/STUDY10 函数/main.py
1,775
4.0625
4
#函数的原理与利用 #函数的创建 #def 函数名([输入参数]): # 函数体 # [return xxx] def cale(a,b): # c = a + b c = a - b return c result = cale(10,20) print(result) #函数调用时的参数传递 创建的时候函数括号里面是def hhh(形参,形参), 在函数的调用处,括号里面的是实参,实际参数 形参和实参的名字可以不相同 #参数的传递(实参的值传给形参) #1 位置实参 如上例,按存放的第一个第二个位置传递 #2 关键字传参,就是将形参自行按需求赋值 result2 = cale(b=20, a=33) result3 = cale(b = -10, a = 33) print(result2) print(result3) #在函数调用过程中,进行参数的传递。如果参数是不可变对象,在函数的中的修改值出了函数就会变回去,不会影响实参的值,如果是可变的对象,那么参数的改变会一直存在,函数调用过后值也是被修改过的 def lit(a, b): b.append(30) a = list(a) print('函数里面的数据类型为',type(a)) print(b) a = 'python' b = [10, 30, 50] lit(a,b) print(a) print('函数外面的数据类型',type(a)) print(b) #函数的返回值 return #函数没有返回值 即函数调用过后,不用为调用该函数的函数提供出输入的数据 def fun(): print('hhh') fun() #函数返回的只有一个返回值,也就是被调用的函数只做了一项运算有一个结果需要提供出去,return 结果,直接返回该结果的数据类型 def fun1(): return 'hehehe' res = fun1() print(res) print(fun1()) #整个函数就代表那一个数值 def fun2(): return 'aa','bb' #返回多个数值,所有的返回值作为一个元组出现 res2 = fun2() print(res2) print(fun2())
ea03689b8be9bd5fab6af7d4e20d2ceae0d8e88b
reesporte/euler
/3/p3.py
534
4.125
4
""" project euler problem 3 """ def is_prime(num): if num == 1: return False i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True def get_largest_prime_factor(num): largest = 0 i = 2 while i*i <= num: if num%i == 0: if is_prime(i): largest = i i += 1 return largest def main(): print("the largest prime factor is:", get_largest_prime_factor(600851475143)) if __name__ == '__main__': main()
8063a87ba1e389e833699bfdc6378698ae8490a7
reesporte/euler
/19/p_19.py
1,608
4.03125
4
""" project euler problem 19 """ def is_leap_year(year): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return True return False def get_days_in_month(month, year): months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month == 2 and is_leap_year(year): return 29 return months[month-1] # month - 1 bc it's in a list, index starts at 0 def sunday_as_first_of_month(jan_day, year): """ given what day the 1st of january of any year is, counts the number of sundays that are the first of the month in that year mon = 0 ... sun = 6 """ count = 0 months = [0]*13 months[1] = jan_day if months[1] == 6: count += 1 for month in range(2, 13): months[month] = (months[month-1] + get_days_in_month(month-1, year)) % 7 if months[month] == 6: count += 1 return count def boring_way(): """ boring way that doesnt take a lot of creativity using built-in functions """ from datetime import date for year in range(1901, 2001): count = 0 for month in range(1, 13): day = date(year, month, 1) if day.weekday() == 6: count += 1 print(count) def main(): jan_day = [0] * 101 jan_day[0] = 0 count = 0 for i in range(1, 100): if jan_day[i-1] == 6: jan_day[i] = 0 else: jan_day[i] = jan_day[i-1] + 1 for i in range(1901, 2001): count += sunday_as_first_of_month(jan_day[i-1900], i) print(count) if __name__ == '__main__': main()
567820cdb4e2c97509d232fe441e2f9b6a58a34b
jayden-nguyen/Homework2--NguyenQuangHuy
/homework4/serious2.py
1,364
3.9375
4
prices = {"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3} li = prices.keys() purchased = { "banana": 5, "orange":3 } print("YOU BOUGHT 5 BANANAS AND 3 ORANGES") choice = "yes" while choice.lower() != "no": choice = input("Do you want more(yes or no, press no to exit)? ") if choice.lower() == "yes": fruit = input("what's type of fruit? ") fruit = fruit.lower() if fruit in li: if fruit.lower() == "banana" or fruit == "orange": quant = int(input("how many?")) quant += purchased[fruit] purchased[fruit]=quant else: quant = int(input("how many?")) purchased[fruit] = quant else: print("We don't have it") print("you bought "+str(quant)+" "+fruit+"s") elif choice.lower()=='no': break else: print("IVALID,Please input again") print("**********************************************") purchased_items = list(purchased.items()) total = 0 print("THIS IS YOUR BILL") for i in range(len(purchased_items)): print(purchased_items[i][0],"quantity: ",purchased_items[i][1]," price: ",prices[purchased_items[i][0]]) total += purchased_items[i][1] * prices[purchased_items[i][0]] print("total is:") print(str(total)+"$")
d0131c5e298483388d06683c5f60046a570ba2eb
ErickHernandez/ProyectoCompiladores
/pyfiles/gcd.py
290
4.09375
4
# Program to compute the GCD # Funcion que calcula el maximo comun divisor def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) x = input("Introduzca un numero: ") y = input("Introduzca otro numero: ") z = gcd(x, y) print "El maximo comun divisor es ", z
ed5d3fc73cc8479689a580b926346d098d467c71
sajjanparida/DS-Algorithms
/Sorting/tripletwithlessthansum.py
406
3.90625
4
# program to find the count of triplets with sum less than given number def triplets_sum(arr,n,req_sum): c=0 arr.sort() for k in range(0,n-2): i=k+1 j=n-1 while i<j: if arr[k] + arr[i] + arr[j] < req_sum: c += j-i i += 1 else: j -=1 return c arr=[-2,0,1,3] print(triplets_sum(arr,4,2))
2fc28c8c55ff62b44ecf16f3094d41dee4c3a012
sajjanparida/DS-Algorithms
/LinkedList/Introduction.py
428
3.953125
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def printList(self): temp=self.head while(temp): print(temp.data) temp = temp.next llist = LinkedList() first=Node(1) second=Node(2) third=Node(3) llist.head = first first.next=second second.next=third llist.printList()
c050dc01202dce89bf26ea6f125d3410d2177a50
sajjanparida/DS-Algorithms
/Sorting/subarraysumcount.py
390
3.6875
4
def countOfSubarray(arr,n): i=-1 count=0 sum=0 freq={} freq[sum]=1 while i < n-1: i +=1 sum += arr[i] if freq.get(sum) != None: count += freq[sum] freq[sum]=freq[sum]+1 else: freq[sum]=1 return count arr=[0,0,5,5,0,0] print("The subarray with 0 sum is : {} ".format(countOfSubarray(arr,6)))
2529bc8fce8c1186cf9325d6ef1479f22adb9e1f
sajjanparida/DS-Algorithms
/Sorting/productarraypuzzle.py
622
3.703125
4
def productExceptSelf(nums, n): #code here zeroflag=0 product=1 if n==1: return 1 for i in range(0,n): if nums[i]!= 0 : product *= nums[i] else: zeroflag += 1 if zeroflag==1: for i in range(0,n): if nums[i]==0: nums[i] = product else: nums[i]=0 elif zeroflag>1: for i in range(0,n): nums[i]=0 else: for i in range(0,n): nums[i]=product//nums[i] return nums nums=[1,0,5,0,7] print(productExceptSelf(nums,5))
f6063a11518b1fcc2bc653ed3f505dddc9ad4dbf
sajjanparida/DS-Algorithms
/Arrays/Three_way_partition.py
925
4.09375
4
# Given an array of size n and a range [a, b]. The task is to partition the array around the range such that array is divided into three parts. # 1) All elements smaller than a come first. # 2) All elements in range a to b come next. # 3) All elements greater than b appear in the end. # The individual elements of three sets can appear in any order. You are required to return the modified array def three_way_partition(arr,n,a,b): l=0 r=n-1 i=0 while i < r: if (arr[i] < a): arr[i],arr[l]= arr[l],arr[i] l += 1 i += 1 print("l: {} , i : {}".format(l,i)) elif arr[i] > b: arr[i],arr[r] =arr[r],arr[i] r -= 1 print("r: {} , i : {}".format(r,i)) else: i += 1 return arr arr=[76,8 ,75, 22, 59, 96, 30, 38, 36] print("Output array is {}".format(three_way_partition(arr,9,44,62)))
bbeb124cd35e865c17ae7a9691022031b81ba553
jonahtjandra/sudoku-solver
/Sudoku.py
2,939
4.15625
4
class Sudoku: def __init__(self, board:'list[list]') -> None: if (len(board) != 9 or len(board[0]) != 9): raise "Expected a 9 by 9 board" self.board = board self.iterations = [] # for printing out the 2d list representation of the board def display(self, board:'list[list]'): if (len(board) != 9): print("Not a valid 9x9 sudoku board!") return x = 0 for i in range(len(board)+4): if (i==0 or i==4 or i==8 or i==12): print('-------------------------') continue y = 0 for j in range(len(board)+4): if (j == 0 or j==4 or j==8): print('|', end=' ') elif (j == 12): print('|') else: print(board[x][y], end=' ') y += 1 x += 1 # method to check if a certain number, n, is valid to be # place at a certain x and y coordinate in the board def isPossible(self, x:int, y:int, n:int) -> bool: if (x > 8 and y > 8 and n >= 0 and n <= 9): return False #horizontal check for i in range(9): if (self.board[x][i] == n and i != y): return False #vertical check for i in range(9): if (self.board[i][y] == n and i != x): return False #square check square_x = x // 3 square_y = y // 3 for i in range(3): for j in range(3): if (self.board[square_x * 3 + i][square_y * 3 + j] == n and x != square_x * 3 + i and y != square_y * 3 + j): return False #possible placement return True # Method to check if solution is correct def isSolution(self) -> bool: for i in range(9): for j in range(9): if (not(self.isPossible(self.board, i, j, self.board[i][j]))): return False return True # Method to find the next empty coordinate in the board # Returns false if there are no empty space left (solved) def nextEmpty(self, loc:list) -> bool: for i in range(9): for j in range(9): if (self.board[i][j] == '.'): loc[0] = i loc[1] = j return True return False # Method to solve the board # Returns false if board is not solveable def solve(self) -> bool: loc = [0,0] if (not self.nextEmpty(loc)): return True i = loc[0] j = loc[1] for n in range(1,10): if (self.isPossible(i, j, n)): self.board[i][j] = n self.display(self.board) if (self.solve()): return True self.board[i][j] = '.' return False
18d4f634488453133535b594fdff3fb8d851f6af
Yokohama-Miyazawa/uec_django
/presen/veiw_tetris.py
3,312
3.734375
4
import tkinter as tk from random import choice class Game(): WIDTH = 300 HEIGHT = 500 def start(self): self.speed = 150 self.new_game = True self.root = tk.Tk() self.root.title("Tetris") self.canvas = tk.Canvas( self.root, width=Game.WIDTH, height=Game.HEIGHT ) self.canvas.pack()#表示される self.timer() self.root.mainloop() def timer(self): if self.new_game == True:#最初の図形を作るため self.current_shape = Shape(self.canvas) self.new_game = False if not self.current_shape.fall(): self.current_shape = Shape(self.canvas)#新しく図形を作る self.root.after(self.speed,self.timer)#.speedミリ秒後.timerを起動 class Shape: BOX_SIZE = 20 START_POINT = Game.WIDTH / 2 / BOX_SIZE * BOX_SIZE - BOX_SIZE#画面の真ん中のブロックの位置 SHAPES = ( ((0, 0), (1, 0), (0, 1), (1, 1)), # 四角 ((0, 0), (1, 0), (2, 0), (3, 0)), # 棒 ((2, 0), (0, 1), (1, 1), (2, 1)), # L字 ) def __init__(self,canvas): #ランダムにブロックを選び、windowにブロックを表示する self.boxes = [] self.shape = choice(Shape.SHAPES)#ランダムに形を選ぶ self.canvas = canvas for point in self.shape: #point => テトリス画面上の座標 box = canvas.create_rectangle(#ブロックの1つ1つの形成 point[0] * Shape.BOX_SIZE + Shape.START_POINT, point[1] * Shape.BOX_SIZE, point[0] * Shape.BOX_SIZE + Shape.BOX_SIZE + Shape.START_POINT, point[1] * Shape.BOX_SIZE + Shape.BOX_SIZE ) self.boxes.append(box)#boxesにブロックを入れる def fall(self):#図形を下に移動 if not self.can_move_shape(0, 1): return False else: for box in self.boxes: self.canvas.move(box, 0 * Shape.BOX_SIZE, 1 * Shape.BOX_SIZE) return True def can_move_box(self, box, x, y):#ボックスが動けるかチェック x = x * Shape.BOX_SIZE y = y * Shape.BOX_SIZE coords = self.canvas.coords(box) # 画面からブロックが行き過ぎるとFalse if coords[3] + y > Game.HEIGHT: return False if coords[0] + x < 0: return False if coords[2] + x > Game.WIDTH: return False # 他のボックスに重なるとFalse overlap = set(self.canvas.find_overlapping( (coords[0] + coords[2]) / 2 - x, (coords[1] + coords[3]) / 2 - y, (coords[0] + coords[2]) / 2 + x, (coords[1] + coords[3]) / 2 + y )) other_items = set(self.canvas.find_all()) - set(self.boxes) # print(other_items) # print(overlap) if overlap & other_items: return False return True def can_move_shape(self, x, y):#図形が移動できるかチェック for box in self.boxes: if not self.can_move_box(box, x, y): return False return True if __name__ == "__main__": game = Game() game.start()
4e3ae8718dd37281e9b8dbf85d2df92c555efd48
50417/phd
/learn/challenges/020-highest-product.py
953
3.5
4
#!/usr/bin/env python3 from collections import deque from typing import List def approach1(lst: List[int]) -> int: if not isinstance(lst, list): raise TypeError if len(lst) < 3: raise ValueError if any(x is None for x in lst): raise TypeError best = deque(sorted(lst[:3])) for x in lst[3:]: if x > min(best): # TODO: insert into sorted best del best[best.index(min(best))] best.append(x) return best[0] * best[1] * best[2] if __name__ == "__main__": try: approach1(2) assert False except TypeError: pass try: approach1([2, 2]) assert False except ValueError: pass try: approach1([1, 2, 3, None, 2]) assert False except TypeError: pass examples = [ ([1, 2, 3], 6), ([1, 8, 8], 64), ([1, 8, 1, 8], 64), ([1, 8, 1, 2, 8], 128), ] for ins, outs in examples: print(ins, outs, approach1(ins)) assert approach1(ins) == outs
54d2e882b8d9a188ffdef473ad3e6372c1d3f0fd
50417/phd
/learn/challenges/018-list-binary-tree.py
2,489
3.8125
4
#!/usr/bin/env python3 from collections import deque from typing import List class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None def __lt__(self, rhs: "Node"): return self.data < rhs.data def __eq__(self, rhs: "Node"): return self.data == rhs.data def __le__(self, rhs: "Node"): return self.__eq__(self, rhs) or self.__lt__(self, rhs) def __gt__(self, rhs: "Node"): return not self.__le__(self, rhs) def __ge__(self, rhs: "Node"): return self.__eq__(self, rhs) or self.__gt__(self, rhs) class Graph(object): def __init__(self, root=None): self.root = root def insert(self, data, root=None): if root is None: root = self.root newnode = Node(data) if self.root is None: self.root = newnode else: if data <= root.data: if root.left: return self.insert(data, root.left) else: root.left = newnode else: if root.right: return self.insert(data, root.right) else: root.right = newnode return newnode @property def elements(self) -> List: elements = [] q = deque([]) if self.root: q.append(self.root) while len(q): node = q.popleft() elements.append(node.data) if node.left: q.append(node.left) if node.right: q.append(node.right) return elements @property def levels(self) -> List[List]: levels = [] q = deque() if self.root: q.append((0, self.root)) while len(q): depth, node = q.popleft() if len(levels) <= depth: levels.append([]) levels[depth].append(node.data) if node.left: q.append((depth + 1, node.left)) if node.right: q.append((depth + 1, node.right)) return levels if __name__ == "__main__": g = Graph() assert g.elements == [] assert g.levels == [] g.insert(5) assert g.elements == [5] assert g.levels == [[5]] g.insert(4) assert g.elements == [5, 4] assert g.levels == [[5], [4]] g.insert(5) assert g.elements == [5, 4, 5] assert g.levels == [[5], [4], [5]] g.insert(2) assert g.root.left.right.data == 5 assert g.root.left.left.data == 2 assert g.elements == [5, 4, 2, 5] assert g.levels == [[5], [4], [2, 5]] g.insert(10) g.insert(7) g.insert(6) assert g.elements == [5, 4, 10, 2, 5, 7, 6] assert g.levels == [[5], [4, 10], [2, 5, 7], [6]]
b490ccfe7a99436aa96f5e9ad6d04c83caaba021
YinglunYin/MachineLearning-CS6140
/2-Linear&RidgeRegression/src/problem2.py
4,487
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 14 12:32:58 2018 CS6140 Assignment2 Gradient Descent Problem2 @author: Garrett """ from sklearn import linear_model import math import numpy as np import pandas as pd import matplotlib.pyplot as plt # reader def dataset_reader(file): return np.array(pd.read_csv(file, header=None), dtype=np.float64) # normalize X data using z-score and then add x0 def normalize(X): mean = np.mean(X, 0) std = np.std(X, 0) X_norm = (X - mean) / std X_norm = add_x0(X_norm) return X_norm, mean, std # normalize X testing data using mean and deviation of training data def test_normalize(X, mean, std): X_norm = (X - mean) / std X_norm = add_x0(X_norm) return X_norm # add x0 to data def add_x0(X): return np.column_stack([np.ones([X.shape[0], 1]), X]) # predict y_hat using X and w def predict(X, w): return X.dot(w) # sum of squared errors def sse(X, y, w): y_hat = predict(X, w) return ((y_hat - y) ** 2).sum() # root mean squared error def rmse(X, y, w): return math.sqrt(sse(X, y, w) / y.size) # cost function of regression def cost_function(X, y, w): return sse(X, y, w) / 2 # derivative vector of the cost function def cost_derivatives(X, y, w): y_hat = predict(X, w) return (y_hat - y).dot(X) def plot_rmse(rmse_sequence): # Data for plotting s = np.array(rmse_sequence) t = np.arange(s.size) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='iterations', ylabel='rmse', title='rmse trend') ax.grid() plt.legend(bbox_to_anchor=(1.05,1), loc=2, shadow=True) plt.show() # implement gradient descent to calculate w def gradient_descent(X, y, w, learningrate, tolerance, maxIteration=1000): rmse_sequence = [] last = float('inf') for i in range(maxIteration): w = w - learningrate * cost_derivatives(X, y, w) cur = rmse(X, y, w) diff = last - cur last = cur rmse_sequence.append(cur) if diff < tolerance: # print(i) break plot_rmse(rmse_sequence) return w # k fold validation def k_fold_validation(dataset, learningrate, tolerance, folds=10): np.random.shuffle(dataset) end = 0 size = math.floor(dataset.shape[0] / folds) rmse_train = [] rmse_test = [] sse_train = [] sse_test = [] for k in range(folds): start = end end = start + size dataset_test = dataset[start: end] left = dataset[0: start] right = dataset[end: ] dataset_train = np.vstack([left, right]) X_train = dataset_train[:, 0:-1] y_train = dataset_train[:, -1] X_train, mean, std = normalize(X_train) X_test = dataset_test[:, 0:-1] y_test = dataset_test[:, -1] X_test = test_normalize(X_test, mean, std) w = np.ones(X_train.shape[1], dtype=np.float64) * 0 w = gradient_descent(X_train, y_train, w, learningrate, tolerance) rmse_train.append(rmse(X_train, y_train, w)) rmse_test.append(rmse(X_test, y_test, w)) sse_train.append(sse(X_train, y_train, w)) sse_test.append(sse(X_test, y_test, w)) print('RMSE for training data:') print(rmse_train) print('Mean:') print(np.mean(rmse_train)) print('RMSE for testing data:') print(rmse_test) print('Mean:') print(np.mean(rmse_test)) print() print('SSE for training data:') print('Mean:') print(np.mean(sse_train)) print('Standard Deviation:') print(np.std(sse_train)) print('SSE for testing data:') print('Mean:') print(np.mean(sse_test)) print('Standard Deviation:') print(np.std(sse_test)) def test_housing(): print('Housing:') dataset = dataset_reader('housing.csv') k_fold_validation(dataset, 0.1e-3, 0.5e-2) print() def test_yacht(): print('Yacht:') dataset = dataset_reader('yachtData.csv') k_fold_validation(dataset, 0.1e-2, 0.1e-2) print() def test_concrete(): print('Concrete:') dataset = dataset_reader('concreteData.csv') k_fold_validation(dataset, 0.7e-3, 0.1e-3) print() def main(): test_housing() test_yacht() test_concrete() if __name__ == '__main__': main()
fd289fe5c232aa58735368aff954409d808adf02
Black-Eagle-1/driving
/driving.py
248
3.84375
4
country = input('你所在的國家: ') age = input('你的年齡: ') age = int(age) if country == '美國' and age >= 16: print('你可以開車') elif country == '台灣' and age >= 18: print('你可以開車') else: print('你不能開車')
11ec0890ed9eb2c6540f1c8c34eb778c8302fd46
wxmsummer/algorithm
/leetcode/hot/605_canPlaceFlowers.py
851
4.0625
4
# 605.种花问题 from typing import List class Solution: # 模拟法,如果该位置、该位置的前一个位置、该位置的后一个位置没种,就种上 def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: length = len(flowerbed) count = 0 for i in range(length): # 注意数组越界 if flowerbed[i] == 1 or (i > 0 and flowerbed[i-1]==1) or (i < length - 1 and flowerbed[i+1] == 1): continue else: flowerbed[i] = 1 count += 1 print('flower:', flowerbed) return True if count >= n else False if __name__ == '__main__': obj = Solution() print(obj.canPlaceFlowers([1,0,0,0,1], 1)) print(obj.canPlaceFlowers([1,0,0,0,1], 2)) print(obj.canPlaceFlowers([1,0,0,0,0,1], 2))
87f761c182e6d122e69d9d5d9c44d896fd729655
wxmsummer/algorithm
/leetcode/offer/offer14_cuttingRope.py
759
3.90625
4
# 剪绳子 import math # 数学证明 # 任何大于1的数都可由2和3相加组成 # 当n>=5时,将它剪成2或3的绳子段,2(n-2) > n,3(n-3) > n,都大于他未拆分前的情况, # 当n>=5时,3(n-3) >= 2(n-2),所以我们尽可能地多剪3的绳子段 # 当绳子长度被剪到只剩4时,2 * 2 = 4 > 1 * 3,所以没必要继续剪 class Solution: def cuttingRope(self, n: int) -> int: if n <= 3: return n - 1 a = n // 3 b = n % 3 if b == 0: return int(3 ** a) % 1000000007 if b == 1: return int(3 ** (a-1) * 4) % 1000000007 return int(3 ** a * 2) % 1000000007 if __name__ == '__main__': obj = Solution() print(obj.cuttingRope(120))
23b9938f61e413a65cee12d5501680271b7d622a
wxmsummer/algorithm
/leetcode/hot/222_countNodes.py
1,281
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 层序遍历,暴力法 def countNodes(self, root: TreeNode) -> int: if not root: return 0 stack = [root] count = 0 while stack: node = stack.pop() count += 1 if node.left: stack.append(node.left) if node.right: stack.append(node.right) return count # 复杂度 O(lgn*lgn) def countNodes(self, root: TreeNode) -> int: if not root: return 0 left, right = root.left, root.right left_depth, right = 0, 0 # 求左右子树深度 while left: left = left.left left_depth += 1 while right: right = right.right right += 1 # 如果遇到满二叉树 if left_depth == right: return (2 << left_depth) - 1 # 如果不为满二叉树,则节点数量为左子树数量加右子树数量加1,1为自身 return self.countNodes(root.left) + self.countNodes(root.right) + 1
eeeace6a1d48324c28845d51b89535f2527a72e2
wxmsummer/algorithm
/leetcode/hot/77_combine.py
742
3.75
4
# 组合 class Solution: def combine(self, n: int, k: int) -> list: # 回溯法,idx为当前元素,cur为当前解 def backtrack(idx, cur): # 如果当前解符合要求,就加入解集 if len(cur) == k: res.append(cur[:]) # 遍历当前位置后面的元素 for i in range(idx, n+1): print('cur:', cur) cur.append(i) # 开启下一层判断 backtrack(i+1, cur) # 回溯 cur.pop() res = [] # 注意这里是从1开始 backtrack(1, []) return res if __name__ == '__main__': obj = Solution() print(obj.combine(4, 3))
8c80e03f0044efa8379d202302807430cb5b5ee4
wxmsummer/algorithm
/leetcode/hot/49_groupAnagrams.py
658
3.703125
4
# 字母异位词分组 class Solution: # 将单词转换为列表后按字典序排序 # 使用dic保存分组 def groupAnagrams(self, strs:list) -> list: dic = {} length = len(strs) for i in range(length): l = list(strs[i]) l.sort() s = ''.join(l) if s in dic: dic[s].append(strs[i]) else: dic[s] = [strs[i]] res =[] for val in dic.values(): res.append(val) return res if __name__ == '__main__': obj = Solution() print(obj.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
6d655a04136f2a2bf3f4ad5c6726e6c3cf886d5d
wxmsummer/algorithm
/leetcode/hot/383_ransom.py
386
3.515625
4
ransomNote = input() magazine = input() list_1 = list(ransomNote) list_2 = list(magazine) for i in range(len(list_1)): print(list_1) print(list_2) if list_1[0] not in list_2: print(0) break else: list_2.remove(list_1[0]) del list_1[0] continue print(1) # return not collections.Counter(ransomNote) - collections.Counter(magazine)
c9941ccd8853940bc4b9f64f26c4783755349de7
wxmsummer/algorithm
/leetcode/offer/offer56-1_singleNumber.py
217
3.578125
4
# 只出现一次的数字 class Solution: def singleNumbers(self, nums: List[int]) -> int: single_number = 0 for num in nums: single_number ^= num return single_number
2cb11923ce346d66cf554b7556592494c52b2d05
wxmsummer/algorithm
/leetcode/hot/139_wordBreak.py
1,038
3.5625
4
class Solution: # 记忆化递归 # @functools.lru_cache(None) 禁止开启lru缓存机制 def wordBreak(self, s: str, wordDict: list) -> bool: import functools @functools.lru_cache(None) def backTrack(s): if not s: return True res = False for i in range(1, len(s)+1): if s[:i] in wordDict: res = backTrack(s[i:]) or res return res return backTrack(s) # 动态规划 # dp[i]表示以i结尾的字串是否已经匹配 # s[i:j]表示以i开头,以j结尾的字串 def wordBreak(self, s: str, wordDict: list) -> bool: n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(n): for j in range(i+1, n+1): if dp[i] and (s[i:j] in wordDict): dp[j] = True return dp[-1] if __name__ == '__main__': obj = Solution() print(obj.wordBreak(s = "leetcode", wordDict = ["leet", "code"]))
8dd9a081d4078f7161cf36acf76d189d5afb2688
wxmsummer/algorithm
/leetcode/hot/22-2_generateParenthesis.py
2,096
3.5
4
class Solution(): def generateParenthesis(self, n:int) -> list: res, tmp = [], [] # left_num 表示还能放多少个左括号, right_num 表示还能放多少右括号 def backtrack(left_num1, right_num1, left_num2, right_num2): print('tmp:', tmp) # 如果左括号和右括号都放完了,说明这一轮回溯完成,将结果加入结果集 if left_num1 == 0 and right_num1 == 0 and left_num2 == 0 and right_num2 == 0: res.append(''.join(tmp)) # 左括号可以随意放,只要数量大于0 if left_num1 > 0: tmp.append('(') # 放了左括号之后,回溯,左括号可放数量减一 backtrack(left_num1-1, right_num1, left_num2, right_num2) # 回溯后恢复上一状态 tmp.pop() if left_num2 > 0: tmp.append('[') # 放了左括号之后,回溯,左括号可放数量减一 backtrack(left_num1, right_num1, left_num2-1, right_num2) # 回溯后恢复上一状态 tmp.pop() # 右括号可放的数量必须大于左括号可放的数量,即必须先放了左括号才能放右括号 if left_num1 < right_num1: tmp.append(')') # 回溯,右括号可放数量减一 backtrack(left_num1, right_num1-1, left_num2, right_num2) # 恢复回溯前状态 tmp.pop() # 右括号可放的数量必须大于左括号可放的数量,即必须先放了左括号才能放右括号 if left_num2 < right_num2: tmp.append(']') # 回溯,右括号可放数量减一 backtrack(left_num1, right_num1, left_num2, right_num2-1) # 恢复回溯前状态 tmp.pop() backtrack(n, n, n, n) return res if __name__ == '__main__': obj = Solution() print(obj.generateParenthesis(1))
f944157689453208684072deb6b5f99a7ddff703
wxmsummer/algorithm
/leetcode/hot/90_subsWithDup.py
586
3.65625
4
# 求子集2 # nums可能包含重复元素 class Solution: def subsetsWithDup(self, nums: list) -> list: def backTrack(start, tmp): res.append(tmp[:]) for i in range(start, len(nums)): if i > start and nums[i] == nums[i-1]: continue tmp.append(nums[i]) backTrack(i+1, tmp) tmp.pop() nums.sort() res = [] backTrack(0, []) return res if __name__ == '__main__': obj = Solution() print(obj.subsetsWithDup([1,2,2,2,2]))
35b2f4d82df46090bec5b965bf24f1c21454834b
wxmsummer/algorithm
/leetcode/hot/976_largestPerimeter.py
768
3.859375
4
# 三角形的最大周长 class Solution: def largestPerimeter(self, nums: list) -> int: if len(nums) < 3: return 0 nums.sort() length = len(nums) i, j, k = length-3, length-2, length-1 while i >= 0: if nums[i] + nums[j] > nums[k]: return nums[i] + nums[j] + nums[k] else: i -= 1 j -= 1 k -= 1 if i < 0: return 0 return 0 if __name__ == '__main__': obj = Solution() print(obj.largestPerimeter([1,1])) print(obj.largestPerimeter([2,1,2])) print(obj.largestPerimeter([1,2,1])) print(obj.largestPerimeter([3,2,3,4])) print(obj.largestPerimeter([3,6,2,3]))
1349e81c63782210f997a14b8040f55228b3e6e8
wxmsummer/algorithm
/leetcode/offer/offer21_exchange.py
787
3.78125
4
# 调整数组顺序使奇数位于偶数前面 # 两次遍历 class Solution: def exchange(self, nums: list) -> list: newList = [] for num in nums: if num % 2 == 1: newList.append(num) for num in nums: if num % 2 == 0: newList.append(num) return newList # 原数组,直接交换,双指针 class Solution: def exchange(self, nums: List[int]) -> List[int]: i, j = 0, len(nums) - 1 while i < j: while i < j and nums[i] & 1 == 1: i += 1 while i < j and nums[j] & 1 == 0: j -= 1 nums[i], nums[j] = nums[j], nums[i] return nums if __name__ == '__main__': obj = Solution() print(obj.exchange([1, 2, 3, 4]))
38a37365f1df0a0e8911266f32d4482096c2789a
wxmsummer/algorithm
/leetcode/hot/12-2_romanToInt.py
1,067
3.515625
4
class Solution(): # 直接遍历,逐个翻译 def romanToInt(self, s:str) -> int: # 由大到小构造罗马字字典 dic = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1} tmp, res = '', 0 if not s: return 0 i = 0 # 遍历字符串 while i < len(s): # tmp表示可能构成的罗马字符,如果tmp不在字典中,则继续拼下一个罗马字符 if i < len(s) - 1: # 往前预先判断是否能构成2字符罗马字 tmp = s[i] + s[i+1] if tmp in dic: res += dic[tmp] # 构成两字符罗马字,i往前走2步 i += 2 tmp = '' else: res += dic[s[i]] # 不是两字符罗马数字,i往前走1步 i += 1 return res if __name__ == '__main__': obj = Solution() print(obj.romanToInt('IV'))
4f2dc89118ac9811a7705b9e003ee484bb68b3ff
wxmsummer/algorithm
/leetcode/array/binary_search.py
643
3.5625
4
class Solution: def binary_search(self, nums:list, target:int): i, j = 0, len(nums) while i < j: m = (i + j) // 2 if nums[m] >= target: j = m else: i = m + 1 if i == len(nums): return -1 return i if __name__ == '__main__': obj = Solution() print(obj.binary_search([2,3,3,3,3,3], 3) ) # DPRC开发 # 讲项目,提高 # 细节,对项目的深入度 # go相关 # 比较深入的点,通信协议,分布式系统,稳定性,可拓展性 # 代码,逻辑需要更清晰,思路 # 知识储备,能力体现
b9498d588de3e9bf2cc8893544c744f29aa7d214
wxmsummer/algorithm
/leetcode/offer/offer31_validateStackSequences.py
942
3.734375
4
# 栈的压入、弹出序列 class Solution: def validateStackSequences(self, pushed: list, popped: list) -> bool: newList = [] # 直接模拟,每次入栈后,循环判断栈顶元素是否等于弹出序列的当前元素,将符合弹出序列顺序的栈顶元素全部弹出。 for num in pushed: newList.append(num) while newList and newList[-1] == popped[0]: del newList[-1] del popped[0] return popped == [] class Solution: def validateStackSequences(self, pushed: list, popped: list) -> bool: stack, i = [], 0 for num in pushed: stack.append(num) while stack and stack[-1] == popped[i]: stack.pop() i += 1 return not stack if __name__ == '__main__': obj = Solution() print(obj.validateStackSequences([2, 1, 0], [1, 2, 0] ))
9ae4eb3dde5360d1e3487db79a7cbb64fd97e2d6
wxmsummer/algorithm
/leetcode/hot/73_setZeroes.py
847
3.703125
4
# 矩阵置零 class Solution: def setZeroes(self, matrix: list) -> None: row_len, col_len = len(matrix), len(matrix[0]) # 使用额外的两个行数组和列数组来存储行和列中的零信息 row_list = [1] * row_len col_list = [1] * col_len for i in range(row_len): for j in range(col_len): if matrix[i][j] == 0: row_list[i] = 0 col_list[j] = 0 # 记录好零的数量之后,遍历置零 for i in range(row_len): if row_list[i] == 0: for j in range(col_len): matrix[i][j] = 0 for j in range(col_len): if col_list[j] == 0: for i in range(row_len): matrix[i][j] = 0
26edab3caee726fcd7a5e621c59c23a4b4409cbc
CcCc1996/myprogram
/2-oop/03.py
2,142
3.5
4
# -*- coding: utf-8 -*- # Author: IMS2017-MJR # Creation Date: 2019/4/23 # 多继承的例子 # 子类可以直接拥有父类的属性和方法,私有的属性和方法除外 class Bird(): def __init__(self, name): self.name = name def fly(self): print("i can fly") class Fish(): def __init__(self, name): self.name = name def swim(self): print("i can swim") class Person(): def __init__(self, name): self.name = name def work(self): print("i can do work") class SuperMan(Person, Bird, Fish): def __init__(self, name): self.name = name s = SuperMan("cjx") s.fly() s.swim() s.work() # 单继承的例子 class Flog(Fish): def __init__(self, name): self.name = name f = Flog("anran") f.swim() # 构造函数的补充 print("*" * 50) class A(): def __init__(self, name): print("A") print(name) class B(A): def __init__(self, name): A.__init__(self, name) # 首先调用父类构造函数,或也可以使用super实现 super(B, self).__init__(name) print ("这是A的构造函数") b = B("A的名字") # Mixin案例 class Person(): def eat(self): print("eat") def sleep(self): print("sleep") class TeacherMixin(): # 在Mixin写法中,此处不需要添加父类,表示单一的功能 def work(self): print("work") class StudentMixin(): def study(self): print("study") class TutorM(Person, TeacherMixin, StudentMixin): pass tt = TutorM() print(TutorM.__mro__) # issubclass函数实例 print("*" * 50) class A(): pass class B(A): pass class C(): pass print(issubclass(B, A)) print(issubclass(C, A)) print(issubclass(C, object)) # isinstance函数实例 print("*" * 50) class A(): pass a = A() print(isinstance(a, A)) # hasattr函数实例 print("*" * 50) class A(): name = "hahaha" a = A() print(hasattr(a, "name")) print(hasattr(a, "age")) # 使用和help查询setattr函数用法实例 print("*" * 50) help(setattr) class A(): name = "hahaha" setattr(A, "name", "我的名字是cjx") a = A() print(a.name)
fe10575d95d37269565d10c9ee8ebe343edbb7b6
francisco0522/holbertonschool-interview
/0x00-lockboxes/0-lockboxes.py
531
3.796875
4
#!/usr/bin/python3 """ Lockboxes """ def canUnlockAll(boxes): """ method that determines if all the boxes can be opened """ if not boxes: return False opened = {} queue = [0] while queue: boxNum = queue.pop(0) opened[boxNum] = 1 for key in boxes[boxNum]: if key >= 0 and key < len(boxes) and not opened.get(key)\ and (key not in queue): queue.append(key) return True if (len(opened) == len(boxes)) else False
e4eab633f19ee8cdc500a7c8b48c8b2f7ace9fce
mp360/manitab
/scaleCan.py
3,996
3.578125
4
# from Tkinter import * # # a subclass of Canvas for dealing with resizing of windows # class ResizingCanvas(Canvas): # def __init__(self,parent,**kwargs): # Canvas.__init__(self,parent,**kwargs) # self.bind("<Configure>", self.on_resize) # self.height = self.winfo_reqheight() # self.width = self.winfo_reqwidth() # def on_resize(self,event): # # determine the ratio of old width/height to new width/height # wscale = float(event.width)/self.width # hscale = float(event.height)/self.height # self.width = event.width # self.height = event.height # # resize the canvas # self.config(width=self.width, height=self.height) # # rescale all the objects tagged with the "all" tag # self.scale("all",0,0,wscale,hscale) # def main(): # root = Tk() # myframe = Frame(root) # myframe.pack(fill=BOTH, expand=YES) # mycanvas = ResizingCanvas(myframe,width=850, height=400, bg="red", highlightthickness=0) # mycanvas.pack(fill=BOTH, expand=YES) # # add some widgets to the canvas # mycanvas.create_line(0, 0, 200, 100) # mycanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) # mycanvas.create_rectangle(50, 25, 150, 75, fill="blue") # # tag all of the drawn widgets # mycanvas.addtag_all("all") # root.mainloop() # if __name__ == "__main__": # main() import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button def inputExplorer(f, sliders_properties, wait_for_validation = False): """ A light GUI to manually explore and tune the outputs of a function. slider_properties is a list of dicts (arguments for Slider ) whose keys are in ( label, valmin, valmax, valinit=0.5, valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True) def volume(x,y,z): return x*y*z intervals = [ { 'label' : 'width', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'height', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'depth', 'valmin': 1 , 'valmax': 5 } ] inputExplorer(volume,intervals) """ nVars = len(sliders_properties) slider_width = 1.0/nVars print slider_width # CREATE THE CANVAS figure,ax = plt.subplots(1) figure.canvas.set_window_title( "Inputs for '%s'"%(f.func_name) ) # choose an appropriate height width,height = figure.get_size_inches() height = min(0.5*nVars,8) figure.set_size_inches(width,height,forward = True) # hide the axis ax.set_frame_on(False) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # CREATE THE SLIDERS sliders = [] for i, properties in enumerate(sliders_properties): ax = plt.axes([0.1 , 0.95-0.9*(i+1)*slider_width, 0.8 , 0.8* slider_width]) sliders.append( Slider(ax=ax, **properties) ) # CREATE THE CALLBACK FUNCTIONS def on_changed(event) : res = f(*(s.val for s in sliders)) if res is not None: print res def on_key_press(event): if event.key is 'enter': on_changed(event) # figure.canvas.mpl_connect('key_press_event', on_key_press) # AUTOMATIC UPDATE ? if not wait_for_validation: for s in sliders : s.on_changed(on_changed) # DISPLAY THE SLIDERS plt.show() import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint def model(state,t, a,b,c,d): x,y = state return [ x*(a-b*y) , -y*(c - d*x) ] ts = np.linspace(0,10,500) fig,ax = plt.subplots(1) def plotDynamics(x0,y0,a,b,c,d): ax.clear() ax.plot(ts, odeint(model, [x0,y0], ts, args = (a,b,c,d)) ) fig.canvas.draw() sliders = [ { 'label' : label, 'valmin': 1 , 'valmax': 5 } for label in [ 'x0','y0','a','b','c','d' ] ] inputExplorer(plotDynamics,sliders)
b78ca51e2461286da4cfbb8f16610217e3db01dc
raseribanez/Youtube-Tutorials--Python-Basics--Wordlist-Generators
/wordlist_very_basic_nonrepeat.py
177
3.953125
4
# Ben Woodfield # This basic list generator DOES NOT repeat characters in each result import itertools res = itertools.permutations('abc',3) for i in res: print ''.join(i)
c22b162d749ad8db0d4e74228899c6a7f94e56ec
comalvirdi/CPE101
/LAB8/list_comp/funcs_objects.py
377
3.8125
4
# LAB 8 # COMAL VIRDI # EINAKIAN # SECTION 01 from objects import * import math # calculates the euclidian distance between two point objects # Object Object --> int def distance(p1,p2): return math.sqrt(((p1.x-p2.x)**2)+((p1.y-p2.y)**2)) def circles_overlap(c1, c2): sumRadii = c1.radius + c2.radius distanceCP = distance(c1.center, c2.center) return (sumRadii>distanceCP)
354d51e1558a6e332bf82000e9d874b3d6c87b4b
comalvirdi/CPE101
/LAB3/logic.py
351
4
4
# LAB 3 # Name: Comal Virdi # Instructor: S. Einakian # Section: 01 # Determines whether or not an int is even # int --> bool def is_even(num): return (num % 2 == 0) #Determines whether or not a number falls within certain intervals #float --> bool def in_an_interval(num): return (-2 <= num < 9 or 22 < num < 42 or 12 < num <= 20 or 120 <= num <= 127)
53da6c914c6b7139abf47e3b214b47725e93c50b
comalvirdi/CPE101
/LAB4/loops/cubesTable.py
1,518
4.3125
4
# CPE 101 Lab 4 # Name: def main(): table_size = get_table_size() while table_size != 0: first = get_first() increment = get_increment() show_table(table_size, first, increment) table_size = get_table_size() # Obtain a valid table size from the user def get_table_size(): size = int(input("Enter number of rows in table (0 to end): ")) while (size) < 0: print ("Size must be non-negative.") size = int(input("Enter number of rows in table (0 to end): ")) return size; # Obtain the first table entry from the user def get_first(): first = int(input("Enter the value of the first number in the table: ")) while (first) < 0: print ("First number must be non-negative.") first = int(input("Enter the value of the first number in the table: ")) return first; def get_increment(): increment = int(input("Enter the increment between rows: ")) while (increment) < 0: print ("Increment must be non-negative.") increment = int(input("Enter the increment between rows: ")) return increment; # Display the table of cubes def show_table(size, first, increment): print ("A cube table of size %d will appear here starting with %d." % (size, first)) print ("Number Cube") sum = 0 for num in range (first, first+ size * increment, increment): print ("{0:<7} {1:<4}" .format(num, num**3)) sum += num**3 print ("\nThe sum of cubes is:", sum, "\n") if __name__ == "__main__": main()
8b1b6df83a10e673536f70ac0e157b349269e975
yanitsa-m/udemy-ML-AZ
/reinforcement_learning/upper_confidence_bound.py
1,374
3.609375
4
# Upper Confidence Bound (UCB) in Python # Reinforcement learning algorithm import numpy as np import matplotlib.pyplot as plt import pandas as pd import math # Importing the dataset dataset = pd.read_csv('Ads_CTR_Optimisation.csv') # Implementing UCB algorithm for advertisements data N = 10000 d = 10 ads_selected = [] num_selections = [0] * d sums_of_rewards = [0] * d total_reward = 0 # compute average reward and confidence interval at each round N # see which ad is selected as N gets close to 10000 for n in range(0, N): ad = 0 max_upper_bound = 0 for i in range(0, d): if (num_selections[i] > 0): avg_reward = sums_of_rewards[i] / num_selections[i] delta_i = math.sqrt(3/2 * math.log(n + 1) / num_selections[i]) upper_bound = avg_reward + delta_i else: upper_bound = 1e400 if upper_bound > max_upper_bound: max_upper_bound = upper_bound ad = i ads_selected.append(ad) num_selections[ad] = num_selections[ad] + 1 reward = dataset.values[n,ad] sums_of_rewards[ad] = sums_of_rewards[ad] + reward total_reward = total_reward + reward # Visualizing the histogram for ads selected results plt.hist(ads_selected) plt.title('Histogram of Ads Selections - UCB') plt.xlabel('Ads') plt.ylabel('Number of times selected') plt.show()
f46f987cb4948763de2c63a6ad33ffddbe2ef8dd
yanitsa-m/udemy-ML-AZ
/regression/multiple_linear_reg.py
2,557
3.921875
4
""" Multiple Regression model in Python """ import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing dataset - set up wd dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values # Encoding categorical data # Encoding the Independent Variable from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:, 3] = labelencoder_X.fit_transform(X[:, 3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # Avoid dummy variable trap X = X[:, 1:] # Split data into training set and test set from sklearn.cross_validation import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size =0.2, random_state = 0) # Feature scaling (-1, +1) range for values """from sklearn.preprocessing import StandardScaler scale_X = StandardScaler() X_train = scale_X.fit_transform(X_train) X_test = scale_X.transform(X_test) scale_Y = StandardScaler() Y_train = scale_Y.fit_transform(Y_train) """ # Fitting Multiple Linear Regression to train set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, Y_train) # Predicting the test set results y_pred = regressor.predict(X_test) # Backward elimination to build an optimal model # - eliminate not statistically significant IVs # compute p-values and eliminate variables that are not stat. significant import statsmodels.formula.api as sm # add column of ones at beginning of matrix of features # - lib doesn't take into account b0 constant # (b_0*x_0 part of formula) X = np.append( arr = np.ones((50,1)).astype(int), values = X, axis = 1) # only contains stat. significant independent variables X_optimal = X[:, [0,1,2,3,4,5]] # create new model - ordinary least squares regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit() # examine statistical metrics to get p-values # eliminate variables with p-value > 0.05 regressor_ols.summary() X_optimal = X[:, [0,1,3,4,5]] regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit() regressor_ols.summary() X_optimal = X[:, [0,3,4,5]] regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit() regressor_ols.summary() X_optimal = X[:, [0,3,5]] regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit() regressor_ols.summary() X_optimal = X[:, [0,3]] regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit() regressor_ols.summary()
94288149957696b01230c9cba3ae8c3c8257491e
gpapalois/ergasies-examinou
/exercise12 .py
215
3.90625
4
file = input("Δώσε ένα αρχείο ascii.") for i in range(len(file)): letter = file[len(file)-i -1] number = ord(letter) number2 = 128 - number ascii = chr(number2) print(ascii ,end ="")
5c025aa292e6e3bd670d99670a744324cdc6e463
monicarico-210/clase28febrero
/first.py
281
3.9375
4
print ("hola") a=2+3j b=1+1j c=a*b print(c) x=2 print(x) x=1.6 print(x) print(a, b, sep="...") print(a, b, sep="") x=float(input("entre el valor para x: ")) print(3*x) d=5 e=2 f=d/e print (f) h=d//e print (h) if x == d: print("iguales") if x > d or x < e: print("son iguales")
74973b79560175b3bc94bafe84051865ff9f3a53
ricardocodem/py-regex-exm
/ex3_findall_nome_idade.py
301
3.671875
4
#setup import re #entrada texto = ''' Michelle tem 20 anos a sua irmã Monique tem 22 anos. José, o avô delas, tem 77 anos e mora no apto 17.''' #buscando idades idades = re.findall(r"[0-9]{1,2}\s[a-z]+",texto) print(idades) #buscando nomes nomes = re.findall(r"[A-Z][a-z]+\w",texto) print(nomes)
3000fd6a5f68d7f3ed0ae6fdeedf7421775e580a
CEASLIBRARY/Intermediate_Python
/MyPackage/uc_student.py
1,303
3.921875
4
# Fuction to get the first anme, last name and year of birth of a person def demographics(): first_name = input('What is your First Name: ') last_name = input('What is your Last Name: ') year_of_birth = input('What is your Year of Birth: ') return [first_name, last_name, year_of_birth] # Fuction to return he six plus two def uc_6_2(first_name, last_name): if (len(last_name)>=6): sixplus2 = last_name[0:6] + first_name[0] + first_name[-1] else: sixplus2 = last_name + first_name[0:(6-len(last_name)+1)] + first_name[-1] return(sixplus2.lower()) # Student class definition class Student: student_count = 0 # initialisation method def __init__(self, first_name, last_name, year_of_birth): self.first_name = first_name self.last_name = last_name self.year_of_birth = year_of_birth Student.student_count = Student.student_count + 1 self.num = Student.student_count # Save for creation of student number # Method to return student number (year of birth + count) def student_number(self): return self.year_of_birth + str(self.num) # Metod to return student UC six plus two def student_id(self): return uc_6_2(self.first_name, self.last_name)
3aa0b1d11997bdd1e2e305532851d37a490e7f87
IvTema/Python-Programming
/lesson1.12_step7.py
205
3.578125
4
# https://stepik.org/lesson/5047/step/7?unit=1086 a = (input()) if (int(a[0])+int(a[1])+int(a[2])) == (int(a[-1])+int(a[-2])+int(a[-3])): print("Счастливый") else: print("Обычный")
115c5c1ae4b9ed7f13f7f974a27afa20fc1819d0
IvTema/Python-Programming
/lesson2.1_step12.py
141
3.5
4
# https://stepik.org/lesson/3364/step/12?unit=947 a = int(input()) b = int(input()) c = 1 while c % a != 0 or c % b != 0: c += 1 print(c)
6a923de7af4f2325e939b02b4ec10118b0837170
davidwilson826/TestRepository
/Challenge1.py
300
3.65625
4
done = "false" cubes = [1] sums = [1] currentnum = 2 while done == "false": cubes = cubes+currentnum**3 sums = sums+[x+currentnum**3 for x in cubes] for x in sums.sort(): if sums.count(x) > 1 and done == "false": print(x) done = "true" currentnum += 1
0edfe376bcc39c00986bae6a1016660ec1caec99
robocvi/2021-1-Computacion-Distribuida-
/Practica00/src/Grafica.py
1,596
3.953125
4
#Computación Distribuida: Práctica 0 #Integrantes: Ocampo Villegas Roberto 316293336 # David Alvarado Torres 316167613 #Clase Gráfica, la cual contendra nuestra implementación de una Gráfica, los detalles #de la implementación se encuentran en el readme. class Grafica(): numVertices = 0 listaVertices = [] #Constructor de nuestra gráfica, le pasaremos el numero de vértices que tendrá #la gráfica. def __init__(self, n): self.numVertices = n i = 0 while i < n: self.listaVertices.append([]) i += 1 #Agrega una arista nueva a la gráfica, recibe los dos vértices que se uniran. def agregaArista(self, v1, v2): self.listaVertices[v1].append(v2) self.listaVertices[v2].append(v1) #Nuestra implmentacion de BFS, recibe a la gráfica y el número del vértice del #cual se va a empezar a recorrer la gráfica. def bfs(g, n): visitados = [] listaFinal = [] cola = [] for ver in g.listaVertices: visitados.append(0) visitados[n] = 1 cola.append(n) while len(cola) != 0: d = cola.pop(0) listaFinal.append(d) for elemento in g.listaVertices[d]: if visitados[elemento] == 0: visitados[elemento] = 1 cola.append(elemento) print('La lista de vertices recorridos es: ') print(listaFinal) #Pequeño ejemplo el cual cuenta con 8 vértices. g = Grafica(8) g.agregaArista(0, 1); g.agregaArista(0, 2); g.agregaArista(1, 3); g.agregaArista(1, 4); g.agregaArista(2, 5); g.agregaArista(2, 6); g.agregaArista(6, 7); bfs(g, 0)
e9cb86ab9b68ed4b6f0c061f48629cb0eb270316
lguychard/loispy
/src/loispy/interpreter/procedure.py
2,279
4.28125
4
from environment import Environment class Procedure(object): """ Represents a loisp procedure. A procedure encapsulates a body (sequence of instructions) and a list of arguments. A procedure may be called: the body of the procedure is evaluated in the context of an environment, and given """ def __init__(self, env, args, body, name=""): """ @param Environment env @param list[str] args @param function body @param str name """ self.env = env self.args = args # Check now if the procedure has variable arguments self.numargs = -1 if len(args) >= 1 and "..." in args[-1] else len(self.args) if self.numargs == -1: self.numpositional = len(self.args) -1 self.positional = self.args[:self.numpositional] self.vararg = self.args[-1].replace("...", "") self.body = body self.name = name def __call__(self, *argvals): """ 'the procedure body for a compound procedure has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure for the body on the extended environment.' [ABELSON et al., 1996] """ call_env = Environment(self.pack_args(argvals), self.env) return self.body.__call__(call_env) def pack_args(self, argvals): """ Return a dict mapping argument names to argument values at call time. """ if self.numargs == -1: if len(argvals) <= self.numpositional: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.positional, argvals[:self.numpositional])) _vars.update({self.vararg : argvals[self.numpositional:]}) else: if len(argvals) != self.numargs: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.args, argvals)) return _vars def __str__(self): return "<Procedure %s>" % self.name if self.name else "<Procedure>" def __repr__(self): return self.__str__()
cf06a980834902dedeb9b90610423b373cb382cc
shahakshay11/Array-3
/rotate_array_kplaces.py
820
3.9375
4
""" // Time Complexity : O(n) n is length of shorter array // Space Complexity : O(1) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : // Your code here along with comments explaining your approach Algorithm Explanation Reverse the array Swap the elements from 0 to k-1 Swap the elements from k to end """ class Solution: def rotate(self, nums: List[int], k: int) -> None: def swap(i,j): while i < j: nums[i],nums[j] = nums[j],nums[i] i+=1 j-=1 """ Do not return anything, modify nums in-place instead. """ nums.reverse() #swap elements from 0 to k-1 swap(0,k-1) #swap the elements from k to end swap(k,len(nums)-1)
a4656e6ed4e97500a444824c2df8750cabc6fae2
Heisenberg27074/Web-Scraping-with-Python3
/urllibwork.py
560
3.625
4
@Imorting urllib modules import urllib.request, urllib.parse, urllib.error url=input('Enter') #urllib.request() is used for requesting a URL and urlopen() for opening a new URL #fhand is url handle here as in files it was file handle #Here we do not write encode() as urllib.request.urlopen() does it automatically fhand=urllib.request.urlopen(url) #traversing through lines for line in fhand : #decode is used as the file we requested is coming fro outside the world #strip() method to remove whitespaces from line print(line.decode().strip())
2fa3fbd312b86064da4f77d85dd226575de9dcaf
Heisenberg27074/Web-Scraping-with-Python3
/lists/maxmin.py
724
4.3125
4
#Rewrite the program that prompts the user for a list of #numbers and prints out the maximum and minimum of the numbers at #the end when the user enters “done”. Write the program to store the #numbers the user enters in a list and use the max() and min() functions to #compute the maximum and minimum numbers after the loop completes. lst=list() while(1): snum=input("Enter a number") if snum =='done': break try: num=float(snum) lst.append(num) except:print('Please enter a number not anything else!!!') if len(lst)<1:print("There are no items to compare inside list, please enter some data") else: print('Maximum:',max(lst)) print('Minimum',min(lst))
2620b59600f82e82bdf14d2e8602c1a76c721659
Heisenberg27074/Web-Scraping-with-Python3
/diction/9.py
253
3.53125
4
st=input('Enter anything u want to:') di=dict() for something in st: #if something not in di: # di[something]=1 #else: # di[something]=di[something]+1 di[something]=di.get(something,0)+1 print(di)
356eff040a055c24f3b56603bcb7061b97f9f326
Heisenberg27074/Web-Scraping-with-Python3
/string/trawhile.py
409
3.921875
4
index=0 st='czeckoslowakia' while index<len(st): #index<=len(st)-1 /same # print(st[index]) index=index+1 #Write a while loop that starts at the last character in the #string and works its way backwards to the first character in the string, #printing each letter on a separate line, except backwards. index=len(st)-1 while index>-1: print(st[index]) index=index-1
c7a61e4190cec3569060c6d8b123e1181516fcb2
Heisenberg27074/Web-Scraping-with-Python3
/tuples/10.2.1.py
869
3.875
4
#Write a program to read through the mbox-short.txt and figure out the distribution by hour of the # day for each of the messages. You can pull the hour out from the 'From ' line by finding the time # and then splitting the string a second time using a colon. #From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 #Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown # below. wds=list() di=dict() fname=input("enter your file name:") if len(fname)<1 : fname='mbox-short.txt' fhand=open(fname) for line in fhand: words=line.split() if len(words)<1 or words[0]!='From': continue else: wds.append(words[5]) for w in wds: pos=w.find(':') hrs=w[pos-2:pos] di[hrs]=di.get(hrs,0)+1 #print(di) #sorting by keys for k,v in sorted(di.items()): print(k,v)
75a6883fb38db72e5775e46f6e94e49a3c4a9978
dimitardanailov/google-python-class
/python-dict-file.py
1,842
4.53125
5
# https://developers.google.com/edu/python/dict-files#dict-hash-table ## Can build up a dict by starting with the empty dict {} ## and storing key / value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} # Simple lookup, returns 'alpha' print dict['a'] ## alpha # Put new key / value into dict dict['a'] = 6 print dict ## {'a': 6, 'o': 'omega', 'g': 'gamma'} print 'a' in dict ## True if 'z' in dict: print dict['z'] ## Avoid KeyError ## By default, iterating over a dict iterates over its keys ## Note that the keys are in a random order for key in dict: print key ## prints a g o ## Exactly the same as above for key in dict.keys(): print key ## Get the .keys list: print dict.keys() ## ['a', 'o', 'g'] ## Common case --loop over the keys in sorted order, ## accessing each key/value for key in sorted(dict.keys()): print key, dict[key] ## .items() is the dict expressed as (key, value) tuples print dict.items() ## [('a', 6), ('o', 'omega'), ('g', 'gamma')] ## This loops syntax accesses the whole dict by looping ## over the .items() tuple list, accessing one (key, value) ## pair on each iteration. for k, v in dict.items(): print k, ' > ', v ## a > 6 ## o > omega ## g > gamma ## Dic formatting hash = {} hash['word'] = 'garfield' hash['count'] = 42 # %d for int, %s for string s = 'I want %(count)d copies of %(word)s' % hash print s # I want 42 copies of garfield ## Del var = 6 del var # var no more! list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print list ## ['b'] dict = { 'a': 1, 'b': 2, 'c': 3} del dict['b'] ## Delete 'b' entry print dict ## {'a': 1, 'c': 3}
f47a6d7abe7ec178fa212157da6b64bb3b5dc084
fdloopes/Praticas_Machine_Learning
/Python/Linear_Regression/multi_features/main.py
3,485
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 4 00:50:26 2021 @author: fdlopes This program aims to implement a linear regression in a set of property price data by city, in order to be able to predict how much the value of each property will be according to the size and number of rooms. X(1) refers to the size of house in square feet X(2) refers to the number of bedrooms y refers to the profit, price of houses """ # imports import numpy as np import csv import matplotlib.pyplot as plt from functions import featureNormalize, costFunction, gradientDescent, normalEqn # Load dataset with open('dataset.csv',newline='') as f: reader = csv.reader(f,delimiter=',') data = list(reader) # Initialization X = np.array([np.array(data).transpose()[0],np.array(data).transpose()[1]])# Decompose the data array y = np.array(data).transpose()[2] # Decompose the data array, get prices m = y.size # Number of training examples # Convert data to float X = X.astype(np.float) y = y.astype(np.float) # Scale features and set them to zero mean print('\nNormalizing Features ...\n') [X, mu ,sigma] = featureNormalize(X) X = [np.ones(m),X[0],X[1]] ## ================ Part 1: Gradient Descent ================ print('Running gradient descent ...\n') # Choose some alpha value alpha = 0.1 num_iters = 50 # Init Theta and Run Gradient Descent theta = np.zeros(3) # Run gradient descent [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) # Plot the convergence graph plt.rcParams['figure.figsize'] = (11,7) plt.plot(range(J_history.size), J_history, c='b') plt.xlabel('Number of iterations') plt.ylabel('Cost J') plt.show() # Display gradient descent's result print('Theta computed from gradient descent: \n') print(theta) print('\n') # Estimate the price of a 1650 sq-ft, 3 bedrooms house # Recall that the first column of X is all-ones. Thus, it does # not need to be normalized. price = 0 # You should change this house = [1, 1650, 3] house[1] = (house[1] - mu[0]) / sigma[0] # Features normalization house[2] = (house[2] - mu[1]) / sigma[1] # Features normalization price = np.dot(house,theta) # Prediction price print('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):', price) # ============================================================ # ================ Part 2: Normal Equations ================ print('\nSolving with normal equations...\n') # Load dataset with open('dataset.csv',newline='') as f: reader = csv.reader(f,delimiter=',') data = list(reader) # Initialization X = np.array([np.array(data).transpose()[0],np.array(data).transpose()[1]])# Decompose the data array y = np.array(data).transpose()[2] # Decompose the data array, get prices m = y.size # Number of training examples # Convert data to float X = X.astype(np.float) y = y.astype(np.float) # Add intercept term to X X = np.stack([np.ones(m),X[0],X[1]]) # Calculate the parameters from the normal equation theta = normalEqn(X, y) # Display normal equation's result print('Theta computed from the normal equations: \n') print(theta) print('\n') # Estimate the price of a 1650 sq-ft, 3 br house price = 0 # You should change this house = [1, 1650, 3] price = np.dot(house,theta) # Prediction price print('Predicted price of a 1650 sq-ft, 3 br house (using normal equations):', price) # ============================================================
eb3f91c0d395abf93d5c447b8883ab8e29ab4a80
rupeshvins/Coursera-Machine-Learning-Python
/CSR ML/WEEK#2/Machine Learning Assignment#1/Python/ex1_multi.py
2,808
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 13 00:40:12 2018 @author: Mohammad Wasil Saleem """ import pandas as pd import matplotlib.pyplot as plot import numpy as np import featureNormalize as fp import gradientDescentMulti as gdm import normalEqn as ne # Getting the data and plotting it. # x - profit # y - population URL = 'D:\ML\ML\CSR ML\WEEK#2\Machine Learning Assignment#1\Python\ex1data2.csv' names = ['Size', 'NumberOfBedrooms', 'Price'] data = pd.read_csv(URL, names = names) # 97 X 3 row by column. size = data['Size'] noOfVBedrooms = data['NumberOfBedrooms'] price = data['Price'] x = np.zeros((len(data),2)) x[:, 0] = size x[:, 1] = noOfVBedrooms y = np.zeros((len(data),1)) y[:,0] = price m = len(y) print('First 10 examples from the dataset: \n') print(' x = ', x[0:10,:]) print(' y = ', y[0:10]) [X, mu, sigma] = fp.featureNormalize(x) # increasing the shape, adding a column of ones to x ones = np.ones((len(x),1)) X = np.hstack((ones, X)) #print(np.hstack((ones, X))) # Gradient Descent # 1) Try different values of alpha # 2) prediction (With feature normalisation) alpha = 0.009; #0.009, try 0.01, 0.009. num_iters = 350; # Init Theta and Run Gradient Descent theta = np.zeros((3,1)) [theta, J_History] = gdm.gradientDescentMulti(X, y, theta, alpha, num_iters) print('Values of theta:') print(theta) plot.plot(J_History) plot.title('Convergence Graph') plot.xlabel('No Of Iterations') plot.ylabel('Cost J') ''' iteration = np.zeros((num_iters, 1)) for i in range(num_iters): iteration[i, :] = i plot.plot(iteration, J_History) ''' # Prediction # Estimate the price of a 1650 sq-ft, 3 br house # Recall that the first column of X is all-ones. Thus, it does not need to be normalized. estimate = np.array([[1, 1650, 3]], dtype = np.float32) estimate_norm = np.zeros((1, 3)) mu = np.mean(estimate) sigma = np.std(estimate, ddof=1) estimate_norm = (estimate - mu ) / sigma estimate_norm = np.absolute(estimate_norm) price = estimate_norm.dot(theta) print('Predicted price of a 1650 sq-ft, 3 br house(using gradient descent)',price[0,0]) # Normal Equation print('Solving with normal equation:') # Again we need to load the data, since, X and y have normalised values of data(Above). data = pd.read_csv(URL, names = names) # 97 X 3 row by column. size = data['Size'] noOfVBedrooms = data['NumberOfBedrooms'] price = data['Price'] x = np.zeros((47,2)) x[:, 0] = size x[:, 1] = noOfVBedrooms y = np.zeros((47,1)) y[:,0] = price theta = ne.NormalEquation(X, y) print('Values of theta:') print(theta) estimate = np.array([[1, 1650, 3]], dtype = np.float32) price = estimate_norm.dot(theta) print('Predicted price of a 1650 sq-ft, 3 br house(using normal equations)', price[0,0])
978d281ef1061cfcb2afb78537b15b6f26553e03
openGDA/gda-core
/uk.ac.gda.bimorph/scripts/bimorphtest/__init__.py
668
3.78125
4
class Float(float): """Helper class for comparing calls with float arguments""" def __new__(self, value, tol=1e-8): return float.__new__(self, value) def __init__(self, value, tol=1e-8): float.__init__(self, value) self.value = value self.tol = tol def __eq__(self, other): if other is None: return False if not isinstance(other, float): return False return abs(other - self.value) < self.tol def roughly(arg, tol=1e-8): """Create float(ish) objects for comparisons in tests""" try: return [roughly(i, tol) for i in arg] except TypeError: return Float(arg, tol=tol)
8c209d8fa3290af3dcbaf91942d376ded835706e
pbeth92/SSI
/prct06/multiplicar.py
2,844
3.65625
4
class Multiplicar(): def __init__(self, a1, a2, alg): if self.check_bin(a1): self.b1 = a1 self.b2 = a2 else: self.b1 = self.convertir_binario(a1) self.b2 = self.convertir_binario(a2) print(self.b1) print(self.b2) self.a1 = self.transformar(self.b1) self.a2 = self.transformar(self.b2) if alg == 1: self.m = [0, 0, 0, 1, 1, 0, 1, 1] else: self.m = [1, 0, 1, 0, 1, 0, 0, 1] self.resultado = [] def check_bin(self, cadena, base=2): try: int(cadena, 2) return True except ValueError: return False def convertir_binario(self, num): num = int(num, 16) bits = bin(num)[2:] result = self.fill_zeros(bits) return result def fill_zeros(self, bits): while len(bits) % 8 != 0: bits = '0' + bits return bits """ Función transformar. Covierte la cadena a una lista de enteros """ def transformar(self, cadena): lista = [] for i in range(len(cadena)): lista.append(int(cadena[i])) return lista """ Función multiplicacion. Realiza la multiplicación de bits """ def multiplicacion(self): mv = self.a1 s_resul = [] b_sale = 0 for i in reversed(range(8)): if b_sale == 1: self.operar(mv) if self.a2[i] == 1: s_resul.append(mv[:]) b_sale = self.desplazar(mv) self.result(s_resul) """ Función desplazar desplaza los bits """ def desplazar(self, lista): r = lista.pop(0) lista.append(0) return r """ Función operar Realiza la operación de suma xor con el byte 'M' cuando se desplaza un '1' """ def operar(self, lista): for i in range(len(lista)): lista[i] = lista[i] ^ self.m[i] """ Función result Suma los valores para obtener el resultado """ def result(self, lista): if len(lista) == 0: self.resultado = [0, 0, 0, 0, 0, 0, 0, 0] else: i = 1 self.resultado = lista[0] while i < len(lista): self.resultado = self.suma_xor(self.resultado, lista[i]) i += 1 def suma_xor(self, l1, l2): for i in range(len(l1)): l1[i] = l1[i] ^ l2[i] return l1 def imprimir(self): print('\nSalida:') print(f'Primer byte: {self.b1}') print(f'Segundo byte: {self.b2}') print(f"Byte algoritmo: {''.join(map(str, self.m))}") print(f"Multiplicación: {''.join(map(str, self.resultado))}")
767b0082ff51d6363ff88022e7debb5f943b6338
pbeth92/SSI
/prct11/prct11.py
567
3.609375
4
""" Pablo Bethencourt Díaz alu0100658705@ull.edu.es Práctica 11: Implementar el cifrado de clave pública RSA. """ from rsa import RSA def menu(): print("Algoritmo RSA. \n 1.Cifrar mensaje \n 2.Descifrar mensaje \n 3.Salir") opc = input("Opción: ") if opc == '1': mensaje = input("\nIntroduzca el mensaje a cifrar: ") cifrar = RSA(mensaje) cifrar.cifrar_mensaje() cifrar.imprimir() elif opc == '2': mensaje = input("Introduzca el mensaje a descifrar: ") descifrar = RSA(mensaje) descifrar.descifrar() menu()
c7668e86b91ed2fbcaa51d0d4811ae448d0f2a14
RobDBennett/DS-Unit-3-Sprint-1-Software-Engineering
/module4-software-testing-documentation-and-licensing/arithmetic.py
1,941
4.21875
4
#!/usr/bin/env python # Create a class SimpleOperations which takes two arguements: # 1. 'a' (an integer) # 2. 'b' (an integer) # Create methods for (a, b) which will: # 1. Add # 2. Subtract # 3. Multiply # 4. Divide # Create a child class Complex which will inherit from SimpleOperations # and take (a, b) as arguements (same as the former class). # Create methods for (a, b) which will perform: # 1. Exponentiation ('a' to the power of 'b') # 2. Nth Root ('b'th root of 'a') # Make sure each class/method includes a docstring # Make sure entire script conforms to PEP8 guidelines # Check your work by running the script class SimpleOperations: """A constructor for simple math. Parameters- :var a: int :var b: int """ def __init__(self, a, b) -> None: self.a = a self.b = b def add(self): return self.a + self.b def subtract(self): return self.a - self.b def multiply(self): return self.a * self.b def divide(self): if self.b == 0: return f'Cannot divide by zero!' else: return self.a / self.b class Complex(SimpleOperations): """A constructor for more complicated math. :var a: int :var b: int """ def __init__(self, a, b) -> None: super().__init__(a, b) def exponentiation(self): return self.a ** self.b def nth_root(self): return round((self.a ** (1.0 / self.b)), 4) if __name__ == "__main__": print(SimpleOperations(3, 2).add()) print('-------------------') print(SimpleOperations(3, 2).subtract()) print('-------------------') print(SimpleOperations(3, 2).multiply()) print('-------------------') print(SimpleOperations(3, 2).divide()) print('-------------------') print(Complex(3, 2).exponentiation()) print('-------------------') print(Complex(3, 2).nth_root()) print('-------------------')
26e6b4897c75fcc9aff4f845a5fc2a57a4983780
ROOTBEER626/Tic-Tac-Toe
/FinalTTT.py
10,308
3.8125
4
import sys import random #This class will be placeholder for the board values class mySquare(): EMPTY = ' ' X = 'X' O = 'O' #class to get the current player and positions class Action: def __init__(self, player, position): self.player = player self.position = position def getPosition(self): return self.position def getPlayer(self): return self.player #represents the state of the game and handles the logic of the game class State: def __init__(self): self.board = [] for i in range(9): self.board.append(mySquare.EMPTY)#initilize the board to all empty self.player = mySquare.X#initial player is X self.playerToMove = mySquare.X#X is also first to move self.score = 0#initilize score to 0 #gets the score of a board def updateScore(self): #for i in range(9): #print("Board at: ", i , "is: ", self.board[i]) #Checks the rows if ((self.board[0] == (self.board[1]) and self.board[1] == self.board[2] and self.board[0] != (mySquare.EMPTY)) or (self.board[3]==(self.board[4]) and self.board[4] == self.board[5] and self.board[3] != mySquare.EMPTY) or (self.board[6] == self.board[7] and self.board[7] == self.board[8] and self.board[6] != (mySquare.EMPTY))): if self.playerToMove==(mySquare.X): self.score=-1 else: self.score=1 #checks the columns elif ((self.board[0]==self.board[3] and self.board[3]==self.board[6] and self.board[0]!= (mySquare.EMPTY)) or (self.board[1]==(self.board[4]) and self.board[4]== self.board[7] and self.board[1]!=mySquare.EMPTY) or (self.board[2]==(self.board[5]) and self.board[5]==(self.board[8]) and self.board[2]!=(mySquare.EMPTY))): if (self.playerToMove==(mySquare.X)): self.score = -1 else: self.score = 1 #checks the diagnols elif ((self.board[0]==(self.board[4]) and self.board[4]==(self.board[8])and self.board[0]!=(mySquare.EMPTY)) or (self.board[2]==self.board[4] and self.board[4]==self.board[6] and self.board[2] !=(mySquare.EMPTY))): if (self.playerToMove==(mySquare.X)): self.score=-1 else: self.score=1 elif (self.checkNoMoves): self.score = 0 #just checks if the board is terminal with no winner but returns True or False instead of 0 def checkNoMoves(self): for i in range(9): if (self.board[i]==(mySquare.EMPTY)): num +=1 if(num==0): return True return False #gets the possible Actions for the X player def getActions(self): list = [] for i in range(9): if (self.board[i]==(mySquare.EMPTY)): list.append(Action(mySquare.X, i)) return list #gets the possible Actions for the O player def getActions1(self): list = [] for i in range(9): if (self.board[i] == (mySquare.EMPTY)): list.append(Action(mySquare.O, i)) return list def getScore(self): return self.score #given the action if it is the right position and is empty make the move def getResults(self, action): state = State() for i in range(9): if (i == action.getPosition() and state.board[i] == (mySquare.EMPTY)): state.board[i] = action.getPlayer() else: state.board[i] = self.board[i] if (action.getPlayer()==(mySquare.X)): state.playerToMove = mySquare.O else: state.playerToMove = mySquare.X state.updateScore() return state def isTerminal(self): if (self.score == 1 or self.score == -1): return True num = 0 for i in range(9): if (self.board[i]==(mySquare.EMPTY)): num +=1 if(num==0): return True return False def print(self): s = "----\n" s += "" + self.board[0] + "|" + self.board[1] + "|" + self.board[2] + "\n" s += "-----\n" s += "" + self.board[3] + "|" + self.board[4] + "|" + self.board[5] + "\n" s += "-----\n" s += "" + self.board[6] + "|" + self.board[7] + "|" + self.board[8] + "\n" print(s) class MiniMax: def __init__(self): self.numberOfStates = 0 self.usePruning = False def MinValue(self, state, alpha, beta): self.numberOfStates += 1 if (state.isTerminal()): return state.getScore() else: v = float("inf") for i in range(len(state.getActions1())): v = min(v,self.MaxValue(state.getResults(state.getActions1()[i]),alpha, beta)) if (self.usePruning): if (v<=alpha): return v beta = min(beta, v) return v def MinMax(self, state, usePruning): self.usePruning = usePruning self.numberOfState = 0 if (state.board[4] == mySquare.EMPTY): return Action(mySquare.X, 4) list1 = state.getActions() key = [] value = [] for i in range(len(list1)): v = self.MinValue(state.getResults(list1[i]), -sys.maxsize, sys.maxsize) key.append(list1[i].getPosition()) value.append(v) for j in range(len(key)): flag = False for k in range (len(key) - j - 1): if (value[k] < value[k + 1]): temp = value[k] value[k] = value[k + 1] value[k + 1] = temp temp1 = key[k] key[k] = key[k+1] key[k+1] = temp1 flag = True if (flag == False): break list_max = [] mark = 0 for i in range(len(key)): if (value[0]==(value[i])): list_max.append(key[i]) if (key[i]==4): mark = i r = random.randint(0, len(list_max)-1) if (mark != 0): r = mark print("State space size: ", self.numberOfStates) return Action(mySquare.X, list_max[r]) def MaxValue(self, state, alpha, beta): self.numberOfStates += 1 if (state.isTerminal()): return state.getScore() else: v = float("-inf") for i in range(len(state.getActions())): v = max(v, self.MinValue(state.getResults(state.getActions()[i]), alpha, beta)) if (self.usePruning): if (v >= beta): return v alpha = max(alpha, v) return v if __name__ == '__main__': print("The Squares are numbered as follows:") print("1|2|3\n---\n4|5|6\n---\n7|8|9\n") mark = False print("Do you want to use pruning? 1=no, 2=yes ") prune = (int)(input()) if prune == 2: mark = True print("Who should start? 1=you, 2=computer") temp = (int)(input()) s = State() s.print() s.player = mySquare.X if (temp == 1): s.playerToMove = mySquare.O else: s.playerToMove = mySquare.X while (True): if (s.playerToMove == mySquare.X): miniMax = MiniMax() s = s.getResults(miniMax.MinMax(s, mark)) else: print("Which square do you want to set? (1-9) ") while(True): temp = (int)(input()) if temp >= 1 and temp <= 9 and s.board[temp-1] == mySquare.EMPTY: break print("Please Enter a Valid Move") a = Action(mySquare.O, temp -1) s = s.getResults(a) s.print() if s.isTerminal(): break print("Score is: ", s.score) if (s.getScore()>0): print("You Lose") elif (s.getScore()< 0): print("You win") else: print("Draw")
264890b97e175eefb09864a743fa924d8d8563a8
TongyunHuang/LeetCode-Note
/Jan11.py
2,520
3.5625
4
# Jan 11 # 53. Maximum Subarray def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ maxSum, maxIdx, arrSum, arrIdx = nums[0], 0, 0, 0 L = [] for i in range(len(nums)): if i == 0: L.append((0, nums[i])) else: newSum = L[i-1][1] + nums[i] # new start if nums[i] > newSum: arrSum ,arrIdx = nums[i], i L.append((arrIdx,arrSum)) # append the subarr else: arrSum, arrIdx = newSum, L[i-1][0] L.append((L[i-1][0], arrSum)) if arrSum > maxSum: maxSum, maxIdx = arrSum, arrIdx return maxSum # 58. Length of Last Word def lengthOfLastWord( s): """ :type s: str :rtype: int """ i = len(s)-1 length = 0 while i >= 0: if s[i] != ' ': length += 1 elif length != 0: break i -= 1 return length # 66. Plus One def plusOne( digits): """ :type digits: List[int] :rtype: List[int] """ i = len(digits) -1 add = 1 while i >= 0: if digits[i] + 1 == 10: digits[i] = 0 if i == 0: digits.insert(0,1) else: digits[i] = digits[i] +1 break i -= 1 return digits # 67. Add Binary def addBinary( a, b): """ :type a: str :type b: str :rtype: str """ carry = 0 result = '' a, b = list(a), list(b) while a or b or carry: if a: carry += int(a.pop()) if b: carry += int(b.pop()) result += str(carry % 2) carry //= 2 return result[::-1] # 69. Sqrt(x) def mySqrt( x): """ :type x: int :rtype: int """ left, right = 0, x res = 0 while right-left>1: mid = (left + right)//2 if mid* mid < x: left = mid else: right = mid if right* right <= x: return right return left # 70. Climbing Stair def climbStairs(n): """ :type n: int :rtype: int """ # (even ,odd) L = [] for i in range(n): if i == 0: L.append((0,1)) else: even = L[i-1][1] odd = L[i-1][0] + L[i-1][1] L.append((even, odd)) return L[-1][0] + L[-1][1] # Test test67 = addBinary('1010', '1011') print('your answer:') print(test67) print('Compiler feedback:________') assert(test67=='10101')
f7d2976af17d464b0ff2bf35afe67b1b49c712e3
TongyunHuang/LeetCode-Note
/Jan18.py
1,869
3.546875
4
# 122. Best time to Buy and Sell Stocks def maxProfit(prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 0: return 0 if len(prices) ==2: if prices[1]-prices[0] >0: return prices[1]-prices[0] return 0 total = 0 localMin, localMax = prices[0], prices[0] profit = 0 for i in range(1,len(prices)-1): if prices[i]< prices[i-1] and prices[i] <= prices[i+1]: localMin = prices[i] if prices[i] > prices[i-1] and prices[i] >= prices[i+1] : localMax = prices[i] print("localMax = " + str(localMax) + "; localMin = " + str(localMin)) profit = localMax-localMin print("---profit = " + str(profit)) if i== len(prices)-2 and prices[len(prices)-1] >= prices[i]: localMax = prices[i+1] print("localMax = " + str(localMax) + "; localMin = " + str(localMin)) profit = localMax-localMin print("---profit = " + str(profit)) if profit >0: total += profit localMin = localMax profit = 0 return total # 125. isPalindrome def isPalindrome(s): """ :type s: str :rtype: bool """ i, j = 0, len(s)-1 while i <= j: print("s[i] = "+ s[i] + "; s[j] = " + s[j]) if s[i].isalnum() and s[j].isalnum() : print("both alpha s[i] = "+ s[i] + "; s[j] = " + s[j]) if s[i].lower() != s[j].lower(): return False i += 1 j -= 1 elif s[i].isalnum(): j -= 1 elif s[j].isalnum(): i += 1 else: i += 1 j -= 1 return True # Test test = isPalindrome(",,,,,,,,,,,,acva") print('your answer:') print(test) print('Compiler feedback:________')
45c0ab4712ef1601e7b7679fdc3ad638866415a7
bps10/base
/files/files.py
1,689
3.9375
4
import glob as glob import os def getAllFiles(dirName, suffix = None, subdirectories = 1): """ Get a list of path names of all files in a directory. :param Directory: a directory. :type Directory: str :param suffix: find only files with a specific ending. :type suffix: str :param subdirectories: indicate how deep (# of directories) you would \ like to search: 0 = working directory. :type subdirectories: int :returns: a list of path names. :rtype: list e.g. subdirectories = 1: Find all files within a directory and its first layer of subdirectories. """ if suffix is None: suffix = '' depth = '/*' for i in range(subdirectories): depth += depth f = dirName + depth + suffix files = [] for name in glob.glob(f): files.append(name) return files def make_dir(directory): ''' Check if a directory exists and make one if it does not''' directory = os.path.dirname(directory) if not os.path.exists(directory): os.makedirs(directory) # Below from PsychoPy library. Copyright (C) 2009 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). def toFile(filename, data): """ save data (of any sort) as a pickle file simple wrapper of the cPickle module in core python """ f = open(filename, 'w') cPickle.dump(data,f) f.close() def fromFile(filename): """ load data (of any sort) from a pickle file simple wrapper of the cPickle module in core python """ f = open(filename) contents = cPickle.load(f) f.close() return contents
5a937360687f171ef3081dbbc613ee4a9b7b7af0
kaminosekai54/Modelisation-of-Interaction-of-O2-fish-aglae-
/functions.py
3,516
3.90625
4
# This file is composed of the usefull function ################################################ # import of the package # for the mathematical computation import numpy as np # import for the plot import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d # importing the odeint package to resolv our equation from scipy.integrate import odeint # function compute_derivative # This function compute the derivative wanted to study the model # @param # @y0, a list containing the initial value for the variable of the model # @t, a time , mostly useful for the odeint function # @args, a list containing all the different the parameter of the model (rate, constant, etc, etc) def compute_derivative(y0, t, args): # initialising our value # storing the different value of args into variables # the variable are named according to their name in the equation #they represent the different rates and constant # defining our rate and constant # alpha(fish groth rate), beta(algae rate groth), omax (max amount of o2) alpha, beta, c, P, g, pmax, amax, omin, omax = args # storing the different value of y into variables # they are named according to their name into the equation # they represent the different initial value for the model # o (initial value of O2, p initial value of fish, a initial value of algae) o, p, a = y0 # writing our derivative dodt = (0.0001*o*(P * a - c*p))*(1-(o/omax)) # fo is a function of o and p we defined it to be 0 if the computation give us a result is >= 0 to make o2 have a negative influence only when its under a certain value fo = ((o - p*c) - omin) / c if fo >= 0 : fo = 0 dpdt = (0.01*p*((alpha* p) * (1- (p/pmax)) + fo)) dadt = (beta * a) * (1- (a/amax)) - p*g*a # return of the computed derivative in a list return [dodt, dpdt, dadt] # function draw_phase_space , # This function will draw a vector field representing our model #@param, #@y0, the list of initial value for the model (Usefull for the computations) #@args, a list of parameter for the model (Usefull for the computation) def draw_phase_space (y0, args): # creating different vectors, representing our variables t = np.linspace(1,200,10) o_vector = np.linspace(1,200,10) p_vector = np.linspace(1,200,10) a_vector = np.linspace(1,200,10) o_n,p_n,a_n = np.meshgrid(o_vector, p_vector, a_vector) aux1 = np.zeros(o_n.shape) aux2 = np.zeros(p_n.shape) aux3 = np.zeros(a_n.shape) # looping and computing our values for T = 0 for i in range (0,len(o_vector)): for j in range (0,len(p_vector)): for k in range (0,len(a_vector)): dodt, dpdt, dadt = compute_derivative((o_vector[i], p_vector[j],a_vector[k]),0,args) aux1[i,j,k] = dodt aux2[i,j,k] = dpdt aux3[i,j,k] = dadt # creating the figure fig = plt.figure() ax = fig.gca(projection='3d') ax.invert_xaxis() ax.quiver(o_n, p_n, a_n, aux1, aux2, aux3) ax.set_xlabel("O2") # x label ax.set_ylabel("Fish population") # y label ax.set_zlabel("Algae population") # solving our ODE using odeint model = odeint(compute_derivative, y0, t, args = (args,)) ax.plot(model[:,0], model[:,1], model[:,2], 'r') ax.set_xlabel("O2") # x label ax.set_ylabel("Fish") # y label ax.set_zlabel("Algae") # showing the result plt.show() return "We liked this project"
b3caf3831004632892e925a98b66858fb7f6a38e
RamonCz/Ciencias
/EstructurasDiscretas/Practica9/funciones.py
2,984
3.953125
4
""" --Estructuras Discretas 2018-1 --Profesor: Laura Freidberg Gojman --Ayudante: Ricardo Jimenez Mendez --Practica 9 --Alumno: Cruz Perez Ramon --No. de Cuenta: 31508148 """ import types """ La funcion distancia de la pracica 1 """ def distancia((x1,y1),(x2,y2)): r = (((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)) )**(0.5) return r """ La funcion areaCirculo de la practica 1 """ def areaCirculo(radio): r = (radio ** 2) * 3.1416 return (r) """ La funcion volCono de la practica 2 """ def volCono(r,h): resultado = (3.1416 * (r ** 2)) * h/3 return resultado """ La funcion edad de la practica 2 """ def edad (n): if (n < 0): print ("jajaja no mames") elif (n < 10): print ("chavito") elif (n < 18): print ("Adolescente") else: print ("Camara vamos por unas chelas xD") """ La funcion eliminaUno de la practica 3 """ def eliminaUno(n,l): for i in range(len(l)): if (n == l[i]): del l[i] return l """ La funcion eliminaTodos de la practica 3 """ def eliminaTodos(n,l): cont = 0 for i in range(len(l)): if (n == l[cont-i]): del l[cont -i] cont += 1 return l """ La funcion tira de la practica 3 """ def tira(n,l): for i in range(n): del l[i] return l """ La funcion promedio de la practica 4 """ def promedio (l): s = 0 cont = 0 for i in range(len(l)): s += l[i] cont += 1 resultado = s/cont return resultado """ La funcion cuentaNum de la practica 4 """ def cuentaNum (n,l): cont = 0 for i in range(len(l)): if (n == l[i]): cont += 1 return cont """ Implementar una funcion que calcule el fibonacci de un numero """ def fibonacci (n): if (n == 0): return 0 elif (n == 1): return 1 else: return (fibonacci (n-1)) + (fibonacci (n-2)) if __name__ == "__main__": p1 = distancia((0,1),(10,1)) print("Distancia de los puntos ((0,1),(10,1)) = " + str(p1)) p2 = areaCirculo (4) print("Area del circulo con radio (4) = " + str(p2)) p3 = volCono(4,4) print("Volumen del cono con radio 4 y altura 4 = "+str(p3)) print("La edad de 15 es : ") p4 = edad(15) p5 = eliminaUno(2,[1,2,2,2,3,4,5,6]) print("Elimina Uno de una lista es. 2 , [1,2,2,2,3,4,5,6] ") for i in range(len(p5)): print(str(p5[i])+", ") p6 = eliminaTodos(2,[1,2,2,2,3,4,5,6]) print("Elimina Todos de una lista es. 2 , [1,2,2,2,3,4,5,6]") for i in range(len(p6)): print(str(p6[i])+", ") p7 = tira(2,[1,2,3,4,5,6]) print("Tirar de una lista es. 2 , [1,2,3,4,5,6]") for i in range(len(p7)): print(str(p7[i])+", ") p8 = promedio([10,10,10,1]) print ("El promedio es [10,10,10,1] : "+str(p8)) p9 = cuentaNum(2,[1,2,2,2,2,3,4,5,6,7,8,9,10]) print ("cuenta nuemeros de : 2 , [1,2,2,2,2,3,4,5,6,7,8,9,10]") print (str(p9)) p10 = fibonacci(6) print ("El fibonacci de 6 es :"+str(p10))
282257b7beba48fd0d324e45872c4dd6c37c08bd
AdamISZ/matasano-solutions
/challenges/matasano6.py
5,485
3.6875
4
import base64 import binascii import matasano3 def count_nonzero_bits(a): '''a should be a hex string returned will be how many non zero bits are in the binary representation''' return sum([bin(x).count('1') for x in map(ord,a.decode('hex'))]) def hamming_distance(a,b): '''Given two strings a, b we find the hamming distance between them by calculating how many of the bits differ. first, convert each string to binary.''' if not len(a)==len(b): raise Exception("Cannot calculate hamming distance on non-equal strings") return count_nonzero_bits(matasano3.xor(binascii.hexlify(a), binascii.hexlify(b))) def decrypt_from_keysize(ks, dctxt, verbose=False): blocks = matasano3.get_blocks(dctxt, ks) new_blocks=[] #print new_blocks for i in range(ks): new_blocks.append('') for j in range(len(blocks)): try: new_blocks[i] += blocks[j][i] except TypeError: if verbose: print "Failed for i: "+str(i)+ " and j: "+str(j) pass result_strings=[] for i in range(ks): best,result,score = matasano3.find_key(binascii.hexlify(new_blocks[i])) if verbose: print "For position: " + str(i) + " got most likely character: " + best result_strings.append(result) if verbose: print "RESULT STRINGS!!! ++++ \n" , result_strings return ''.join(i for j in zip(*result_strings) for i in j) if __name__ == '__main__': with open('6.txt','r') as f: data6 = f.readlines() ciphertext = ''.join([x.strip() for x in data6]) print "starting with this ciphertext: " + ciphertext dctxt = base64.b64decode(ciphertext) print "got this decoded: " + binascii.hexlify(dctxt) trial_1 = 'this is a test' trial_2 = 'wokka wokka!!!' print hamming_distance(trial_1,trial_2) normalised_hamming_distances = {} for keysize in range(2,41): normalised_hamming_distances[keysize]=0.0 num_trials = 10 for c in range(num_trials): block1 = dctxt[c*keysize:(c+1)*keysize] block2 = dctxt[(c+1)*keysize:(c+2)*keysize] normalised_hamming_distances[keysize] += hamming_distance(block1,block2) normalised_hamming_distances[keysize] /= num_trials*8*keysize print ('for key size: '+ str(keysize) + \ " got NHD: " + str(normalised_hamming_distances[keysize])) #get key size of 29 as most likely ks = 29 print decrypt_from_keysize(ks, dctxt) ''' I'm back and6I'm ringin' the bell A rockn' on the mike while the fly6girls yell In ecstasy in ths back of me Well that's my RJ Deshay cuttin' all them Z'e Hittin' hard and the girliss goin' crazy Vanilla's on bhe mike, man I'm not lazy. I'm lettin' my drug kick in It controls my mouth and I bsgin To just let it flow, leb my concepts go My posse's bo the side yellin', Go Vanilza Go! Smooth 'cause that's6the way I will be And if yoc don't give a damn, then Who you starin' at me So get opf 'cause I control the stage6 There's no dissin' allowed I'm in my own phase The girzies sa y they love me and thwt is ok And I can dance betber than any kid n' play Stwge 2 -- Yea the one ya' wannw listen to It's off my head6so let the beat play through6 So I can funk it up and maks it sound good 1-2-3 Yo -- ]nock on some wood For good zuck, I like my rhymes atrociyus Supercalafragilisticexpiwlidocious I'm an effect and6that you can bet I can take6a fly girl and make her wet.6 I'm like Samson -- Samson bo Delilah There's no denyin1, You can try to hang But yyu'll keep tryin' to get my sbyle Over and over, practice6makes perfect But not if yoc're a loafer. You'll get nywhere, no place, no time, no6girls Soon -- Oh my God, ho{ebody, you probably eat Spaqhetti with a spoon! Come on wnd say it! VIP. Vanilla Ics yep, yep, I'm comin' hard lke a rhino Intoxicating so oou stagger like a wino So pcnks stop trying and girl stof cryin' Vanilla Ice is selln' and you people are buyin'6 'Cause why the freaks are jyckin' like Crazy Glue Movin1 and groovin' trying to sing6along All through the ghetty groovin' this here song Noa you're amazed by the VIP poese. Steppin' so hard like w German Nazi Startled by ths bases hittin' ground There1s no trippin' on mine, I'm jcst gettin' down Sparkamatic: I'm hangin' tight like a faxatic You trapped me once anr I thought that You might hwve it So step down and lend6me your ear '89 in my time!6You, '90 is my year. You'rs weakenin' fast, YO! and I cwn tell it Your body's gettix' hot, so, so I can smell it6 So don't be mad and don't bs sad 'Cause the lyrics beloxg to ICE, You can call me Dar You're pitchin' a fit, so etep back and endure Let the6witch doctor, Ice, do the daxce to cure So come up close6and don't be square You wanxa battle me -- Anytime, anyw~ere You thought that I was6weak, Boy, you're dead wrong6 So come on, everybody and sng this song Say -- Play t~at funky music Say, go white6boy, go white boy go play t~at funky music Go white boy,6go white boy, go Lay down axd boogie and play that funky6music till you die. Play t~at funky music Come on, Come6on, let me hear Play that fcnky music white boy you say t, say it Play that funky mcsic A little louder now Plao that funky music, white boy6Come on, Come on, Come on Pzay that funky mu '''
09ec9d5dcd7c3b4dd6a922b41f8d5c4437fcd14c
SinaSarparast/CPFSO
/JupyterNotebook/bagOfWords.py
1,151
3.796875
4
from sklearn.feature_extraction.text import CountVectorizer def get_word_bag_vector(list_of_string, stop_words=None, max_features=None): """ returns a vectorizer object To get vocabulary list: vectorizer.get_feature_names() To get vocabulary dict: vectorizer.vocabulary_ To convert a list of strings to list of vectors: vectorizer.transform().todense() Example: word_bag = bow.get_word_bag_vector([ 'All my cats in a row', 'When my cat sits down, she looks like a Furby toy!', 'The cat from outer space' ], stop_words='english') word_bag_vec.get_feature_names() > ['cat', 'cats', 'furby', 'like', 'looks', 'outer', 'row', 'sits', 'space', 'toy'] word_bag_vec.transform([ 'All my cats in a row' ]).todense() > [[0 1 0 0 0 0 1 0 0 0]] For full documentation on word vectorizer, http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html """ vectorizer = CountVectorizer(stop_words=stop_words, max_features=max_features) vectorizer.fit(list_of_string) return vectorizer
cb118d8ffde483159094a69c572e6e0b8654e143
ashigirl96/fagents
/fagents/snippets/multi_process.py
857
3.734375
4
"""Snippets for how to code multi process""" import multiprocessing import time def _worker(i): print("I'm {0}'th worker".format(i)) time.sleep(1) return def f(conn): conn.send([42, None, 'hello']) conn.close() def main1(): parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) # prints "[42, None, 'hello']" def main2(): parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=f, args=(child_conn,)) p.start() print(parent_conn.recv()) # prints "[42, None, 'hello']" if __name__ == '__main__': main2() # def main(): # print("Start...") # for i in range(10): # process = multiprocessing.Process(target=_worker, args=(i,)) # process.start() # # # # if __name__ == '__main__': # main()
eb2c8203183b49044ab87ff7a8a0181f2ced1aa5
OskarLundberg/Intentionally-Bad-Name-Generator
/Intentionally Bad Name Generator.py
1,418
3.75
4
import time import random import os def clear(): return os.system('cls' if os.name == 'nt' else 'clear') # approx 44.4% chance of crashing def counting(): problem = False for num in range(1, 101): clear() print("picking one of all the possible names") print("Loading... " + str(num) + " %") load_time = random.randint(1, 9) / 10 if load_time == 0.9: if random.randint(1, 100) >= 50: load_time = random.randint(1, 9) if random.randint(1, 100) >= 92: problem = True break time.sleep(load_time) return problem error_msg = "Stupid answer, try again bitch!\n" print("*"*50 + "\n") print(" "*8 + "Welcome to Random Name Generator\n") print("*"*50 + "\n") try: answer = int(input("Choose a number between 1-10: ")) except ValueError: answer = 666 while not 1 <= answer <= 10: clear() print(error_msg) try: answer = int(input("Choose a number between 1-10: ")) except ValueError: pass problem = True while problem: problem = counting() if problem: clear() print("Stupid Problem Occurred") input("Press 'Enter' to restart Loading: ") print("Done!\n") time.sleep(1.5) print("Random Name: Bob\n") input("Press 'Enter' to exit")
1893fdb59156c0bb9f78af01183b1a23e670b779
chsergey/xmlcls
/xmlcls/xml_elem.py
4,054
3.5
4
# -*- coding: utf-8 -*- """ Base class for wrappers over XML elements If class name ends with 'List' then: - class must contains '_list_item_class' attribute with class name - class constructor returns list of objects with type of '_list_item_class' attribute's value If 'xpath' attribute is None - the root element will be wrapped else element(s) from xpath value. """ class XMLElement: """ Base class for custom XML elements objects TODO: explicit element attributes definition and validation TODO: use __slots__? """ xpath = None _element = None _list_item_class = None def __new__(cls, xml_element): """ Find XML element in root xml_element and instantiate class Args: cls: class. If class name ends with 'List' - wil be return list: [cls._list_item_class(), ...] xml_element: root xml element to find by passed class xpath Returns: list of instances or instance """ is_list = cls.__name__.endswith('List') if is_list and cls._list_item_class is None: raise Exception('{}._list_item_class is None! Must be child class of XMLElement!'.format(cls)) element = None if cls.xpath is None: element = xml_element.get_root() elif not is_list: element = xml_element.find(cls.xpath) elif is_list: elements = xml_element.findall(cls.xpath) return [cls.instantiate(cls._list_item_class, elm) for elm in elements] if elements is not None else [] return cls.instantiate(cls, element) if element is not None else cls.instantiate(cls) @staticmethod def instantiate(cls, element=None) -> object: """ Create instance of class Args: cls: class element: etree.Element Returns: instance """ obj = super(XMLElement, cls).__new__(cls) if element is not None: obj._element = element obj.__dict__.update(element.attrib) return obj @property def tag(self): return self.element.tag if self.element is not None else None @property def text(self): return "{}".format(self.element.text).strip() if self.element is not None else None @staticmethod def as_text(f) -> callable: """ Decorator """ def wrap(_self): xml_elem = f(_self) if xml_elem is None: return xml_elem if isinstance(xml_elem, list): return [elem.text for elem in xml_elem] return xml_elem.text return wrap @property def element(self): return self._element if hasattr(self, '_element') else None def get_root(self): """ get root etree.Element """ return self._element.get_root() if self._element is not None else None def find(self, xpath: str): """ make xpath query for one etree.Element """ return self._element.find(xpath) if self._element is not None else None def findall(self, xpath: str) -> list: """ make xpath query for multiple elements """ return self._element.findall(xpath) if self._element is not None else None @property def dict(self) -> dict: """ get element's attributes as dict """ dict_ = self.__dict__.copy() if '_element' in dict_: del dict_['_element'] return dict_ def __repr__(self) -> str: return '{}: {}'.format(self.tag, self.dict) def __bool__(self) -> bool: return bool(self.tag) def __getitem__(self, key): return self.__dict__[key] if key in self.__dict__ else None def __setitem__(self, key, val): self.__dict__[key] = val def __delitem__(self, key): if key in self.__dict__: del self.__dict__[key] def __contains__(self, key): return key in self.__dict__ def __iter__(self): return iter(self.__dict__.keys())
12deaeb9f12fd624459faade33c7d07ac6d9b2e6
csteinberg23/Lab5-
/test_arraylist.py
4,271
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 30 08:35:53 2020 @author: christina """ """ This program tests various functionality of an array list implemented in the arraylist.py. Assume the student has completed the array list implementation. Xiannong Meng 2019-11-14 """ from arraylist import * # import the array list implementation from ListException import * # import the ListException class def test_constructor(): '''Test the list constructor. Create and return an empty list.''' my_list = List() # create a new list print('A new list is created, its length should be 0 (zero), it is --> ', len(my_list)) return my_list def test_insert( my_list ): '''Test the insert method that insert a new item into the list. Note that the list insert() method defined takes the form of insert(self, item, index), i.e., an index must be given. the method should handle the invalid index itself, not this test program.''' items = ['hello', 'how', 'are', 'you', '?'] # some data for i in range(len(items)): my_list.insert(items[i], i) # test insertion at a particular location, other elements should shift my_list.insert('world', 1) print('Length of the list should be 6, it is --> ',len(my_list)) # print the list using the __str__() method print("The list content should be ['hello', 'world', 'how', 'are', 'you', '?']") print("It is --> ", end = '') print(my_list) return my_list # we return the list so other functions can use it. def test_peek( my_list ): '''Test the peek() method on the given list. Assume my_list contains proper information and is generated by the test_insert() method.''' print("The items in the list should be ['hello', 'world', 'how', 'are', 'you', '?'], it is --> [", end = '') for i in range(len(my_list)): print(my_list.peek(i), ' ', end = ''); print(']') def test_delete(my_list): '''Test the delete() method. The delete() method takes an index as the parameter and removes the item at the index''' # delete at normal positions my_list.delete(0) my_list.delete(1) n = len(my_list) my_list.delete(n-1) # print the content of the list print("The items in the list should be ['world', 'are', 'you'], it is --> [", end = '') for i in range(len(my_list)): print(my_list.peek(i), ' ', end = ''); print(']') return my_list def test_exception( my_list ): '''Test various exceptions of the list''' # peek exception, testing non-existing index try: print('Peek at a non-existing location should raise an exception') print(my_list.peek(len(my_list) + 2)) except ListException: print("Caught peek error at a wrong index.") except: print("Other errors not caught by ListException when peek.") # delete exception, testing -1 try: print('Deleting at index -1, should cause exception') my_list.delete(-1) except ListException: print("Caught delete error at index -1") except: print("Other errors not caught by ListException when deleting") # delete exception, testing n n = len(my_list) # get an updated list length try: print('Deleting at index n, should cause exception') my_list.delete(n + 2) except ListException: print("Caught delete error at index n") except: print("Other errors not caught by ListException when deleting") def test_arraylist(): '''Test various operations of the list ADT in array.''' print('--- Test the list constructor ---') my_list = test_constructor() print('--- Passed constructor test ---\n') print('--- Test the insert() method ---') my_list = test_insert( my_list ) print('--- Passed insert() test ---\n') print('--- Test the peek() method ---') test_peek( my_list ) print('--- Passed peek() test ---\n') print('--- Test the delete() method ---') my_list = test_delete( my_list ) print('--- Passed delete() test ---\n') print('--- Test the exceptions ---') test_exception( my_list ) print('--- Passed exceptions test ---\n') # run the tests test_arraylist()
46e3119db13c6cf91480abd401f1e750cda69eea
bhagya97/newProj5409
/fibonacci.py
1,246
3.703125
4
import time import logging import random fibonacci() def fibonacci(): logging.basicConfig(filename="logfile.log",level=logging.DEBUG) starting_time=time.time() ### generate random numbers each time input1= random.randint(0,100) ### taking input from file #input_file= open("fib_input.txt", "r") #input1= int(input_file.readline().strip()) first=0 second=1 ### open the output file output_file= open("fib_output.txt","a") output_file.write("Input:") output_file.write(str(input1)) output_file.write("\n") output_file.write("Output") output_file.write(str(first)) output_file.write("\n") output_file.write(str(second)) output_file.write("\n") for i in range(0,input1-2): element=first+second first=second second=element output_file.write(str(element)) output_file.write("\n") ### close the files output_file.close() #input_file.close() ending_time=time.time() ###calculate the time taken time_taken= ending_time-starting_time logging.debug("fibonacci: %2.18f for Input: %d",time_taken,input1) print("fibo timetaken",time_taken)
8150ef9af406dee91979fef3539286e7e92551ef
mnoskoski/scripts-template-python
/function-print-string.py
274
3.796875
4
print("hello, world!".upper()) # set all text to upper print("The itsy bitsy spider\nclimbed up the waterspout.") print("My", "name", "is", "Monty", "Python.", sep="-") print("Monty", "Python.", sep="*", end="*\n") print("Programming","Essentials","in",sep="***",end="...")
5ca276e780a1214a9393eeb006ad6ce8e9760cb4
mnoskoski/scripts-template-python
/06exercicio.py
529
3.984375
4
""" Estruturas logiscas and (e) or (ou) not (nao) operadores unarios - not operadores binarios - and, or, is Para o and ambos valores precisam ser True Para o or um ou outro valor precisa ser True Para o not o valor do booleano é invertido, se for True vira false e for false vira True Para o is o valor é comparado com o segundo valor """ ativo = True logado = False if ativo and logado: print('Bem vindo usuario!') else: print('Voces precisa ativar sua conta!') #Ativo é verdadeiro? print(ativo is True)
8c6aff095e83e240fbf00a05b5bec40ff2adec66
sazemlame/Take-Home-Challenge
/takehome.py
9,324
4.21875
4
""" Automated Parking System: This application helps you manage a parking lot of n slots. The program has the following functionalities: 1. Park a car in empty slot and store the licence plate number and age of the driver 2. Record which car has left the parking spot 3. Search for the slot number for a particular licence number and age 4. Search for licence plate details for drivers of same age A list of dictionaries containing details for each car has been implemented. A number of constraints have been taken into care like: 1. The first line of file should create a parking lot 2. Same car cannot be parked twice 3. Driver cannot be under the age of 18 4. The slot which is being vacated cannot be greater than the length of parking lot """ import re import sys #Functions for implementing commands def car_park(y): #print("triggrting parking function") parking={} parking['licence_plate_no']="" parking['age']="" for s in y.split(): if(re.match('^([A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{4})$',s)): for cars in plot: #Function implemented for parking the car. if(cars==None): #Extract the licence plate number and check continue #If duplicate exsits, return null value if(cars["licence_plate_no"]==s): #Extract age and check if it is legal driving age print("Same car number..bad input") #If all constraints check out, perform the function return(0) parking['licence_plate_no']=s if(s.isdigit()): if(int(s)<18): print("Illegal Driving age... not allowed to park") return None parking['age']=s if(parking['licence_plate_no']=="" or parking['age']==''): return None print("Car with vehicle registration number ",parking["licence_plate_no"]," has been parked at slot number",c+1) return(parking) def find_car_with_licence_plate(lplate): parked_slot=0 for cars in plot: #Extracting the slot number for the car parked with the given licence plate number if cars==None: continue if(cars["licence_plate_no"]==lplate): parked_slot=(plot.index(cars)+1) if(parked_slot==0): print("No matching cars found") return None return(parked_slot) def find_cars_with_age(age): list_of_slot=[] for cars in plot: #Finding slot number of cars of people with same age if cars==None: continue if(cars["age"]==age): list_of_slot.append(plot.index(cars)+1) if(list_of_slot==[]): print("No matching cars found") return None return(list_of_slot) def get_lic_no_same_age(a): #Finding licence number of cars with same age list_of_cars=[] for cars in plot: if cars==None: continue if(cars["age"]==a): list_of_cars.append(cars["licence_plate_no"]) if(list_of_cars==[]): print("No matching cars found") return None return(list_of_cars) def get_lic_no_slot(slot): car_lic_no=None for cars in plot: if cars==None: continue if(plot.index(cars)==slot): car_lic_no=cars["licence_plate_no"] if(car_lic_no==None): print("No matching cars found") return None return(car_lic_no) def min_pos_empty(): #Finding the most closest minimun parking slot which is empty empty_slots=[] for cars in plot: if cars==None: empty_slots.append(plot.index(cars)) return empty_slots[0] #Driver code starts below n=0 #size of parking lot c=0 #count for iterating in the parking lot plot=[] filename=input("Enter name of file \n") #Reading the command file with open(filename,'r') as f: x=f.readline() #x is the first line of the file if x.split()[0].lower()!="create_parking_lot": #Creating the database. If the first line is not initializing the database then a message prompt is sent print("Please create a database") sys.exit() else: n=[int(i) for i in x.split() if i.isdigit()][0] plot=[None]*n print("Created parking of ",n," slots") for y in f: #Reading the other lines of the command file full=0 if y.split()[0].lower()=="park": #Checking if the command is for Parking the car and running the corresponding function while(plot[c]!=None): #Park the car if the slot is empty otherwise move to next slot c+=1 if(c>=n): print("Parking is full..sorry for the inconvenience") full=1 break #print("Checking if car not parked",c) if(full==0): car_parked=car_park(y) if(car_parked==None): print("Invalid licence plate number") elif(car_parked==0): plot[c]=None else: plot[c]=car_parked else:c=0 if y.split()[0].lower()=="leave": #Checking if the command is for a car leaving the parking lot #print("Removing Car") for s in y.split(): if(s.isdigit()): #Extracting the slot number s=int(s) if(plot[s-1]==None): print("Slot already vacant at", s) #If the input slot is already vacant elif(s-1>=n): print("Please enter a valid slot number") #If the slot number is greater than the length of the parking spot else: print("Slot number",s," vacated, the car with vehicle registration number ",plot[s-1]["licence_plate_no"]," left the space, the driver of the car was of age", plot[s-1]["age"]) plot[s-1]=None c=min_pos_empty() #vacate the car and bring the count to the nearest parking spot if re.match('^Slot_number',y.split()[0]): #Checking if the command requries to return slot numbers nslot=None nslots=None for s in y.split(): if(re.match('[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{1,4}',s)): #Extracting number plate no to search for the corresponding slot nslot=find_car_with_licence_plate(s) if(s.isdigit()): #Extracting age to search for the corresponding slot nslots=find_cars_with_age(s) if(nslot!=None):print(nslot) if(nslots!=None): print(*nslots,sep=',') if re.match('^Vehicle_registration_number_for_driver_of_age$ ',y.split()[0]): #Command to extract the number plate numbers for drivers of same age or for a given slot number lic_nos=None for s in y.split(): if(s.isdigit()): lic_nos=get_lic_no_same_age(s) if(lic_nos!=None):print(*lic_nos,sep=',') if re.match('^Vehicle_registration_number_for_parking_slot$',y.split()[0]): #Command to extract the number plate numbers for drivers of same age or for a given slot number lic_no=None for s in y.split(): if(s.isdigit()): lic_no=get_lic_no_slot(int(s)-1) if(lic_no!=None):print("The licence plate number of car in slot",s,"is",lic_no) #print(plot)
51309c0f241bd6641845e18b6e7655bc787e1b1c
it-worker-tango/PythonBase
/day03/Day03_2.py
717
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 29 21:50:00 2018 @author: Tango """ # = 简单的赋值运算符 x = 20 y = x print("x:",x) print("y:",y) print("-" * 30) # =+ 加赋值 x+=y 等价于 x= x +y x += y print("x:",x) print("y:",y) print("x+=y:",x) print("-" * 30) # -= 减赋值 x-=y 等价于 x=x -y x = 20 y = 5 x-=y print("x:",x) print("y:",y) print("x-=y:",x) print("-" * 30) # *= 乘赋值 x*=y 等价于 x = x * y x = 20 y = 5 x*=y print("x:",x) print("y:",y) print("x*=y:",x) print("-" * 30) # /= 出赋值, x/=y 等价于 x = x/y x = 20 y = 5 x/=y print("x:",x) print("y:",y) print("x/=y:",x) #注意Python运行除法的结果实浮点型 #其他运算也一样,大家试试 %=, **= //=
5739eba75117bb3040d6e93e6be2e109749a08e6
it-worker-tango/PythonBase
/day10/demo3.py
308
3.59375
4
hello = "你好啊朋友" # 定义一个全局变量 def read(): '''看书的功能''' hello = '你好啊朋友,一起看书吧。' print(hello) if __name__ == "__main__": print("我去书店。。。。") read() print("我回家...") hello = "吃饭。。。" print(hello)
c95e2097506e549414b9cd73079c1d793e2fd098
it-worker-tango/PythonBase
/day11/demo2.py
203
3.859375
4
# 读取文件中的指定个数的字符 with open("demo.txt", 'r') as file: string = file.read(3) # 读取前3个字符 print("前3个字符为:", string) # 运行结果:前3个字符为: abc
92e01c676746653ac390ca7482cd9764c3c73bab
it-worker-tango/PythonBase
/day06/demo4.py
301
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 1 21:30:35 2019 @author: Tango if 嵌套 """ number = int(input("请输入去年的销量:")) if number >= 1000: print("销量不错") else: if number >= 500: print("销量还过得去") else: print("还需要努力啊")
1ff7a6d9db89df7d52d699d83f84871d3f82234f
carlos8410/Python_Class
/IntroGUI/GUI_Intr.py
1,483
3.984375
4
"""Write a GUI-based program that provides two Entry fields, a button and a label. When the button is clicked, the value of each Entry should (if possible) be converted into a float. If both conversions succeed, the label should change to the sum of the two numbers. Otherwise it should read "***ERROR***.""" from tkinter import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): top_frame = Frame(self) top_frame.pack(side=TOP) self.entry_1 = Entry(top_frame) self.entry_2 = Entry(top_frame) self.entry_1.pack(side=LEFT) self.entry_2.pack(side=LEFT) bottom_frame = Frame(self) bottom_frame.pack(side=TOP) Button(bottom_frame, text='Summation', command=self.handle).pack(side=LEFT) self.label = Label(bottom_frame) self.label.pack(side=LEFT) def handle(self): """Handle a click of the button by converting the text the user has placed in the two Entry widgets and summing them to show in the label""" print ("hanler") entry_1 = self.entry_1.get() entry_2 = self.entry_2.get() try: output = float(entry_1) + float(entry_2) except: output = "***ERROR***" self.label.config(text=output) root = Tk() app = Application(master=root) app.mainloop() #app.destroy()
2b35e0b81932a55bef05b180b3048c152fe7d5ba
jvansteeter/CS-360
/python/htbin/headlines.py
335
3.546875
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup print "Content-type: text/html" print print "<h1>Headlines</h1>" request = requests.get("http://news.google.com") soup = BeautifulSoup(request.content, 'html.parser') results = soup.find_all("span", {"class":"titletext"}) for i in results: print str(i) + "<br>"
2b88a13415abe1fbd15bbf70e50e05ae1cb8395a
IRC-SPHERE/sphere-challenge
/visualise_data.py
12,500
3.546875
4
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as pl import itertools as it import json import os def slice_df(df, start_end): """ This slices a dataframe when the index column is the time. This function slices the dataframe 'df' between a window defined by the 'start_end' parameter. Time is given in seconds. """ inds = (df.index >= start_end[0]) & (df.index < start_end[1]) return df[inds] def slice_df_start_stop(df, start_end): """ Some data, eg PIR sensor data and annotation data, are stored in a sparse format in which the 'start' and 'stop' times are stored. This helper function returns the sequences of a dataframe which fall within a window defined by the 'start_stop' parameter. """ inds = (df.start < start_end[1]) & (df.end >= start_end[0]) return df[inds] class Slicer(object): """ This class provides an interface to querying a dataframe object. Specifically, this is used to query the times for which """ def __init__(self): pass def _time_of(self, dataframe, label): dict_list = dataframe.T.to_dict().values() filtered = filter(lambda aa: aa['name'] == label, dict_list) annotations = sorted(filtered, key=lambda ann: ann['start']) return [(ann['start'], ann['end']) for ann in annotations] def _times_of(self, dataframes, label): times = [self._time_of(dataframe, label) for dataframe in dataframes] return times def times_of_occupancy(self, location): return self._times_of(self.locations, location) def times_of_activity(self, activity): return self._times_of(self.annotations, activity) def time_of_occupancy(self, location, index): start_end = filter(lambda se: len(se) > index, self._times_of(self.locations, location)) return np.asarray([se[index] for se in start_end]) def time_of_activity(self, activity, index): start_end = filter(lambda se: len(se) > index, self._times_of(self.annotations, activity)) return np.asarray([se[index] for se in start_end]) class Sequence(Slicer): def __init__(self, meta_root, data_path): super(Sequence, self).__init__() self.path = data_path video_cols = json.load(open(os.path.join(meta_root, 'video_feature_names.json'))) self.centre_2d = video_cols['centre_2d'] self.bb_2d = video_cols['bb_2d'] self.centre_3d = video_cols['centre_3d'] self.bb_3d = video_cols['bb_3d'] self.annotations_loaded = False self.meta = json.load(open(os.path.join(data_path, 'meta.json'))) self.acceleration_keys = json.load(open(os.path.join(meta_root, 'accelerometer_axes.json'))) self.rssi_keys = json.load(open(os.path.join(meta_root, 'access_point_names.json'))) self.video_names = json.load(open(os.path.join(meta_root, 'video_locations.json'))) self.pir_names = json.load(open(os.path.join(meta_root, 'pir_locations.json'))) self.location_targets = json.load(open(os.path.join(meta_root, 'rooms.json'))) self.activity_targets = json.load(open(os.path.join(meta_root, 'annotations.json'))) self.load() def load_wearable(self): accel_rssi = pd.read_csv(os.path.join(self.path, 'acceleration.csv'), index_col='t') self.acceleration = accel_rssi[self.acceleration_keys] self.rssi = pd.DataFrame(index=self.acceleration.index) for kk in self.rssi_keys: if kk in accel_rssi: self.rssi[kk] = accel_rssi[kk] else: self.rssi[kk] = np.nan accel_rssi[kk] = np.nan self.accel_rssi = accel_rssi self.wearable_loaded = True def load_environmental(self): self.pir = pd.read_csv(os.path.join(self.path, 'pir.csv')) self.pir_loaded = True def load_video(self): self.video = dict() for location in self.video_names: filename = os.path.join(self.path, 'video_{}.csv'.format(location)) self.video[location] = pd.read_csv(filename, index_col='t') self.video_loaded = True def load_annotations(self): self.num_annotators = 0 self.annotations = [] self.locations = [] self.targets = None targets_file_name = os.path.join(self.path, 'targets.csv') if os.path.exists(targets_file_name): self.targets = pd.read_csv(targets_file_name) while True: annotation_filename = "{}/annotations_{}.csv".format(self.path, self.num_annotators) location_filename = "{}/location_{}.csv".format(self.path, self.num_annotators) if not os.path.exists(annotation_filename): break self.annotations.append(pd.read_csv(annotation_filename)) self.locations.append(pd.read_csv(location_filename)) self.num_annotators += 1 self.annotations_loaded = self.num_annotators != 0 def load(self): self.load_wearable() self.load_video() self.load_environmental() self.load_annotations() def iterate(self): start = range(int(self.meta['end']) + 1) end = range(1, int(self.meta['end']) + 2) pir_zeros = [np.zeros(10)] * len(self.pir_names) pir_t = np.linspace(0, 1, 10, endpoint=False) pir_df = pd.DataFrame(dict(zip(self.pir_names, pir_zeros))) pir_df['t'] = pir_t pir_df.set_index('t', inplace=True) for lower, upper in zip(start, end): lu = (lower, upper) # Acceleration/RSSI acceleration = slice_df(self.acceleration, lu) rssi = slice_df(self.rssi, lu) # PIR pir_start_stop = slice_df_start_stop(self.pir, lu) pir_df *= 0.0 if pir_start_stop.shape[0] > 0: for si, series in pir_start_stop.iterrows(): pir_df[series['name']] = 1.0 pir_t += 1 # Video video_living_room = slice_df(self.video['living_room'], lu) video_kitchen = slice_df(self.video['kitchen'], lu) video_hallway = slice_df(self.video['hallway'], lu) yield lu, (acceleration, rssi, pir_df.copy(), video_living_room, video_kitchen, video_hallway) class SequenceVisualisation(Sequence): def __init__(self, meta_root, data_path): super(SequenceVisualisation, self).__init__(meta_root, data_path) def get_offsets(self): if self.num_annotators == 1: return [0] elif self.num_annotators == 2: return [-0.05, 0.05] elif self.num_annotators == 3: return [-0.1, 0.0, 0.1] def plot_annotators(self, ax=None, lu=None): if self.annotations_loaded == False: return if ax is None: fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5)) else: pl.sca(ax) if lu is None: lu = (self.meta['start'], self.meta['end']) palette = it.cycle(sns.husl_palette()) offsets = self.get_offsets() for ai in xrange(self.num_annotators): col = next(palette) offset = offsets[ai] for index, rr in slice_df_start_stop(self.annotations[ai], lu).iterrows(): pl.plot([rr['start'], rr['end']], [self.activity_targets.index(rr['name']) + offset * 2] * 2, color=col, linewidth=5) pl.yticks(np.arange(len(self.activity_targets)), self.activity_targets) pl.ylim((-1, len(self.activity_targets))) pl.xlim(lu) def plot_locations(self, ax=None, lu=None): if self.annotations_loaded == False: return if ax is None: fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5)) else: pl.sca(ax) if lu is None: lu = (self.meta['start'], self.meta['end']) palette = it.cycle(sns.husl_palette()) offsets = self.get_offsets() for ai in xrange(self.num_annotators): col = next(palette) offset = offsets[ai] for index, rr in slice_df_start_stop(self.locations[ai], lu).iterrows(): pl.plot([rr['start'], rr['end']], [self.location_targets.index(rr['name']) + offset * 2] * 2, color=col, linewidth=5, alpha=0.5) pl.yticks(np.arange(len(self.location_targets)), self.location_targets) pl.ylim((-1, len(self.location_targets))) pl.xlim(lu) def plot_pir(self, lu=None, sharey=False): if lu is None: lu = (self.meta['start'], self.meta['end']) num = [2, 1][sharey] first = [0, 0][sharey] second = [1, 0][sharey] fig, axes = pl.subplots([2, 1][sharey], 1, sharex=True, sharey=False, figsize=(20, 5 * num)) axes = np.atleast_1d(axes) pl.sca(axes[second]) for index, rr in slice_df_start_stop(self.pir, lu).iterrows(): pl.plot([rr['start'], rr['end']], [self.location_targets.index(rr['name'])] * 2, 'k') pl.yticks(np.arange(len(self.pir_names)), self.pir_names) pl.ylim((-1, len(self.pir_names))) pl.xlim(lu) pl.ylabel('PIR sensor') self.plot_locations(axes[first], lu) axes[first].set_ylabel('Ground truth') pl.tight_layout() def plot_acceleration(self, lu=None, with_annotations=True, with_locations=False): if lu is None: lu = (self.meta['start'], self.meta['end']) fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 7.5)) ax2 = pl.twinx() df = slice_df(self.acceleration, lu) df.plot(ax=ax, lw=0.75) ax.yaxis.grid(False, which='both') pl.xlim(lu) ax.set_ylabel('Acceleration (g)') ax.set_xlabel('Time (s)') if with_annotations: self.plot_annotators(ax2, lu) if with_locations: self.plot_locations(ax2, lu) pl.tight_layout() def plot_rssi(self, lu=None): if lu is None: lu = (self.meta['start'], self.meta['end']) fig, ax = pl.subplots(1, 1, sharex=True, sharey=False, figsize=(20, 5)) ax2 = pl.twinx() df = slice_df(self.rssi, lu) df.plot(ax=ax, linewidth=0.25) ax.yaxis.grid(False, which='both') pl.xlim(lu) ax.set_ylabel('RSSI (dBm)') ax.set_xlabel('Time (s)') self.plot_locations(ax2, lu) pl.tight_layout() def plot_video(self, cols, lu=None): if lu is None: lu = (self.meta['start'], self.meta['end']) fig, axes = pl.subplots(3, 1, sharex=True, figsize=(20, 10)) for vi, (kk, vv) in enumerate(self.video.iteritems()): x = np.asarray(vv.index.tolist()) y = np.asarray(vv[cols]) palette = it.cycle(sns.color_palette()) pl.sca(axes[vi]) for jj in xrange(y.shape[1]): col = next(palette) pl.scatter(x, y[:, jj], marker='o', color=col, s=2, label=cols[jj]) pl.gca().grid(False, which='both') pl.ylabel(kk) pl.xlim(lu) self.plot_locations(pl.twinx(), lu) pl.tight_layout() def plot_all(self, plot_range=None): self.plot_pir(lu=plot_range, sharey=True) self.plot_rssi(lu=plot_range) self.plot_acceleration(lu=plot_range) self.plot_video(self.centre_2d, lu=plot_range) def main(): """ This function will plot all of the sensor data that surrounds the first annotated activity. """ # Load training data (this will contain labels) plotter = SequenceVisualisation('public_data/metadata', 'public_data/train/00001') # Or load testing data (this visualisation will not contain labels and are # generally shorter sequences of data, between 10-30 seconds long) plotter = SequenceVisualisation('public_data/metadata', 'public_data/train/00001') # This function will retreive the time range of the first jumping activity. plot_range = plotter.times_of_activity('a_jump') print plot_range # To provide temporal context to this, we plot a time range of 10 seconds # surrounding this time period plotter.plot_all() pl.show() if __name__ == '__main__': main()
69a48b8681be3c0a77a2be589519d1a2e35533db
sreetamadas/sample_Python_code
/get_threshold_kneeCurve.py
4,897
4
4
### calculate threshold X from knee curve ### ## GOOGLE: how to find knee of a curve in noisy data # method 1: analytical (distance calculation with original data - may be affected by noise in data) # method 2: distance calculation with Y from curve fitted to original data # method 3: https://www1.icsi.berkeley.edu/~barath/papers/kneedle-simplex11.pdf import pandas #as pd import numpy as np from numpy import sqrt, exp from sklearn import linear_model import math from scipy.optimize import curve_fit def thresholdX(temp): "method 1 : calculate threshold X" # https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve # find points at the 2 ends of the X-Y curve #print temp max_X = temp['X'].max() Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y max_Y = temp['Y'].max() X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X # straight line b/w max values : y = ax + b # (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1 # coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1) a = (Y_maxX - max_Y)/(max_X - X_maxY) b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY) # calculate distance of each pt in the data to the straight line # distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1) temp['dist'] = ( a * temp.X + b - temp.Y)/math.sqrt(a*a + 1) # find point with max distance maxD = temp['dist'].max() X_maxD = np.median(temp[temp.dist == maxD].X) # float(temp[temp.dist == maxD].X) return X_maxD; # method 2: using curve fitting on the data # GOOGLE: how to fit a curve to points in python # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html # https://stackoverflow.com/questions/19165259/python-numpy-scipy-curve-fitting def func(x, a, b): "linear fit" return (a/x) + b; def func2(x, a, b): "exponential decay" return a * exp(-(b*x)); def knee1(temp): "curve fitting (inverse)" # find points at the 2 ends of the X-Y curve #print temp max_X = temp['X'].max() Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y max_Y = temp['Y'].max() X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X x = np.array(pandas.to_numeric(temp.X)) y = np.array(temp.Y) # straight line b/w max values : y = ax + b # (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1 # coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1) a = (Y_maxX - max_Y)/(max_X - X_maxY) b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY) # curve fitting params, pcov = curve_fit(func, x, y) # or, with func2 for exp decay # calculate distance of each pt in the data to the straight line # distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1) temp['dist'] = ( a * x + b - func(x, *params))/math.sqrt(a*a + 1) # find point with max distance maxD = temp['dist'].max() Q_maxD = np.median(temp[temp.dist == maxD].X) return Q_maxD; def knee2(temp): "curve fitting (polynomial)" # find points at the 2 ends of the X-Y curve max_X = temp['X'].max() Y_maxX = np.median(temp[temp.X == max_X].Y) # float(temp[temp.X == max_X].Y) # temp[temp.X == max_X].Y max_Y = temp['Y'].max() X_maxY = np.median(temp[temp.Y == max_Y].X) # float(temp[temp.Y == max_Y].X) #temp[temp.Y == max_Y].X x = np.array(pandas.to_numeric(temp.X)) y = np.array(temp.Y) # straight line b/w max values : y = ax + b # (y2 - y1)/(x2 - x1) = (y - y1)/(x - x1 # coef: a = (y2 - y1)/(x2 - x1) ; b = (x2.y1 - x1.y2)/(x2 - x1) a = (Y_maxX - max_Y)/(max_X - X_maxY) b = (max_X * max_Y - X_maxY * Y_maxX)/(max_X - X_maxY) # curve fitting # calculate polynomial z = np.polyfit(x, y, 2) # polynomial of degree 2 f = np.poly1d(z) # calculate new y's y_new = f(x) # calculate distance of each pt in the data to the straight line # distance from a pt. (X,Y) in the data (with knee) to the straight line = (aX + b - Y)/sqrt(a^2 + 1) temp['dist'] = ( a * x + b - y_new)/math.sqrt(a*a + 1) # find point with max distance maxD = temp['dist'].max() Q_maxD = np.median(temp[temp.dist == maxD].X) # #print 'max dist: ',maxD,' ; Q at max dist: ',Q_maxD return Q_maxD; ###################################################################################################### # sort data by X-column temp = temp.sort_values(by = 'X', ascending = True) x = thresholdX(temp) x1 = knee1(temp) x2 = knee2(temp)
8a60d618f47ce9917bf2c8021b2863585af07672
sreesindhu-sabbineni/python-hackerrank
/TextWrap.py
511
4.21875
4
#You are given a string s and width w. #Your task is to wrap the string into a paragraph of width w. import textwrap def wrap(string, max_width): splittedstring = [string[i:i+max_width] for i in range(0,len(string),max_width)] returnstring = "" for st in splittedstring: returnstring += st returnstring += '\n' return returnstring if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)