blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
11123bbab0f9f4e4f939cc86b1ce235330b1caed
ChWeiking/PythonTutorial
/Python基础/day03(运算、if判断、循环)/demo/02_if语句/07_if判断复习.py
886
3.609375
4
import random com = random.randint(0,2) players = input('输入:(剪刀 石头 布):') # dicts = {1:'剪刀',2:"石头",3:'布'} mylist = ('剪刀',"石头",'布') if players not in mylist: print('输入的东西不太对!') else: print('你:%s 它:%s'%(players,mylist[com])) if players == mylist[com]: print('平手呢!') else: if players == '剪刀' and mylist[com] == '石头': print('Lose!') elif players == '剪刀' and mylist[com] == '布': print('Win!') elif players == '石头' and mylist[com] == '布': print('Lose!') elif players == '石头' and mylist[com] == '剪刀': print('Win!') elif players == '布' and mylist[com] == '剪刀': print('Lose!') elif players == '布' and mylist[com] == '石头': print('Win!')
35f60514ec8786b329995344a6bc3e838c3eb046
ChWeiking/PythonTutorial
/Python基础/day11(继承、多态、类属性、类方法、静态方法)/demo/01_继承/02_覆盖重写.py
2,862
4.34375
4
''' 子类和父类都有相同的属性、方法 子类对象在调用的时候,会覆盖父类的,调用子类的 与参数无关,只看名字 覆盖、重写: 扩展功能 ''' class Fu(object): def __init__(self): print('init1...') self.num = 20 def sayHello(self): print("halou-----1") class Zi(Fu): def __init__(self): print('init2...') self.num = 200 def sayHello(self): print("halou-----2") ''' 改变指针 def sayHaha(self): print("haha-----1") def sayHaha(self): print("haha-----2") ''' zi = Zi() zi.sayHello() print(zi.num) print(Zi.__mro__) print('*****************************************华丽的分割线*****************************************') class C1: def haha(self): print('C1...haha') class C2: def haha(self): print('C2...haha') class C3(C1,C2): def haha(self): print('C3...haha') c3 = C3() c3.haha() print(C3.__mro__) print('*****************************************华丽的分割线*****************************************') ''' super() 这个super类的对象,可以在子类中,找到父类的属性、方法。 并不是直接的父类对象 ''' class Fu(object): def sayHello(self): print("halou-----1...self=%s"%self) class Zi(Fu): def sayHello(self): print("halou-----2...self=%s"%self) #super(Zi,self).sayHello() #super().sayHello() Fu.sayHello(self) print('super=%s...super()=%s...id(super())=%s'%(super,super(),hex(id(super())))) zi = Zi() zi.sayHello() print(zi) print('*****************************************华丽的分割线*****************************************') class Fu1(object): def sayHello(self): print("halou-----fu1") class Fu2(object): def sayHello(self): print("halou-----fu2") class Zi(Fu1,Fu2): def sayHello(self): print("halou-----zi") #super().sayHello() Fu2.sayHello(self) zi = Zi() zi.sayHello() print('*****************************************华丽的分割线*****************************************') class Fu(object): def sayHello(self,name): print("halou-----fu") class Zi(Fu): def sayHello(self): super().sayHello('老王') print("halou-----zi") zi = Zi() zi.sayHello() #zi.sayHello('xxx') print('*****************************************华丽的分割线*****************************************') ''' class Fu(object): def __init__(self,name,age): self.name = name self.age = age class Zi(Fu): def __init__(self,sex,name,age): self.sex = sex self.name = name self.age = age zi = Zi('女','老王',20) print(zi.name) print(zi.age) print(zi.sex) ''' class Fu(object): def __init__(self,name,age): self.name = name self.age = age class Zi(Fu): def __init__(self,sex,name,age): self.sex = sex #super().__init__(name,age) Fu.__init__(self,name,age) zi = Zi('女','老王',20) print(zi.name) print(zi.age) print(zi.sex)
a2a4481984ab02aa0ef7cfcd031b58df618dba0f
ChWeiking/PythonTutorial
/Python基础/day06(字符串、函数)/demo/01_字符串/02_常用功能.py
4,474
3.6875
4
''' find 从左面找第一次出现的位置 rfind 从右面找第一次出现的位置 找不到返回-1 index rindex 功能和find一样,但是找不到会报错,一般不用 下标依然从左面0开始 ''' info = '今天,中华人民共和国今天终于成立中国啦' sub_info = '今天' index1 = info.find(sub_info) print(index1) index1 = info.find(sub_info,-9,-1) print(index1) index1 = info.find(sub_info,3) print(index1) index1 = info.rfind(sub_info) print(index1) index1 = info.rfind('老王') print(index1) index1 = info.index(sub_info) print(index1) ''' index1 = info.index('老王') print(index1) ''' print('**************************华丽的分割线**************************') ''' count 统计次数 ''' info = '今天,中华人民共和国今天终于成立中国啦' sub_info = '今天' num = info.count(sub_info) print(num) print('**************************华丽的分割线**************************') ''' 字符串的遍历 ''' info = '今天,中华人民共和国今天终于成立中国啦' for i in info: print(i) print('**************************华丽的分割线**************************') ''' split 按照固定字符分隔,返回一个列表 splitlines 按照换行符分割 partition 从左面分割一个,左中右都保留 rpartition 从右面分割一个,左中右都保留 ''' hobby = '抽烟-烫头发-喝酒' ret = hobby.split('-') print(type(ret)) print(ret) hobby = '抽烟-烫头发-喝酒' ret = hobby.split('abc') print(type(ret)) print(ret) hobby = '抽烟,烫头发,喝酒' ret = hobby.split(',') print(type(ret)) print(ret) info = '《静夜思》\n\n床前明月光\n疑是地上霜\n举头望明月\n低头思故乡' ls = info.split('\n') print(ls) info = '《静夜思》\n\n床前明月光\n疑是地上霜\n举头望明月\n低头思故乡' ls = info.splitlines() print(ls) info='''《静夜思》 床前明月光 疑是地上霜 举头望明月 低头思故乡''' ls = info.splitlines() print(ls) info = '《静夜思》\r\n床前明月光\r\n疑是地上霜\r\n举头望明月\r\n低头思故乡' print(info) ls = info.split('\n') print(ls) info = '《静夜思》\r\n床前明月光\r\n疑是地上霜\r\n举头望明月\r\n低头思故乡' print(info) ls = info.splitlines() print(ls) hobby = '抽烟-烫头发-喝酒' ret = hobby.partition('-') print(type(ret)) print(ret) hobby = '抽烟-烫头发-喝酒' ret = hobby.rpartition('-') print(type(ret)) print(ret) print('**************************华丽的分割线**************************') ''' startswith 开头 endswith 结尾 isalnum 判断是否是字符和数字 isupper 大写 islower 小写 isspace ''' info = '我叫老王.jpg' print(info.startswith('你')) print(info.endswith('.jpg')) print('abc123中文'.isalnum()) print('abc中文'.isalpha()) print('1243'.isdigit()) print('ABC123中文'.isupper()) print('abc123中文'.islower()) print(' '.isspace()) print('\t'.isspace()) print('\n'.isspace()) print('**************************华丽的分割线**************************') ''' capitalize 首字母大写 upper 全大写 lower 全小写 ''' name = 'abc' print(name.capitalize()) print(name[0].upper()+name[1:]) print(name) print(name.upper()) print(name.lower()) print('**************************华丽的分割线**************************') ''' ljust rjust center ''' info = 'abc' ret = info.ljust(10) print(ret+'-') info = 'abc' ret = info.rjust(10) print('-'+ret) info = 'abc' ret = info.center(11) print('-'+ret+'-') print('**************************华丽的分割线**************************') ''' strip 裁剪,默认裁剪左右空格 lstrip 左裁剪 rstrip 右裁剪 ''' #name = input('输入姓名:') name = ' 老 王 ' name = name.strip(' ') #name = name.strip() print('-'+name+'-') name = '**老 王****' name = name.strip('*') print(name) print('**************************华丽的分割线**************************') ''' join ''' info = '吃-喝-玩-乐' print(info.split('-')) ls = ['吃', '喝', '玩', '乐'] info = '-'.join(ls) print(info) ''' encode 编码 字符串--->字节 decode 解码 字节--->字符串 ''' info = '我还活着' ret = info.encode() print(type(ret)) print(ret) info = 'abc123我还活着' ret = info.encode('utf-8') print(type(ret)) print(ret) info = b'abc123' print(info) print(type(info)) info = 'abc123我还活着' ret1 = info.encode('utf-8') ret2 = ret1.decode('utf-8') print(ret2)
782d959a221631b777677fd9528059ab9bf0913c
ChWeiking/PythonTutorial
/Python高级/day40(算法整理回顾)/demo/01_几种排序算法/03.选择排序.py
297
3.5625
4
def selection_sort(list2): for i in range(0, len (list2)): min = i for j in range(i + 1,len(list2)): if list2[j] < list2[min]: min = j list2[i], list2[min] = list2[min], list2[i] if __name__ == '__main__': ls = [11,22,88,66,77,99,44,55,33] selection_sort(ls) print(ls)
91e720afd1e2680f41f518ee32ac548300dc1b2a
ChWeiking/PythonTutorial
/Python基础/day04(while循环、列表)/demo/01_while循环/02_九九乘法表.py
309
3.515625
4
''' 九九乘法表 n*m=结果 ''' m = 1 #第几次循环,第几行 n = 1 #这一行,打印几次 while m<10: while n<=m: print('%sx%s=%s\t'%(n,m,m*n),end='') n+=1 print('') n=1 m+=1 ''' print('老王',end='') print('旺财') ''' ''' print('老王\t旺财') \n换行 \t制表位 '''
2311416d1a66e4362b9f966edf4cf74a92990fdf
ChWeiking/PythonTutorial
/Python基础/day06(字符串、函数)/demo/练习/day_06.py
1,895
3.5
4
''' a = '窗前明月光\n疑是地上霜\n举头望明月\n低头思故乡' print(a) print(len(a)) #b = ''' #窗前明月光 #疑是地上霜 #举头望明月 #低头思故乡 ''' print(b) print(len(b)) name = '老王' print(name) name = '老\t王' print(name) name = '老\\t王' print(name) name = '"老王"' print(name) name = '\'老王\'' print(name) print('A\t'*10) ''' ''' a = 'abcdfauiyapflj' a = a.split('a') print(a) print(type(a)) a = 'a-c-b-d-f' print(a.count('-',0,8)) print(a.count('-')) a = 'a-c-b-d-f' print(a.count('-',2)) print(a.count('-')) a = 'a\nc-b-d-f' a = a.splitlines() print(a) a = 'sdfsagfdiawhoi' print(a.partition('a')) a = 'sdfsagfdiawhoi' print(a.rpartition('a')) a = '2sdfsagfdiawhoi' a = a.startswith('1') print(a) a = 'safgsdj3452' print(a.isalnum()) print(a.isalpha()) print(a.isdigit()) a = 'safadfsf' print(a.isupper()) print(a.islower()) a = ' ' print(a.isspace()) a = ' \t\n' print(a.isspace()) a = 'egterf' a = a.ljust(10) print(a) print(len(a)) a = 'egterf' a = a.rjust(10) print(a) print(len(a)) a = 'egterf' a = a.center(10) print(a) print(len(a)) a = 'wang' print(a.capitalize()) print(a.upper()) print(a.lower()) a = 'ab' print(a.join('hfdjsh')) a = 'das324老来乐' b = a.encode() print(b) print(b.decode()) a = 'wgterf' print(a.rindex('t')) print(a.swapcase()) print(a.istitle()) ''' def c(a): b = 10 d = 3 c(d) print(d) def lala(ll): ll.append([1,2,3]) print('函数内取值:',ll) return la = [11,12,13] lala(la) print('函数外取值:',la) def num(a): b = 10 a += b return a print(num(200)) def kk(a,b): ''' 吸烟喝酒烫头发 ''' la = a if(la<b): la = b print(la) return la print(kk(20,25)) help(kk) def k(a,b): a = a + b a = 20 b = 30 k(a,b) print(a) def k(a,b): a.append(b) a = [20,78,98] b = [34,45] k(a,b) print(a) def k(a,b): a.extend(b) a = [20,78,98] b = [34,45] k(a,b) print(a)
70c3af5be6a4a3684e5a6b761dbb18230ae04022
ChWeiking/PythonTutorial
/Python基础/day04(while循环、列表)/demo/练习/01_集合容器多项方法.py
1,481
3.875
4
''' list = [1,2,3,4,5,6] list.append(3) print(list) lala = list.index(3) print(lala) print(list[5]) print(list.count(3)) lenth = len(list) print(lenth) print(max(list),min(list)) list.insert(1,9) print(list) list.extend([10,12,15]) print(list) aaa = [1,2,'nihao',3,[11,14,15,['老王'],18]] print(aaa[4][3]) ''' ''' aaa = [1,2,'nihao',3,[11,14,15,['老王'],18],55] aaa.pop() print(aaa) aaa.pop(1) print(aaa) del aaa[0] print(aaa) aaa.remove(3) print(aaa) ''' ''' b = [1,2,5,4,3,9,6,8,7,11,45,25] b.sort() print(b) b.reverse() print(b) c = b[1:12:2] print(c) k = b[2:10] print(k) f = b[:11] print(f) d = b[:11:3] print(d) ''' ''' a = tuple([1,2,3]) c = list((4,5,6)) print(c,a) print(11 in a) print([14,15,16]+[1,2,3]) print('hello\000'*3) ''' ''' nums = ([1,2,3,4],'老王') nums[0][3] = 66 print(nums) print(type(nums)) ''' ''' a = [1,2,3,4,5,6,7,8,9] i = 0 while i<=8: print(a[i],'\000',end='') i+=1 print() for dd in a: print ('结果是:',dd,'\000',end='') print() a.sort(reverse=True) print(a) ''' ''' dict={1:'a',2:'b',3:'c',4:'d'} print(dict) a = dict.pop(2) print(a) del dict[3] print(dict) dict.clear() print(dict) dict1={1:'a',2:'b',3:'c',4:'d'} print(len(dict1)) print(str(dict1)) print(dict1.keys()) print(dict1.values()) print(dict1.items()) ''' ''' a = 10 b = a b = 11 print(a) print(b) a = [1,2,3,4] b = a b.append(5) print(a) print(b) a = [1,2,3,4] b = a b = [2,3,1,6] print(a) print(b) a = 10 b = a a = 20 print(a) print(b) '''
f895be8e15f66b241820646ff499bc41e5b2a117
ChWeiking/PythonTutorial
/Python基础/day10(私有化、魔法方法del、类的继承)/demo/03_继承/03_多继承.py
399
3.921875
4
''' python支持多继承。 一个类可以有多个父类 ''' class Donkey: def f1(self): print('Donkey。。。') class Horse: def f2(self): print('Horse。。。') class Mule(Donkey,Horse): def f3(self): print('Mule。。。') mule = Mule() print(dir(mule)) mule.f1() mule.f2() mule.f3() ''' 基类(父类) 派生类(子类) ''' print(Mule.__bases__) print(Mule.__mro__)
1106b6b68f093954c719f72f0f5e5244b4368dda
ChWeiking/PythonTutorial
/Python基础/day02(注释、变量、运算符)/demo/04_运算符/运算符.py
792
3.859375
4
num1 = 10 num2 = 20 #算术运算 ret = num1+num2 print(ret) str1 = 'a' str2 = 'b' #字符串拼接 ret = str1+str2 print(ret) num1 = 10 num2 = 20 #算术运算 ret = num1*num2 print(ret) print('--------------------------------') print('-'*20) print(2**4) #结果是浮点型 print(10/2) print(10/3) print(10/4) print('-'*20) #取余 print(10%2) print(10%3) print(10%4) print(1%4) print('-'*20) #取整 print(10//2) print(10//3) print(10//4) print(1//4) ''' 比较运算符,得到的结果是bool类型 True False == 判断变量的值是否相等 ''' #赋值符号 name = '老王' num1 = 1 num2 = 1 #==是比较符号 ret = (num1==num2) print('a'=='a') print(ret) print(num1!=num2) a = 10 #a = a+2 #a+=2 a//=2 #a = a//2 print(a) print(60&13) print(60<<2) print(60>>2)
f2bedd9135dddbeb2dfc022b3c5ee00572e2c7a6
ChWeiking/PythonTutorial
/Django/day58(回顾整理)/demo/01_python写的cgi脚本部分代码.py
3,227
3.765625
4
''' 什么是Web框架? Django是一个卓越的新一代Web框架,而使用Django 这个web框架的意义是什么呢? 要回答这个问题,让我们来看看通过编写标准的CGI程序来开发Web应用,这在大约1998年的时候非常流行。 编写CGI Web应用时,你需要自己处理所有的操作,就像你想烤面包,但是都需要自己生火一样。 下面是实例,一个简单的CGI脚本,用Python写的,读取数据库并显示最新发布的十本书: ''' #!/usr/bin/python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() #从数据库查询所有书的名字 cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") #遍历所有的书 for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() ''' 代码十分简单。首先,根据CGI的要求输出一行Content-Type,接下来是一个空行。 再接下来是一些HTML的起始标签,然后连接数据库并执行一些查询操作,获取最新的十本书。 遍历这些书,同时生成一个HTML的无序序列。 最后,输出HTML的结束标签并且关闭数据库连接。3Matty 类似这样的一次性动态页面,从头写起并不是最好的办法。 其中一点,这些代码简单易懂,就算是一个开发初学者都能理解这16行代码从开始到结束做了些什么,不需要阅读额外的代码。 同样这16行代码也很容易部署:只需要将它保存在名为“latestbooks.cgi”的文件里,上传至网络服务器,通过浏览器访问即可。 但是Web应用远远要复杂很多,这种方法就不再适用,而且你将会要面对很多问题: 1、当多个动态页面需要同时连接数据库时,将会发生什么? 当然,连接数据库的代码不应该同时存在于各个独立的CGI脚本中,所以最踏实的做法是把这些代码重新组织到一个公共函数里面。 2、一个开发人员真的需要去关注如何输出Content-Type以及完成所有操作后去关闭数据库么? 此类问题只会降低开发人员的工作效率,增加犯错误的几率。那些初始化和释放相关的工作应该交给一些通用的框架来完成。 3、如果这样的代码被重用到一个复合的环境中会发生什么? 每个页面都分别对应独立的数据库和密码吗?从这点看来,就需要一些环境相关的配置文件。 4、如果一个Web设计师,完全没有Python开发经验,但是又需要重新设计页面的话,又将 发生什么呢? 理想的情况是,页面显示的逻辑与从数据库中读取书本记录分隔开,这样 Web设计师的重新设计不会影响到之前的业务逻辑。 以上正是Web框架致力于解决的问题。 Web框架为应用程序提供了一套程序框架, 这样你可以专注于编写清晰、易维护的代码,而无需从头做起。简单来说, 这就是Django所能做的。 '''
28624d6b4fe400671cec84c3b57ff5948db2a323
ChWeiking/PythonTutorial
/Python高级/day38(算法)/demo/02_二叉树_广度优先.py
2,028
4.1875
4
class MyQueue(object): """队列""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): """出队列""" return self.items.pop() def size(self): """返回大小""" return len(self.items) class MyNode(object): """节点""" def __init__(self,item,lchild=None,rchild=None): self.item = item self.lchild = lchild self.rchild = rchild class MyTree(object): """二叉树""" def __init__(self, item=None): node = None if item: node = MyNode(item) self.__root = node def add(self,item): """新增""" myNode = MyNode(item) if self.__root==None: self.__root = myNode return myQueue = MyQueue() #创建新的队列:先进先出 myQueue.enqueue(self.__root) #放入根节点 while myQueue.size(): #循环 cur = myQueue.dequeue() #出队列 if cur.lchild == None: #左孩子是否为None cur.lchild = myNode return elif cur.rchild == None: cur.rchild = myNode return else: myQueue.enqueue(cur.lchild) myQueue.enqueue(cur.rchild) def travel(self): myQueue = MyQueue() # 创建新的队列:先进先出 myQueue.enqueue(self.__root) # 放入根节点 while myQueue.size(): # 循环 cur = myQueue.dequeue() # 出队列 print(cur.item) if cur.lchild != None: # 左孩子是否为None myQueue.enqueue(cur.lchild) if cur.rchild != None: myQueue.enqueue(cur.rchild) if __name__ == '__main__': myTree = MyTree() myTree.add(1) myTree.add(2) myTree.add(3) myTree.travel()
46a4b5fac21253cff9e24012c4c6a5d1053f65f0
ChWeiking/PythonTutorial
/Python基础/day05(集合容器、for循环)/demo/02_tuple/01_tuple.py
555
4.28125
4
''' 元组:是用小括号的 ''' directions = ('东','西','南','北','中') print(directions) print(directions[1]) print('*'*20) t1 = (1,2,3) #t1[0]=2 t2 = ([1,2,3],110,'120',(1,2,3)) t2[0].append(110) print(t2) ''' 列表和元组相互转换 ls = list(元组) tu = tuple(列表) ''' ls = [1,2,3] print(type(ls)) print(ls) tu = tuple(ls) print(type(tu)) print(tu) tu = (1,2,3) print(type(tu)) print(tu) ls = list(ls) print(type(ls)) print(ls) ''' 变量赋值 ''' a,b = [110,120] print(a) print(b) a,b = (110,120) print(a) print(b)
6b2294cc8c6d68c6aaed002c3ddc90f5d9060ae8
ChWeiking/PythonTutorial
/Python基础/day03(运算、if判断、循环)/demo/练习/02_判断是否为闰年.py
456
3.71875
4
''' if: 条件语句1……………… 条件语句2……………… else: 条件语句a 条件语句b ……………… 注意: 1.if else 后面都需要有冒号 2.if条件语句中只存在真True或者假False 3.条件语句要进行缩进 ''' read = int(input('请输入年份:')) if ((read%4==0) and (read%100!=0)) or (read%400==0): print('%d是闰年'%(read)) else: print('%d不是闰年'%(read)) print('判断结束')
15ed26f5268192a2b767cd372ac3401a3a70bbbe
ChWeiking/PythonTutorial
/Python基础/day02(注释、变量、运算符)/demo/练习/02_类型转化.py
337
3.9375
4
#类型转化 a = 1 b = float(a) print(b) print(type(b)) a = 1 b = str(a) print(b) print(type(b)) a = 1 b = bool(a) print(b) print(type(b)) a = 1.1 b = int(a) print(b) print(type(b)) a = 1.1 b = bool(a) print(b) print(type(b)) a = 1.1 b = str(a) print(b) print(type(b)) a = '12.3' a = float(a) b = int(a) print(b) print(type(b))
251b26428c895b27abb3e0db7ff0316e5bc8a7e1
Filjo0/PythonProjects
/Ch3.py
2,197
4.25
4
""" Chapter 3. 11. In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7, the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible, a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and so on. A little mathematical analysis reveals that there are not enough ways to win to make the game worthwhile; however, because many people’s eyes glaze over at the first mention of mathematics, your challenge is to write a program that demonstrates the futility of playing the game. Your program should take as input the amount of money that the player wants to put into the pot, and play the game until the pot is e mpty. At that point, the program should print the number of rolls it took to break the player, as well as maximum amount of money in the pot. """ import random from time import sleep pot = 0 print("Hello. Lets play \"The Lucky Sevens game\"!", "\nRules: You roll a pair of dice. If the dots add up to 7, you WIN $4" "\nOtherwise, you lose $1" "\nThere are lots of ways to WIN: (1, 6), (2, 5), (3, 4)") while True: try: pot = int(input("How much money would you like to deposit into the pot: $")) print("Press ENTER to roll a pair of dice") input() except ValueError: print("Please print the number: ") while pot > 0: print("Rolling...") sleep(2) dice_roll = random.randint(1, 6), random.randint(1, 6) print("You rolled number:", dice_roll[0], "and", dice_roll[1]) my_roll = (dice_roll[0] + dice_roll[1]) if my_roll == 7: pot += 4 print("Congratulations! The dots add up to 7! You've won $4 " "\nYour balance is: $" + str(pot), "\nPress ENTER to try again") else: pot -= 1 print("Unlucky! The dots add up to:", my_roll, "You've lost $1" "\nYour balance is: $" + str(pot), "\nPress ENTER to try again") input() print("You need to deposit money into your pot")
3cd6ff12af16a6a3d672cad425a9df0d398cedb1
lslewis1/Python-Labs
/Week 5 Py Labs/Seconds converter.py
747
4.21875
4
#10/1/14 #This program will take a user input of a number of seconds. #The program will then display how many full minutes, hours, days, and leftover seconds there are #ts is the input of seconds #s1 is the leftover seconds for the minutes #s2 is the seconds for hours #s3 is the seconds for days #m is the number of minutes #h is the number of hours #d is the number of days ts=int(input("Enter the number of seconds :")) if ts>=60: m=ts//60 s1=(ts%60) if ts>=3600: h=ts//3600 s2=(ts%3600) if ts>=86400: d=ts//86400 s3=(ts%86400) print(ts,"Seconds are equal to :") print(m,"full minute(s) and",s1,"seconds.") print(h,"full hour(s) and",s2,"seconds.") print(d,"full day(s) and",s3,"seconds.")
c46d80d326ba0b65ca97c0679faa2e50aa384371
lslewis1/Python-Labs
/Week 5 Py Labs/BMI.py
530
4.34375
4
#10/1/14 #This program will determine a person's BMI #Then it will display wheter the person in optimal weight, over, or under #bmi is the body mass indicator #w is the weight #h is the height w=float(input("Enter your weight in pounds :")) h=float(input("Enter your height in inches :")) bmi=(w*703)/(h*h) print("Your body mass indicator is", \ format(bmi, '.2f')) if bmi>25: print("You are overweight.") elif bmi>=18.5: print("Your weight is optimal.") else: print("You are underweight.")
f22d1886a08da98b613d9ed89432a39d47679830
lslewis1/Python-Labs
/Week 6 Py Labs/calories burned.py
327
4.125
4
#10/6/14 #This program will use a loop to display the number of calories burned after time. #The times are: 10,15,20,25, and 30 minutes #i controls the while loop #cb is calories burned #m is minutes i=10 while i<=30: m=i cb=m*3.9 i=i+5 print(cb,"Calories burned for running for", m,"minutes.")
fc0c81055407aa4869426c1b2fd843cc0cfd71c3
lslewis1/Python-Labs
/Week 3 Py Labs/Dollar calculation game.py
765
3.8125
4
#9/17/14 #This program will ask a user to enter the exact amount of coins to make a dollar #If the user correctly enters the amount of coins for a dollar, a message is displayed #If not, the progam tells the usere if they were above or below a dollar #p is the number of pennies #n is the nickels #d is dimes #q is quarters p=int(input("How many pennies are there? :")) n=int(input("How many nickels are there? :")) d=int(input("How many dimes are there? :")) q=int(input("How many quarters are there? :")) if ((p*1)+(n*5)+(d*10)+(q*25))==100: print("Congratulations, you have won the game") else: if ((p*1)+(n*5)+(d*10)+(q*25))>100: print("You have more than a dollar") else: print("You have less than a dollar")
29260166c31c491e47c68e1674e384bc56c6a2d5
lslewis1/Python-Labs
/Week 8 Py Labs/Temperature converter.py
919
4.4375
4
#10/20/14 #This program will utilize a for loop to convert a given temperature. #The conversion will be between celsius and fahrenheit based on user input. ch=int(input("Enter a 1 for celsuis to fahrenheit, or a 2 for fahrenheit to celsius: ")) if ch==1: start=int(input("Please enter your start value: ")) end=int(input("Please enter your end value: ")) step=int(input("Please enter what you want to count by: ")) for temp in range(start,end+1,step): F=(9/5*temp)+32 print(temp,"degrees Celsius =",format(F,'.2f'),"degrees Fahrenheit.") elif ch==2: start=int(input("Please enter your start value: ")) end=int(input("Please enter your end value: ")) step=int(input("Please enter what you want to count by: ")) for temp in range(start,end+1,step): F=(temp-32)*(5/9) print(temp,"degrees Fahrenheit =",format(F,'.2f'),"degrees Celsius.")
d31c472acb56ddda5e696e10c957d3d85cf88220
lslewis1/Python-Labs
/Week 4 Py Labs/Letter grade graded lab.py
536
4.375
4
#9/26/14 #This program will display a student's grade. #The prgram will print a letter grade after receiving the numerical grade #Grade is the numerical grade #Letter is the letter grade Grade=float(input("Please enter your numerical grade :")) if Grade>=90: print("Your letter grade is an A.") elif Grade>=80: print("Your letter grade is a B.") elif Grade>=70: print("Your letter grade is a C.") elif Grade>=60: print("Your letter grade is a D.") else: print("Your letter grade is an F.")
d2c0a048d7ff8e29edeeceb1239e51202efab2cd
lslewis1/Python-Labs
/Week 12 Py Labs/Week 12 Graded Lab funcitons.py
942
4.0625
4
#11/21/14 #This program will take an input of five test scores. #Two fucntions will be used to display the letter grade of the scores, and #The overall average #A list will be used for the test scores in the calc_average function def calc_average(mylist): sum=0 for i in range(len(mylist)): sum+=mylist[i] average=sum/(len(mylist)) return average def determine_grade(a): if a>=90: grade="A" elif a>=80: grade="B" elif a>=70: grade="C" elif a>=60: grade="D" else: grade="F" return grade gradelist=[0]*5 for x in range(5): gradelist[x]=int(input("Please enter a grade: ")) grade=determine_grade(gradelist[x]) average=calc_average(gradelist) for y in range(5): grade=determine_grade(gradelist[y]) print(gradelist[y],"-",grade) grade=determine_grade(average) print("Average is: ",average,"-",grade)
0496c19404d9e80edc3e63cdefeeec8d1a6de78b
lslewis1/Python-Labs
/Week 3 Py Labs/Gross pay if 2.py
476
4.03125
4
#9/15/14 #This program will determine the gross pay for an employee of a company. #the hourly rate is $10 #if an employee works more than 20 hours there is a $5 extra for each hour. #hrs is the hours worked #gross is the gross pay #othrs is overtime hours #otpay is overtime pay hrs=float(input("Please enter the hours worked:")) gross=10*hrs if hrs>20: othrs=hrs-20 otpay=othrs*5 gross=(gross+otpay) print("The take home pay will be: $",gross)
13221ac3c781524a6eb988f988bb02c3b562caab
lslewis1/Python-Labs
/Week 8 Py Labs/Series 2.py
187
3.953125
4
#10/22/14 n=int(input("Please enter how many numbers are in the series: ")) sum=0 for tn in range(1,n+1): tv=((tn**2)+1) print(tv) sum+=tv print("The sum is: ",sum)
598595e2f8c924f11b5012f226e8e3d8254a3ce5
lslewis1/Python-Labs
/Week 12 Py Labs/property value functions.py
344
3.609375
4
#11/19/14 def assesment(a): asmt= actual*.60 return asmt def proptax(a): ptax= (asmt//100)*.64 return ptax actual=int(input("What is the actual property value? ")) asmt=assesment(actual) print("The assessment is: ",format(asmt,'.2f')) ptax=proptax(actual) print("The tax owed is: ",format(ptax,'.2f'))
609f7fa62dc98f98ae9fa4dd97752f54db454b71
lslewis1/Python-Labs
/Week 4 Py Labs/Credit limit.py
509
4
4
#9/22/14 #This program will determine whether one is going over their credit limit or not #maxcred is the maximum credit limit #npb is the not paid balance #exp is the expenses for the current month maxcred=float(input("Enter your maximum credit limit :")) np=float(input("Enter the outstanding not paid balance :")) exp=float(input("Enter your expenses for the current month :")) if (np+exp)>maxcred: print("You are over your credit limit") else: print("You are not over your limit")
1948e1d43d1fb61ed5abb32217f22d67ff26b6ce
ryanwolters/geohasher
/Geohasher.py
1,129
3.546875
4
import hashlib from datetime import date today = date.today() userDegLat = input("Your current degrees latitude? (Number before decimal point): ") userDegLong = input("Your current degrees longitude? (Number before decimal point): ") dow = input("Today's Dow opening price: ") geoString = str(today) + "-" + dow # create the string "yyyy-mm-dd-dowopening" hashResult = hashlib.md5(geoString.encode()) geoHash = hashResult.hexdigest() print("\nGeohash: " + geoHash) # create a fractional hex value from each half of the string firstHalf = geoHash[0:16] secondHalf = geoHash[16:32] # convert both hex values to decimal latTail = 0; longTail = 0; for x in range(0, 16): latTail += int(firstHalf[x], 16) * 16 ** -(x + 1) longTail += int(secondHalf[x], 16) * 16 ** -(x + 1) print(str(latTail) + " " + str(longTail)) latitude = str(userDegLat) + str(round(latTail, 6))[1:8] longitude = str(userDegLong) + str(round(longTail, 6))[1:8] print("\nLatitide: " + latitude) print("Longitude: " + longitude) print("Coordinates: " + latitude + ", " + longitude) input("\nPress enter to close")
03ee87714b5de1f9db70051b215fe07ec991a8b2
ShurfLL/infa_2020_kuruts
/lab8_gun/gun.py
9,107
3.578125
4
import math from random import choice from random import randint as rnd import pygame from pygame.draw import * FPS = 60 TRANSPARENT = (0, 0, 0, 0) GREY = (150, 150, 150) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) GAME_COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN] WIDTH = 800 HEIGHT = 600 g = 0.6 class Ball: def __init__(self, screen: pygame.Surface, x=40, y=450): """ Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали """ self.screen = screen self.x = x self.y = y self.r = 10 self.vx = 0 self.vy = 0 self.color = choice(GAME_COLORS) self.live = 30 def move(self): """Переместить мяч по прошествии единицы времени. Метод описывает перемещение мяча за один кадр перерисовки. То есть, обновляет значения self.x и self.y с учетом скоростей self.vx и self.vy, силы гравитации, действующей на мяч, и стен по краям окна (размер окна 800х600). """ self.x += self.vx self.y -= self.vy self.vy -= g if(self.y > HEIGHT-self.r): self.y = HEIGHT-self.r self.vy *= -0.7 def draw(self): pygame.draw.circle( self.screen, self.color, (self.x, self.y), self.r ) pygame.draw.circle( self.screen, BLACK, (self.x, self.y), self.r, width=1 ) def hittest(self, obj): """Функция проверяет сталкивалкивается ли данный обьект с целью, описываемой в обьекте obj. Args: obj: Обьект, с которым проверяется столкновение. Returns: Возвращает True в случае столкновения мяча и цели. В противном случае возвращает False. """ if (self.x-obj.x)**2+(self.y-obj.y)**2 <= (self.r+obj.r)**2: return True else: return False class Gun: def __init__(self, screen): self.screen = screen self.f2_power = 10 self.f2_on = 0 self.an = 1 self.color = GREY self.x = 40 self.y = 450 def fire2_start(self, event): self.f2_on = 1 def fire2_end(self, event): """Выстрел мячом. Происходит при отпускании кнопки мыши. Начальные значения компонент скорости мяча vx и vy зависят от положения мыши. """ global balls, bullet bullet += 1 new_ball = Ball(self.screen) new_ball.r += 5 self.an = math.atan2( (event.pos[1]-new_ball.y), (event.pos[0]-new_ball.x)) new_ball.vx = self.f2_power * math.cos(self.an)/2 new_ball.vy = - self.f2_power * math.sin(self.an)/2 balls.append(new_ball) self.f2_on = 0 self.f2_power = 10 def targetting(self, event): """Прицеливание. Зависит от положения мыши.""" if event: if(event.pos[0]-20): self.an = math.atan((event.pos[1]-450) / (event.pos[0]-20)) if self.f2_on: self.color = RED else: self.color = GREY def draw(self): """surf = pygame.Surface((self.f2_power+20, 10)).convert_alpha() surf.fill(TRANSPARENT) rect(surf, self.color, (0, 0,self.f2_power+20,10)) pygame.Surface.blit(self.screen, pygame.transform.rotate(surf, -self.an), (self.x, self.y))""" #line(self.screen, self.color, (self.x,self.y), (self.x+(self.f2_power+20)*math.cos(self.an),self.y+(self.f2_power+20)*math.sin(self.an)), width=10) width = 10 coords = [ (self.x, self.y), (self.x+(self.f2_power+20)*math.cos(self.an), self.y+(self.f2_power+20)*math.sin(self.an)), (self.x+(self.f2_power+20)*math.cos(self.an)+width*math.sin(self.an), self.y+(self.f2_power+20)*math.sin(self.an)-width*math.cos(self.an)), (self.x+width*math.sin(self.an), self.y-width*math.cos(self.an)) ] polygon(self.screen, self.color, (coords), width=0) def power_up(self): if self.f2_on: if self.f2_power < 100: self.f2_power += 1 self.color = RED else: self.color = GREY class Target: def __init__(self, type=1): """ Инициализация новой цели. """ self.x = rnd(600, 780) self.y = rnd(300, 550) self.r = rnd(15, 50) self.vx=rnd(-7, 7) self.vy=rnd(-7, 7) self.color = GAME_COLORS[rnd(0,5)] self.live=type self.type=type def hit(self, point=1): """Попадание шарика в цель.""" self.live -= 1 global points points += point def draw(self): if(self.type==1): pygame.draw.circle( screen, self.color, (self.x, self.y), self.r ) pygame.draw.circle( screen, BLACK, (self.x, self.y), self.r, width=1 ) elif self.type == 2: pygame.draw.rect( screen, self.color, (self.x-self.r, self.y-self.r, self.r*2,self.r*2) ) pygame.draw.rect( screen, BLACK, (self.x-self.r, self.y-self.r, self.r*2,self.r*2), width=1 ) def move(self): """перемещает себя значение скорости""" self.x += self.vx self.y += self.vy def drawscore(): """вывод очков на экран""" f1 = pygame.font.Font(None, 36) tbl = 'points: ' tbl += str(points) text1 = f1.render(tbl, True, BLACK) screen.blit(text1, (10, 10)) def showtext(): f1 = pygame.font.Font(None, 36) tbl = 'вы уничтожили цель за ' tbl += str(bulletshow) tbl += ' выстрелов' text1 = f1.render(tbl, True, BLACK) screen.blit(text1, (180, 250)) def collision(obj): """функция коллизии, получает объект и при столкновении отражает его от стен Xbound, Ybound - границы экрана, заданы вне функции """ if(obj.x + obj.r > WIDTH): obj.vx *= -1 obj.x = WIDTH-obj.r elif(obj.x - obj.r < 0): obj.vx *= -1 obj.x = obj.r elif(obj.y - obj.r < 0): obj.vy *= -1 obj.y = obj.r elif(obj.y + obj.r > HEIGHT): obj.vy *= -1 obj.y = HEIGHT-obj.r pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) bullet = 0 bulletshow=0 balls = [] points = 0 clock = pygame.time.Clock() gun = Gun(screen) target1 = Target(1) target2 = Target(2) finished = False do_showtext=0 pause = False while not finished: screen.fill(WHITE) gun.draw() target1.draw() target2.draw() for b in balls: b.draw() drawscore() pause=False if(do_showtext > 0): showtext() do_showtext-=1 pause=True pygame.display.update() clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: finished = True elif event.type == pygame.MOUSEBUTTONDOWN: if(not pause): gun.fire2_start(event) elif event.type == pygame.MOUSEBUTTONUP: if(not pause): gun.fire2_end(event) elif event.type == pygame.MOUSEMOTION: gun.targetting(event) for b in balls: b.move() if b.hittest(target1): target1.hit() if(target1.live == 0): target1 = Target(1) bulletshow=bullet bullet = 0 balls = [] do_showtext=100 if b.hittest(target2): target2.hit() if(target2.live == 0): target2 = Target(2) bulletshow=bullet bullet = 0 balls = [] do_showtext=100 gun.power_up() target1.move() target2.move() collision(target1) collision(target2) pygame.quit()
5b331dd77269f762c7752b184b3bebd8d3bc7c89
mike-alesso/MaxTextStringReverser
/mtsr/mtsr.py
3,008
4.34375
4
import argparse import os import re import sys def filter_non_words(word): """ Filtering words that have characters or symbols not found in a word Parameters: arg1 (str): Word to be checked Returns: bool: Returns true if only letters are present """ regex = r'[\W0-9]' return not bool(re.search(regex, word, re.MULTILINE)) def find_largest_word(list_of_words): """ Return the longest word and filter for non-words Parameters: arg1 (List(str)): List of words to be checked Returns: str or None: Largest word or None """ result = list(filter(lambda w: filter_non_words(w), list_of_words)) if result: return max(result, key=len) else: return def read_file_to_list(filename): """ Read a given file and split by lines to a set Parameters: arg1 (str): name of file to be parsed Returns: Set(str): set of lines from the file """ with open(filename, 'r', encoding='utf8') as f: return set(f.read().splitlines()) def check_file(filename): """ Check if a given file exists and can be opened Parameters: arg1 (str): name of file to be checked Returns: Bool: True or false depending on if file can be opened """ if os.path.exists(filename) and os.access(filename, os.R_OK): return True else: print(f'File: {filename} does not exist or is not readable.') return False def text_reverse(filename): """ Attempts to find the largest word in a string and print it to the console Parameters: arg1 (str): name of file to be processed Returns: max_word: Largest word in file max_word_reversed: Largest word reversed None: returned if operation is not possible """ if check_file(filename): " Read file and turn it into a list by line " list_of_words = read_file_to_list(filename) " Strip leading and trailing whitespace from the words in the list " list_of_words_stripped = map(str.strip, list_of_words) " Call function to retrieve largest word " max_word = find_largest_word(list_of_words_stripped) " Print word and word reversed (transposed) " if max_word: print(f'{max_word}') max_word_reversed = max_word[::-1] print(f'{max_word_reversed}') return max_word, max_word_reversed else: print('No valid words found in file.') return def main(): args = parse_args(sys.argv[1:]) text_reverse(args.filename) def parse_args(args): """ Parses commandline args Parameters: arg1 (str): name of file to be processed Returns: args: arguments object for arguments given at commandline """ parser = argparse.ArgumentParser() parser.add_argument("filename", help="Filename for the strings you want to provide", type=str) return parser.parse_args(args) if __name__ == "__main__": main()
ace072fe1f59697c4e7d876bda7d6fbb5f48e121
sarthak625/python-scripts
/passwordLocker.py
500
3.984375
4
#! python3 # passwordLocker.py - A password locker program import sys import pyperclip PASSWORDS = { 'gmail': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345' } if len(sys.argv) < 2: print ('Usage: python passwordLocker.py [account] - copy account password') sys.exit() account = sys.argv[1] if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print('Password for '+account+' copied to clipboard') else: print('There is no account named '+account)
2133da4d37bcfce301984b336ee076b9dd7b5728
zachwitz/eMPRess
/empress/clumpr/HistogramMainInput.py
4,263
3.546875
4
# HistogramMainInput.py # Adrian Garcia, March 2020 # Main input function for HistogramMain from pathlib import Path def getInput(filename, d, t, l, args): """ Get additional input from user for computing and saving the PDV :param filename <str> - the path to a .newick file with the input trees and tip mapping :param d <float> - the cost of a duplication :param t <float> - ^^ transfer :param l <float> - ^^ loss :param args <dict str->str> - dictionary that contains all parameters needed to compute, save, and/or output the PDV :return inputs <dict str->str> - all input from user for computing and saving the PDV """ inputs = {} inputs.update(args) getOptionalInput(inputs) cost_suffix = ".{}-{}-{}".format(d, t, l) # If args is unset, use the original .newick file path but replace .newick with .pdf if inputs["histogram"] is None: inputs["histogram"] = str(filename.with_suffix(cost_suffix + ".pdf")) # If it wasn't set by the arg parser, then set it to None (the option wasn't present) elif inputs["histogram"] == "unset": inputs["histogram"] = None #TODO: check that the specified path has a matplotlib-compatible extension? # Do the same for .csv if inputs["csv"] is None: inputs["csv"] = str(filename.with_suffix(cost_suffix + ".csv")) elif inputs["csv"] == "unset": inputs["csv"] = None # If it was user-specified, check that it has a .csv extension else: c = Path(inputs["csv"]) assert c.suffix == ".csv" return inputs def getOptionalInput(inputs): """ Add additional arguments to 'inputs' dictionary :param inputs <dict str->str> - dictionary that contains given parameters to compute, save, and/or output the PDV :return None - inputs is simply updated with new information """ string_params = ("histogram", "time", "csv") bool_params = ("xnorm", "ynorm", "omit_zeros", "cumulative", "stats", "time") for param in string_params: if param not in inputs: inputs[param] = "unset" for param in bool_params: if param not in inputs: inputs[param] = True print("Enter additional input in the form <parameter name> <value>") print("Enter 'Done' when you have no additional input to enter.") print("Enter '?' if you would like to see additional input options.") while True: user_input = input(">> ").split() param = user_input[0] value = None if len(user_input) > 1: value = " ".join(user_input[1:]) if param == "Done": break elif param == "?": print_usage() elif param in bool_params: if value[0] in ('y', 'Y', 'n', 'N'): inputs[param] = value[0] in ('y', 'Y') else: print("Value must begin with Y, y, N, or n. Please try again.") elif param in string_params: inputs[param] = value else: print("That is not a valid parameter name. Please try again.") def print_usage(): """ Print information on all optional parameter inputs """ data = [ ("histogram", ("Output the histogram at the path provided. " "If no filename is provided, outputs to a filename based on the input .newick file.")), ("xnorm", "Normalize the x-axis so that the distances range between 0 and 1."), ("ynorm", "Normalize the y-axis so that the histogram is a probability distribution."), ("omit_zeros", ("Omit the zero column of the histogram, " "which will always be the total number of reconciliations.")), ("cumulative", "Make the histogram cumulative."), ("csv", ("Output the histogram as a .csv file at the path provided. " "If no filename is provided, outputs to a filename based on the input .newick file.")), ("stats", ("Output statistics including the total number of MPRs, " "the diameter of MPR-space, and the average distance between MPRs.")), ("time", "Time the diameter algorithm.") ] col_width = max(len(x) for x,y in data) + 2 for name, hint in data: print(name.ljust(col_width) + " " + hint)
7f0bcddba963482972f1c6b2e9d6d9688cf5cee6
samanta-antonio/python_basics
/fizz.py
283
4.21875
4
#Receba um número inteiro na entrada e imprima Fizz se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada. numero = int(input("Digite um número: ")) resto = (numero % 3) if resto == 0: print("Fizz") else: print(numero)
6ae4c647e621a3e7e2ea807840c7fb64217685f6
samanta-antonio/python_basics
/vogais.py
271
3.8125
4
#Escreva a função vogal que recebe um único caractere como parâmetro e devolve True se ele for uma vogal e False se for uma consoante. def vogal(v): if v == "a" or v == "e" or v == "i" or v == "o" or v == "u": return True else: return False
fbaf2e1cfb11b783fae84e043a70e8ea0af6943a
mimixtvxq/data_science_projects
/Churn Prediction ANN Implementation/ann.py
4,496
3.53125
4
# -*- coding: utf-8 -*- # Artificial Neural Network # Data Preprocessing # Classification template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:-1].values y = dataset.iloc[:, -1].values # Encode categorical data (Label encode then do one hot encoding) from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:,1] = labelencoder_X_1.fit_transform(X[:,1]) labelencoder_X_2 = LabelEncoder() X[:,2] = labelencoder_X_2.fit_transform(X[:,2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:,1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Create ANN Classifier import keras from keras.models import Sequential from sklearn.model_selection import GridSearchCV from keras.layers import Dense from keras.layers import Dropout # Initialise the ANN classifier = Sequential() # Add input layer and first hidden layer classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform', input_dim = 11)) classifier.add(Dropout(rate = 0.1)) # Add second hidden layer classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform')) classifier.add(Dropout(rate = 0.1)) # Add output layer classifier.add(Dense(units = 1, activation = 'sigmoid', kernel_initializer = 'uniform')) #Compile ANN (Apply stochastic gradient descent on the whole network) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) #Fit ANN to the training set classifier.fit(x=X_train, y=y_train, batch_size = 10, epochs = 100) # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) y_test = (y_test > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #Use the NN to predict for one customer customer = np.array([0,0,600,1,40,3,60000,2,1,1,50000]).reshape(1,-1) customer = sc.transform(customer) customer_pred = classifier.predict(customer) #7.9% probability of leaving = False, customer wont leave # K-fold CV implementation from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform', input_dim = 11)) classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform')) classifier.add(Dense(units = 1, activation = 'sigmoid', kernel_initializer = 'uniform')) classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier #build a new classifier trained with k-fold CV classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100) accuracies = cross_val_score(classifier,X_train, y_train, cv = 10, n_jobs = 1) cv_score = accuracies.mean() variance = accuracies.std() # If you have high variance in the accuracies, apply dropout # Parameter Tuning (create dict with keys = params, values = all diff values) parameters = {'batch_size':[25,32], 'epochs':[100,500], 'optimizer':['adam','rmsprop']} grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10) # fit gridsearch ANN to the training set grid_search = grid_search.fit(X_train,y_train) best_parameters = grid_search.best_params_ best_accuracy = grid_search.best_score_ #best param {'batch_size': 32, 'epochs': 500, 'optimizer': 'rmsprop'} #best acc: 85%
58a2ddd3c64f04deff58812d6f13da29e79745ed
harshadrai/DataStructures
/BinarySearchTree.py
2,885
4.0625
4
import Queue class BinarySearchTree(object): def __init__(self,value,left=None,right=None): self.value=value self.left=left self.right=right def search_tree(tree,key): if not tree: return elif key==tree.value: return tree elif key<tree.value: return search_tree(tree.left,key) else: return search_tree(tree.right,key) def tree_height(tree): if not tree: return 0 else: return 1 + max(tree_height(tree.left),tree_height(tree.right)) def tree_size(tree): if not tree: return 0 else: return 1 + tree_size(tree.left) + tree_size(tree.right) class DepthFirst(object): def in_order_traversal(self): if not self: return else: DepthFirst.in_order_traversal(self.left) print(self.value) DepthFirst.in_order_traversal(self.right) def pre_order_traversal(self): if not self: return else: print(self.value) DepthFirst.pre_order_traversal(self.left) DepthFirst.pre_order_traversal(self.right) def post_order_traversal(self): if not self: return else: DepthFirst.post_order_traversal(self.left) DepthFirst.post_order_traversal(self.right) print(self.value) class BreadthFirst(object): def level_traversal(self): if not self: return else: q=Queue.Queue() q.enqueue(self) while not q.is_empty(): node=q.dequeue() if node.left: q.enqueue(node.left) if node.right: q.enqueue(node.right) # Tree Creation t12=BinarySearchTree(12) t10=BinarySearchTree(10) t11=BinarySearchTree(11,t10,t12) t9=BinarySearchTree(9,None,t11) t7=BinarySearchTree(7) t8=BinarySearchTree(8,t7,t9) t5=BinarySearchTree(5) t6=BinarySearchTree(6,t5,t8) t1=BinarySearchTree(1) t3=BinarySearchTree(3) t2=BinarySearchTree(2,t1,t3) t4=BinarySearchTree(4,t2,t6) #Function Testing search_tree(t4,7).value print(search_tree(t4,13)) print(search_tree(t4,0)) search_tree(t4,9).value search_tree(t4,1).value search_tree(t4,12).value search_tree(t4,3).value search_tree(t4,4).value search_tree(t4,1).value search_tree(t4,11).value tree_height(t4) tree_height(t2) tree_height(t12) tree_height(t9) tree_height(t6) tree_height(t11) tree_size(t4) tree_size(t12) tree_size(t1) tree_size(t11) tree_size(t8) DepthFirst.in_order_traversal(t4) DepthFirst.in_order_traversal(t6) DepthFirst.pre_order_traversal(t4) DepthFirst.pre_order_traversal(t9) DepthFirst.pre_order_traversal(t1) DepthFirst.post_order_traversal(t4) DepthFirst.post_order_traversal(t12) DepthFirst.post_order_traversal(t8) BreadthFirst.level_traversal(t4) BreadthFirst.level_traversal(t12)
fae9d7dd8592dbaec63eba892d077f5b5a55c5f4
harshadrai/DataStructures
/BinaryMaxHeap.py
3,103
3.53125
4
from math import * class Element(object): def __init__(self,value=None,description=None): self.value=value self.description=description class BinaryMaxHeap(object): def __init__(self,element=None): self.heap=[element] self.size=len(self.heap) def parent(self,position): return floor((position-1)/2) def left_child(self,position): return 2*position+1 def right_child(self,position): return 2*position+2 def sift_up(self,element_position): parent_position=self.parent(element_position) while element_position>0 and self.heap[element_position].value>self.heap[parent_position].value: self.heap[element_position],self.heap[parent_position]=self.heap[parent_position],self.heap[element_position] element_position=parent_position parent_position=self.parent(element_position) def sift_down(self,element_position): max_value_index=element_position l=self.left_child(element_position) if l<self.size and self.heap[l].value>self.heap[max_value_index].value: max_value_index=l r=self.right_child(element_position) if r<self.size and self.heap[r].value>self.heap[max_value_index].value: max_value_index=r if max_value_index!=element_position: self.heap[element_position],self.heap[max_value_index]=self.heap[max_value_index],self.heap[element_position] element_position=max_value_index self.sift_down(element_position) def get_max(self): return self.heap[0] def insert(self,element): self.heap.append(element) self.sift_up(self.size) self.size+=1 def extract_max(self): if self.size>0: max_element=self.heap[0] self.heap[0]=self.heap[self.size-1] self.size-=1 self.sift_down(0) return max_element else: return None def remove(self,position): self.heap[position].value=inf self.sift_up(position) self.extract_max() def change_priority(self,position,priority_value): previous_value=self.heap[position].value self.heap[position].value=priority_value if priority_value>previous_value: self.sift_up(position) else: self.sift_down(position) e7=Element(7) e12=Element(12) e13=Element(13) e11=Element(11) e14=Element(14) e29=Element(29) e18=Element(18) e18ii=Element(18) e42=Element(42) my_binary_heap=BinaryMaxHeap(e7) my_binary_heap.insert(e12) my_binary_heap.insert(e13) my_binary_heap.insert(e11) my_binary_heap.insert(e14) my_binary_heap.insert(e29) my_binary_heap.insert(e18) my_binary_heap.insert(e18ii) my_binary_heap.insert(e42) my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value my_binary_heap.extract_max().value
c5fdb0f6a37c397aba0145606608798ac05d2259
ybdesire/WebLearn
/15_python/multi_thread/1_start_new_thread.py
532
3.875
4
#!/usr/bin/python # python 3.x import threading import time # Define a function for the thread def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("{0}: {1}".format( threadName, time.ctime(time.time()) )) # Create two threads as follows try: threading.Thread( target=print_time, args=("Thread-1", 2, ) ).start() threading.Thread( target=print_time, args=("Thread-2", 4, ) ).start() except: print("Error: unable to start thread")
be5432b5a1785fc52c64c26e50b75fff8b9a1c17
liyigao/ANLY-501-Introduction-to-Data-Analytics
/InClassActivityWeek10/part3.py
602
3.59375
4
import networkx as nx import matplotlib.pyplot as plt def main(): with open("dataset.txt", "rb") as file: G = nx.read_edgelist(file, delimiter = ',', create_using = nx.Graph(), nodetype = str, data = [("weight", int)]) print("Graph is", G.edges(data = True)) edge_labels = dict( ((z1, z2), z["weight"]) for z1, z2, z in G.edges(data = True) ) pos = nx.random_layout(G) nx.draw(G, pos, edge_labels = edge_labels, with_labels = True) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels = labels) plt.show() main()
209efe9460bf209ea4a33a32be5d865bab710699
aaqibgouher/python
/ifelse.py
150
4.0625
4
if 10>2: print("10") elif 2==2: print("3") else: print("2") a=2 b=3 min = a if a<b else b print(min) print("a") if False else print("b")
2404343037a0b87df3ae0ab3acbbcc38f2bd464c
aaqibgouher/python
/trycatch.py
239
4.09375
4
try: n = input("Enter a positive number ") if type(n) != int: raise Exception("input should be integer") n = int(n) if n<0: raise Exception("number cannot be negative") except Exception as e: print("error") print(e)
aaa2074b588a9d417b05c244f2dd53ae00fcc32e
aaqibgouher/python
/pandas_eg/Iteration.py
379
4
4
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(6,3),columns=["x","y","z"]) print(df) # Iteration through column : for key, values in df.iteritems() : print(key,values) # Iteration through row : for row_index,row in df.iterrows() : print(row_index,row) # Iteration through in rows but in tuples for row in df.itertuples() : print(row)
c03523d806625a1fe3fe5f243702564c2ac439b9
aaqibgouher/python
/numpy_eg/vector/Set_operations.py
785
3.890625
4
import numpy as np # 1. finding unique elements in set # arr = np.array([1,1,1,1,2,2,2,3,4,5,6,7,7,7]) # set_ = np.unique(arr) # print(set_) # print(type(set_)) # 2. Union for two sets : # arr_1 = np.array([1,3,5,7,9]) # arr_2 = np.array([2,4,6,8]) # print(np.union1d(arr_1,arr_2)) # 3.Intersection for two sets : # arr_1 = np.array([1,2,3,4,5]) # arr_2 = np.array([2,4,6,8]) # print(np.intersect1d(arr_1,arr_2)) # 4. Set Difference i.e A-B and B-A # arr_1 = np.array([1,2,3,4,5]) # arr_2 = np.array([2,4,6,8]) # print(np.setdiff1d(arr_1,arr_1)) # 5. finding symmetric difference # arr_1 = np.array([1,2,3,4]) # arr_2 = np.array([3,4,5,6]) # print(np.setxor1d(arr_1,arr_2,assume_unique=True)) #without using assu. fx it will also give output but that fx will speed the output
27d22cb8815a9c0f3af3d0cc9455789a89b6dd25
aaqibgouher/python
/pandas_eg/dataframe.py
707
3.9375
4
import pandas as pd df = pd.DataFrame() print(df) print(type(df)) # df from list df = pd.DataFrame([1,2,3,4,5]) print(df) # from list custom index df = pd.DataFrame([1,2,3,4,5], columns=["Age"]) print(df) # df from 2d list arr = [ ["nazish", 25], ["aaqib", 20], ["danish", 30] ] df = pd.DataFrame(arr, columns=["Name", "Age"]) print(df) # df from dict mydict = { "name" : ["nazish", "aaqib", "danish", "bhabhi"], "age" : [25, 20, 30, 30] } df = pd.DataFrame(mydict) print(df) # df from list of dict arr = [ { "name" : "nazish", "age" : 25 }, { "name" : "aaqib", "age" : 20, "sex" : "male" } ] df = pd.DataFrame(arr) print(df)
6b6bee3144bce48f71c9eb02c574d7540f0f42da
aaqibgouher/python
/numpy_random/generate_rn.py
815
4.34375
4
from numpy import random # 1. for random integer till 100. also second parameter is size means how much you wanna generate # num_1 = random.randint(100) #should give the last value # print(num_1) # 2. for random int array : # num = random.randint(100,size=10) # print(num) # 3. for random float ; # num_2 = random.rand() # last value is not required but if will give n digit then it will show a list containing n elements # print(num_2) # 4. for 2d random int array : # num = random.randint(100,size=(3,5)) # print(num) # 5. for 2d random float array : # num = random.rand(3,5) # print(num) # 6. random value from an array : # num = random.choice([1,2,3,4,5]) # print(num) # 7. from random value in the array generate a 2d array : # num = random.choice([1,2,3,4,5],size=(2,2)) # print(num)
9a52bf83259b55eddb32603836b235dec291cf38
aaqibgouher/python
/set.py
784
3.9375
4
# declare myset = {"nazish", "aaqib", "danish"} print(myset) # you cannot access using index value # access through loop for i in myset: print(i) # check from value in set print("nazish" in myset) # you cannot modify a value because you dont have access for a speciac index # only adding new value allow myset.add("saqib") print(myset) # insert multiple item myset.update(["nicey", "asif"]) print(myset) # remove # remove -> if value does not exist then it will through error # discard -> not through error myset.remove("asif") myset.discard("nicey") print(myset) # join two set # union set1 = {1,2,3,4} set2 = {3,4,5,6} set3 = set1.union(set2) print(set3) # intersection set4 = set1.intersection(set2) print(set4) # a-b set5 = set1.difference(set2) #set1-set2 print(set5)
962557880d2b679913ac49c86658aa8e5bb1205d
aaqibgouher/python
/numpy_eg/vector/summation.py
995
4.21875
4
import numpy as np # 1. simple add element wise # arr_1 = np.array([1,2,3,4,5]) # arr_2 = np.array([1,2,3,4,5]) # print(np.add(arr_1,arr_2)) # 2. summation - first it will sum the arr_1,arr_2 and arr_3 individually and then sum it at once and will give the output. also axis means it will sum and give the output in one axis # arr_1 = np.array([1,2,3,4,5]) # arr_2 = np.array([1,2,3,4,5]) # arr_3 = np.array([2,4,6,8,10]) # new_arr = np.sum([arr_1,arr_2,arr_3],axis=1) # print(new_arr) # 3. cummulative sum # arr_1 = np.array([1,2,3,4,5]) # print(np.cumsum(arr_1)) # 4. product # arr_1 = np.array([1,2,3,4,5]) # print(np.prod(arr_1)) # 5. product of more than 2 arrays # arr_1 = np.array([1,2,3,4,5]) # arr_2 = np.array([1,2,3,4,5]) # print(np.prod([arr_1,arr_2],axis=1)) #if will not give that axis,then it will give prod of both 2 arrays but after giving axis = 1, it will give individual product # 6. cummulative product # arr_1 = np.array([1,2,3,4,5]) # print(np.cumprod(arr_1))
95d294cbff2e851b9e541be789d63edf5060c37c
foanwang/Python-learn
/bank.py
472
3.703125
4
class Account: def __init__(self, name, number, balance): self.name = name self.number = number self.balance = balance def deposit(self, amount): if amount <= 0: print('amount should > 0') else: self.balance += amount def withdraw(self, amount): if amount > self.balance : print('balance is not enoguh!') else: self.balance -= amount def __str__(self): return 'Account({0}, {1}. {2})'.format( self.name, self.number, self.balance)
1f8069cf46fb5e40f28dbedb81b26caef387d5e7
paymantohidifar/DNAtaxis
/motifanalysis/scripts/py_classes/sequence.py
910
3.53125
4
class Sequence: # acceptable DNA base pairs ValidChars = 'TCAGtcag' + 'YMRWSK' + '[]' # construction a complement table to use with str.translate to generate complement sequence ComplementTable = str.maketrans('TCAGtcag[]', 'AGTCagtc][') @classmethod def invalid_char(cls, seqstring): return {chr for chr in seqstring if chr not in cls.ValidChars} def __init__(self, seqstring): invalid = self.invalid_char(seqstring) if invalid: raise Exception(type(self).__name__ + 'Sequence contains one or more invalid characters:' + str(invalid)) self.__seq = seqstring def get_sequence(self): return self.__seq def complement(self, seq): return seq.translate(self.ComplementTable) def reverse_complement(self, seq): return self.complement(seq)[::-1]
3d9f9ce0867eb9fb9928220370f1f462a7b4a859
Ashish-Jagarlamudi/Python_Learning
/HackerRank/Mutations.py
337
4
4
def mutate_string(string, position, character): lst=list(string) lst[position]=character output="".join(lst) return output output=mutate_string(input("Enter a String:"),int(input("Enter position of the string to be replaced:")) ,input("Enter the character to be updated at position")) print(output)
49bf861bfbb04989bde002edcb54380d753d6377
MAPSWorks/pySlipQt
/pySlipQt/examples/tkinter_error.py
3,187
3.890625
4
""" A small function to put an error message on the screen with Tkinter. Used by GUI programs started from a desktop icon. """ import textwrap try: from tkinter import * except ImportError: print("You must install 'tkinter'") print("Ubuntu: apt-get install python-tk") print("Windows: ???") sys.exit(1) def tkinter_error(msg, title=None): """Show an error message in a Tkinter dialog. msg text message to display (may contain newlines, etc) title the window title (defaults to 'ERROR') The whole point of this is to get *some* output from a python GUI program when run from an icon double-click. We use tkinter since it's part of standard python and we may be trying to say something like: +-------------------------+ | You must install PyQt | +-------------------------+ Under Linux and OSX we can run the program from the commandline and we would see printed output. Under Windows that's hard to do, hence this code. NOTE: For some reason, Ubuntu python doesn't have tkinter installed as part of the base install. Do "sudo apt-get install python-tk". """ ###### # Define the Application class ###### class Application(Frame): def createWidgets(self): self.LABEL = Label(self, text=self.text, font=("Courier", 14)) self.LABEL["fg"] = "black" self.LABEL["bg"] = "yellow" self.LABEL["justify"] = "left" self.LABEL.pack() def __init__(self, text, master=None): self.text = text Frame.__init__(self, master) self.pack() self.createWidgets() self.tkraise() # set the title string if title is None: title = 'ERROR' # get the message text msg = '\n' + msg.strip() + '\n' msg = msg.replace('\r', '') msg = msg.replace('\n', ' \n ') app = Application(msg) app.master.title(title) app.mainloop() if __name__ == '__main__': # just a simple "smoke test" of the error notification long_msg = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' 'sed do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Ut enim ad minim veniam, quis nostrud exercitation ' 'ullamco laboris nisi ut aliquip ex ea commodo consequat. ' 'Duis aute irure dolor in reprehenderit in voluptate velit ' 'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' 'occaecat cupidatat non proident, sunt in culpa qui officia ' 'deserunt mollit anim id est laborum.' ) tkinter_error('A short message with initial TAB:\n\tHello, world!\n\n' 'Some Unicode (你好, สวัสดี, こんにちは)\n\n' 'A large text paragraph. You must wrap and indent the text yourself:\n' + textwrap.fill(long_msg, initial_indent=' ', subsequent_indent=' '), title='Test Error Message')
8b12eadd79467b7c31cc71b3f2535a7eba1de09e
GHubgenius/DevSevOps
/2.python/0.python基础/day6/代码/集合的内置方法.py
1,184
3.703125
4
# ========================集合基本方法=========================== # 用途: 去重、关系运算 # 定义方式: 通过大括号存储数据,每个元素通过逗号分隔 # 定义空集合,必须使用set()来定义 # l1 = [] # s1 = "" # d1 = {} # ss1 = set() # 常用方法: """ 合集:| 交集:& 差集:- 对称差集:^ """ """ 1、集合中不可能出现两个相同的元素 """ python_student = {'egon', 'jason', 'tank', 'owen', 'egon'} linux_student = {'frank', 'alex', 'egon'} go_student = {'egon'} print(python_student) # print(python_student | linux_student) # print(python_student & linux_student) # print(python_student - linux_student) # print(linux_student - python_student) # print(python_student ^ linux_student) # print(python_student > go_student) # print(python_student < linux_student) # l1 = [1, 2, 3, 1, 2, 9, 1, 5, 6, 7] # print(l1) # # s1 = set(l1) # print(s1) # print(type(s1)) # l2 = list(s1) # print(l2) # print(type(l2)) for i in python_student: print(i) # =========================类型总结========================== # 有序or无序 : 无序 # 可变or不可变 : 不可变 # 存一个值or存多个值 : 存多个值
eafb27b52d7258758ce39e6228f765533bd55be3
GHubgenius/DevSevOps
/2.python/0.python基础/day11/01 函数对象应用复习.py
457
3.703125
4
''' : ȡif֧ ''' # ATM 100 def login(): pass def register(): pass # ֵ func_dic = { '1': login, '2': register, } choice = input('빦: ').strip() if choice in func_dic: # ʹdict.getʽȡֵ func_dic.get(choice)() # # if choice == 'login': # login() # elif choice == 'register': # register() # else: # print('!')
ac79aa0e13ff2748571b1c47fa92e779ae85cd6b
GHubgenius/DevSevOps
/2.python/0.python基础/day8/代码/文件打开模式的补充.py
543
3.9375
4
""" r w a # 纯净模式 # 可读可写 除了可读·可写之外剩下都是自己的特性 r+ w+ a+ """ # with open(r'a.txt','r+',encoding='gbk')as f: # f.write("亚峰牛批") # print(f.read()) # print(f.readable()) # print(f.writable()) # with open(r'c.txt','w+',encoding='gbk')as f: # f.write("亚峰牛批") # print(f.read()) # print(f.readable()) # print(f.writable()) # with open('a.txt','a+',encoding='utf-8')as f: # f.write('亚峰牛批') # print(f.readable()) # print(f.writable())
5846ab5ebd0cf10b4b8ade3fc54cdf9af24b83f9
GHubgenius/DevSevOps
/2.python/0.python基础/day7/代码/文件打开模式.py
1,063
3.640625
4
""" 打开文件的三种模式: r : 1、只读 2、如果文件不存在,会报错 w:(慎用) 1、只写 2、如果文件不存在,则新建一个文件写入数据 3、如果文件内存在数据,会将数据清空,重新写入 a: 1、追加写 2、如果文件内存在数据,会在已有数据的后面追加数据 3、如果文件不存在,则新建一个文件写入数据 处理文件的模式: t b """ # with open(r'dir\b.txt','r',encoding='gbk')as f: # print(f.readable()) # print(f.read()) # print(f.readline()) # 执行一次,打印一行内容 # print(f.readlines()) # print(f.read()) # print(f.readable()) # print(f.read()) # for i in f: # print(i) # with open(r'dir\b.txt', 'w', encoding='gbk')as f: # # f.write("上海校区第一帅-sean") # f.writelines(["上午没翻车\n",'我很高兴']) # with open(r'dir\aaaaa.txt','a',encoding='gbk')as f: # print(f.writable()) # f.write("\n翻车是不可能的")
c0af4782f04ee35396b0ca77e1187a7f1a2d95bf
GHubgenius/DevSevOps
/2.python/0.python基础/day14/代码/02 剩余内置函数.py
1,741
3.8125
4
''' map: 映射 map(函数地址, 可迭代对象) ---> map对象 map会将可迭代对象中的每一个值进行修改,然后映射一个map对象中, 可以再将map对象转换成列表/元组。 注意: 只能转一次。 reduce: 合并 reduce(函数地址, 可迭代对象, 默认为0) reduce(函数地址, 可迭代对象, 初始值) filter: 过滤 filter(函数地址, 可迭代对象) --> filter 对象 ''' # def func(): # pass # map(func) # 姓名列表 # name_list = ['egon', 'jason', 'sean', '大饼', 'tank'] # map_obj = map(lambda name: name + '喜欢吃生蚝' if name == 'tank' else name + 'DJB', name_list) # print(map_obj) # map_obj ---> list/tuple # print(list(map_obj)) # map_obj ---> 生成器(迭代器) ---> 用完后,不能再取了 # print(tuple(map_obj)) # reduce # from functools import reduce # 每次从可迭代对象中获取两个值进行合并, # 初始值: 执行reduce函数时,都是从初始值开始合并 # reduce(lambda x, y: x + y, range(1, 101), 0) # 需求: 求1——100的和 # 普通 # init = 1000 # for line in range(1, 101): # init += line # # # print(init) # 5050 # print(init) # 6050 # reduce # res = reduce(lambda x, y: x + y, range(1, 101), 1000) # print(res) # 6050 # filter name_list = ['egon_dsb', 'jason_dsb', 'sean_dsb', '大饼_dsb', 'tank'] # filter_obj = filter(lambda x: x, name_list) # 将后缀为_dsb的名字 “过滤出来” # filter会将函数中返回的结果为True 对应 的参数值 “过滤出来” # 过滤出来的值会添加到 filter对象中 filter_obj = filter(lambda name: name.endswith('_dsb'), name_list) print(filter_obj) print(list(filter_obj)) # # print(tuple(filter_obj))
f81990e2965f39346a35129b8614a71c702191a5
GHubgenius/DevSevOps
/2.python/0.python基础/day3/代码/逻辑运算符.py
395
4
4
# 与 或 非 # and or not a = 1 b = 2 c = 3 # print(a < b and b > c) # and:如果有一个式子不符合条件,整条式子都为False # print(a > b and b < c) # print(a < b or b < c) # or:只要有一个式子符合条件,整条式子都为True # print(a > b or b < c) # print(not a < b) # 取反 print(a < b and b < c or a > c) # True print(a > b or b < c and a > c) # False
cc22a9186c232e9b318940858ad2f0757b6ae77a
GHubgenius/DevSevOps
/2.python/0.python基础/day13/代码/7 匿名函数.py
659
4.25
4
''' 匿名函数: 无名字的函数 # :左边是参数, 右边是返回值 lambda : PS: 原因,因为没有名字,函数的调用 函数名 + () 匿名函数需要一次性使用。 注意: 匿名函数单独使用毫无意义,它必须配合 “内置函数” 一起使用的才有意义。 有名函数: 有名字的函数 ''' # 有名函数 def func(): return 1 print(func()) # func函数对象 + () print(func()) # 匿名函数: # def (): # pass # # () # + () # 匿名(), return 已经自动添加了 # lambda 匿名(): return 1 # func = lambda : 1 # print(func()) # func = lambda : 1 # print()
1a62de36ae15d14bdfbe63084863d64b8f2fe278
GHubgenius/DevSevOps
/2.python/0.python基础/day13/代码/0 昨日回顾.py
2,665
3.765625
4
# def wrapper1(func): # def inner1(*args, **kwargs): # print('1---start') # # 被裝飾對象在調用時,如果還有其他裝飾器,會先執行其他裝飾器中的inner # # inner2 # res = func(*args, **kwargs) # print('1---end') # return res # return inner1 # # # def wrapper2(func): # inner3 # def inner2(*args, **kwargs): # print('2---start') # res = func(*args, **kwargs) # inner3() # print('2---end') # return res # # return inner2 # # # def wrapper3(func): # index # def inner3(*args, **kwargs): # print('3---start') # res = func(*args, **kwargs) # index() # print('3---end') # return res # # return inner3 # # # ''' # 叠加裝飾器的裝飾順序與執行順序: # - 裝飾順序: 调用wrapper装饰器拿到返回值inner # 由下往上裝飾 # # - 執行順序: 调用装饰过后的返回值inner # 由上往下執行 # ''' # # # @wrapper1 # index《---inner1 = wrapper1(inner2) # @wrapper2 # inner2 = wrapper2(inner3) # @wrapper3 # inner3 = wrapper3(index) # def index(): # 被裝飾對象 # inner1 ---》 # print('from index...') # # # # 正在装饰 # # inner3 = wrapper3(index) # # inner2 = wrapper2(inner3) # # inner1 = wrapper1(inner2) # # ''' # inner1() # inner2() # inner3() # index() # ''' # index() # 此处执行 # inner1() --> inner2() ---> inner3() # 无参装饰器: 装饰在被装饰对象时,没有传参数的装饰器。 ''' # 以下是无参装饰器 @wrapper1 # inner1 = wrapper1(inner2) @wrapper2 # inner2 = wrapper2(inner3) @wrapper3 ''' # 有参装饰器: 在某些时候,我们需要给用户的权限进行分类 ''' # 以下是有参装饰器 @wrapper1(参数1) # inner1 = wrapper1(inner2) @wrapper2(参数2) # inner2 = wrapper2(inner3) @wrapper3(参数3) ''' # 有参装饰器 def user_auth(user_role): # 'SVIP' def wrapper(func): def inner(*args, **kwargs): if user_role == 'SVIP': # 添加超级用户的功能 res = func(*args, **kwargs) return res elif user_role == '普通用户': print('普通用户') # 添加普通用户的功能 res = func(*args, **kwargs) return res return inner return wrapper # 被装饰对象 # @user_auth('SVIP') # wrapper = user_auth('普通用户') # @wrapper # @user_auth('SVIP') # wrapper = user_auth('普通用户') # def index(): # pass # index() # list1 = [1, 2, 3] # iter_list = list1.__iter__() # print(len(iter_list))
45511470c4e3732cb408a609b81daf21b0567553
GHubgenius/DevSevOps
/2.python/0.python基础/day13/代码/8 内置函数.py
1,042
4.21875
4
''' 内置函数: range() print() len() # python内部提供的内置方法 max, min, sorted, map, filter sorted: 对可迭代对象进行排序 ''' # max求最大值 max(可迭代对象) # list1 = [1, 2, 3, 4, 5] # max内部会将list1中的通过for取出每一个值,并且进行判断 # print(max(list1)) # # dict1 = { # 'tank': 1000, # 'egon': 500, # 'sean': 200, # 'jason': 500 # } # 获取dict1中薪资最大的人的名字 # 字符串的比较: ASCII # print(max(dict1, key=lambda x: dict1[x])) # 获取dict1中薪资最小的人的名字 # print(min(dict1, key=lambda x:dict1[x])) # sorted: 默认升序(从小到大) reverse:反转 reverse默认是False # list1 = [10, 2, 3, 4, 5] # print(sorted(list1)) # # reverse=True--> 降序 # print(sorted(list1, reverse=True)) dict1 = { 'tank': 100, 'egon': 500, 'sean': 200, 'jason': 50 } # new_list = ['egon', 'sean', 'tank', 'jason'] new_list = sorted(dict1, key=lambda x: dict1[x], reverse=True) print(new_list)
a7f71f51a443042364a36a82503ab431e29394a8
GHubgenius/DevSevOps
/2.python/0.python基础/day10/代码/02 函数的嵌套.py
551
4.15625
4
# 函数的嵌套调用:在函数内调用函数 # def index(): # print('from index') # # # def func(): # index() # print('from func') # # # func() # def func1(x, y): # if x > y: # return x # else: # return y # print(func1(1,2)) # def func2(x, y, z, a): # result = func1(x, y) # result = func1(result, z) # result = func1(result, a) # return result # # # print(func2(1, 200000, 3, 1000)) # 函数的嵌套定义: def index(): def home(): print("from home") home() index()
ddc120377da0e7c2c7e0ef8594abc91cb0335640
GHubgenius/DevSevOps
/2.python/0.python基础/day15/代码/05 sys模块.py
328
3.53125
4
import sys import os # 获取当前的Python解释器的环境变量路径 print(sys.path) # 将当前项目添加到环境变量中 BASE_PATH = os.path.dirname(os.path.dirname(__file__)) sys.path.append(BASE_PATH) # 获取cmd终端的命令行 python3 py文件 用户名 密码 print(sys.argv) # 返回的是列表['']
dc2a706e7b5f0c577aed8879ed3185ecece313ce
Gnome0512/LearnPython
/LazyProperty/lazyproperty.py
3,011
3.625
4
#!/usr/bin/env python class LazyProperty(): def __init__(self,func): self.func = func def __get__(self,instance,owner): value = self.func(instance) setattr(instance,self.func.__name__,value) return value class Test(): Pi = 3.14 def __init__(self,r): self.r = r @LazyProperty def area(self): print('area calcu...') return self.Pi*self.r**2 t=Test(1) a=t.area b=t.area c=t.area print(a,b,c) ''' OUTPUT >>> t.area area calcu... 3.14 >>> t.area 3.14 >>> t.area 3.14 ''' ''' --------------------------------------------------- 装饰器(用类实现)说明: --------------------------------------------------- 和用函数实现的装饰器类似,只不过这种装饰器返回的是一个被类 __init__ 修饰的实例,在上例中,运行t.area时,实际上是在运行 t.LazPproperty(area) 事实上,如果直接使用 t.LazPproperty(area) 是会报错的,毕竟LazPproperty(area)这个实例是无法被调用的(没有实现__call__方法),这里就相当于把Test类中的area函数转换成了area类属性,而area属性值就是上面的 LazPproperty(area),这一点可以通过 Test.__dict__ 查看确认 相当于: LazyProperty类不变 class Test(): Pi = 3.14 def __init__(self,r): self.r = r def area(self): print('area calcu...') return self.Pi*self.r**2 area = LazyProperty(area) (上面本来是想用"def area_t(self) ...... area = LazyProperty(area_t)"的,但是这样写了之后用t.arae发现print还是会打印,后来发现是本描述符在setattr时会把值绑定到函数名的【同名】变量上,即要调用t.area_t才行,所以又改回了函数名) --------------------------------------------------- 描述符说明: --------------------------------------------------- 通过"实例.属性"得到值时,顺序如下: 1,调用实例的 __getattribute__ 方法 2,type(实例).__dict__('属性').__get__(实例,type(实例)) 查找数据描述符 3,实例.__dict__('属性') 查找本实例中是否有此属性 4,type(实例).__dict__('属性') 查找本类的类属性中是否有此属性 5,type(实例).__dict__('属性').__get__(实例,type(实例)) 查找非数据描述符 6,查找父类的类属性中是否有此属性 7,通过 __getattr__ 方法查找是否有此属性,没有则抛出异常 上例中,t.area首先查看t是否有area属性,很明显,上面的装饰器部分已经讲过,area被转换为了类属性,实例是没有此属性的,所以按顺序到第二部找的时候发现有此类属性,故调用 type(t).__dict__('area'),即LazPproperty(area)得到其值,又因为解释器发现LazPproperty是一个描述符,则进一步调用 type(t).__dict__('area').__get__(self,t,type(t))方法 --------------------------------------------------- 综上,类实现装饰器和描述符的运用构成了LazyProperty特性 --------------------------------------------------- '''
525de0cf414116db445adf077538308c4682ba66
duedil-ltd/pyfilesystem
/fs/multifs.py
10,616
3.75
4
""" fs.multifs ========== A MultiFS is a filesystem composed of a sequence of other filesystems, where the directory structure of each filesystem is overlaid over the previous filesystem. When you attempt to access a file from the MultiFS it will try each 'child' FS in order, until it either finds a path that exists or raises a ResourceNotFoundError. One use for such a filesystem would be to selectively override a set of files, to customize behavior. For example, to create a filesystem that could be used to *theme* a web application. We start with the following directories:: `-- templates |-- snippets | `-- panel.html |-- index.html |-- profile.html `-- base.html `-- theme |-- snippets | |-- widget.html | `-- extra.html |-- index.html `-- theme.html And we want to create a single filesystem that looks for files in `templates` if they don't exist in `theme`. We can do this with the following code:: from fs.osfs import OSFS from fs.multifs import MultiFS themed_template_fs.addfs('templates', OSFS('templates')) themed_template_fs.addfs('theme', OSFS('themes')) Now we have a `themed_template_fs` FS object presents a single view of both directories:: |-- snippets | |-- panel.html | |-- widget.html | `-- extra.html |-- index.html |-- profile.html |-- base.html `-- theme.html A MultiFS is generally read-only, and any operation that may modify data (including opening files for writing) will fail. However, you can set a writeable fs with the `setwritefs` method -- which does not have to be one of the FS objects set with `addfs`. The reason that only one FS object is ever considered for write access is that otherwise it would be ambiguous as to which filesystem you would want to modify. If you need to be able to modify more than one FS in the MultiFS, you can always access them directly. """ from fs.base import FS, synchronize from fs.path import * from fs.errors import * from fs import _thread_synchronize_default class MultiFS(FS): """A filesystem that delegates to a sequence of other filesystems. Operations on the MultiFS will try each 'child' filesystem in order, until it succeeds. In effect, creating a filesystem that combines the files and dirs of its children. """ _meta = { 'virtual': True, 'read_only' : False, 'unicode_paths' : True, 'case_insensitive_paths' : False } def __init__(self, auto_close=True): """ :param auto_close: If True the child filesystems will be closed when the MultiFS is closed """ super(MultiFS, self).__init__(thread_synchronize=_thread_synchronize_default) self.auto_close = auto_close self.fs_sequence = [] self.fs_lookup = {} self.fs_priorities = {} self.writefs = None @synchronize def __str__(self): return "<MultiFS: %s>" % ", ".join(str(fs) for fs in self.fs_sequence) __repr__ = __str__ @synchronize def __unicode__(self): return u"<MultiFS: %s>" % ", ".join(unicode(fs) for fs in self.fs_sequence) def _get_priority(self, name): return self.fs_priorities[name] @synchronize def close(self): # Explicitly close if requested if self.auto_close: for fs in self.fs_sequence: fs.close() if self.writefs is not None: self.writefs.close() # Discard any references del self.fs_sequence[:] self.fs_lookup.clear() self.fs_priorities.clear() self.writefs = None super(MultiFS, self).close() def _priority_sort(self): """Sort filesystems by priority order""" priority_order = sorted(self.fs_lookup.keys(), key=lambda n: self.fs_priorities[n], reverse=True) self.fs_sequence = [self.fs_lookup[name] for name in priority_order] @synchronize def addfs(self, name, fs, write=False, priority=0): """Adds a filesystem to the MultiFS. :param name: A unique name to refer to the filesystem being added. The filesystem can later be retrieved by using this name as an index to the MultiFS, i.e. multifs['myfs'] :param fs: The filesystem to add :param write: If this value is True, then the `fs` will be used as the writeable FS :param priority: A number that gives the priorty of the filesystem being added. Filesystems will be searched in descending priority order and then by the reverse order they were added. So by default, the most recently added filesystem will be looked at first """ if name in self.fs_lookup: raise ValueError("Name already exists.") priority = (priority, len(self.fs_sequence)) self.fs_priorities[name] = priority self.fs_sequence.append(fs) self.fs_lookup[name] = fs self._priority_sort() if write: self.setwritefs(fs) @synchronize def setwritefs(self, fs): """Sets the filesystem to use when write access is required. Without a writeable FS, any operations that could modify data (including opening files for writing / appending) will fail. :param fs: An FS object that will be used to open writeable files """ self.writefs = fs @synchronize def clearwritefs(self): """Clears the writeable filesystem (operations that modify the multifs will fail)""" self.writefs = None @synchronize def removefs(self, name): """Removes a filesystem from the sequence. :param name: The name of the filesystem, as used in addfs """ if name not in self.fs_lookup: raise ValueError("No filesystem called '%s'" % name) fs = self.fs_lookup[name] self.fs_sequence.remove(fs) del self.fs_lookup[name] self._priority_sort() @synchronize def __getitem__(self, name): return self.fs_lookup[name] @synchronize def __iter__(self): return iter(self.fs_sequence[:]) def _delegate_search(self, path): for fs in self: if fs.exists(path): return fs return None @synchronize def which(self, path, mode='r'): """Retrieves the filesystem that a given path would delegate to. Returns a tuple of the filesystem's name and the filesystem object itself. :param path: A path in MultiFS """ if 'w' in mode or '+' in mode or 'a' in mode: return self.writefs for fs in self: if fs.exists(path): for fs_name, fs_object in self.fs_lookup.iteritems(): if fs is fs_object: return fs_name, fs raise ResourceNotFoundError(path, msg="Path does not map to any filesystem: %(path)s") @synchronize def getsyspath(self, path, allow_none=False): fs = self._delegate_search(path) if fs is not None: return fs.getsyspath(path, allow_none=allow_none) if allow_none: return None raise ResourceNotFoundError(path) @synchronize def desc(self, path): if not self.exists(path): raise ResourceNotFoundError(path) name, fs = self.which(path) if name is None: return "" return "%s (in %s)" % (fs.desc(path), name) @synchronize def open(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, line_buffering=False, **kwargs): if 'w' in mode or '+' in mode or 'a' in mode: if self.writefs is None: raise OperationFailedError('open', path=path, msg="No writeable FS set") return self.writefs.open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, **kwargs) for fs in self: if fs.exists(path): fs_file = fs.open(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, line_buffering=line_buffering, **kwargs) return fs_file raise ResourceNotFoundError(path) @synchronize def exists(self, path): return self._delegate_search(path) is not None @synchronize def isdir(self, path): fs = self._delegate_search(path) if fs is not None: return fs.isdir(path) return False @synchronize def isfile(self, path): fs = self._delegate_search(path) if fs is not None: return fs.isfile(path) return False @synchronize def listdir(self, path="./", *args, **kwargs): paths = [] for fs in self: try: paths += fs.listdir(path, *args, **kwargs) except FSError: pass return list(set(paths)) @synchronize def makedir(self, path, recursive=False, allow_recreate=False): if self.writefs is None: raise OperationFailedError('makedir', path=path, msg="No writeable FS set") self.writefs.makedir(path, recursive=recursive, allow_recreate=allow_recreate) @synchronize def remove(self, path): if self.writefs is None: raise OperationFailedError('remove', path=path, msg="No writeable FS set") self.writefs.remove(path) @synchronize def removedir(self, path, recursive=False, force=False): if self.writefs is None: raise OperationFailedError('removedir', path=path, msg="No writeable FS set") if normpath(path) in ('', '/'): raise RemoveRootError(path) self.writefs.removedir(path, recursive=recursive, force=force) @synchronize def rename(self, src, dst): if self.writefs is None: raise OperationFailedError('rename', path=src, msg="No writeable FS set") self.writefs.rename(src, dst) @synchronize def settimes(self, path, accessed_time=None, modified_time=None): if self.writefs is None: raise OperationFailedError('settimes', path=path, msg="No writeable FS set") self.writefs.settimes(path, accessed_time, modified_time) @synchronize def getinfo(self, path): for fs in self: if fs.exists(path): return fs.getinfo(path) raise ResourceNotFoundError(path)
03d2bf8a74e0c8bf1565c87d41365ce21aec58f8
BigRLab/pottery
/pottery/bloom.py
9,975
3.53125
4
# --------------------------------------------------------------------------- # # bloom.py # # # # Copyright © 2015-2020, Rajiv Bakulesh Shah, original author. # # All rights reserved. # # --------------------------------------------------------------------------- # import itertools import math import mmh3 from .base import Base class BloomFilter(Base): '''Redis-backed Bloom filter with an API similar to Python sets. Bloom filters are a powerful data structure that help you to answer the question, "Have I seen this element before?" but not the question, "What are all of the elements that I've seen before?" So think of Bloom filters as Python sets that you can add elements to and use to test element membership, but that you can't iterate through or get elements back out of. Bloom filters are probabilistic, which means that they can sometimes generate false positives (as in, they may report that you've seen a particular element before even though you haven't). But they will never generate false negatives (so every time that they report that you haven't seen a particular element before, you really must never have seen it). You can tune your acceptable false positive probability, though at the expense of the storage size and the element insertion/lookup time of your Bloom filter. Wikipedia article: https://en.wikipedia.org/wiki/Bloom_filter Reference implementation: http://www.maxburstein.com/blog/creating-a-simple-bloom-filter/ Instantiate a Bloom filter and clean up Redis before the doctest: >>> dilberts = BloomFilter( ... num_values=100, ... false_positives=0.01, ... key='dilberts', ... ) >>> dilberts.clear() Here, num_values represents the number of elements that you expect to insert into your BloomFilter, and false_positives represents your acceptable false positive probability. Using these two parameters, BloomFilter automatically computes its own storage size and number of times to run its hash functions on element insertion/lookup such that it can guarantee a false positive rate at or below what you can tolerate, given that you're going to insert your specified number of elements. Insert an element into the Bloom filter: >>> dilberts.add('rajiv') Test for membership in the Bloom filter: >>> 'rajiv' in dilberts True >>> 'raj' in dilberts False >>> 'dan' in dilberts False See how many elements we've inserted into the Bloom filter: >>> len(dilberts) 1 Note that BloomFilter.__len__() is an approximation, so please don't rely on it for anything important like financial systems or cat gif websites. Insert multiple elements into the Bloom filter: >>> dilberts.update({'raj', 'dan'}) Remove all of the elements from the Bloom filter: >>> dilberts.clear() ''' def __init__(self, iterable=frozenset(), *, num_values, false_positives, redis=None, key=None): '''Initialize a BloomFilter. O(n * k) Here, n is the number of elements in iterable that you want to insert into this Bloom filter, and k is the number of times to run our hash functions on each element. ''' super().__init__(redis=redis, key=key) self.num_values = num_values self.false_positives = false_positives self.update(iterable) def size(self): '''The required number of bits (m) given n and p. This method returns the required number of bits (m) for the underlying string representing this Bloom filter given the the number of elements that you expect to insert (n) and your acceptable false positive probability (p). More about the formula that this method implements: https://en.wikipedia.org/wiki/Bloom_filter#Optimal_number_of_hash_functions ''' try: return self._size except AttributeError: self._size = ( -self.num_values * math.log(self.false_positives) / math.log(2)**2 ) self._size = math.ceil(self._size) return self.size() def num_hashes(self): '''The number of hash functions (k) given m and n, minimizing p. This method returns the number of times (k) to run our hash functions on a given input string to compute bit offsets into the underlying string representing this Bloom filter. m is the size in bits of the underlying string, n is the number of elements that you expect to insert, and p is your acceptable false positive probability. More about the formula that this method implements: https://en.wikipedia.org/wiki/Bloom_filter#Optimal_number_of_hash_functions ''' try: return self._num_hashes except AttributeError: self._num_hashes = self.size() / self.num_values * math.log(2) self._num_hashes = math.ceil(self._num_hashes) return self.num_hashes() def _bit_offsets(self, value): '''The bit offsets to set/check in this Bloom filter for a given value. Instantiate a Bloom filter: >>> dilberts = BloomFilter( ... num_values=100, ... false_positives=0.01, ... key='dilberts', ... ) Now let's look at a few examples: >>> tuple(dilberts._bit_offsets('rajiv')) (183, 319, 787, 585, 8, 471, 711) >>> tuple(dilberts._bit_offsets('raj')) (482, 875, 725, 667, 109, 714, 595) >>> tuple(dilberts._bit_offsets('dan')) (687, 925, 954, 707, 615, 914, 620) Thus, if we want to insert the value 'rajiv' into our Bloom filter, then we must set bits 183, 319, 787, 585, 8, 471, and 711 all to 1. If any/all of them are already 1, no problems. Similarly, if we want to check to see if the value 'rajiv' is in our Bloom filter, then we must check to see if the bits 183, 319, 787, 585, 8, 471, and 711 are all set to 1. If even one of those bits is set to 0, then the value 'rajiv' must never have been inserted into our Bloom filter. But if all of those bits are set to 1, then the value 'rajiv' was *probably* inserted into our Bloom filter. ''' encoded_value = self._encode(value) for seed in range(self.num_hashes()): yield mmh3.hash(encoded_value, seed=seed) % self.size() def update(self, *iterables): '''Populate a Bloom filter with the elements in iterables. O(n * k) Here, n is the number of elements in iterables that you want to insert into this Bloom filter, and k is the number of times to run our hash functions on each element. ''' iterables, bit_offsets = tuple(iterables), set() with self._watch(iterables): for value in itertools.chain(*iterables): bit_offsets.update(self._bit_offsets(value)) self.redis.multi() for bit_offset in bit_offsets: self.redis.setbit(self.key, bit_offset, 1) def __contains__(self, value): '''bf.__contains__(element) <==> element in bf. O(k) Here, k is the number of times to run our hash functions on a given input string to compute bit offests into the underlying string representing this Bloom filter. ''' bit_offsets = set(self._bit_offsets(value)) with self._watch(): self.redis.multi() for bit_offset in bit_offsets: self.redis.getbit(self.key, bit_offset) bits = self.redis.execute() return all(bits) def add(self, value): '''Add an element to a BloomFilter. O(k) Here, k is the number of times to run our hash functions on a given input string to compute bit offests into the underlying string representing this Bloom filter. ''' self.update({value}) def _num_bits_set(self): '''The number of bits set to 1 in this Bloom filter. O(m) Here, m is the size in bits of the underlying string representing this Bloom filter. ''' return self.redis.bitcount(self.key) def __len__(self): '''Return the approximate the number of elements in a BloomFilter. O(m) Here, m is the size in bits of the underlying string representing this Bloom filter. Please note that this method returns an approximation, not an exact value. So please don't rely on it for anything important like financial systems or cat gif websites. More about the formula that this method implements: https://en.wikipedia.org/wiki/Bloom_filter#Approximating_the_number_of_items_in_a_Bloom_filter ''' len_ = ( -self.size() / self.num_hashes() * math.log(1 - self._num_bits_set() / self.size()) ) return math.floor(len_) def __repr__(self): 'Return the string representation of a BloomFilter. O(1)' return '<{} key={}>'.format(self.__class__.__name__, self.key) if __name__ == '__main__': # pragma: no cover # Run the doctests in this module with: # $ source venv/bin/activate # $ python3 -m pottery.bloom # $ deactivate import contextlib with contextlib.suppress(ImportError): from tests.base import run_doctests run_doctests()
07923c14b2d3cc7e14a49c0eaff1e20d8769b7cb
Jonaugustin/MyContactsAssignment
/main.py
2,408
4.34375
4
contacts = [["John", 311, "noemail@email.com"], ["Robert", 966, "uisemali@email.com"], ["Edward", 346, "nonumber@email.ca"]] menu = """ Main Menu 1. Display All Contacts Names 2. Search Contacts 3. Edit Contact 4. New Contact 5. Remove Contact 6. Exit """ def displayContact(): if contacts: print("Contact Names are: ") for i in range(len(contacts)): print(contacts[i][0]) else: print("Sorry, as of right now there are no contacts.") callInput() def searchContact(): txt = """ Name: {} Phone Number: {} Email: {} """ cherch = str(input("Please enter name of individual you would wish to search: ")) for i in range(len(contacts)): for x in contacts[i]: if cherch == x: print(txt.format(contacts[i][0], contacts[i][1], contacts[i][2])) callInput() def editContact(): cherch = str(input("Please enter name of individual you would wish to search: ")) for i in range(len(contacts)): for x in contacts[i]: if cherch == x: contacts[i][0] = str(input("Please enter in a new name for this contact: ")) contacts[i][1] = int(input("Please enter in a new number for this contact: ")) contacts[i][2] = str(input("Please enter in a new email for this contact: ")) callInput() def newContact(): name = str(input("Please enter in a name for this contact: ")) phone = int(input("Please enter in a number for this contact: ")) email = str(input("Please enter in an email for this contact: ")) contacts.append([name, phone, email]) callInput() def removeContact(): cherch = str(input("Please enter name of individual you would wish to remove: ")) for i in range(len(contacts)): if cherch == contacts[i][0]: del contacts[i] break callInput() def callInput(): print(menu) option = int(input("Please select a number from 1 to 6: ")) if option == 1: displayContact() elif option == 2: searchContact() elif option == 3: editContact() elif option == 4: newContact() elif option == 5: removeContact() elif option == 6: exit() else: option = int(input("Please select a number again from 1 to 6: ")) callInput()
f0172ce268dd5be4c51c45c8d401f8430c267b1c
davidadeola/My_Hackerrank_Solutions
/python/text_wrap.py
783
3.953125
4
# Init solution # def wrap(string, max_width): # div_count = int(len(string)/max_width) # div_count = None # if(len(string)%max_width != 0): # div_count = int(len(string)/max_width) # else: # div_count = int(len(string)/max_width) + 1 # start = 0 # stop = max_width # arr = [] # for i in range(div_count): # arr.append(string[start:stop]) # start+=max_width # stop+=max_width # return "\n".join(arr) import textwrap def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) return "\n".join(word_list) if __name__ == '__main__': string, max_width = input("Enter String"), int(input("Enter max_width")) result = wrap(string, max_width) print(result)
5e24db4e26278f2e13d471437c3bb4b744b45fd9
davidadeola/My_Hackerrank_Solutions
/python/sparseArrays.py
379
3.734375
4
def matchingStrings(strings, queries): # Write your code here def str_count(arr, text): count = 0 for x in arr: if x == text: count+= 1 return count arr_of_counts = map(lambda query: str_count(strings, query), queries) return list(arr_of_counts) result = matchingStrings(["ab", "ab", "abc"], ["ab", "abc", "bc"]) print(result)
5c3ba45bdf9f033132f356bb6cdd0bcd41db24bd
benstafford/vndly_taxes
/store.py
1,146
3.640625
4
import math from scanner import Scanner class Store: def __init__(self, items): self.items = items def print_receipt(self): output = '' total_tax = 0 total = 0 for item in self.items: item_total, item_tax = self.calculate_item_tax(item) total_tax += item_tax total += item_total output += f'{item["quantity"]} {item["item"]}: {item_total:.2f}\n' output += f'Sales Taxes: {total_tax:.2f}\n' output += f'Total: {total:.2f}' return output def calculate_item_tax(self, item): item_subtotal_cents = round(float(item['price']) * 100, 0) tax_rate = 0 if "book" in item['item'] or "pills" in item['item'] or "chocolate" in item['item']: tax_rate = 0 else: tax_rate = 0.10 if "imported" in item['item']: tax_rate += 0.05 # round up to nearest 0.05, but with cents tax = math.ceil(item_subtotal_cents * tax_rate / 5) * 5 item_total = item_subtotal_cents + tax return item_total / 100, tax / 100
7ad516362ed65cf597cc5f358a0a8c7dd339aa67
cabb99/Tools
/math2py.py
631
4.0625
4
#!/usr/bin/python #Mathematica to python #Parse text text="" t = input("Insert mathematica text here: (end with new line)\n") while t!="": text+=t t = input() #Replace new line with space text=text.replace("\n"," ") #Merge extra spaces while " " in text: text=text.replace(" "," ") #Replace ", " with new line text=text.replace(", ","\n") #Other replacements text=text.replace(" -> ","=") text=text.replace("( ","(") text=text.replace(" )",")") text=text.replace(" + ","+") text=text.replace(" - ","-") text=text.replace(" ","*") text=text.replace("^","**") #Output print ("Python equations\n") print (text+"\n")
2b03baf1b9820a25b227b9efaa0e8a3a6967b8f4
Suhee05/sentenceGenerate
/sentGenerate.py
8,278
4
4
from tkinter import * from collections import Counter import re # 1) This N-gram Viewer enables to set value N.(N cannot exceed 3) # 2) According to the value, N grams are presented # 3) If you click any pair of N gram (or any unique word in case of unigram), its approximated probablity will show up # 4) is the most advanced technology in this program. Its algorithm employs Simple(Unsmoothed) N-gram Model. # Since this is my first trial for the N-gram Model, this algorithm can be revised later on. # I hope to see Smoothed N gram Model in this program... # This program ONLY accept files that are written in txt.(plain text) # All headers and footers must be removed # Opening a Corpus data that is too big can be overloading... # This program will get better if you get rid of all the global variables and make classes for the whole app. # , root = Tk() root.title("N-gram Viewer for Text files") root.geometry('900x500+200+100') ######################################## Open and Save Files #ONLY one file at one time can be processed #the saved file will be written in the following format ,.. file_read = '' def openfiles(): global file_read open_name= filedialog.askopenfilename(defaultextension = '.txt') f = open(open_name, encoding='UTF8') file_read = f.read() #불러온 파일을 file_read 전역변수에 남긴다 f.close() filepath_spt = open_name.split('/') fileShow_label.config(text=filepath_spt[-1]) #fileShow_label에 부른 파일 이름이 뜨게 만들어야함 #file 을 불러서 ngram을 만들기 위한 준비를 해야함 # proabable sentences 들이 저장되게 만들어야 한다 def savefile(): name= filedialog.asksaveasfilename(defaultextension='.txt', filetypes = (("파이썬파일", "*.py"), ("텍스트파일", "*.txt"), ("모든파일", "*.*"))) open(name,'w').write(ngram_listbox.get(0, END)) #현재는 ngram listbox가 저장됨 menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="파일", menu=filemenu) filemenu.add_command(label="열기", command=openfiles) filemenu.add_command(label="저장", command=savefile) #여기에 추가해서 probable senteces 도 저장하게 만들어볼까 filemenu.add_separator() filemenu.add_command(label="종료", command=root.destroy) filemenu.add_separator() """ N gram pairs and Frequency (N gram pair) \t (Freq) ... # and most probable sentences will be added in the end Most Probable sentences (sentence1) \n (sentence2) \n ... """ ########################################### Setting labels, boxes etc ################################################## ## grid method will be used for the location for the buttons and labels #그리드 셀크기를 알아야할거같은 ########################################### 1st Column ## Set the label "File Name" file_label = Label(root, text="File Name", width=10) file_label.grid(row = 0, column = 0, padx = 60, pady = 20) ## Set a Show-up label for the file (after opening a file, the file name will pop up) fileShow_label = Label(root, text="FileName", fg = '#000fff000' , width=20) fileShow_label.grid(row = 1, column = 0, padx = 60, pady = 20) ## Set the label "Choose N for N gram" chooseN_label = Label(root, text="Choose N for N gram", width=15) chooseN_label.grid(row = 2, column = 0, padx = 60, pady = 20) ## Set the radiobutton for N MODES = [("Unigram", 1), ("Bigram", 2), ("Trigram", 3)] v = IntVar() v.set(1) # initialize r = 0 for text, mode in MODES: rad = Radiobutton(root, text=text, indicatoron = 0, width = 20, variable=v, value=mode) rad.grid(row = 3+r , column = 0 , padx = 60, pady = 10) r += 1 # Set function that extracts Ngram from the selected file # set freq_list def ngram(x): return ' '.join(x) def extract_ngram(): global freq_list freq_list = [] sen_list = re.split('[.;!?\n]',file_read) # split a sentence by the mark . # not only by '.', ',?!' should be added sen_trim = [] for i in sen_list: sen_trim.append(i.strip(' \n0123456789')) # trim those sentences fin_comp = [] #final components. an element is a list which consists of trimmed words in one sentence for x in sen_trim: # for every trimmed sentence a = x.split() # split into a list of words # Use regular expression if len(a) > 1: b = [] # for every x (that is a trimmed sentence), b, a parsed sentence, consists of trimmed words for index,word in enumerate(a): word = word.lower() b.append(word.strip(",'?!():-><[]")) # for every word in a, trimmed words go into b if index == 0: b.insert(0,"<s>") elif index == (len(a)-1): b.insert(len(b),"</s>") fin_comp.append(b) # 5 lines above will be substituted for regular expression which is simpler cnt = Counter() if (v.get()) == 1: # Unigram for i in fin_comp: for k in i: cnt[k] += 1 elif (v.get()) == 2: #Bigram for i in fin_comp: temp02 = list(zip(i,i[1:])) temp12 = list(map(ngram, temp02)) for k in temp12: cnt[k] += 1 else: #Trigram for i in fin_comp: temp03 = list(zip(i,i[1:],i[2:])) temp13 = list(map(ngram, temp03)) for k in temp13: cnt[k] += 1 freq_list = cnt.most_common() for i in freq_list: ngram_listbox.insert(END,i[0]) #For the probablity, count all the tokens # for i in freq_list: # allword_num = allword_num + i[-1] ## Set Run Button run_button = Button(root, text = "Run", width = 5, height = 2, command = extract_ngram) run_button.grid(row = 6, column = 0, padx = 60, pady = 40) ########################################### 2nd Column ## Set the label "N grams" nGrams_label = Label(root, text="N grams", width=15) nGrams_label.grid(row = 0, column = 1, padx =60, pady = 20) ## Set a list box for N gram pairs # Add a vertical scroll bar to the list box """ scrollbar = Scrollbar(root) scrollbar.pack(side=RIGHT, fill=Y) # attach listbox to scrollbar listbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview) """ #scroll for ngram textbox ngram_yScroll = Scrollbar(root, orient=VERTICAL) ngram_yScroll.grid(row = 1, column = 2, rowspan = 4, pady = 10, sticky = SW+NW) #function that calculates the probability for the selected Ngram def prob_cal(event): widget = event.widget sel = widget.curselection() word = widget.get(sel[0]) word_num = 0 allword_num = 0 for i in freq_list: allword_num = allword_num + i[-1] for i in freq_list: #prob_cal 에서 확률계산하지 말고 아예 extract ngram에서 계 if i[0] == word: word_num = i[-1] prob = word_num / allword_num prob = round(prob,10) probShow_label.config(text = str(prob)) #ngram text box ngram_listbox = Listbox(root, width = 15, height = 15, yscrollcommand = ngram_yScroll.set) ngram_listbox.bind('<<ListboxSelect>>',prob_cal) ngram_listbox.grid(row = 1, column = 1, rowspan = 4, pady = 10, sticky = N+S+E+W) ngram_yScroll['command'] = ngram_listbox.yview ## Set a label for probability prob_label = Label(root, text="Probability", width=15) prob_label.grid(row = 5, column = 1, padx =60) ## Set a Show-up label for probability probShow_label = Label(root, text="Prob", fg = '#000fff000' , width=15) probShow_label.grid(row = 6, column = 1, padx = 60 ) ########################################### 3rd Column ## Set a label for Most probable sentences sent_label = Label(root, text="Most Probable Sentences", width= 20) sent_label.grid(row = 0, column = 3, padx = 60 ) ## Set a listbox for Most probable sentences sent_yScroll = Scrollbar(root, orient=VERTICAL) sent_yScroll.grid(row = 1, column = 4, rowspan = 6, pady = 20, sticky = SW+NW) sent_listbox = Listbox(root, width = 15, height = 20, yscrollcommand = sent_yScroll.set) sent_listbox.grid(row = 1, column = 3, rowspan = 6, pady = 10, sticky= N+S+E+W) mainloop()
185d6b1b2d4e8d49949d85e483cbb80696efbe66
hb5105/LabsSem6
/DS LAB/WEEK1/check.py
172
4.03125
4
#capitalize() #count(): str.count("substring"), counts the no of times a substring occurs in a paticular string str #str.find("sub"): returns index of sub in str if found #
66f4a01eb2398ae91b1865f595bf022eec9d134d
Mahdieh-Aghagoli/Maktab44-Group8-Smart-home-management-panel-simulation
/Home/home.py
4,275
3.984375
4
from Home import room import csv from hashlib import sha256 class Home: def __init__(self, rooms, sensors, password): """ :param rooms: different rooms of the house :param sensors: different sensors in a specific house :param password: users password to check her house """ self.rooms = rooms self.sensors = sensors # i think there is no need for this! self.password = password def __str__(self): return """ your rooms : {} sensors in your home : {} """.format(self.rooms, self.sensors) @staticmethod def home_definition(): set_of_sensors = set() number_of_rooms = int(input("How many rooms do you want to have?")) password = input("Please enter a password : ") while Home.does_exist(password, Home.home_db()): print("Try with different info!") password = input("Please enter a password : ") rooms_of_house = {} for i in range(number_of_rooms): num_of_sensors = int(input("Please Enter the number of sensors for room {}: ".format(i + 1))) this_room = room.Room.rooms_definition(i, num_of_sensors) for item in this_room.sensor: set_of_sensors.add(item) rooms_of_house[i] = this_room return Home(rooms_of_house, set_of_sensors, password) @staticmethod def home_db(): file = r"Home\home_db.csv" return file @staticmethod def sign_up(): """ :return: user can sign up and add her home to DB """ # all this problems (in this case, again using the db_file location) are because of not having username ( # specific email address) because it was not asked, and by having that in mind i coded this part and i didn't # wanted to change the code due to time limits db_file = Home.home_db() new_home = Home.home_definition() password = sha256(new_home.password.encode()).hexdigest() # if Home.does_exist(new_home.password, db_file): # print("Try with different info!") # Home.sign_up() # else: Home.write_in_db(password, new_home.sensors, new_home.rooms) @staticmethod def write_in_db(*args): db_file = Home.home_db() row = [args] # writing to csv file with open(db_file, 'a') as csv_file: # creating a csv writer object csv_writer = csv.writer(csv_file) # writing the data rows csv_writer.writerows(row) @staticmethod def login(): ''' :return: print the info of users home or if the does not exist it tells about it ''' password = input("Please enter your password : ") db_file = Home.home_db() if Home.does_exist(password, db_file): with open(db_file, 'r') as csv_file: # creating a csv reader object csv_reader = csv.reader(csv_file) for row in csv_reader: try: if row[0] == sha256(password.encode()).hexdigest(): for elem in range(len(row)): if elem == 0: pass else: print(row[elem]) except IndexError: pass else: print("password didn't match!") @staticmethod def does_exist(password, db_file): ''' :param password: get password entered by user :param db_file: our simple .csv file :return: True if the password exists in .csv file ''' pass_hash = sha256(password.encode()).hexdigest() # reading csv file with open(db_file, 'r') as csv_file: # creating a csv reader object csv_reader = csv.reader(csv_file) for row in csv_reader: try: if row[0] == pass_hash: return True except IndexError: pass # h = Home.home_definition() # room1 = h.rooms[0] # print(room1.sensor)
412e77a957e32678dd1bbdc9f4dde0c8bd05df34
blackplusy/0706
/0722-练习参考1.py
517
3.828125
4
#coding=utf-8 dic={'admin':'123','user1':'123','heygor':'456'} while 1: name=input('请输入您的用户名:') if name not in dic.keys() or len(name)==0 : print('请重新输入您的用户名') else: print('yes') while 1: password=input('请输入您的密码') if dic[name]==password: print('已经登录') break else: print('您的密码有误!') break
7d9c73c2e51ca6e212557d53f865f59e74146b83
blackplusy/0706
/例子-0722-02.字典.py
795
3.921875
4
#coding=utf-8 dic={'name':'heygor','age':18} dic1={'name':'o8ma'} #直接访问 print(dic) #数据筛选 print(dic['name']) print(dic['age']) #删除字典 #del dic={'name':'heygor','age':18} print(dic) del dic['age'] print(dic) del dic #print(dic) #clear dic={'name':'heygor','age':18} print(dic) dic.clear() print(dic) #字典的修改 dic={'name':'5kong','age':1000} print(dic) dic['name']='8jie' print(dic) dic['age']=10 print(dic) #keys dic={'name':'5kong','age':1000} print(dic.keys()) for i in dic.keys(): print(i) #values dic={'name':'5kong','age':1000} print(dic.values()) for i in dic.values(): print(i) #items dic={'name':'5kong','age':1000} print(dic.items()) for key,value in dic.items(): print(key+':'+str(value))
08ad7e95bcd680f5323a82226afe9480187eafbc
blackplusy/0706
/例子-0721-06.列表.py
595
3.953125
4
#coding=utf-8 #直接访问 l=['李元芳','李白','钟馗'] print(l) #遍历访问 for i in l: print(i) #成员访问 if '张小敬' in l: print('is here') else: print('not here!') #列表的索引和切片 l1=['黄忠','赵云','关羽','马超','张飞'] print(l1[0]) print(l1[-2]) #print(l1[5]) print(l1[2:]) print(l1[2:3]) #列表的拼接 l=[1,2,3,4] m=['a','b'] print(l+m) #列表的更新(修改) l=[1,2,3] print(l) l[2]='柳岩' print(l) l[-2]='离线' print(l) #列表的删除 l=[1,2,3] print(l) del l[2] print(l)
827a81f68dac1efc06f5b4f9a63d15d5a816253e
dogsoft0937/SEOULIT_PYTHON_LEARN
/day1/exampl2.py
179
3.859375
4
num1=int(input("입력:")) if num1>=90: print("A") elif num1>=80: print("B") elif num1 >= 70: print("C") elif num1 >= 60: print("D") else: print("F")
231de3811ff5e25460cf7a6d1e100b01c668a41c
dogsoft0937/SEOULIT_PYTHON_LEARN
/day2/function06.py
373
3.984375
4
import turtle as t def polygon(n): for x in range(n): t.forward(50) t.left(360/n) def polygon2(n,a): for x in range(n): t.forward(a) t.left(360/n) polygon(3)#삼각형 polygon(5)#오각형 polygon(7)#7각형 polygon(9)#9각형 polygon(11)#11각형 t.up() t.forward(150) t.down() polygon2(3,75) polygon2(5,100)
9883714347754e1813afebad16bc7117107d7848
dogsoft0937/SEOULIT_PYTHON_LEARN
/day1/for_range.py
258
4.09375
4
# Standard range for x in range(10): print('Hello') # Block example for x in range(3): print(100) print(200) for y in range(5): print(y) print(300) sum=0 for x in range(1,11): print(x) sum+=x print(sum)
380134e8d4ff8a293366ce18dd3caec8e5d2e7f8
StBies/Drifttube-practicalCourse
/Drifttube.py
7,082
3.671875
4
import numpy as np import matplotlib.pyplot as plt class Data: """ The Data class is basically a container for an array that contains the raw voltage This class offers a method to plot the event using matplotlib Author: Stefan Bieschke Date: 02/12/2018 """ def __init__(self,data_array,event_number): """ Constructor Initializes a new Data object with the raw data measured by a FADC given as parameter. Also sets an event number. Author: Stefan Bieschke Date: 02/12/2018 Parameters ---------- dataArray : array Array containing the raw voltage readings from the FADC eventNumber : int Number of the event """ self._raw_data = data_array self._event_number = event_number def get_drift_time(self,threshold,calibrated,triggertime = 0): """ Returns the drift time of this event's Data in nanoseconds The DataSet must be calibrated prior to calculating the drift time. Author: Stefan Bieschke Date: 02/12/2018 Parameters ---------- threshold : float threshold in volts that must be undershot in order to find drift time calibrated : bool specifying if DataSet is calibrated triggertime : int Time in the event where the trigger is located in ns Returns ------- int Drift time in nanoseconds """ #TODO: implement return 0 def get_array(self): """ Getter method for the raw array Author: Stefan Bieschke Date: 02/12/2018 Returns ------- array Array containing the raw voltage """ return self._raw_data def plot_data(self): """ Plot the Data Plots the event's voltage pulse form using matplotlib with time [ns] on the x-axis and voltage [V] on the y-axis. Author: Stefan Bieschke Date: 02/12/2018 """ #TODO: implement time axis scale plt.title("Event #{} voltage".format(self._event_number)) plt.xlabel("time [ns]") plt.ylabel("voltage [V]") plt.plot(self._raw_data) plt.show() class DataSet: """ A collection of Data objects. This class offers some methods to pull out events, to ask for the size and, most important, to perform a ground calibration """ def __init__(self,events): """ Constructor with an event list as parameter. Initializes a new DataSet object and sets the passed event list as its events. After construction, the DataSet size will be the same as the passed list's size. Author: Stefan Bieschke Date: 02/12/2018 Parameters ---------- events : list list of Data objects """ self._n_events = len(events) self._is_calibrated = False self._events = events def get_event(self,event_no): """ Returns the event specified by the parameter eventNo as Data class object if at least eventNo events exist in the DataSet. Author: Stefan Bieschke Date: 02/12/2018 Parameters ---------- eventNo : int number of the requested Data object. Must be smaller than self.nEvents. Returns ------- Data Data object containing the event """ if event_no < self._n_events: return self._events[event_no] def get_size(self): """ Getter method for the size of the DataSet. Returns the size of the DataSet, thus the maximum number of an event that can be requested using the getEvent(...) method. Author: Stefan Bieschke Date: 02/12/2018 Returns ------- int Number of events stored in this DataSet object. """ return self._n_events def is_calibrated(self): """ Returns the status of the calibration True if calibration was already performed, False else Returns ------- bool True if calibrated, False else """ return self._is_calibrated def perform_ground_calibration(self): """ Perform a ground calibration on all data in this DataSet. After the ground calibration, ground potential should read around 0.0 Volts. Author: Stefan Bieschke Date: 02/12/2018 Returns ------- float shift of the ground level before calibration. float mean noise amplitude. """ zero = 0 noise = 0 #TODO implement return zero, noise # Function - not part of a class def calculateEfficiency(self,n_triggers,n_valid): """ Calculate the detection efficiency for a given given number of valid events (a.k.a events with a valid drift time and a given number of total triggers Author: Stefan Bieschke Date: 08/14/2019 Parameters ---------- n_triggers : int Number of triggers in total n_valid : int Number of events with valid drift times Returns ------- float, float Efficiency [0,1], error [0,1] """ efficiency, error = 0, 0 #TODO implement return efficiency, error #---------------------------------------------------------------------- # Begin program execution #---------------------------------------------------------------------- """ Toggle comment if you want to give the file name as command line parameter #import sys #file = open(sys.argv[1],'rb') """ file = open("event.npy",'rb') #read binary mode #Read first 8 Bytes n_events = np.fromfile(file,np.int64,1)[0] n_bins = np.fromfile(file,np.int32,1)[0] events = [0] * n_events #Read events from binary file for i in range(n_events): data = np.fromfile(file,np.float64,n_bins) events[i] = Data(data,i) #Build DataSet object from events read above dataset = DataSet(events) zero, noise = dataset.perform_ground_calibration() dataset.get_event(1).plot_data() #TODO: Create drift time spectrum drifttimes = [0] * n_events for i in range(dataset._n_events): drifttimes[i] = dataset.get_event(i).get_drift_time(-0.25,dataset.is_calibrated()) histrange = (0,4095) nBins = int((histrange[1] - histrange[0]) / 4) hist = plt.hist(drifttimes,range=histrange,bins=nBins) #TODO: Add title and axis labels plt.show() #TODO: Create rt-relation #TODO: Drift time spectrum and rt-relation for several threshold voltages #TODO: Efficiency with errors for all these threshold voltages #TODO: plot eff with errorbars vs. threshold
73ad42dfc62970e717c437a6b6599fb84b57aeb4
KyleSMarshall/LeetCode
/[849] Maximize Distance to Closest Person.py
1,355
4.03125
4
# Problem: ''' In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to closest person. Example - Input: [1,0,0,0,1,0,1] Output: 2 ''' # Solution: (Faster than 97.93% of python3 submissions) class Solution: def maxDistToClosest(self, seats: List[int]) -> int: L = -1 # left index tracker R = 0 # right index tracker max_ = 0 # max distance to nearest person maxLind = -1 # left index of the seat which provides max distance for i in range(len(seats)): if seats[i] == 1: R = i if max_ < (R-L)//2 and maxLind != -1: max_ = (R-L)//2 maxLind = L # Check first edge case elif max_ < (R-L) and maxLind == -1: max_ = (R) maxLind = 0 L = R # Check second edge case elif i == len(seats)-1: R = i if max_ < R-L: return R-L return max_
49eac1715b6c7b72904e5b0577cbaa702e26ac10
KyleSMarshall/LeetCode
/[1282] Group the People Given the Group Size They Belong To.py
1,702
3.65625
4
# Problem: ''' There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people's IDs each group includes. You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution. Example - Input: groupSizes = [3,3,3,3,3,1,3] Output: [[5],[0,1,2],[3,4,6]] Explanation: Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. ''' # Solution: (Faster than 32.11% of python3 submissions) class Solution: def groupThePeople(self, groupSizes): # Create a dict to keep track of the group sizes and the number of counts # for each size in order to determine how many groups of that size we need group_counts = {} group_ids = {} for person_id, group_size in enumerate(groupSizes): if group_size in group_counts: group_counts[group_size] += 1 group_ids[group_size].append(person_id) else: group_counts[group_size] = 1 group_ids[group_size] = [person_id] output = [] # Now we need to split the str of person_ids for i, j in group_counts.items(): num_groups = int(j/i) temp_group = set(group_ids[i]) # Now add these people to their groups for k in range(num_groups): new_group = [] for m in range(i): new_group.append(temp_group.pop()) output.append(new_group) return output
363e45e54a4803717070ce3fabe1b1ed8e45d0b8
hnishi/TrainingProject_DA_TeamOseti
/hnishi/test_nan.py
225
3.703125
4
import pandas as pd import numpy as np s = pd.Series([2,3,np.nan,7,"The Hobbit"]) s s.isnull() print (s) print (s.isnull()) #https://chartio.com/resources/tutorials/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe/
7521ad06856aa16cf0e88cefb6e0d3b72377f3af
Team-Cha0s/CCC-Solutions
/2021-j3.py
701
3.609375
4
number = int(input()) number = [int(x) for x in str(number)] sum = number[0] + number[1] + number[2] + number[3] + number[4] direction = 0 sum1 = 0 while sum != 45: sum1 = number[0] + number[1] if (sum1 == 0): print(previous + str(number[2]) + str(number[3]) + str(number[4])) elif (sum1 % 2) == 0: print("right " + str(number[2]) + str(number[3]) + str(number[4])) previous = "right " elif (sum1 % 2) == 1: print("left " + str(number[2]) + str(number[3]) + str(number[4])) previous = "left " number = input() number = [int(x) for x in str(number)] sum = number[0] + number[1] + number[2] + number[3] + number[4]
9b4710aa46107b5bd94aa643f94ff6e5b7b9e572
Team-Cha0s/CCC-Solutions
/2013-j2.py
151
4.125
4
string = input() rotate = "IOSHZXN" final = "YES" for i in string: if i not in rotate: final = "NO" break print(final)
11fbbd7e664ef5078bc18f6ed2c5ef04a1ef15d2
Team-Cha0s/CCC-Solutions
/2014-j1.py
359
3.640625
4
# made by mohammed s1 = int(input()) s2 = int(input()) s3 = int(input()) Total = s1 + s2 + s3 if Total == 180: if s1 == s2 or s2 == s3 or s1 == s3: variable = "Isosceles" if s1 == s2 == s3: variable = "Equilateral" else: variable = "Scalene" else: variable = "Error" print(variable)
096707681911d70ef27dd0c46db54c406efd8cc0
Team-Cha0s/CCC-Solutions
/2015-j2.py
226
3.78125
4
#made by mohammed string = str(input()) h = string.count(":-)") s = string.count (":-(") total = h + s if total == 0: print("none") elif h == s: print("unsure") elif h > s: print("happy") else: print("sad")
34cea829d60a1c9e75f55d2566d0cb61cf14758e
kezia-petch/COMP150
/Lab 10/QUEST 2 Lab 10.py
344
3.734375
4
def dollars(filename): file = open(filename) text = file.read() words = text.split() new_string = "" for word in words: new_string += "$" + word + ",000" + "\n" return new_string my_file = open('numbers.txt', 'w') my_file.write("35 15 353 1 30 54 44 501") my_file.close() print(dollars('numbers.txt'))
a9fb9c7ed0b8049b2474d765be8ee743829413a0
kezia-petch/COMP150
/PROGRESSION 5/PRO 5 quest 5.py
844
3.75
4
def save_word_lengths(file_name, destination): """ >>> save_word_lengths("russia.txt", "russia_word_lengths.txt") >>> f1 = open("russia_word_lengths.txt") >>> text1 = f1.read() >>> f2 = open("russia_answer_word_lengths.txt") >>> text2 = f2.read() >>> text1 == text2 True >>> save_word_lengths("antigua.txt", "antigua_word_lengths.txt") >>> f1 = open("antigua_word_lengths.txt") >>> text1 = f1.read() >>> f2 = open("antigua_answer_word_lengths.txt") >>> text2 = f2.read() >>> text1 == text2 True """ file_in = open(file_name) file_out = open(destination, 'w') text = file_in.read() word = text.split() for word in word: file_out.write(str(len(word)) + " ") if __name__=='__main__': import doctest doctest.testmod(verbose=True)
17e4ec95fa480a53df11784e4ae27b69e0680ccd
kezia-petch/COMP150
/PRO 6 quest 7.py
508
3.5
4
myfile = open("text.txt", "w") myfile.write("I have a bunch\nof red roses") myfile.close() myfile = open('text.txt', 'r') text = myfile.read() def line_length(filename, line): file = open(filename) text = file.read().replace("\n","") i = 0 new = '' while i < len(text): if text[i].isspace(): new += '_' if i % line == 0 and i != 0: new += '\n' + text[i] else: new += text[i] i += 1 return new print(line_length("text.txt", 7))
4e66727d658e663835d86fe29b4cdb51b9446f40
nprun/f12
/5448/hw1/Shapes.py
2,193
3.8125
4
import random ##Python program ''' Generic 2-D point ''' class Point: def __init__(self, x, y): self.x = x self.y = y def display(self): return 'x={0}, y={1}'.format(self.x, self.y) ''' Base shape class ''' class Shape: def display(): pass def sort_order(self): return self.__sort_order def __init__(self): self.__sort_order = random.Random().randint(0,10) ''' Shape subclasses ''' class Circle(Shape): def __init__(self, center_point, radius): Shape.__init__(self) self.radius = radius self.center_point = center_point def display(self): return 'Circle - Sort {0} - Radius {1} center @ {2}'.format(self.sort_order(), self.radius, self.center_point.display()) class Square(Shape): def __init__(self, start_point, side_len): Shape.__init__(self) self.side_len = side_len self.start_point = start_point def display(self): return 'Square - Sort {0} -Side Length {1} starting @ {2}'.format(self.sort_order(), self.side_len, self.start_point.display()) class Triangle(Shape): def __init__(self, vertex_one, vertex_two, vertex_three): Shape.__init__(self) self.vertex_one = vertex_one self.vertex_two = vertex_two self.vertex_three = vertex_three def display(self): return 'Triangle - Sort {0} - Vertices @ {1}, {2} and {3}'.format(self.sort_order(), self.vertex_one.display(), self.vertex_two.display(), self.vertex_three.display()) ''' Main Program and helper functions ''' def init_shapes_db(): return [ Circle(Point(3,3), 5), Square(Point(7,4), 4), Triangle(Point(4,4), Point(3,3), Point(2,2)), Triangle(Point(14,4), Point(33,3), Point(-2,2)), Square(Point(0,0), 4), ] #initialize the shapes db shapes = init_shapes_db() #sort the shapes sorted_shapes = sorted(shapes, key=lambda x:x.sort_order()) print #empty line print 'Number of Shapes: {0}'.format(len(shapes)) print #empty line #display all shapes for shape in sorted_shapes: print shape.display() print #empty line #display all shapes in sorted order
f475992eed78724908315c200e0851170df69fb2
lukejskim/sba19-seoulit
/Sect-A/source/sect06_function/s633_arbitrary_argument.py
620
3.671875
4
# Arbitrary Arguments, 가변 인자 리스트 활용 def introduceMyFamily(my_name, *family_names, **family_info): print('안녕하세요, 저는 %s 입니다.'%(my_name)) print('-'*35) print('제 가족들의 이름은 아래와 같아요. ') for name in family_names: print('* %s ' % (name), end='\t') else: print() print('-' * 35) for key in family_info.keys(): print('- %s : %s ' %(key, family_info[key])) introduceMyFamily('진수', '희영', '찬영', '준영', '채영', 주소='롯데캐슬', 가훈='극기상진', 소망='세계일주')
7e46a856a34046e99f4353318d1cc9bf787973b2
lukejskim/sba19-seoulit
/Sect-A/source/sect07_class/s720_gen_object.py
255
4.125
4
# 클래스 정의 class MyClass: name = str() def sayHello(self): hello = "Hello, " + self.name + "\t It's Good day !" print(hello) # 객체 생성, 인스턴스화 myClass = MyClass() myClass.name = '준영' myClass.sayHello()
d8ce92f3cc9d892a6b6978d3bcd27a59b975cf81
lukejskim/sba19-seoulit
/Sect-A/source/sect04_control/s410_if_ex07_leapyear2.py
330
3.671875
4
year = int(input("서기 몇 년 ? ")) # 윤년 판정 --- (*1) is_leap = False if year % 400 == 0: is_leap = True elif year % 100 == 0: is_leap = False elif year % 4 == 0: is_leap = True else: is_leap = False # 결과 표시 if is_leap: print("윤년입니다.") else: print("윤년이 아닙니다.")
6b85ba08d25071f8d55f0518c560eed24840aec0
lukejskim/sba19-seoulit
/Sect-A/source/sect00_turtle/draw_color_polygon.py
760
3.65625
4
import turtle as t t.pensize(3) # 삼각형 만들기 t.penup() t.goto(-200, -50) t.pendown() t.begin_fill() t.color('red') t.circle(40, steps=3) t.end_fill() # 사각형 만들기 t.penup() t.goto(-100, -50) t.pendown() t.begin_fill() t.color('blue') t.circle(40, steps=4) t.end_fill() # 오각형 만들기 t.penup() t.goto(0, -50) t.pendown() t.begin_fill() t.color('green') t.circle(40, steps=5) t.end_fill() # 육각형 만들기 t.penup() t.goto(100, -50) t.pendown() t.begin_fill() t.color('yellow') t.circle(40, steps=6) t.end_fill() # 원 만들기 t.penup() t.goto(200, -50) t.pendown() t.begin_fill() t.color('purple') t.circle(40) t.end_fill() t.color('green') t.penup() t.goto(-100, 50) t.pendown() t.write("도형 색칠하기") t.done()
4353a5bb8b67db3637dd46b357cfcc99c28623aa
lukejskim/sba19-seoulit
/Sect-A/source/sect05_project/gugudan.py
242
3.609375
4
#준영이가 스스로 만든 구구단_01 단 = int(input('구구단을 몇단을 출력 할까요? 숫자를 입력하세요.: ')) print(단, '단') for x in range(1, 10): 값 = int(단 * x ) print(단, ' x ', x, ' = ', 값)
51e38c2f22a6a41a8c4c8e55399ab28e99cd13f9
lukejskim/sba19-seoulit
/Sect-A/source/sect00_turtle/PY-C02_for_dot_line.py
144
3.578125
4
import turtle as t t.pensize(3) t.color('red') for i in range(10): t.forward(15) t.penup() t.forward(15) t.pendown() t.done()
074602ae42dc365199b1c4930c6556990b755d91
lukejskim/sba19-seoulit
/Sect-A/source/sect08_module/fibo.py
510
4.0625
4
### 피보나치 수열을 위한 모듈 def fib(n): ''' n 까지의 피보나치 수열을 출력 하는 함수 :param n: Integer :return: None ''' a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib2(n): ''' n 까지의 피보나치 수열을 반환 하는 함수 :param n: Integer :return: List ''' result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
49713880f6ddd0e8594f6ddd241cbed8702f0faa
capt-alien/CDJ_Python
/python_dir/fundamentals/hello_world.py
390
3.90625
4
#!python3 hw="Hello World!" # Variables myself="Captain Alien!" num = 12 food_1="rice" food_2="BBQ" def main(): print(hw) print("Hello ",myself) print(f"Hello {myself}") print("Hello ", num) print(f"Hello {num}") print("I like to eat ",food_1, "and ", food_2) print(f"I like to eat {food_1} and {food_2}") # Exicutable code if __name__ == '__main__': main()
b034a6757d736e41fc4815822066c68720e7dcf6
capt-alien/CDJ_Python
/python_dir/oop/zoo.py
2,005
3.953125
4
#!python3 class Cat: def __init__(self, name): self.name = name self.coat = 'striped' self.size = 200 self.diet = 'meat' self.health = 500 self.happiness = 300 def eat(self, amount=50): self.health += 10 self.size += amount/100 return self def run(self): self.health -= 10 self.happiness += 5 self.size -= 5 return self def laz(self): self.health -= 5 self.happiness -=15 return self def display_info(self): print("="*30) print("Name: ", self.name) print("Coat: ", self.coat) print("size: ", self.size) print("Health: ", self.health) print("happiness: ", self.happiness) class Lion(Cat): def __init__(self, name): super().__init__(name) self.coat = "gold" class Tiger(Cat): def __init__(self, name): super().__init__(name) self.coat = 'striped' class Hippo: def __init__(self, name): self.name = name self.weight = 5000 self.temperment = "angry" def display_info(self): print("="*30) print("Name: ", self.name) print("Weight: ", self.weight) print("temperment: ", self.temperment) class Zoo: def __init__(self, zoo_name): self.animals = [] self.name = zoo_name def add_lion(self, name): self.animals.append( Lion(name) ) def add_hippo(self, name): self.animals.append( Hippo(name) ) def add_tiger(self, name): self.animals.append( Tiger(name) ) def print_all_info(self): print("-"*30, self.name, "-"*30) for animal in self.animals: animal.display_info() def main(): zoo1 = Zoo("John's Zoo") zoo1.add_lion("Nala") zoo1.add_hippo("Berry") zoo1.add_lion("Simba") zoo1.add_tiger("Rajah") zoo1.add_tiger("Shere Khan") zoo1.print_all_info() if __name__ == '__main__': main()
9d008fbcdab18fd562f74367abe5796d7f8f99fb
souzajean/iniciandopython
/20180922_aula6.py
341
4.03125
4
#Version: Python 3.6 -> data:22/09/2018 # coding: utf-8 print('Seja bem vindo ao mundo PYTHON') print('''Vamos aprender desde o inicio PYTHON ''') print("Objetivo inicial 'aprender a sintaxe' PYTHON") print('Estudar "logica de programação"') linguagem = str (input('Qual é a "melhor" linguagen para aprender?')) print(linguagem)