blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
acca1bdf168640ad83c0a5b28ff8782bb26a40e9
faseehahmed26/Python-Practice
/studentslist.py
123
3.578125
4
l1=[] no=int(input("Enter number of students:\n")) for i in range (no): a=int(input("Enter marks",i)) l1.append(a)
a2a5ffd066242090e100d58959ba1500e0919b44
faseehahmed26/Python-Practice
/starfor.py
71
3.953125
4
num=int(input("enter num")) for n in range(1,num+1): print('* '*n)
4ac12ebd70ffc8a9b882babe386acf38efc99944
Devesh0/210-CT-COURSEWORK
/Week3/6_reverse_string.py
168
4.0625
4
def reverse(string): y = string. split () x = y[::-1] # "SLICING" not the reverse function return " ". join (x) print (reverse("This is awesome ."))
c956e8e31d7e5102e1cbf85f3db0350315613216
Devesh0/210-CT-COURSEWORK
/Week3/8_vowal_removal.py
226
3.796875
4
def vowel_removal(s): if (len(s) <= 1): # base case return s elif s[0] in "aeiouAEIOU": return vowel_removal(s[1:]) return s[0] + vowel_removal(s[1:]) print(vowel_removal("beautiful"))
809492c6b23f8429aad6cea8724f95df0c4c5727
chdlkl/python
/PythonScientificCalculation/chap2/ufunc.py
3,577
3.546875
4
import numpy as np x = np.linspace( 0, 2*np.pi, 10 ) y = np.sin( x ) # ufunc函数产生的结果为数组 z = np.sin( x, out = x ) # 使用out将计算的结果存储在x数组中 # ------------------------------------------------------------------------------- # 比较运算和布尔运算 a = np.array( [1, 2, 3] ) b = np.array( [3, 2, 1] ) print( a < b ) # [ True, False, Flase ] print( a != b ) # [ True, False, True ] a = np.arange( 5 ) b = np.arange( 4, -1, -1 ) print( a == b ) # [False False True False False] print( a >= b ) # [False False True True True] print( np.logical_or( a==b, a>b ) ) # 等效于print ( a >= b ) # 对两个布尔数组使用and\or\not等进行布尔运算时,需要使用all()或any() # and等只能作用于单个的逻辑元素,不能作用于逻辑数组整体 print( np.any( a == b ) ) # a == b 返回[False False True False False],里面有True元素,所以输出为True print( np.any( a > b ) ) # a > b 返回[False False False True True],输出为True print( np.any( a == b ) and np.any( a > b ) ) # 根据上面,输出True # 位运算 # 1. 与运算& # a == b返回[False False True False False],a > b返回[False False False True True] print( (a==b)&(a>b) ) # 所以&运算返回[False False False False False] print( np.bitwise_and((a==b),(a>b)) ) # 与上句等效 # 2. 或运算| # a == b返回[False False True False False],a > b返回[False False False True True] print( (a==b)|(a>b) ) # 所以|运算返回[False False True True True] print( np.bitwise_or((a==b),(a>b)) ) # 与上句等效 # 3. 非运算~ # a > b返回[False False False True True] print( ~(a>b) ) # 所以~运算返回[True True True False False] print( np.bitwise_not((a>b)) ) # 与上句等效 # 4. 异或运算^(异或:相同为假,不同为真) # a == b返回[False False True False False],a > b返回[False False False True True] print( (a==b)^(a>b) ) # 所以^运算返回[False False True True True] print( np.bitwise_xor((a==b),(a>b)) ) # 与上句等效 # ------------------------------------------------------------------------------- # 动态数组 # 1. 一维 import numpy as np from array import array a = array( 'd', [1,2,3,4] ) # 创建一个array数组 # 通过np.frombuffer() 创建一个和a共享内存的Numpy数组 na = np.frombuffer( a, dtype = np.float ) print( a ) # array('d', [1.0, 2.0, 3.0, 4.0]) print( na ) # [ 1. 2. 3. 4.] na[1] = 20 print( a ) # array('d', [1.0, 20.0, 3.0, 4.0]) print( na ) # [ 1. 20. 3. 4.] # 2. 二维 import math # ============================================================================= # while ( j < 3 ): # 与下句j的for循环等价 # j = j + 1 # print( j ) # ============================================================================= for j in range(3): buf = array( 'd' ) # 要是将动态数组的定义写在j的循环之外,在j循环内清空动态数组的内存回报错 for i in range(5): buf.append( math.sin(i*j*0.1) ) buf.append( math.cos(i*j*0.1) ) data = np.frombuffer( buf, dtype = np.float ) data = data.reshape( -1, 2 ) print( data ) # del buf 与下句等价 buf = [] print( '--------------------------------' ) print ( data[1,1] ) # 查找数组沿着某一个位置,最大值的位置 a = np.array( [ [1,2,3],[2,3,4],[3,4,5] ] ) m = len( a ) # 行数 n = len( a[0,:] ) # 列数 for j in range(n): re = np.where( a[:,j] == np.max( a[:,j] ) ) print( re[0] ) for i in range(1,1): print('a')
4c76d5a43999acf107c3d8fe0362251b404ab52d
chdlkl/python
/character/testcharacter.py
1,329
3.953125
4
# 访问字符串中的值 var1 = 'hello world!' var2 = 'luk' print ( 'var1[0]: ', var1[0] ) # 这里要注意 # 1. python中的元素下标从0开始,Fortran中默认从1开始 # 2. 引用方式也不一样,python是[],fortran是() # 3. 引用单个元素时,比如,python是var[1],fortran是var(1:1) # 字符串更新(替换) var = 'lkl' print ( 'before var:', var ) var = var[0] + 'uk' print ( 'after var', var ) # 字符串运算符 a = 'hello'; b = 'python' print ( ' a is ', a ) print ( ' b is ', b ) print ( ' a + b is ', a + b ) # 字符串拼接,fortran用//拼接字符串 print ( ' a*2 is ', a * 2 ) # 连续输出字符串a两次 if ( 'h' in a ): # 判断字符'h'是否在字符串a中 print ( ' h in a ' ) else: print ( ' h not in a ' ) # 字符串格式化 print ( ' I am %s, and I am %d years old! ' %( 'luk', 10 ) ) # 这里单引号中的内容与%后面内容之间无逗号 # 数字格式化 print ( '%.15f' %(1.2) ) # 格式化输出数字,python为%.15f输出15位小数,fortran为fn.15,此处的n一般要满足n-15>=3 # 按规律输出字符 a = 'abcdefgh' print ( a[::2] ) # 从第一个字符输出,步长为2 # 使用负数从字符串右边末尾向左边反向索引,最右侧索引为-1,正向的话,最左侧为0 str = 'luklukluk' print ( str[-3] )
fa3404e643730448011f1f4aa261431f8d2360c4
chdlkl/python
/function/func1.py
8,231
4.25
4
# 函数规则: # 函数代码块以def关键词开头,后接函数标识符名称(函数名)和圆括号() # 任何传入参数和自变量必须放在圆括号中间 # 函数内容以冒号起始,并且缩进 # return [表达式]结束函数。不代表达式的return相当于返回none # python1 def hello(): print ( " hello, world! " ) hello ( ) # 自定义函数用于输出信息 # python2 import math def area( r ): s = math.pi * r * r return s print ( " area = ", area(1.0) ) def print_luk( name ): return name print ( " name = ", print_luk( "luk" ) ) # 这样调用,return后面必须跟返回值,否则返回none # print_luk( "luk" ) # 这样调用函数,因为函数print_luk中无执行语句,就算有返回值,也无输出 # python3 # python传不可变对象 def ChangeInt(a): print ( ' before a = ', a ) a = 10 print ( ' after a = ', a ) return a b = 2 print ( " func value: ", ChangeInt(b) ) print ( " b = ", b ) # 经过测试,建议写print ( 函数名(参数) ),即print ( ChangeInt(b) ) # 如果写ChangeInt(b)不会输出信息 # python传入可变参数 def Changme( list1 ): list1.append( 1 ) # append()函数里面的参数为1个整数,或列表(字典等) print ( " in : ", list1 ) return list1 list2 = [ 10, 20, 30, 40 ] Changme( list2 ) # 如果写成Change( list2[:] ),则两者的id不同 print ( " out : ", list2 ) # 特别注意 def Changeme( mylist ): mylist = [1,2,3,4]; print ( " In function: ", mylist ) return mylist = [10,20,30,40]; Changeme( mylist ); print ( " Out function: ", mylist ) # 这样写也不会影响外部的mylist,这是因为外面的mylist为全局变量,Changeme函数中的mylist为局部变量,两者id不同 # python传入时不指定参数顺序 def printinfo(name, age): print(" name: ", name); print(" age: ", age); return; # 调用printinfo函数 printinfo( age = 50, name = "runoob" ) # 如果写成printinfo( 50, 'runoob' )则要按顺序 # python传入默认参数,在调用函数时,如果没有传递参数(fortran中的实参),则会使用默认参数。 def printinfo( name, age = 35 ): print ( " name: ", name ) print ( " age: ", age ) return printinfo( age = 50, name = 'luk' ) print ( "--------------------" ) # 当函数中虚参有数值,并且在程序内部过程有输出,只写printinfo()也会输出35 printinfo( name = 'luk' ) # python传入可变长度变量 def printinfo( arg1, *vartuple ): print ( " arg1: ", arg1 ) for var in vartuple: print ( " var: ", var ) return printinfo ( 10 ) printinfo ( 10, 20, 30 ) # python匿名函数 # 1. python使用lambda来创建匿名函数 # 2. lambda只是一个表达式,函数体比def简单 # 3. lambda函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数 sum1 = lambda arg1, arg2: arg1 + arg2 print ( " 10 + 20 = ", sum1( 10, 20 ) ) print ( " 20 + 30 = ", sum1( 20, 30 ) ) # return语句 def sum1( arg1, arg2 ): total = arg1 + arg2 print ( " in function: ", total ) return total print ( " out function: ", sum1( 10, 20 ) ) # 变量作用域 # python中,程序的变量并不是哪个位置都可以访问的,访问权限决定于这个变量在哪里赋值 # 变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。python的作用域一共有四种 # 1. L(Local) 局部作用域 # 2. E(Enclosing) 闭包函数外的函数中 # 3. G(Global) 全局作用域 # 4. B(Bulit-in) 内建作用域 x = int(2.9) # 内建作用域 g_count = 0 # 全局作用域 def outer(): o_count = 1 # 闭包函数外的函数中 def inner(): i_count = 2 # 局部作用域 # python中只有模块(module),类(class),以及函数(def,lambda),才会引入新的作用域 # 其他代码块(如if/elif/else/、try/expect、for/while等)是不会引入新的作用域,也就是说这些语句内定义的变量,外部也可以访问 # 下面例子中,msg变量定义在if语句块中,但外部还是可以访问的 if True: msg = ' I am lukailiang! ' print ( msg ) # 如果将msg定义在函数中,则它就是局部变量,外部不能访问 def test(): msg1 = ' error! ' # print ( msg1 ) 这句报错,因为在全局中没定义变量msg1 # 这里值得注意一下,将局部变量与全局变量的命名最好不一致,如果一致,有时会混淆 # 例如,上面如果在函数test中定义为msg,然后再print(msg),如果全局中定义了msg,就会输出全局中msg的值,而不是函数test中msg的值,这里注意一下 # 全局变量与局部变量 # 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域 # 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问 total = 0; # 这是一个全局变量 def sum( arg1, arg2 ): total = arg1 + arg2; # total在这里时局部变量 print ( " In function total is ", total ) return total; # 调用函数sum,输出函数执行语句结果 sum(10,20) print ( " Out function total is ", total ) # global 和 nonlocal 关键字 num = 1 def fun1(): global num # 说明num是全局变量和局部变量,意思是局部变量num改变后,全局变量中的num也会改变 print ( " before: num = ", num ) num = 123 # 修改num的值 print ( " after: num = ", num ) # 调用函数 fun1() # 如果要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量则需要nonlocal关键字 def outer(): num = 10 def inner(): nonlocal num # nonlocal关键字声明 num = 100 print ( " num = ", num ) # 调用函数inner inner() print ( " num = ", num ) # 调用函数outer outer() # lambda匿名函数也是可以用“关键字参数”进行参数传递,为了不记混淆,建议在调用函数的同时进行指定,例如g(x=1,y=2) g = lambda x, y: x**2 + y**2 print ( " g(2,3) = ", g(2,3) ) # 默认为g(x=2, y=3) print ( " g(y=3,x=2) = ", g(y=3,x=2) ) # 不选择默认时,需要指定 # 传入一个参数 g = lambda x=0, y=0: x**2 + y**2 print ( " g(2) = ", g(2) ) # 默认为g(x=2),y值为函数中y的值 print ( " g(y=3) = ", g(y=3) ) # 此时需要指定 # 下面这个例子证明全局变量在局部变量中仍然起作用(但是局部改变后并不影响外部的值),反之则不行 # 如果想通过改变局部变量的值,而改变全局变量的值,需要使用global b = 1 def ss(): a = 1 + b print ( " a = ", a ) # 第一次调用函数ss() ss() # 该变b的值 b = 10 # 再次调用ss() ss() # 严重注意:函数内能访问全局变量,但不能更新(修改)其值,除非使用global # 例如 a = 10 def test(): a = a + 1 print ( " a = ", a ) # test() # 这种情况报错,主要原因还是函数中局部变量a没有声明(fortran为初始化)或是非法修改全局变量a的值,记住,只能访问不能修改 a = 10 def sum(n): n = n + a # 访问全局变量的值 # 如果加下面一句会报错 # a = 1,不能修改全局变量的值 print ( " a = ", a, end = "," ) print ( " n = ", n ) sum(3) # 下面代码是变量作用域的例子 # 1. 局部作用域 x = int(3.3) x = 0 def outer(): x = 1 def inner(): x = 2 print ( " x = ", x ) # 执行结果为2,因为在函数inner内部找到了变量x inner() outer() # 2. 闭包函数外的函数中 x = int(3.3) x = 0 def outer(): x = 1 def inner(): i = 2 print ( " x = ", x ) # 在局部变量中找不到,去局部外的局部寻找 inner() outer() # 3. 全局作用域 x = int(3.3) x = 0 def outer(): o = 1 def inner(): i = 2 print ( " x = ", x ) # 在局部(inner函数),局部的局部(outer函数)中都没找到,去全局找 inner() outer() # 4. 内建作用域 x = int(3.3) g = 0 def outer(): o = 1 def inner(): i = 2 print ( " x = ", x ) inner() outer() # 寻找列表中绝对值最大的下标 myList = [-1,2,-3,4,6,-5] absList = ( map(abs, myList) ) #对于Python3.x需要用list函数对map的返回值转换为列表 absList = list ( absList ) print (absList) print ( absList.index( max( absList ) ) )
ca27691f8b714bfde6af454a4ccfb6af5064ca1f
diyinqianchang/python
/src/detail/repTest.py
1,068
3.671875
4
#coding:UTF8 ''' Created on 2016��6��1�� @author: Administrator ''' import re x = 'HELLO WORLD' print(re.findall("hello", x,re.IGNORECASE)) print(re.findall("WORLD$", x, re.IGNORECASE)) #有转义字符 print(re.findall(r"\b\w+\b", x)) #sub先创建原变量的拷贝,然后在拷贝中替换字符串,并不会改变变量s的内容 print(re.sub("HELLO", "hi", x, 0, re.IGNORECASE)) s = '你好 WORLD2' print('匹配字母数字'+re.sub(r"\w", "hi", s)) print("替换次数"+str(re.subn(r"\w", "hi", s))) print("匹配非字母数字"+re.sub(r"\W", "hi", s)) print("匹配非字母数字"+re.sub(r"\s", "*", s)) s1 = '1abc23def45' p = re.compile(r'\d+') print(p.findall(s1)) print(p.pattern) print(re.findall(r"\d+", s1)) pre = re.compile(r"(abc)\1") m = pre.match("abcabc") print(m.group(0)) #返回整个表达式 print(m.group(1)) #没有见过这种匹配 (?P<one>abc)给分组命名 one (?P=one)调用分组 pre2 = re.compile(r"(?P<one>abc)(?P=one)") ma = pre2.search("abcabc") print(ma.group("one"))
1f949dccd4f245e250636ab296d45b3c69366034
diyinqianchang/python
/src/class/__init__.py
1,167
3.828125
4
#coding:utf-8 ''' Created on 2016年6月12号 @author: 张国林 ''' class Fruit: price = 0 #类属性 def __init__(self): # self.color = 'red' #实例属性 self.__color = 'red' zone = "China" #局部变量 self.__weight = 120 #私有属性 instance._classname__attribute def getColor(self): return self.__color @ staticmethod def getPrice(): #没有self参数 return Fruit.price # def ggetPrice(): # Fruit.price = Fruit.price+20 # return Fruit.price # count = staticmethod(ggetPrice) #staticmethod装换为静态方法 #Python的类和对象都可以访问类属性,而java中的静态变量只能被类调用 if __name__ == '__main__': print(Fruit.price) apple = Fruit() print(apple.getColor()) print(apple._Fruit__weight) Fruit.price = Fruit.price+10 print(apple.price) banana = Fruit() print(banana.price) print(apple.__dict__) print(apple.__doc__) print(Fruit.getPrice()) # print(Fruit.count())
72c796cf6cf5340bd5ba4075be5a494143e0861c
AaryanRS/Odd_-_Even
/OddorEven.py
246
4.09375
4
def oddEven(num) : if (num % 2 == 0) : print("Even") else: print("Odd") while True: num = int(input("Hi welcome to my project, Please enter the number here = ")) oddEven(num)
65d56039fe3688d16aeb6737fbcd105df044155a
pranshulrastogi/karumanchi
/doubleLL.py
2,884
4.40625
4
''' implement double linked list ''' class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class doubleLL: def __init__(self): self.head = None # insertion in double linked list def insert(self,data,pos=-1): assert pos >=-1, "make sure to give valid pos argument" # get the new node new_node = Node(data) # insertion when list is empty if not self.head: if pos > 0: print("list is empty, can't insert node at defined location") else: self.head = new_node else: # insertion when list is not empty # 1. insertion at beginning if pos == 0: new_node.next = self.head self.head = new_node # 2. insertion at middle elif pos > 0: i=0 n=self.head while(i<pos and n.next ): i+=1 n=n.next new_node.next = n new_node.prev = n.prev n.prev.next = new_node n.prev = new_node else: #3. insertion at last (default) n=self.head while(n.next): n=n.next new_node.prev = n n.next = new_node # deletion in double linked list def delete(self,pos=-1): # by default deletes the last node n = self.head # check empty if not n: print("Can't perform delete on empty list!!") return False # deletion of head node if pos==0: n.next.prev = None self.head = n.next n.next = None # deletion at certain position elif pos > 0: i=0 while ( i<=pos and n.next ): i+=1 n=n.next if i<pos: print("not valid positon to delete") return False n.prev.next = n.next n.next.prev = n.prev n.next = None else: while(n.next): n = n.next n.prev.next = None n.prev = None # display def printLL(self): n = self.head while(n.next): print(n.data,end=' <-> ') n = n.next print(n.data) # driver if __name__ == '__main__': #insert in dll dll = doubleLL() for i in range(2,33,2): dll.insert(i) dll.printLL() print("inserting at 0") dll.insert(1,0) dll.printLL() print("inserting at 2") dll.insert(3,2) dll.printLL() print("inserting at last") dll.insert(34) dll.printLL()
c87e47793e45a54750072e9cd55e5bbc3e5ae806
pranshulrastogi/karumanchi
/ch3p28.py
478
3.921875
4
# Problem: Display linked list from the last import singleLL def reversep(sll): if sll.head.next == None: # last node print(sll.head.data) else: p = sll.head sll.head = sll.head.next reversep(sll) print(p.data) if __name__ == "__main__": # create a single linked list sll = singleLL.singleLL() for i in range(10): sll.insert(i+1) sll.printLL() print("reverse print") reversep(sll)
d813ec86a78ab66bf1bbf58ca0a5b1d992611892
maheshganee/python-data
/8shallow copy.py
1,142
4
4
"""shallow copy: the process of copying the memory location from 1 variable to another variable is known as shallow copy rules of shallow copy: 2 r more variables must share a single memory location if 1 variable data gets change another data will get change automatically syntax: variable 2 = variable 1 shallow copy on mutable objects: as we can change the data of mutable data structures they will obey the rules of shallow copy perfectly ex:a=[1,2,3] b=a print id(a) print id(b) a[1] = 10 print a print b shallow copy on immutable objects: as we can't modify the data in immutable data structures they will not obey the properties of shallow copy completely ex:s='hello' v=s print v print id(v) print id(s) s = 'python' print id(s) print v deep copy:the process of copying the data from 1 variable to another variable is known as deep copy in deep copy 2 r more variables will share the same data with diff memory location Note:in orderd data structures we can perform deep copy by using slicing process and to acheive deep copy unorderd data structures we will copy ex:a=[1,2,3] b=a[::] print b print id(a),id(b) """
0765b7bc193f7bc799aa0b713b32b9c97ce7b3eb
maheshganee/python-data
/13file operation.py
2,798
4.65625
5
""" file operation:python comes with an inbuilt open method which is used to work with text files //the text files can operated in three operation modes they are read write append //open method takes atleast one parameter and atmost two parameters //first parameter represents the file name along with full path and second parameter represents operation modes //operation modes represents with single carrcter they are r for read w for write a for append //open method returns a file pointer object which contains file name and operation mode details read operation mode-------use second parameter r to open the the file in read operation mode //when a file opened in read mode we can only perform read operations so read operation will applicable only when the file exit syntax-----open('file name,'mode) ex------fp = open('data.txt','r') read functions 1 read 2 readline 3 readlines read----this method will return the file data in a string format //this method takes atmost one parameter that is index position //the default value of index position is always length of the file syntax-----fp.read(index position) note ------all the read operation function will cause a shifting of file pointer courser to reset the file pointer courser we can use seek method seek------this method takes exactly one parameter that is index position to reset syntax-----fp.seek(index position) readline-------this method will return one line of the file at a time //this method takes atmost one parameter that is index position and default value is first line of file syntax-----fp.readline(index position) readlines--------this method will return list of lines in given files //no parameters required //output is always list syntax-----fp.readlines() 2.write operation mode------use w as second parameter in open function to work with the files in write operation //w o m will always creates new file with given name //in write operation mode we can use two functions they are write writelines write-------this method is used to write one string into the given file //write method take exactly one parameter that is one string syntax-----fp.write() writelines-------this method is used to add multipule strings to given file //this method takes exactly one parameter list r tuple syntax-----fp.writelines() 3.append operation mode-------use a as second parameter in open function to work with the files in append o m //to work with a o m the file should exit in the system //we can perform two functions in a o m which are similar to write operation mode they are write writelines rb --------read + binary(read + append) rb+---------read + append/write wb----------write +read wb+---------write+raed+append """ fp = open('/home/mahesh/Desktop/data.txt','w') fp.write('hi')
9e2e7029b391be661e4b9ff1f5abbd53aefa4840
ActionArts/PythonPlay
/sum.py
333
3.703125
4
#Sum all the numbers containing a '9' between 0-50 and 100-150, non-inclusive (meaning, the upper bound of each range is not included) totalsum = 0 counter = 0 while counter < 150: if counter < 50 or counter > 99: if '9' in str(counter): totalsum = totalsum + counter counter = counter + 1 print "total sum = ", totalsum
1e171d3183670dd0bac6ab179a3b7c13c42f834c
rronakk/python_execises
/day.py
2,705
4.5
4
print "Enter Your birth date in following format : yyyy/mm/dd " birthDate = raw_input('>') print" Enter current date in following format : yyyy/mm/dd " currentDate = raw_input('>') birth_year, birth_month, birth_day = birthDate.split("/") current_year, current_month, current_day = currentDate.split("/") year1 = int(birth_year) month1 = int(birth_month) day1 = int(birth_day) year2 = int(current_year) month2 = int(current_month) day2 = int(current_day) def daysBetweenDates(year1, month1, day1, year2, month2, day2): # Counts total number of days between given dates days = 0 assert(dayBeforeNext(year1, month1, day1, year2, month2, day2) > 0) while (dayBeforeNext(year1, month1, day1, year2, month2, day2)): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def nextDay(year, month, day): # Helper function to return the year, month, day of the next day. if (day < daysInMonth(month, year)): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def dayBeforeNext(year1, month1, day1, year2, month2, day2): # Validates if user has not entered future date before past date if (year1 < year2): dbn = True elif(year1 == year2): if(month1 < month2): dbn = True elif(month1 == month2): if(day1 < day2): dbn = True else: dbn = False else: dbn = False else: dbn = False return dbn def daysInMonth(month, year): # Calculate days in a given month and year # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month if (month == 2): days = 28 + isLeapYear(year) else: days = 31 - (month - 1) % 7 % 2 return days def isLeapYear(year): # Determine if give year is lear year or not. # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/determining_leap_years """ if ((year % 4 == 0) or ((year % 100 == 0) and (year % 400 == 0))): leapYear = 1 else: leapYear = 0 return leapYear """ if (year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): leapYear = 1 else: leapYear = 0 else: leapYear = 1 else: leapYear = 0 return leapYear print "=============================================================== \n Your age in days is : %d " % daysBetweenDates(birth_year, birth_month, birth_day, current_year, current_month, current_day)
a81a346e355d82d8132a93843f0da9f38eabb790
ciankehoe/py-dsa
/sequences_sets_maps/previous_numbers.py
280
3.734375
4
seen = set() dups = [] #duplicates num = input().lstrip().strip() # read our input while num != "-1": if num not in seen: seen.add(num) else: dups.append(num) num = input().lstrip().strip() print("Enter numbers (-1 to end): " + ' '.join(dups) + " ")
090a6019784c9724f39ee8f99bc4c3ba16c1fab3
chandudasari1988/Modern-Python-Cookbook-Second-Edition
/Chapter_03/ch03_r05.py
2,271
3.75
4
"""Python Cookbook 2nd ed. Chapter 3, Recipe 5 """ from math import radians, sin, cos, sqrt, asin from typing import Callable MI = 3959 NM = 3440 KM = 6373 def haversine( lat_1: float, lon_1: float, lat_2: float, lon_2: float, R: float = NM ) -> float: """Distance between points. R is radius, R=MI computes in miles. Default is nautical miles. >>> round(haversine(36.12, -86.67, 33.94, -118.40, R=6372.8), 5) 2887.25995 """ Δ_lat = radians(lat_2) - radians(lat_1) Δ_lon = radians(lon_2) - radians(lon_1) lat_1 = radians(lat_1) lat_2 = radians(lat_2) a = sin(Δ_lat / 2) ** 2 + cos(lat_1) * cos(lat_2) * sin(Δ_lon / 2) ** 2 c = 2 * asin(sqrt(a)) return R * c # Note the lack of parameter type hints -- the *args anonymizes the parameters. def nm_haversine(*args): """ >>> round(nm_haversine(36.12, -86.67, 33.94, -118.40), 2) 1558.53 """ return haversine(*args, R=NM) # To avoid confusion about whether or not R is in *args, we're forced to provide explicit parameter types. def nm_haversine1(lat_1: float, lon_1: float, lat_2: float, lon_2: float) -> float: """ >>> round(nm_haversine(36.12, -86.67, 33.94, -118.40), 2) 1558.53 """ return haversine(lat_1, lon_1, lat_2, lon_2, R=NM) from functools import partial nm_haversine2 = partial(haversine, R=NM) # Lambda's don't permit type hints without some rather complex-looking syntax NM_Hav = Callable[[float, float, float, float], float] nm_haversine3: NM_Hav = lambda lat_1, lon_1, lat_2, lon_2: haversine( lat_1, lon_1, lat_2, lon_2, R=NM ) __test__ = { "manual": """\ >>> round(nm_haversine1(36.12, -86.67, 33.94, -118.40), 2) 1558.53 """, "partial": """\ >>> round(nm_haversine2(36.12, -86.67, 33.94, -118.40), 2) 1558.53 """, "lambda": """\ >>> round(nm_haversine3(36.12, -86.67, 33.94, -118.40), 2) 1558.53 """, } from pytest import approx # type: ignore def test_haversine(): assert nm_haversine1(36.12, -86.67, 33.94, -118.40) == approx(1558.526) assert nm_haversine2(36.12, -86.67, 33.94, -118.40) == approx(1558.526) assert nm_haversine3(36.12, -86.67, 33.94, -118.40) == approx(1558.526) assert haversine(36.12, -86.67, 33.94, -118.40, R=NM) == approx(1558.526)
d1bbb4444af9eaf5347174a23450b5d8bf085fcc
raghu1199/Advance_Python
/OOPS/FullCalculator_usingOnly_addtion.py
727
3.9375
4
from utils.addition import Addition class Calculator: @classmethod def add(cls, num1, num2): return Addition.add(num1, num2) @classmethod def subtract(cls,num1,num2): return cls.add(num1,-num2) @classmethod def mutiply(cls,num1,num2): res=0 for x in range(0,num2): res=cls.add(res,num1) return res @classmethod def divide(cls,num1,num2): res=0 while num1>=num2: num1=cls.subtract(num1,num2) res=cls.add(res,1) return res calc=Calculator() print("Addition:",calc.add(5,4)) print("Subtraction:",calc.subtract(5,4)) print("Mutiply:",calc.mutiply(5,4)) print("Divison:",calc.divide(10,2))
c987da5d77b52ff6f6cbcde57f64c53ba72fb3ab
raghu1199/Advance_Python
/Errors_Exeception_Handling/raiseErroe.py
582
4.0625
4
class Car: def __init__(self,make,model): self.make=make self.model=model def __repr__(self): return f"<Car {self.make} {self.model}" class Garage: def __init__(self): self.cars=[] def __len__(self): return len(self.cars) def add_car(self,car): if not isinstance(car,Car): raise TypeError(f"Only 'Car' object is allowed to add ur object is:{car.__class__.__name__}") self.cars.append(car) ford=Garage() #ford.add_car("MAruti") car=Car("ford","fiesta") ford.add_car(car) print(len(ford))
bd9766b33dc4f0332da60352b0854b3097bcb3ae
raghu1199/Advance_Python
/File_Handling/Basic_Read_Write.py
205
3.6875
4
user_name=input("Enter ur name:") my_file=open("data.txt","a") my_file.write(user_name) my_file.close() my_file_r=open("data.txt","r") file_content=my_file_r.read() my_file_r.close() print(file_content)
f62bebe6614a71a099d59c73bcbc1e8e9836420e
raghu1199/Advance_Python
/Concurrenancy/threads.py
650
3.65625
4
import time from threading import Thread def ask_user(): start=time.time() user_input=input("Enter Your name:") greet=f"Hello,{user_input}" print(greet) print(f"ask_user,{time.time()-start}") def complex_calc(): start=time.time() print("Started calculating..") [x**2 for x in range(20000000)] print(f"complex_calc,{time.time()-start}") start=time.time() ask_user() complex_calc() print(f"Single thread {time.time()-start}") start=time.time() t1=Thread(target=ask_user) t2=Thread(target=complex_calc) t1.start() t2.start() t1.join() t2.join() print(f"Two thread {time.time()-start}")
7f5b2c724012122a57dcac79614d21205f272925
raghu1199/Advance_Python
/OOPS/basic_class.py
485
3.765625
4
class Student: def __init__(self, name, new_grades): self.name = name self.grades = new_grades def average(self): return sum(self.grades) / len(self.grades) st1=Student("RAHUL MC",[60,55,34,21,17]) st2=Student("RAGHU HERO",[96,98,97,90,93]) print(st1.name,st1.grades) print(st2.name,st2.grades) print(st1.average()) print(st2.average()) def average1(student): return sum(student.grades)/len(student.grades) print("average by separate :",average1(st1))
ba131ca609c18ee3cf0d5fb5673dd4b18166df08
van950105/leetcode
/moveZeroes.py
537
3.609375
4
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i=0 length=len(nums) while i<length: if nums[i]!=0: i+=1 else: j=i while (j<length) and nums[j]==0: j+=1 if j==length: return nums[i]=nums[j] nums[j]=0 i+=1 return a=Solution() print a.moveZeroes([0,1,2,3])
278dcd1b7a8f3807c699b26a813ce54c96b96043
daxata/assignment_II
/11_replace_last_value_tuple.py
389
3.640625
4
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> lis1 = [(10,20,40), (40,50,60), (70,80,90)] >>> lis2 = [] >>> for i in lis1: t1 = list(i) t1[-1] = 30 t2 = tuple(t1) lis2.append(tuple(t2)) >>> print(lis2) [(10, 20, 30), (40, 50, 30), (70, 80, 30)] >>>
f9baac6271366884fbb8caaf201ccb6b4e53e254
sunilmummadi/Trees-3
/symmetricTree.py
1,608
4.21875
4
# Leetcode 101. Symmetric Tree # Time Complexity : O(n) where n is the number of the nodes in the tree # Space Complexity : O(h) where h is the height of the tree # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Approach: To check for symmetry of a tree, check if the extremes of a sub tree i.e. left child of # left subtree and right child of right subtree are same. And if middle elements i.e. right child of # left subtree and left child of right subtree are same. If the condition is not satisfied at any node # then the tree is not symmetric. If the entire tree can be recurrsively verified for this condition then # the tree is symmetric. # Your code here along with comments explaining your approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: # BASE if root == None: return True return self.helper(root.left, root.right) def helper(self, left, right): # Leaf Node if left == None and right == None: return True # Un symmetric if left == None or right == None or left.val != right.val: return False # recurssive call for left and right extremes and # recurssive call for left and right middle elements to check for symmetry return self.helper(left.left, right.right) and self.helper(left.right, right.left)
bbb9a92005149b0c398cc11b08b64590d238abed
jenniferlim07/swap-meet
/swap_meet/vendor.py
2,469
3.546875
4
class Vendor: def __init__(self, inventory=None): if inventory is None: inventory = [] self.inventory = inventory def add(self, item): self.inventory.append(item) return item def remove(self, item): if item in self.inventory: self.inventory.remove(item) return item return False def get_by_category(self, category): item_list = [] for item in self.inventory: if item.category == category: item_list.append(item) return item_list def swap_items(self, vendor, my_item, their_item): if my_item in self.inventory and their_item in vendor.inventory: self.inventory.remove(my_item) vendor.inventory.append(my_item) vendor.inventory.remove(their_item) self.inventory.append(their_item) return True return False def swap_first_item(self, vendor): if self.inventory and vendor.inventory: return self.swap_items(vendor, self.inventory[0], vendor.inventory[0]) return False def get_best_by_category(self, type): best_condition = 0 highest_category = None for item in self.inventory: if item.category == type: if best_condition < item.condition: best_condition = item.condition highest_category = item return highest_category def swap_best_by_category(self, other, my_priority, their_priority): my_item = self.get_best_by_category(their_priority) their_item = other.get_best_by_category(my_priority) return self.swap_items(other, my_item, their_item) def swap_by_newest(self, other, my_priority, their_priority): if not self.inventory or not other.inventory: return False my_newest_age = self.inventory[0].age my_item = self.inventory[0] for item in self.inventory: if item.age < my_newest_age: my_newest_age = item.age my_item = item their_newest_age = other.inventory[0].age their_item = other.inventory[0] for item in other.inventory: if item.age < their_newest_age: their_newest_age = item.age my_item = item return self.swap_items(other, my_item, their_item)
5eb4e40394794a720e2e79a25a0a778bb0bcf23a
ERNESTO553/deberes
/def multiply.py
114
3.59375
4
def multiply(a, b): return a*b print(multiply(3,4)) def multiply (a,b): return print(multiply(3,4))
371d2c464ecef440e0f944b4e7f986d58bc044bf
ERNESTO553/deberes
/año bisiesto.py
181
3.71875
4
a=int(input("ingresa año\n")) if(a % 4 == 0 and a % 100 != 0 or a % 400 == 0): print("El año "+str(a)+" Si es bisiesto ") else: print("El año "+str(a)+" No es bisiesto ")
a4528243ef5de093ed02bd4299d30d69724d390c
ERNESTO553/deberes
/De 3 numeros devuelve el mayor.py
355
4.0625
4
numero_1= int(input("ingresar 1er numero?")) numero_2= int(input("ingresar 2do numero?")) numero_3= int(input("ingresar 3er numero?")) if numero_1>numero_2 and numero_1>numero_3: print (str(numero_1)) if numero_2>numero_1 and numero_2>numero_3: print (str(numero_2)) if numero_3>numero_1 and numero_3>numero_2: print(str(numero_3))
49b1e6cf1f9b9de78fff616960864dfac3e878fe
elzup/algo-py
/dp/lcs.py
505
3.5625
4
def memoize(f): cache = {} def helper(x, y): if x not in cache: cache[(x, y)] = f(x, y) return cache[(x, y)] return helper # 最長共通部分列 @memoize def lcs(a, b): if len(a) == 0 or len(b) == 0: return 0 t = max(lcs(a, b[:-1]), lcs(a[:-1], b)) if a[-1] == b[-1]: return max(lcs(a[:-1], b[:-1]) + 1, t) else: return t n = int(input()) d = [(input(), input()) for _ in range(n)] for (a, b) in d: print(lcs(a, b))
567e790552c1ba9c1029d37d8dee7c5b0a2d6946
jspaulino/UriQuest
/q1009.py
811
3.65625
4
# -*- coding: utf-8 -*- ''' Faça um programa que leia o nome de um vendedor, o seu salário fixo e o total de vendas efetuadas por ele no mês (em dinheiro). Sabendo que este vendedor ganha 15% de comissão sobre suas vendas efetuadas, informar o total a receber no final do mês, com duas casas decimais. Entrada O arquivo de entrada contém um texto (primeiro nome do vendedor) e 2 valores de dupla precisão (double) com duas casas decimais, representando o salário fixo do vendedor e montante total das vendas efetuadas por este vendedor, respectivamente. Saída Imprima o total que o funcionário deverá receber, conforme exemplo fornecido. ''' nome = input() salario = float(input()) t_vendas = float(input()) t_salario = salario + (t_vendas * 0.15) print("TOTAL = R$ %.2f" %t_salario)
0d45465a22f4bd7ec5400bac785f785e36eb0dc6
fordmay/ghosts_attack_python
/ball.py
1,294
3.765625
4
import pygame from random import randint from pygame.sprite import Sprite class Ball(Sprite): """A class to manage ball fired from the wizard""" def __init__(self, ga_game): """Create a ball object at the wizard's current position.""" super().__init__() self.screen = ga_game.screen self.settings = ga_game.settings # Takes random color or not for the ball. if self.settings.random_ball_color: self.color = (randint(0, 255), randint(0, 255), randint(0, 255)) else: self.color = self.settings.ball_color # Create a ball rect at (0, 0) and then set correct position self.rect = pygame.Rect(0, 0, self.settings.ball_width, self.settings.ball_height) self.rect.midtop = ga_game.wizard.rect.midtop # Store the ball's position as a decimal value. self.y = float(self.rect.y) def update(self): """Move the ball up the screen.""" # Update the decimal position of the bullet self.y -= self.settings.ball_speed # Update the rect position. self.rect.y = self.y def draw_ball(self): """Draw the ball to the screen.""" pygame.draw.ellipse(self.screen, self.color, self.rect)
2ad249f9828ba11b7edd279358a9adb9408dae05
MrEricL/daily-code-problem
/1.py
527
3.953125
4
''' Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? ''' ''' Explanation: Store the complement in a set and check at O(1) time ''' def fxn(l, k): s = set() for each in l: complement = k-each if each in s: return set([each, complement]) else: s.add(complement) return -1 x = [10, 15, 3, 7] y = 17 z = set([10, 7]) print(fxn(x, y) == z)
a56252eb525ccec1d06f2e4a679758d5ed1518ce
Granc3k/PONG
/Project/project_1v1.py
4,938
3.75
4
""" File: project.py ----------------- This program is an empty program for your final project. Update this comment with a summary of your program! """ from graphics import Canvas import time import random CANVAS_WIDTH = 1280 CANVAS_HEIGHT = 720 board_width = 100 board_height = 50 offset_paddle = 100 PADDLE_WIDTH = 20 PADDLE_HEIGHT = 150 BALL_RADIUS = 15 DELAY = 1 / 60 paddle_speed = 10 NET_WIDTH = 1 NET_PART_HEIGHT = 70 NET_GAP = 2 def main(): max_score = int(input("Enter the maximal score that could be reached: ")) canvas = Canvas(CANVAS_WIDTH, CANVAS_HEIGHT) canvas.set_canvas_title("Final Project") paddle_1 = create_paddle_1(canvas) paddle_2 = create_paddle_2(canvas) dx = 6 dy = 6 score_1 = 0 score_2 = 0 net = create_net(canvas) s_1_board = canvas.create_text(CANVAS_WIDTH/2-board_width/2, board_height, score_1) s_2_board = canvas.create_text(CANVAS_WIDTH/2+board_width/2, board_height, score_2) canvas.set_font(s_1_board, "Arial", 30) canvas.set_font(s_2_board, "Arial", 30) ball = create_ball(canvas) canvas.wait_for_click() while True: canvas.set_text(s_1_board, score_1) canvas.set_text(s_2_board, score_2) presses = canvas.get_new_key_presses() if collision(canvas, ball, paddle_1, paddle_2): dx *= -1 dx, dy, ball, score_1, score_2 = move_ball(canvas, dx, dy, ball, score_1, score_2) move_paddle(canvas, paddle_1, "w", "s", presses) move_paddle(canvas, paddle_2, "Up", "Down", presses) canvas.move(ball, dx, dy) time.sleep(DELAY) canvas.update() if score_1 == max_score or score_2 == max_score: end_screen(canvas, score_1, score_2) canvas.update() canvas.wait_for_click() return False else: pass canvas.update() canvas.mainloop() def create_paddle_1(canvas): y = CANVAS_HEIGHT / 2 - PADDLE_HEIGHT / 2 paddle_1 = canvas.create_rectangle(offset_paddle, y, offset_paddle + PADDLE_WIDTH, y + PADDLE_HEIGHT) canvas.set_color(paddle_1, "black") return paddle_1 def create_paddle_2(canvas): x = CANVAS_WIDTH - offset_paddle - PADDLE_WIDTH y = CANVAS_HEIGHT / 2 - PADDLE_HEIGHT / 2 paddle_2 = canvas.create_rectangle(x, y, x + PADDLE_WIDTH, y + PADDLE_HEIGHT) canvas.set_color(paddle_2, "black") return paddle_2 def create_ball(canvas): x = CANVAS_WIDTH / 2 - BALL_RADIUS y = CANVAS_HEIGHT / 2 - BALL_RADIUS ball = canvas.create_oval(x, y, x + 2 * BALL_RADIUS, y + 2 * BALL_RADIUS) canvas.set_color(ball, "black") return ball def move_ball(canvas, dx, dy, ball, score_1, score_2): if canvas.get_left_x(ball) <= 1: canvas.delete(ball) ball = create_ball(canvas) score_2 += 1 canvas.wait_for_click() elif canvas.get_left_x(ball) >= CANVAS_WIDTH - canvas.get_width(ball) - 1: canvas.delete(ball) ball = create_ball(canvas) score_1 += 1 canvas.wait_for_click() if canvas.get_top_y(ball) <= 1: dy *= -1 elif canvas.get_top_y(ball) >= CANVAS_HEIGHT - canvas.get_height(ball) - 1: dy *= -1 return dx, dy, ball, score_1, score_2 def collision(canvas, ball, paddle_1, paddle_2): ball_coords = canvas.coords(ball) x1 = ball_coords[0] y1 = ball_coords[1] x2 = ball_coords[2] y2 = ball_coords[3] colliders = canvas.find_overlapping(x1, y1, x2, y2) for collider in colliders: if collider == ball: return False elif collider == paddle_1 or collider == paddle_2: return True def move_paddle(canvas, paddle, up, down, presses): x = canvas.get_left_x(paddle) if canvas.get_top_y(paddle) <= 0: canvas.move_to(paddle, x, 1) elif canvas.get_top_y(paddle) >= CANVAS_HEIGHT-PADDLE_HEIGHT: canvas.move_to(paddle, x, CANVAS_HEIGHT-PADDLE_HEIGHT-1) else: for press in presses: if press.keysym == down: canvas.move(paddle, 0, paddle_speed) elif press.keysym == up: canvas.move(paddle, 0, -paddle_speed) def create_net(canvas): x = CANVAS_WIDTH/2 for i in range(10): net = canvas.create_rectangle(x-1, 10, x + 1, CANVAS_HEIGHT-10) canvas.set_color(net, "black") def end_screen(canvas, score_1, score_2): screen = canvas.create_rectangle(0, 0, CANVAS_WIDTH,CANVAS_HEIGHT) canvas.set_color(screen, "black") if score_1 > score_2: text = canvas.create_text(CANVAS_WIDTH/2,CANVAS_HEIGHT/2, "Player 1 won the game!!!") canvas.set_fill_color(text, "white") canvas.set_font(text, "Arial", 60) else: text = canvas.create_text(CANVAS_WIDTH/2,CANVAS_HEIGHT/2, "Player 2 won the game!!!") canvas.set_fill_color(text, "white") canvas.set_font(text, "Arial", 60) if __name__ == '__main__': main()
eff2c5d6e97d961bb24651bc688a1164310018fe
TobiObeck/CogSci-WS2020-ANNs-in-Tensorflow
/homework02/code/other/Homework2_kristina.py
4,043
4.03125
4
import numpy as np import matplotlib.pyplot as plt x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # targets t_and = np.array([0, 0, 0, 1]) t_or = np.array([0, 1, 1, 1]) t_nand = np.array([1, 1, 1, 0]) t_nor = np.array([1, 0, 0, 0]) t_xor = np.array([0, 1, 1, 0]) # activation function def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoidprime(x): # this is the first derivate of the sigmoid function return sigmoid(x) * (1 - sigmoid(x)) class Perceptron: """insert documentation here""" def __init__(self, input_units): self.input_units = input_units self.alpha = 0.01 self.weights = np.random.randn(input_units) self.bias = np.random.randn(1) self.alpha = 0.01 # these will be needed for the values from the neuron later, so setting up the variables to store them self.inputs = 0 self.drive = 0 def forward_step(self, inputs): self.inputs = inputs self.drive = self.weights @ inputs + self.bias # calculate the drive return sigmoid(self.drive) # return the activation function with drive as its argument def update(self, delta): # delta is the error term, it will be obtained from back-propagation weights_gradient = delta * self.inputs bias_gradient = delta self.weights -= self.alpha * weights_gradient self.bias -= self.alpha * bias_gradient class MLP: def __init__(self): # we need to initialise the perceptrons for the hidden layer of our MLP.. self.hidden_layer = [ Perceptron(input_units=2), Perceptron(input_units=2), Perceptron(input_units=2), Perceptron(input_units=2) ] # ..and also one output neuron self.output_neuron = Perceptron(input_units=4) # output variable will later store our output self.output = 0 def forward_step(self, inputs): # compute forward step = activation for each neuron in the hidden layer... hidden_layer_activations = np.array([p.forward_step(inputs) for p in self.hidden_layer]) hidden_layer_activations = np.reshape(hidden_layer_activations, newshape=(-1)) # ...and compute the activation of the output neuron self.output = self.output_neuron.forward_step(hidden_layer_activations) def backprop_step(self, inputs, target): # first, compute the delta at the output neuron according to the formula output_delta = - (target - self.output) * sigmoidprime(self.output_neuron.drive) # now update the parameters of the output neuron by inserting the obtained delta self.output_neuron.update(output_delta) # next, compute the deltas for the hidden neurons hidden_deltas = [output_delta * sigmoidprime(p.drive) * self.output_neuron.weights[i] for i, p in enumerate(self.hidden_layer)] # again, update the parameters for all neurons in the hidden layer for i, p in enumerate(self.hidden_layer): p.update(hidden_deltas[i]) # TRAINING PART mlp = MLP() # initialize lists to store epochs, loss, accuracy of the predictions steps = [] # a.k.a epochs losses = [] accuracies = [] for i in range(1000): steps.append(i) # 1. Draw a random sample from x and the corresponding t. Check 'np.random.randint'. # index = np.random.randint(len(x)) # sample = x[index] # label = t_xor[index] accuracy = 0 loss = 0 for k in range(len(x)): sample = x[k] label = t_xor[k] mlp.forward_step(sample) mlp.backprop_step(sample, label) accuracy += int(float(mlp.output >= 0.5) == label) loss += (label - mlp.output) ** 2 # mean squared error accuracies.append(accuracy/4) losses.append(loss) plt.figure() plt.plot(steps, losses) plt.xlabel("Training Steps") plt.ylabel("Loss") plt.show() plt.figure() plt.plot(steps, accuracies) plt.xlabel("Training Steps") plt.ylabel("Accuracy") plt.ylim([-0.1, 1.2]) plt.show()
cb57bdc71c8f61001c7cad4e5279bd389e3adf56
jorge-armando-navarro-flores/coffee_machine
/main.py
1,905
3.890625
4
from machine_data import MENU, resources, coins machine_money = 0 def print_report(): print(f"Water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}g") print(f"Money: ${machine_money}") def resources_sufficient(coffee_ingredients): for key in resources.keys(): if key in coffee_ingredients: if resources[key] < coffee_ingredients[key]: print(f"Sorry there is not enough {key}.") return False return True def process_coins(): inserted_money = 0 for key in coins.keys(): inserted_coins = int(input(f"how many {key}?: ")) inserted_money += coins[key] * inserted_coins return inserted_money def transaction_successful(inserted_money, coffee_price): if inserted_money < coffee_price: return False else: return True def make_coffee(coffee_ingredients): for key in resources.keys(): if key in coffee_ingredients: resources[key] -= coffee_ingredients[key] order = input("What would you like? (espresso/latte/cappuccino): ") while order != "off": if order == "report": print_report() else: coffee = MENU[order] if resources_sufficient(coffee["ingredients"]): print("Please insert coins.") user_money = process_coins() if transaction_successful(user_money, coffee["cost"]): make_coffee(coffee["ingredients"]) machine_money += coffee["cost"] user_change = round(user_money - coffee["cost"], 2) print(f"Here is ${user_change} in change.") print(f"Here is your {order} ☕️. Enjoy!") else: print("Sorry that's not enough money. Money refunded.") order = input("What would you like? (espresso/latte/cappuccino): ")
5c8bc5c3e5fbbcaac259163ee7248e97a0d5f0c2
sherke/hacktoberfest
/2021/Python/BestPractice/enumerate.py
196
3.625
4
input_list = [1, 2, 3, 4, 5, 6, 7] # bad practice for i in range(len(input_list)): print(i, input_list[i]) # best practice for index, value in enumerate(input_list): print(index, value)
e5ddcc0f0025db9009aa123adf1e33a5882a8756
dltech-xyz/Alg_Py_Xiangjie
/.history/第2章/2-3/tiqu_20171113223515.py
507
3.640625
4
prices = {'ASP.NET': 49.9, 'Python': 69.9, 'Java': 59.9, 'C语言': 45.9, 'PHP': 79.9} p1 = {key: value for key, value in prices.items() if value > 50} print(p1) tech_names = {'Python', 'Java', 'C语言'} p2 = {key: value for key, value in prices.items() if key in tech_names} print(p2) p3 = dict((key, value) for key, value in prices.items() if value > 50) # 慢 print(p3) tech_names = {'Python', 'Java', 'C语言'} p4 = {key: prices[key] for key in prices.keys() if key in tech_names} # 慢 print(p4)
939f4eaebaa114dc2a4df77a2654c4b679b0e38b
dltech-xyz/Alg_Py_Xiangjie
/.history/第3章/di_20200528232637.py
505
3.53125
4
#!/usr/bin/env python # coding=utf-8 ''' @version: @Author: steven @Date: 2020-05-27 22:20:22 @LastEditors: steven @LastEditTime: 2020-05-28 23:26:37 @Description: ''' fib_table = {} # memoization table to store previous terms def fib_num(n): if (n <= 1): return n if n not in fib_table: fib_table[n] = fib_num(n - 1) + fib_num(n - 2) return fib_table[n] n = int(input("输入斐波那契数列的第n项 \n")) print("斐波那契数数列的第 ", n, "项是", fib_num(n))
7a619c0a23673ae7c5bf280059d9bff86419ee12
dltech-xyz/Alg_Py_Xiangjie
/.history/第2章/2-1/chuantong_20171112223825.py
126
3.75
4
squares = [] for x in range(10): squares.append(x**2) print(squares) squares1 = [x**2 for x in range(10)] print(squares1)
60e62b673f4abc12162d2560d4dd24f820214917
dltech-xyz/Alg_Py_Xiangjie
/.history/第3章/qi_20200607165646.py
1,351
3.75
4
#!/usr/bin/env python # coding=utf-8 ''' @version: @Author: steven @Date: 2020-05-27 22:20:22 @LastEditors: steven @LastEditTime: 2020-06-07 16:56:46 @Description:分治算法,判断某元素是否再列表里 ''' # 子问题算法(子问题规模为 1) def is_in_list(init_list, el): return [False, True][init_list[0] == el] # 不过在Python3.x 中,终于把这个两变量变成了关键字,而不再是内建(built-in)变量(在Python2.7)。 # 也就是说,程序员再也没法给这两变量赋新的值了,从此True永远指向真对象,False指向假对象 # https://foofish.net/python-true-false.html # 分治法 def solve(init_list, el): n = len(init_list) if n == 1: # 若问题规模等于 1,直接解决 return is_in_list(init_list, el) # 分解(子问题规模为 n/2) left_list, right_list = init_list[:n // 2], init_list[n // 2:] # 递归(树),分治,合并(此处为深度优先,注意逻辑短路) # 短路逻辑:如果a为true,那么跳过b的判断,直接true res = solve(left_list, el) or solve(right_list, el) return res if __name__ == "__main__": # 测试数据 test_list = [12, 2, 23, 45, 67, 3, 2, 4, 45, 63, 24, 23] # 查找 print(solve(test_list, 45)) # True print(solve(test_list, 5)) # False
51315060e1221b7266f9b78e7f74a40405b4b1e9
dltech-xyz/Alg_Py_Xiangjie
/.history/第2章/2-3/del_20171113163945.py
185
3.71875
4
#创建字典“dict” dict = {'Name': 'Toppr', 'Age': 7, 'Class': 'First'} del dict['Name'] #删除键 'Name' print (dict) #显示字典“dict”中的元素
d908a2daa4ce12ec185d64cd232d1475598582a2
dltech-xyz/Alg_Py_Xiangjie
/.history/第2章/2-2/neizhi_20171113104609.py
561
4.375
4
car = ['奥迪', '宝马', '奔驰', '雷克萨斯'] #创建列表car print(len(car)) #输出列表car的长度 tuple2 = ('5', '4', '8') #创建元组tuple2 print(max(tuple2)) #显示元组tuple2中元素的最大值 tuple3 = ('5', '4', '8') #创建元组tuple3 print(min(tuple3)) #显示元组tuple3中元素的最小值 list1= ['Google', 'Taobao', 'Toppr', 'Baidu'] #创建列表list1 tuple1=tuple(list1) #将列表list1的值赋予元组tuple1 print(tuple1) #再次输出元组tuple1中的元素
6c8e13d208beafae5b669f07b0dadd18d1c6a2b4
dltech-xyz/Alg_Py_Xiangjie
/第5章/huo.py
1,953
3.921875
4
class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = None self.right = None class Huffman(object): def __init__(self, items=[]): while len(items)!=1: a, b = items[0], items[1] newvalue = a.value + b.value newnode = Node(value=newvalue) newnode.left, newnode.right = a, b items.remove(a) items.remove(b) items.append(newnode) items = sorted(items, key=lambda node: int(node.value)) # 每次都要记得更新新的霍夫曼树的根节点 self.root = newnode def print(self): queue = [self.root] while queue: current = queue.pop(0) print(current.value, end='\t') if(current.left): queue.append(current.left) if current.right: queue.append(current.right) print() def sortlists(lists): return sorted(lists, key=lambda node: int(node.value)) def create_huffman_tree(lists): while len(lists)>1: a, b = lists[0], lists[1] node = Node(value=int(a.value+b.value)) node.left, node.right = a, b lists.remove(a) lists.remove(b) lists.append(node) lists = sorted(lists, key=lambda node: node.value) return lists def scan(root): if root: queue = [root] while queue: current = queue.pop(0) print(current.value, end='\t') if current.left: queue.append(current.left) if current.right: queue.append(current.right) if __name__ == '__main__': ls = [Node(i) for i in range(1, 5)] huffman = Huffman(items=ls) huffman.print() print('===================================') lssl = [Node(i) for i in range(1, 5)] root = create_huffman_tree(lssl)[0] scan(root)
4e1bc4ed86486ee94c63f439d96d7f663df5587c
mcfarland422/python101
/loops.py
277
4.21875
4
print "Loops file" # A for loop expects a starting point, and an ending point. # The ending poin (in range) is non-inclusive, meaning, it will stop when it gets there # i (below) is going to be the number of the loop it's on for i in range(1,10): if (i == 5): print
bea97dff439a3f97b51df2e79eea4e359b20d826
BecsMarconi/Prog2
/Exercícios/verifica_entrada.py
374
3.765625
4
def lerEntrada(mensagem=" Insira um número: "): n = int(input(mensagem)) print("Valor digitado: ", n) return n def tupla0 (numeros="Digite dois números separdos por espaços: "): nu = str(input(numeros)) li = [] li.extend(nu) print(li) print("Valores digitados -> primeiro: {} ; segundo: {} ".format(li[0], li[2])) return li[0], li[2]
17ba7db92d8e3227191882f02073e45e39ab274a
Hobit2002/HigherLower
/RunMe.py
4,219
3.59375
4
import random print("Welcome in Higher Lower Casiono. The higher will be your risk, the lower you'll win!") #Prepare deck GameDeck=[] Table=[] DiscardDeck=[] for Symbol in ['♠','♥','♦','♣']: for relValue,imageValue in enumerate(['2','3','4','5','6','7','8','9','10','J','Q','K','A']): GameDeck.append({'image':imageValue+Symbol,'value':relValue}) random.shuffle(GameDeck) def placeCards(): global Table global GameDeck global DiscardDeck NeededCards=10-len(Table) try: Table+=GameDeck[0:NeededCards] except IndexError: random.shuffle(DiscardDeck) GameDeck+=DiscardDeck DiscardDeck=[] Table+=GameDeck[0:NeededCards] print("I've shuffeld discarded card to the deck, so be ready to see them") del GameDeck[0:NeededCards] LineToPrint = Table[0]["image"] + 9*" ?" print(LineToPrint) def turnCard(serialNum): ToPrint="" for sn in range(serialNum+1): ToPrint+=Table[sn]['image']+" " ToPrint+="? "*(9-serialNum) print(ToPrint) #Introduce player to the game print(""" Hi, You came here with 1000€ and my job is to strip you of them. However I'll give you a chance to be the one, who enriches himself. I've already placed ten cards here, of with only one is turned faced up. At first, you'll choose a number from interval <4,10> and amount of money, you're willing to bet. Then I'll start turning the cards over. Their count will be equal to the number you've chosen. Before each turnover, youl'll bet if the next card has higher,lower or equal value to the preceding one. If the truth will be on your side, the amount of money you've bet will be multiplied by two (and if you keep your success till the end, I'll giv it to you). However, if you'll mislead, I'll take your money away. Leave by pressing Ctrl+C """) #Start the game Finances = 1000 while Finances>0: #Show cards and ask player for Game parameters placeCards() #Ask for a number of cards player wants to play with CardNum=0 while CardNum<3 or CardNum>9: try: CardNum = int(input("With how many cards do you want play? Choose at least 4 and at most 9. ")) if CardNum>9:print("Your number can't be higher than 9.") elif CardNum<4:print("Your number can't be lower than 4") except ValueError: print("Your answer has to be a number.") #Let the player bet his money Bet=-1 while Bet > Finances or Bet<0: try: Bet = int(input("How much money do you bet(You have %s€ in the moment)?"%(Finances))) if Bet>Finances:print("Come on! You can't bet money you don't have.") elif Bet<0:print("Do you think we I'm a fool? Stop begging and play!") except ValueError: print("Your answer has to be a number.") Finances-=Bet #Start turning the cards over for cn in range(1,CardNum+1): #Let player bet Prediction = input("Higher:h; Lower:l;Equal: nothing, just press Enter:")+" " #Turn over the next card print("Lets turn the card:") turnCard(cn) #If the prediction was wrong, end the turn and move to the next OldValue=Table[cn-1]['value'] NewValue=Table[cn]['value'] HigherCond = Prediction[0].lower()=="h" and NewValue>OldValue LowerCond = Prediction[0].lower()=="l" and NewValue<OldValue EqualCond = len(Prediction)==1 and NewValue==OldValue if HigherCond or LowerCond or EqualCond: Bet*=2 print("Lucky you! Your bet was multiplied so now I owe you %s€"%Bet) else: print("I'm sorry. But you've lost.") Bet=-1 break #If player wins all guesses, give him money he deserves if Bet>0: print("Congratulations. You've won and I'll give you %s€"%Bet) Finances+=Bet #Discard revealed cards except the last one DiscardDeck+=Table[0:cn] del Table[0:cn] #End the turn print("One turn behind us. I'm looking forward to the next, but if you want to leave, press Ctrl+C.") print("You've lost all your money, so goodbye,looser!!!")
8b9add441cc947f5b12a1b5377df16b0fb31edd8
krypten/competitive-coding
/competitive-coding/spoj/iitwpcj.py
409
3.734375
4
def gcd ( a, b) : if a%b == 0: return b return gcd(b, a%b) def lcm( a, b): d = gcd(a,b) l = a*b/d; x = l/a y = l/b return l,x,y t = int(raw_input()) while (t): t -= 1 string = [] string = str(raw_input()).split(); tmp1 = string[0] tmp2 = string[1] n = len(tmp1) m = len(tmp2) lc,x,y = lcm( n , m) tmp3 = tmp1*x; tmp4 = tmp2*y; if tmp3 == tmp4: print ("YES") else : print ("NO")
843c9767375d84fbbf1f743df50952ddf23afee1
krypten/competitive-coding
/competitive-coding/spoj/prismsa.py
152
3.5625
4
t = int(input()) while(t): t -= 1 n = float(input()) #print ((18*n)/((4.0*n)**(1/3)*(3*0.5))) print (3*(3**0.5)*((4*n)**(2/3))/2)
c73a278354aca1ef6b1a7daaa5c64d8722397228
ty1996/python
/hw01/main.py
592
3.921875
4
def binary_search(find, list1) : low = 0 high = len(list1) while low <= high : mid = (low + high) / 2 if list1[mid] == find : return mid elif list1[mid] > find : high = mid -1 else : low = mid + 1 return -1 list1 = [1,2,3,7,8,9,10,5] list1.sort() print "原有序列表为:",list1 try : find = int(raw_input("请输入要查找的数:")) except : print "请输入正整数!" exit() result = binary_search(find, list1) if result != -1 : print "要找的元素%d的序号为:%d" %(find,result) else : print "未找到!"
8747da31349ada5ed58c399d9f6e4a9b6e5b42c5
bleaz01/base-de-python
/gessing_game.py
375
3.8125
4
import random print("tapé le numero\n") guess = int(input()) nb_secret = random.randint(1,100) while guess != nb_secret: if guess < nb_secret: print("ton nombre est inferieur") else: print("ton nombre est trop haute") print("recommance casse pas les couille") guess = int(input()) print("bravo, c'eatis bien le bon" +str(nb_secret) )
4df919c2b292cf09bf210ea8337023dea1c63bbf
Rosswell/CS_Exercises
/linked_list_manipulation.py
2,673
4.15625
4
'''Prompt: You have simple linked list that specifies paths through a graph. For example; [(node1, node2), (node2, node3)] node 1 connects to node 2 and node 2 connects to node 3. Write a program that traverses the list and breaks any cycles. So if node 1 links to both node 2 and node 2374, one link should be broken and reset. Give the first link formed priority. You can use helper methods .get(index) and .set(index, (new_value)) to get and set new links in the list or write your own ''' '''Explanation: Given the constraints, there are basically two cases that we want to control for: cycles and multiple links. Will be maintaining 2 lists in addition to the original: one to store previously seen values, one to return. 1. Iterate through the list of edges, check if the source node (n1 in (n1, n2)) is already in the seen nodes dict 2. If it's not in the seen nodes dict, add it to the dict and make sure n1's pointer doesn't create a cycle or is the second edge from that node. If those are both true, append the edge to the return list 3. If it is in the dict, check if there is a cycle by comparing to the previous edge. If a cycle is present, append an edge containing (n1, n4), where original two edges were [(n1, n2)(n3, n4)], effectively skipping the node creating the cycle 4. All other cases are skipped, as they are not the original edges from a particular source node ''' from operator import itemgetter class linked_list(object): def __init__(self, edge_list): self.edge_list = edge_list def get(self, index): return self.edge_list[index] def set(self, index, new_value): self.edge_list[index] = new_value return self.edge_list def list_iter(self): ret_list = [] seen_dict = {} for i, edge in enumerate(self.edge_list): node_from, node_to = itemgetter(0, 1)(edge) if node_from not in seen_dict: # new node addition to seen dict seen_dict[node_from] = True if node_to not in seen_dict: # source and destination nodes are unique and create no cycles ret_list.append(edge) else: prev_node_from, prev_node_to = itemgetter(0, 1)(self.edge_list[i-1]) if prev_node_to == node_from: # cycling case - skips the cycled node to preserve path continuity ret_list.append((prev_node_from, node_to)) return sorted(list(set(ret_list))) input_list = [('n1', 'n2'), ('n2', 'n3'), ('n3', 'n1'), ('n1', 'n4'), ('n4', 'n5'), ('n1', 'n123')] x = linked_list(input_list) print(x.list_iter())
8e38385ce7acc7ff104fbff45c3d90dc274a897f
psg25/pachaqtecH7
/Grupo1/salon.py
6,032
3.515625
4
from connection.conn import Connection import menu Connection = Connection('mongodb+srv://paola:pachaqtec@pachaqtec.sdvq7.mongodb.net/test', 'pachacteq') lstSalon=[] class salones: collection = 'salones' def __init__(self, nombreSalon, idAlumno, idProfesor): self.nombreSalon = nombreSalon self.idAlumno = idAlumno self.idProfesor = idProfesor def mantenimiento_salones(): dicM_Salones = {"Ver todos los salones": 1, "Buscar por No. de Salón": 2, "Modificar Salón por No. de Salón": 3, "Crear Salón": 4,"Borrar Salón": 5} menuM_Salones = menu.Menu("Mantenimiento de Salones", dicM_Salones) resM_Salones = menuM_Salones.mostrarMenu() if (resM_Salones == 1): listar_salones = Connection.obtenerRegistros(salones.collection) print(listar_salones) print("") print ("-\t¿Desea volver al menu?"+ "-\tVolver al menu: S-\t"+ "-\tVolver a consultar: N") ver_salones = input("S/N: ") if (ver_salones=="S"): mantenimiento_salones() else: return listar_salones elif (resM_Salones == 2): buscador_numero = input("Escribe el No. de salón a ubicar: ") listar_porsalon = Connection.obtenerRegistro(salones.collection, {'nombreSalon': buscador_numero}) print(listar_porsalon) print("") print ("-\t¿Desea volver al menu?"+ "-\tVolver al menu: S-\t"+ "-\tVolver a consultar: N") ver_salones = input("S/N: ") if (ver_salones=="S"): mantenimiento_salones() else: return buscador_numero elif (resM_Salones == 3): listar_salones = Connection.obtenerRegistros(salones.collection) listar_salones = list(listar_salones) print("Escoja el ID del cliente que desea modificar") print(listar_salones) print("") print("Ahora escriba el nuevo valor el No. de Salón") nombreSalon = input() mostrar_profesor = Connection.obtenerRegistros('profesores') mostrar_profesor = list(mostrar_profesor) print("Ahora escriba el nombre del Profesor") print(mostrar_profesor) idProfesor= input() resM_Cambio = Connection.actualizarRegistro(salones.collection, { 'nombreSalon': nombreSalon, 'idAlumno': idAlumno, 'idProfesor': idProfesor }) while(resM_Cambio): print("Éxito. Se actualizó el contacto") print ("-\t¿Desea volver al menu?"+ "-\tVolver al menu: S-\t"+ "-\tVolver a consultar: N") modificar_salones = input("S/N: ") if (modificar_salones=="S"): mantenimiento_salones() elif (modificar_salones != "S"): return listar_salones else: print("Hubo un error. Intente nuevamente.") return listar_salones elif (resM_Salones == 4): nuevoingreso = True while (nuevoingreso): print("Para crear un nuevo registro, ingrese los siguientes datos:") salones.Salon = input("Nombre del salón: ") salones.Alumno = None salones.Profesor = None resM_NuevoSalon = Connection.insertRegistro(salones.collection, { 'nombreSalon': salones.Salon, 'idAlumno': salones.Alumno, 'idProfesor': salones.Profesor }) print("Exito. Se creo el nuevo resgitro") print("") print ("-\t¿Desea volver al menu?"+ "-\tVolver al menu: S-\t"+ "-\tIngresar nuevo registro: N") opcion_nuevosalon = input("S/N: ") if (opcion_nuevosalon=="S"): mantenimiento_salones() elif (opcion_nuevosalon !="S"): return nuevoingreso else: nuevoingreso = False print("Hubo un error. Intente nuevamente") return nuevoingreso elif (resM_Salones == 5): eliminarsalon = True while (eliminarsalon): print("Escoja el ID del cliente que desea eliminar") listar_salones = Connection.obtenerRegistros(salones.collection) print(listar_salones) print("") print("Ahora scriba el No. Salon que desea eliminar") salones.Salon = input("Escribe el No.: ") resM_Borrar = connection.eliminarRegistro(salones.collection, { 'nombreSalon': salones.Salon, }) if(resM_Borrar): print("Éxito. Se borró el salón") print("") print ("-\t¿Desea volver al menu?"+ "-\tVolver al menu: S-\t"+ "-\tIngresar nuevo registro: N") opcion_borrar = input("S/N: ") if (opcion_borrar=="S"): mantenimiento_salones() elif (opcion_nuevosalon !="S"): return eliminarsalon else: print("Hubo un error. Intente nuevamente") return eliminarsalon mantenimiento_salones()
ebd55dd4b65a1701b6fe57c3279285bab3ff165c
soumyap00/SID_pythonDev
/prgm9.py
317
4.0625
4
A = [] n = int(input("Enter number of elements in the list : ")) print("Enter elements:") for i in range(0, n): elm = int(input()) A.append(elm) print("The entered list is: \n",A) k =int(input("Enter which smallest number you want to see:")) A.sort() print(k,"'th smallest element is",A[k-1])
3cdab5157490d20386f631419f37239e9ba084b4
psglinux/MS
/cs-265/assignment-2/assignment2.py
1,104
3.828125
4
#!/usr/bin/env python def find_prime_factor(n): for i in xrange(1,n+1,1): d = n/i r = n%i if r == 0: print "i = ", i, n,"/i = ", n/i," ", n,"%i = ", n%i def find_one_e_or_d(tot, e): i = 1 while 1: p = (i*e)%tot if p == 1: print "e*d =", i*e, "e = ", e, " d = ", i break i += 1 def find_C(M, e, N, m): C = pow(M, e)%N print m, ":", C return C def find_d_for_e(e, r, tot): print "e = ", e print "------------------------------------" for i in xrange(e,1000,1): if (e*i%40 == 1 and i%e != 0): print "e =", e, " d =", i def problem_1(): print "problem 1 : ------- starts" find_prime_factor(187) find_one_e_or_d(160, 107) find_C(8, 107, 187, "Cipher") print "problem 1 : ------- ends" def problem_2(): print "problem 2 : ------- starts" find_d_for_e(3, 1000, 40) find_d_for_e(5, 1000, 40) find_d_for_e(7, 1000, 40) c = find_C(8, 3, 55, "Cipher") find_C(c, 67, 55, "Plain") print "problem 2 : ------- ends" problem_1() problem_2()
41585c6dca2b0c40fbdd86fecbedecfa663e306a
Shadow-Arc/Eleusis
/hex-to-dec.py
1,119
4.25
4
#!/usr/bin/python #TSAlvey, 30/09/2019 #This program will take one or two base 16 hexadecimal values, show the decimal #strings and display summations of subtraction, addition and XOR. # initializing string test_string1 = input("Enter a base 16 Hexadecimal:") test_string2 = input("Enter additional Hexadecimals, else enter 0:") # printing original string print("The original string 1: " + str(test_string1)) print("The original string 2: " + str(test_string2)) # using int() # converting hexadecimal string to decimal res1 = int(test_string1, 16) res2 = int(test_string2, 16) # print result print("The decimal number of hexadecimal string 1 : " + str(res1)) print("The decimal number of hexadecimal string 1 : " + str(res2)) basehex = test_string1 sechex = test_string2 basehexin = int(basehex, 16) sechexin = int(sechex, 16) sum1 = basehexin - sechexin sum2 = basehexin + sechexin sum3 = basehexin ^ sechexin print("Hexidecimal string 1 subtracted from string 2:" + hex(sum1)) print("Hexidecimal string 1 added to string 2:" + hex(sum2)) print("Hexidecimal string 1 XOR to string 2:" + hex(sum3))
50d3d8fe9a65b183a05d23919c255b71378c7af5
alejandrox1/CS
/documentation/sphinx/intro/triangle-project/trianglelib/shape.py
2,095
4.6875
5
"""Use the triangle class to represent triangles.""" from math import sqrt class Triangle(object): """A triangle is a three-sided polygon.""" def __init__(self, a, b, c): """Create a triangle with sides of lengths `a`, `b`, and `c`. Raises `ValueError` if the three length values provided cannot actually form a triangle. """ self.a, self.b, self.c = float(a), float(b), float(c) if any( s <= 0 for s in (a, b, c) ): raise ValueError('side lengths must all be positive') if any( a >= b + c for a, b, c in self._rotations() ): raise ValueError('one side is too long to make a triangle') def _rotations(self): """Return each of the three ways of rotating our sides.""" return ((self.a, self.b, self.c), (self.c, self.a, self.b), (self.b, self.c, self.a)) def __eq__(self, other): """Return whether this triangle equals another triangle.""" sides = (self.a, self.b, self.c) return any( sides == rotation for rotation in other._rotations() ) def is_similar(self, triangle): """Return whether this triangle is similar to another triangle.""" return any( (self.a / a == self.b / b == self.c / c) for a, b, c in triangle._rotations() ) def is_equilateral(self): """Return whether this triangle is equilateral.""" return self.a == self.b == self.c def is_isosceles(self): """Return whether this triangle is isoceles.""" return any( a == b for a, b, c, in self._rotations() ) def perimeter(self): """Return the perimeter of this triangle.""" return self.a + self.b + self.c def area(self): """Return the area of this triangle.""" s = self.perimeter() / 2.0 return sqrt(s * (s - self.a) * (s - self.b) * (s - self.c)) def scale(self, factor): """Return a new triangle, `factor` times the size of this one.""" return Triangle(self.a * factor, self.b * factor, self.c * factor)
c036a96d5aa70c49899f7fb514f8a5bf760880a9
SValchev/AoC2020
/day3/day3.py
1,686
3.59375
4
from pathlib import Path class Position: def __init__(self, x=0, y=0): self.x = x self.y = y def change(self, x, y): self.x += x self.y += y class MoveStrategy: def __init__(self, move_x, move_y): self.position = Position() self.move_x = move_x self.move_y = move_y def move(self): self.position.change(self.move_x, self.move_y) class Track: TREE = '#' def __init__(self, grid): self._grid = grid self.max_x_location = len(self._grid[0]) self.end_y_location = len(self._grid) def is_coliding(self, position, obsticle=TREE): overload_x = position.x % self.max_x_location return self._grid[position.y][overload_x] == obsticle def is_in_boundery(self, position): return position.y < track.end_y_location def count_collisions(track, strategy): result = 0 while track.is_in_boundery(strategy.position): result += track.is_coliding(strategy.position) strategy.move() return result def solution_one(track): count_collisions(track, MoveStrategy(3, 1)) def solution_two(track): strategies = [ MoveStrategy(1, 1), MoveStrategy(3, 1), MoveStrategy(5, 1), MoveStrategy(7, 1), MoveStrategy(1, 2), ] result = 1 for strategy in strategies: result *= count_collisions(track, strategy) return result if __name__ == "__main__": with Path('input.txt').open() as file_: # Clear new lines input_ = [line.strip('\n') for line in file_] track = Track(grid=input_) solution_one(track) solution_two(track)
5e4c5593c59e8218630172dd9690da00c7d8fc1c
CostaNathan/ProjectsFCC
/Python 101/While and for loops.py
1,090
4.46875
4
## while specify a condition that will be run repeatedly until the false condition ## while loops always checks the condition prior to running the loop i = 1 while i <= 10: print(i) i += 1 print("Done with loop") ## for variable 'in' collection to look over: ## the defined variable will change each iteration of the loop for letter in "Giraffe academy": print(letter) ## the loop will print each letter individualy for the defined variable ## letter will correspond to the first, than the second, than ... each iteration friends = ["Jim", "Karen", "Jorge"] for name in friends: print(name) for index in range(10): print(index) ## range() = will count up to the design value, but without it ## in the above example, index will correspond to 0,1,2,...,9 for each iteration for index in range(3,10): print(index) ## an example of for loop to loop through an array for index in range(len(friends)): print(friends[index]) for index in range(5): if index == 0: print("Begin iteration!") elif index == 4: print("Iteration complete!")
959aae8e60bcc42ea90447dc296262c791e18d8c
CostaNathan/ProjectsFCC
/Python 101/Try & Except.py
298
4.21875
4
## try/except blocks are used to respond to the user something when an error occur ## best practice to use except with specific errors try: number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print(err) except ValueError: input("Invalid input")
fd9bf5095ff6f4c8e34c8dbbe77f2dc7855de014
Nguyen-Van-Huy/huynguyenydd
/8.6.py
903
3.5
4
from tkinter import * def NewFile(): print("New File!") def About(): print("This is a simple example of a menu") def OpenFile(): print("Open File") def Exit(): print("Exit") def Instext(): print("Instext") def Inspic(): print("Inspic") root = Tk() menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New",command=NewFile) filemenu.add_command(label="Open",command=OpenFile) filemenu.add_separator() filemenu.add_command(label="Exit",command=Exit) filemenu = Menu(menu) menu.add_cascade(label="Insert", menu=filemenu) filemenu.add_command(label="Text",command=Instext) filemenu.add_command(label="Picture",command=Inspic) helpmenu=Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=About) mainloop()
a73adef1e945ae833b52fbb37c4d35b262ae527a
Nguyen-Van-Huy/huynguyenydd
/8.5.py
599
4.03125
4
import tkinter as tk root = tk.Tk() v = tk.Intvar() v.set(1) languages = [ ("Python",1), ("Perl",2), ("Java",3), ("c++",4), ("c",5) ] def ShowChoice(): print(v.get()) tk.Label(root,text="""Choose your favourite programming language:""", justify = tk.LEEF, padx = 20).pack() for val, language in enumerate(language): tk.Radiobutton(root, text=language, padx=20, variable=v, command=ShowChoice, value=val).pack(anchor=tk.w) root.mainloop()
11810329106c9a26112fa4b5875c3cf1e1b87ae9
dbertho/covid-deaths-graph
/covid_deaths_graph_fra.py
10,547
3.59375
4
import urllib.request from urllib.error import URLError, HTTPError import json import random from PIL import Image, ImageDraw, ImageFont import time from sys import exit start_time = time.time() font_regular = ImageFont.truetype("arial.ttf", size=10) font_small = ImageFont.truetype("arial.ttf", size=8) def calc_moving_average(data, n): """Calculates the average of the last n values in the data dictionary :param data: dictionary :param n: number of days used to calculate the moving average :return: integer value of the average """ past_n_days = data[-n:] sum_values = 0 for day in past_n_days: sum_values += day["daily_deaths"] n_moving_average = int(sum_values / n) return n_moving_average def print_ten_thousand_text(draw, total_deaths, date, line_y, text_left): """Draws a line every 10000 deaths, the date and the total exact number of deaths at this date :param draw: ImageDraw object that will be the final output image :param total_deaths: integer :param date: date with format yyyy-mm-dd :param line_y: y coordinate of the line that is drawn :param text_left: x coordinate from which the text must be drawn :return: n/a """ line_y -= 2 ten_thousand_text_date = date ten_thousand_text_deaths = str(total_deaths) ten_thousand_text_date_width, ten_thousand_text_date_height = draw.textsize(ten_thousand_text_date, font=font_small) ten_thousand_text_deaths_width, ten_thousand_text_deaths_height = draw.textsize(ten_thousand_text_deaths, font=font_regular) draw.text((text_left, line_y - ten_thousand_text_deaths_height - ten_thousand_text_date_height), ten_thousand_text_date, font=font_small, fill=(255, 0, 0)) draw.text((text_left, line_y - ten_thousand_text_deaths_height), ten_thousand_text_deaths + " morts", font=font_regular, fill=(255, 0, 0)) def print_new_year(draw, year, line_y, year_left): """Draws a line when a new year is beginning and writes the years :param draw: ImageDraw object that will be the final output image :param year: year that is ending :param line_y: y coordinate of the line that is drawn :param year_left: x coordinate from which the text with the year must be drawn :return: n/a """ line_y -= 1 new_year = year + 1 year_width, year_height = draw.textsize(str(year), font=font_regular) draw.text((year_left, line_y - year_height), str(year), font=font_regular, fill=(0, 0, 255)) draw.text((year_left, line_y), str(new_year), font=font_regular, fill=(0, 0, 255)) def generate_image(data): """Generates the image output from the data collected :param data: dictionary that contains all data, formatted and ready to be used to draw the image output :return: n/a """ # Variables used to set the layout. Small changes are generally fine. nb_days = len(data) margin = 15 max_moving_average = max(item['moving_average'] for item in data) margin_top = 50 margin_bottom = 30 margin_right = 6 * margin line_multiplier = 2 # set a higher number to have a thinner, more vertical output (careful: might break layout) day_line_length = 3 day_line_margin = 2 ten_thousand_deaths_length = 3 * margin img_height = line_multiplier * nb_days + margin_top + margin_bottom + 2 * margin img_width = int(max_moving_average / line_multiplier) + 2 * margin + margin_right text_left = img_width - margin_right img = Image.new(mode="RGB", size=(img_width, img_height), color=(255, 255, 255)) draw = ImageDraw.Draw(img) # Main title of the graph title = "MORTS DU COVID-19 EN FRANCE DU " + data[0]['date'] + " AU " + data[-1]['date'] title_width, title_height = draw.textsize(title, font=font_regular) # Subtitle to give secondary information sub_title_1 = "1 pixel noir = 1 décès" sub_title_1_width, sub_title_1_height = draw.textsize(sub_title_1, font=font_regular) sub_title_2 = "Décès lissés sur 7 jours" # Footer for credit information. footer_1 = "David Bertho" footer_2 = "bertho.eu/covid" source_1 = "Source : Ministère des Solidarités et de la Santé" source_2 = "data.gouv.fr" footer_1_width, footer_1_height = draw.textsize(footer_1, font=font_regular) footer_2_width, footer_2_height = draw.textsize(footer_2, font=font_regular) source_1_width, source_1_height = draw.textsize(source_1, font=font_regular) source_2_width, source_2_height = draw.textsize(source_2, font=font_regular) footer_width = max(footer_1_width, footer_2_width) draw.text(((img_width - title_width) / 2, 10), title, font=font_regular, fill=(0, 0, 0)) draw.text((margin, 10 + title_height * 2), sub_title_1, font=font_regular, fill=(0, 0, 0)) draw.text((margin, 10 + title_height * 2 + sub_title_1_height), sub_title_2, font=font_regular, fill=(0, 0, 0)) draw.text((margin, img_height - margin_bottom - source_2_height), source_1, font=font_regular, fill=(0, 0, 0)) draw.text((margin, img_height - margin_bottom), source_2, font=font_regular, fill=(0, 0, 0)) draw.text((img_width - margin - footer_1_width, img_height - margin_bottom - footer_2_height), footer_1, font=font_regular, fill=(0, 0, 0)) draw.text((img_width - margin - footer_2_width, img_height - margin_bottom), footer_2, font=font_regular, fill=(0, 0, 0)) day_increment = 0 ten_thousand_deaths = 0 year = int(data[0]['date'][0:4]) for day in data: single_victim = 0 line_y = margin + margin_top + day_increment * line_multiplier # loop to print victims in the image randomly while single_victim < day["moving_average"]: pixel_x = random.randint(margin, img_width - margin - margin_right - 1) pixel_y = random.randint(margin_top + margin + day_increment * line_multiplier, margin_top + margin + (day_increment + 1) * line_multiplier) # check if the pixel is already "dead" to avoid the superposition of victims if img.getpixel((pixel_x, pixel_y)) == (255, 255, 255): img.putpixel((pixel_x, pixel_y), (0, 0, 0)) single_victim += 1 # check if a multiple of 10k victime has passed # if so, a line is printed with the date and exact count if int(day["total_deaths"] / 10000) > ten_thousand_deaths: ten_thousand_deaths = int(day["total_deaths"] / 10000) draw.line((margin - day_line_margin, line_y, img_width - margin - margin_right + ten_thousand_deaths_length, line_y), fill=(255, 0, 0), width=1) print_ten_thousand_text(draw, day["total_deaths"], day["date"], line_y, text_left) else: draw.line((img_width - margin - margin_right + day_line_margin, line_y, img_width - margin - margin_right + day_line_margin + day_line_length - 1, line_y), fill=(255, 0, 0), width=1) # check if new year # if so, a line is printed with a text that shows both years if year < int(day['date'][0:4]): print_new_year(draw, year, line_y, img_width - 2 * margin) draw.line((margin - day_line_margin, line_y, img_width - margin, line_y), fill=(0, 0, 255), width=1) year += 1 day_increment += 1 img.save('covid.png') def main(): """ this is the URL for a JSON file containing data for France change it with the URL of your choice the JSON file contains the following information used in this script: { "deces": 69596, "decesEhpad": 26044, "date": "2021-03-31" } deces and decesEhpad count the number of deaths respectively in general hospitals and nursing homes They must be added to have the total count of deaths """ req = urllib.request.Request("https://www.data.gouv.fr/fr/datasets/r/d2671c6c-c0eb-4e12-b69a-8e8f87fc224c") full_data = [] try: response = urllib.request.urlopen(req) except HTTPError as e: print('Service indisponible.') print('Erreur : ', e.code) exit(0) except URLError as e: print('Serveur inaccessible.') print('Erreur : ', e.reason) exit(0) with response as json_file: json_data = json.load(json_file) # this loop parses each day of the JSON file and adds the relevant processed data in a new dictionary file for day in json_data: # during the first days of the pandemic, nursing home deaths were not included in the file # or were marked as "null" if day.get("decesEhpad") is not None: total_deaths_ehpad = day["decesEhpad"] else: total_deaths_ehpad = 0 date = day["date"] total_deaths = day["deces"] + total_deaths_ehpad if full_data: daily_deaths = total_deaths - full_data[-1]["total_deaths"] else: daily_deaths = total_deaths if len(full_data) >= 7: moving_average = calc_moving_average(full_data, 7) else: moving_average = daily_deaths date_data = {"date": date, "daily_deaths": daily_deaths, "total_deaths": total_deaths, "moving_average": moving_average } full_data.append(date_data.copy()) generate_image(full_data) if __name__ == '__main__': main() print("-- Temps d'exécution : %s secondes --" % (time.time() - start_time))
346c94b4c65d6bfc9fa2fce77954cc3ac3cf431e
JokerQyou/algorithms
/sort/_base.py
446
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals class SortBase(object): @staticmethod def sort(l): raise NotImplementedError('Should be implemented in subclass') def is_sorted(l, descending=False): '''Check whether a sequence is sorted''' if descending: return all(l[i] >= l[i + 1] for i in xrange(len(l) - 1)) return all(l[i] <= l[i + 1] for i in xrange(len(l) - 1))
a023af20b12afd80ac5d9afe224ee7c7643fa245
dkumor/remotecontrol
/data/parser.py
541
3.578125
4
from pylab import * def getint(): a=raw_input() isint=False while (not isint): a=raw_input() try: a=int(a) isint=True except: pass return a #First read in data: #First line is the startnum i=getint() num=800 x=zeros(2*num) y=zeros(2*num) total=0 y[0]=i y[1]=i x[0]=0 i=abs(i-1) for p in xrange(1,len(y)/2): y[2*p]=i y[2*p+1]=i i=abs(i-1) total += getint() x[2*p-1]=total x[2*p]=total x[len(x)-1]=total+getint() plot(x,y) ylim((-1,2)) show()
13056eb828a21ea37dc89cbd36de80d75b7bbc7e
Royz2123/Deep-Learning
/HW1/main.py
6,148
3.875
4
''' Some 1 and 2 layer networks written using Python2.7 and Tensorflow This example is using the MNIST database of handwritten digits Authors: Roy Zohar and Roy Mezan ''' import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # MNIST data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # Parameters learning_rate = 0.001 training_epochs = 15 batch_size = 100 display_step = 1 # Network Parameters number_of_neurons = 256 n_hidden_1 = 256 # 1st layer number of features n_hidden_2 = 256 # 2nd layer number of features n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # tf Graph input # None because we don't know how many inputs x = tf.placeholder(tf.float32, [None, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) # MAIN FUNCTION # Main in the same format that as asked def main(): number_of_neurons = 256 one_hidden_layer_no_activation(number_of_neurons) two_hidden_layers_no_activation(number_of_neurons) two_hidden_layers_sigmoid(number_of_neurons) two_hidden_layers_relu(number_of_neurons) # HELPER FUNCTIONS: # Create model def multilayer_perceptron( x, weights, biases, activation, layers=2, ): layers = [] # Hidden layer 1 layers.append(tf.add(tf.matmul(x, weights['h1']), biases['b1'])) layers[0] = activation(layers[0]) # Hidden layer 2 if layers == 2: layers.append(tf.add(tf.matmul(layers[0], weights['h2']), biases['b2'])) layers[1] = activation(layers[1]) # Output layer with no activation return tf.matmul(layers[-1], weights['out']) + biases['out'] # Store layers weight & bias # initializes the weights and biases. Assumes that all hidden layers have the # same amount of neurons def init_weights( layers=2, inp=n_input, hid=number_of_neurons, out=n_classes ): weights = { 'h1': tf.Variable(tf.random_normal([inp, hid])), 'out': tf.Variable(tf.random_normal([hid, out])) } biases = { 'b1': tf.Variable(tf.random_normal([hid])), 'out': tf.Variable(tf.random_normal([out])) } # Create more vars if more layers # currently only handling 2 layers max if layers==2: weights['h2'] = tf.Variable(tf.random_normal([hid, hid])) biases['b2'] = tf.Variable(tf.random_normal([hid])) return (weights, biases) # Run the tensorflow graph def run_graph( init, optimizer, cost, pred ): # Launch the graph with tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", \ "{:.9f}".format(avg_cost)) print("Optimization Finished!") # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) def one_hidden_layer_no_activation(number_of_neurons): weights, biases = init_weights(1, hid=number_of_neurons) pred = multilayer_perceptron( x, weights, biases, lambda _: _, # No activation layers=1, ) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.global_variables_initializer() run_graph(init, optimizer, cost, pred) def two_hidden_layers_no_activation(number_of_neurons): weights, biases = init_weights(layers=2, hid=number_of_neurons) pred = multilayer_perceptron( x, weights, biases, lambda _: _, # No activation layers=2, ) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.global_variables_initializer() run_graph(init, optimizer, cost, pred) def two_hidden_layers_sigmoid(number_of_neurons): weights, biases = init_weights(layers=2, hid=number_of_neurons) pred = multilayer_perceptron( x, weights, biases, tf.nn.sigmoid, # Sigmoid activation layers=2, ) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.global_variables_initializer() run_graph(init, optimizer, cost, pred) def two_hidden_layers_relu(number_of_neurons): weights, biases = init_weights(layers=2, hid=number_of_neurons) pred = multilayer_perceptron( x, weights, biases, tf.nn.relu, # RElu activation layers=2, ) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Initializing the variables init = tf.global_variables_initializer() run_graph(init, optimizer, cost, pred) if __name__ == '__main__': main()
7f79f20efb60630ef7967457d761f11c40c92700
DerekLW6/python_apps
/01_the_basics/first_app_v2.py
430
3.703125
4
# text_list = [] # modified_text_list = [] # #interrogatives = ('how', 'what', 'why') # while True: # user_input = input("Say something: ") # if user_input == '\end': # for element in text_list: # x = element.capitalize() + "." # modified_text_list.append(x) # break # else: # text_list.append(user_input) # continue # print(" ".join(modified_text_list))
c260bdf51bc8b68c50649f6e0e860c95513410da
fernandorssa/CeV_Python_Exercises
/Desafio 10.py
124
3.8125
4
n1 = float(input('Quanto você tem na carteira? R$ ')) print ('Valor convertido em Dólares: USD {:.2f}'.format(n1/3.27))
1af27f8fc94bb9cb268b5cd713ba73ecfcf961e9
fernandorssa/CeV_Python_Exercises
/Desafio 82.py
619
3.84375
4
listaGeral = [] listaPar = [] listaImpar = [] while True: n = int(input('Digite um número: ')) # listaGeral.append(int(input('Digite: '))) listaGeral.append(n) continuar = int(input('Digite 1 para continuar e 2 para sair: ')) if continuar == 2: break for analise in listaGeral: if analise % 2 == 0: listaPar.append(analise) if analise % 2 == 1: listaImpar.append(analise) ''' for i, v in enumerate(listaGeral): if v % 2 == 0: listaPar.append(v) elif v % 2 == 1: listaImpar.append(v) ''' print('') print(listaGeral) print(listaPar) print(listaImpar)
808eb356948dd8e2c20a7805246c50aa1d663730
fernandorssa/CeV_Python_Exercises
/Desafio 46.py
560
3.640625
4
from time import sleep print('') print('Vai começar a contagem regressiva!!!!!') print('') sleep(1) cont = 10 for tempo in range(10, -1, -1): if cont == 0: print('0!!!!!!!!!!!!!! AEEEEEEEEEE!!!!!!!!!!! BUUUUUUUM TCHAMMMMMMMMMMMM CATAPUMMMMMMM!!!!!') else: print(cont) cont -= 1 sleep(1) # Para fazer a contagem, eu poderia ter usado somente a variável tempo, e não o cont -=1. Isso porque essa variável # diminiu a cada passo do range. Aí também não precisaria do cont == 0, colocando o AEEE fora do range...
3f6098a38ca9db8e5d82696d9b9589ce68e034de
fernandorssa/CeV_Python_Exercises
/Desafio 73.py
883
3.96875
4
times = ('Palmeiras', 'Flamengo', 'Internacional', 'Grêmio', 'São Paulo', 'Atlético', 'Atlético - PR', 'Cruzeiro', 'Botafogo', 'Santos', 'Bahia', 'Corinthians', 'Ceará', 'Fluminense', 'Vasco', 'Chapecoense', 'América', 'Sport', 'Vitória', 'Paraná') print('') print('Classificação dos 5 primeiros colocados:') # Guanabara fez times[0:5] for a in range(0, 5): print(f'{a + 1}°', f'{times[a]}') print('') print('Classificação dos 4 últimos colocados:') # Guanabara fez times[-4:] for b in range(16, 20): print(f'{b + 1}°', f'{times[b]}') print('') print('Lista dos times em ordem alfabética:') ordenados = sorted(times) for c in range(0, 20): print(f'{c + 1}°', f'{ordenados[c]}') print('') chapeco = times.index('Chapecoense') print(f'C) O Chapecoense está na {chapeco + 1}ª posição')
c7e3a7c69635adc1fcf105d33b9cc137065f35fe
fernandorssa/CeV_Python_Exercises
/Desafio 101.py
768
3.75
4
# Minha solução def voto1(x): if 2019 - x <= 16: print(f'Com {2019 - x} anos: Não vota.') elif 2019 - x >= 16 and 2019 - x < 65: print(f'Com {2019 - x} anos: Voto obrigatório.') else: print(f'Com {2019 - x} anos: Voto opcional.') nascimento = int(input('Em que ano você nasceu? ')) voto1(nascimento) # Solução do Guanabara """ def voto2(ano): from datetime import date atual = date.today().year idade = atual - ano if idade < 16: return f'Com {idade} anos: Não vota!' elif 16 <= idade < 18 or idade > 65: return f'Com {idade} anos: Voto opcional!' else: return f'Com {idade} anos: Voto obrigatório!' nasc = int(input('Em que ano você naceu? ')) print(voto2(nasc)) """
ae0c54650b8f0b0be18e527f1d50a841a20ac367
fernandorssa/CeV_Python_Exercises
/Desafio 28.py
883
3.953125
4
import random from time import sleep lista = [1, 2, 3, 4, 5] n = random.choice(lista) print('') chute = int(input('Olá, eu pensei em um número de 1 a 5. Qual é o número? ')) print('PENSANDO...') sleep(3) if chute == n: print('PARABÉNS! Você acertou!') else: if chute <= 5: print('ERROU! Eu pensei no número {}! Tente outra vez!'.format(n)) else: print('NÚMERO DE 1 a 5!!!!!') ''' from random import randint computador = randint(0, 5) # Faz o computador "pensar" print('-=-'*20) print('Vou pensar em um número entre 0 e 5. Tente adivinhar...') print('-=-'*20) jogador = int(input('Em que número eu pensei?')) # jogador tenta adivinhar if jogador == computador: print('PARABÉNS! Você conseguiu me vencer!') else: print('GANHEI! Eu pensei no número {} e não no número {}!'.format(computador, jogador)) '''
82b449bdab3b9fd097d8e83c6506b1b80e096799
fernandorssa/CeV_Python_Exercises
/Desafio 12.py
166
3.53125
4
n1 = float(input('Preço do produto: R$ ')) # n1 = 100 # x = 5 # Resultado é igual N1 - 5% print('O valor com desconto é: R$ {:.2f}'.format(n1-(n1*5)/100))
a55172d774791aef6d96d4059e423f6d6e659870
fernandorssa/CeV_Python_Exercises
/Desafio 29.py
322
3.75
4
v = float(input('Velocidade: ')) if v <= 80: print('Você está respeitando os limites de velocidade.') else: print('Você passou no radar a {} km/h e excedeu o limite de velocidade.'.format(v)) print('MULTADO no valor de R$ {:.2f}'.format((v-80)*7)) print('Tenha um bom dia! Dirija com segurança!')
97e9ef88bf14bd8990b1e102b24be1d1c062a512
fernandorssa/CeV_Python_Exercises
/Desafio 94.py
1,993
3.734375
4
n = int(input('Quantas pessoas: ')) dict = {} acima_da_media = {} mulheres = [] cont = soma = 0 for i in range(n): nome = str(input('Digite um nome: ')) sexo = str(input('Digite o sexo (m/f): ')) idade = int(input('Digite a idade: ')) if sexo == 'f': mulheres.append(nome) soma += idade dict[f'Nome da pessoa {cont + 1}'] = nome dict[f'Sexo da pessoa {cont + 1}'] = sexo dict[f'Idade da pessoa {cont + 1}'] = idade acima_da_media[f'{nome}'] = idade cont += 1 media = soma / cont print(f'A: foram cadastradas {cont} pessoa(s)') print(f'B: A média de idade é {media} anos') print(f'C: Lista de mulheres: {mulheres}') print('D: Lista de pessoas com idade acima da média:') for k,v in acima_da_media.items(): if int(v) > media: print(f'{k}, com {v} anos') # Solução do Guanabara """ galera = list() pessoa = dict() soma = media = 0 while True: pessoa.clear() pessoa['nome'] = str(input('Nome: ')) while True: pessoa['sexo'] = str(input('Sexo(M/F): ')).upper()[0] if pessoa['sexo'] in 'MF': break print('ERRO! Por favor, digite apenas M ou F.') pessoa['idade'] = int(input('Idade: ')) soma += pessoa['idade'] galera.append(pessoa.copy()) while True: resp = str(input('Quer continuar (S/N)? ')).upper()[0] if resp in 'SN': break print('ERRO! Responsa apenas S ou N.') if resp == 'N': break print('-=' * 30) print(f'A) Ao todo temos {len(galera)} pessoas cadastradas.') media = soma / len(galera) print(f'B) A média de idade é de {media:5.2f} anos.') print('C) As mulheres cadastradas foram: ', end='') for p in galera: if p['sexo'] in 'Ff': print(f'{p["nome"]} ', end=',') print() print('D) Lista das pessoas que estão acima da média: ') for p in galera: if p['idade'] >= media: for k, v in p.items(): print(f'{k} = {v}') print() print('ENCERRADO') """
67039f2ee14bfd5044297365b8d6d5a380b068e0
fernandorssa/CeV_Python_Exercises
/Desafio 14.py
223
3.96875
4
a = float(input('Digite a temperatura em °C: ')) print('A temperatura de {} corresponde à {} °F!'.format(a, 32 + (a * 1.8))) print('A temperatura de {} corresponde à {} °F! [Versão 2]'.format(a, ((9 * a) / 5) + 32))
1a4bc19b9deb798a2b3e18fabb62b53babd7e101
fernandorssa/CeV_Python_Exercises
/Desafio 63.py
1,077
4.15625
4
'''# Pede quantos termos da sequência Fibonacci n = int(input('Digite quantos termos da sequência: ')) # O contador foi definido como 4 pois n0, n1 e n2 não entram no WHILE. Dessa forma, o programa roda 3 vezes a menos cont = 4 n1 = n2 = 1 # Se o usuário pede 5 termos, o cont vai rodar 2 vezes, somado ao n0, n1 e n2: totalizando os 5 termos while cont <= n: # Essas quatro linhas são usadas para imprimir os 3 primeiros números da sequência if n1 == 1 and n2 == 1: print(n1 - n2) print(n1) print(n2) # Daqui em diante são calculados os próximos termos da sequência, depois de 0, 1, 1... resultado = n1 + n2 # Aqui será impresso o próximo termo da sequência Fibonacci print(resultado) n2 = n1 n1 = resultado cont += 1''' # Meu programa funciona mas a lógica é complicada n = int(input('Quantos termos: ')) t1 = 0 t2 = 1 print('{} -> {}'.format(t1, t2), end='') cont = 3 while cont <= n: t3 = t1 + t2 print(' -> {} '.format(t3), end='') t1 = t2 t2 = t3 cont += 1 print('-> FIM')
c70e08596bca769dd772cb989ad529f4fc9e3a01
ilyakh/atsp
/atsp/encoder.py
1,186
3.546875
4
#!/usr/bin/env python2.7 # -*- coding: utf8 -*- class Encoder: pass class LetterEncoder(Encoder): """ Maps chromosomes to the symbols from the ASCII table with corresponding limitations, beginning with the letter 'A' """ def __init__( self, ALL_GENES ): self.ALL_GENES = ALL_GENES # creates mappings for the encoding self.mapping = dict( enumerate( self.ALL_GENES ) ) # maps the genotype to phenotype {A -> Bergen, ... } self.mapping = dict( [ ( chr(65 + int(k)), v ) for k,v in self.mapping.items() ] ) # maps the phenotype to genotype {Bergen -> A, ... } self.inverse_mapping = dict( [ (v, k) for k,v in self.mapping.items() ] ) def encode( self, phenotype ): return self.inverse_mapping[phenotype] def decode( self, genotype ): return self.mapping[genotype] def to_genotype( self, phenotype_set ): genotype = [ self.encode(g) for g in phenotype_set ] return "".join( genotype ) def to_phenotype( self, genotype_set ): phenotype = [ self.decode(g) for g in genotype_set ] return phenotype
df3955f45591745ac7c20b87d71d01a16f774cf1
OlivierParpaillon/Contest
/code_and_algo/Xmas.py
1,504
4.21875
4
# -*- coding:utf-8 -* """ Contest project 1 : Christmas Tree part.1 Olivier PARPAILLON Iliass RAMI 17/12/2020 python 3.7.7 """ # Python program to generate branch christmas tree. We split the tree in 3 branches. # We generate the first branch of the christmas tree : branch1. # We will use the same variables for the whole code : only values will change. # nb_blank represents the number of blanks between the "*" ; # star_top represents the number of "*" on the top of the tree ; # and nb_branch defines the number of times we repeat the operation. def branch1(): nb_blank = 15 star_top = 1 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 1 star_top += 2 # We generate the middle branch of the christmas tree. # Same variables but we add 4 to star_top and we remove 2 from nb_blank def branch2(): nb_blank = 14 star_top = 3 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 2 star_top += 4 # We generate the last branch of the christmas tree. # We use the same variables but we remove 3 from nb_blank and we add 6 to star_top def branch3(): nb_blank = 13 star_top = 5 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 3 star_top += 6 # Main function to start the program. def main(): branch1(), branch2(), branch3() main()
226b39a7fc1fa454eb949ba25471c308d7fc22e0
frankipod/leetcode
/mergeTwoLists.py
2,138
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 07 14:58:34 2016 @author: yaoxia """ import linklst as ll #Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def insert(l1,l2): n2 = l2 # print ll.CrtList(l1),ll.CrtList(l2) l2 =n2.next # print ll.CrtList(l1),ll.CrtList(l2) n1 = l1.next # print ll.CrtList(l1),ll.CrtList(l2) l1.next = n2 # print ll.CrtList(l1),ll.CrtList(l2) n2.next = n1 n3 = l1 # print ll.CrtList(l1),ll.CrtList(l2) # a = l1.next.next return n3,l2 if not l1 and l2: return l2 if not l2 and l1: return l1 if not l1 and not l2: return l1 if l1.val >= l2.val: b,s = l1, l2 else: s,b = l1, l2 result = s while s.next and b: if b.val <= s.next.val: (s,b) = insert(s,b) else: s = s.next # print ll.CrtList(result),ll.CrtList(b),ll.CrtList(s) if not s.next: s.next = b # print ll.CrtList(result),ll.CrtList(b),ll.CrtList(s) return result l1 = [3,4,5,6] l2 = [1,2,3,4] a1 = ll.CreatLinkList(l1) a2 = ll.CreatLinkList(l2) print ll.CrtList(a1),ll.CrtList(a2) #(a3,a2) = insert(a1,a2) #(a3,a2) = insert(a3,a2) b = Solution() c = b.mergeTwoLists(a1,a2) #a2 = insert(a1.next.next,a2) #a1 = insert(a1,a2) #print ll.CrtList(a1),ll.CrtList(a2),ll.CrtList(a3) #a2 = insert(a1,a2) #print ll.CrtList(a1),ll.CrtList(a2) #print ll.CrtList(dum.next) #print ll.CrtList(swap(dum).next) #b = Solution() #c = b.mergeTwoList(a) # ## print ll.CrtList(c), 'Results'
118115215f5fbd91d7e85287bcc46d8c787e3f18
liviaerxin/zipline
/dual_moving_average.py
3,869
3.515625
4
#dual_moving_average.py #!/usr/bin/env python # # Copyright 2014 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dual Moving Average Crossover algorithm. This algorithm buys apple once its short moving average crosses its long moving average (indicating upwards momentum) and sells its shares once the averages cross again (indicating downwards momentum). """ from zipline.api import order_target, record, symbol, history, add_history,order from zipline import TradingAlgorithm import matplotlib.pyplot as plt import pandas as pd def initialize(context): # Register 2 histories that track daily prices, # one with a 100 window and one with a 300 day window #add_history(100, '1m', 'price') #add_history(300, '1m', 'price') context.i = 0 context.sym = 'Close' def handle_data(context, data): # Skip first 300 days to get full windows #print data['Close'].dt #context.i += 1 #if context.i < 300: # return # Compute averages # history() has to be called with the same params # from above and returns a pandas dataframe. sym = symbol('Close') if data['short_mavg'].price > data['long_mavg'].price: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.sym, 1000) elif data['short_mavg'].price < data['long_mavg'].price: order_target(context.sym, 0) # Save values for later inspection record(Close=data[context.sym].price, short_mavg=data['short_mavg'].price, long_mavg=data['long_mavg'].price) def analyze(context, perf): fig = plt.figure() ax1 = fig.add_subplot(211) perf.portfolio_value.plot(ax=ax1) ax1.set_ylabel('portfolio value in $') ax2 = fig.add_subplot(212) perf['AAPL'].plot(ax=ax2) perf[['short_mavg', 'long_mavg']].plot(ax=ax2) perf_trans = perf.ix[[t != [] for t in perf.transactions]] buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]] sells = perf_trans.ix[ [t[0]['amount'] < 0 for t in perf_trans.transactions]] ax2.plot(buys.index, perf.short_mavg.ix[buys.index], '^', markersize=10, color='m') ax2.plot(sells.index, perf.short_mavg.ix[sells.index], 'v', markersize=10, color='k') ax2.set_ylabel('price in $') plt.legend(loc=0) plt.show() if __name__ == '__main__': import pylab as pl # Read data from yahoo website #start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc) #end = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc) #data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,end=end) #data = data.dropna() # Read data from csv data = pd.read_csv('EURUSD.csv') # DataFrame data = data.dropna() data.set_index('Date', inplace=True) # set the Date as index data.index = pd.to_datetime(data.index, utc=True) # convert to datetime format print data.head() # Or directly #data = pd.DataFrame.from_csv('AAPL.csv') data['short_mavg'] = pd.rolling_mean(data['Close'], 100) data['long_mavg'] = pd.rolling_mean(data['Close'], 300) algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data) #identifiers=['AAPL']) results = algo.run(data) results.to_csv('EURUSD_DMA.csv')
d5843f3d76d55f5050dfe17e997b81ef5fbed5f4
macs-h/326_pair
/etude06/test2.py
954
4
4
''' Mersenne primes and perfect numbers ''' def primes(n): """ Return a list of primes < n """ # From http://stackoverflow.com/a/3035188/4014959 sieve = [True] * (n//2) for i in range(3, int(n**0.5) + 1, 2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n - i*i - 1) // (2*i) + 1) return [2] + [2*i + 1 for i in range(1, n//2) if sieve[i]] def lucas_lehmer(p): ''' The Lucas-Lehmer primality test for Mersenne primes. See https://en.wikipedia.org/wiki/Mersenne_prime#Searching_for_Mersenne_primes ''' m = (1 << p) - 1 s = 4 for i in range(p - 2): s = (s * s - 2) % m return s == 0 and m or 0 #Lucas-Lehmer doesn't work on 2 because it's even, so we just print it manually :) print('1 2\n3\n6\n') count = 1 for p in primes(1280): m = lucas_lehmer(p) if m: count += 1 n = m << (p - 1) print(count, p) print(m) print(n, '\n')
20e1417f2f3199475381bf8fdefea37f2a68146c
macs-h/326_pair
/etude06/test.py
1,825
4.03125
4
def primes(known_primes=[7, 11, 13, 17, 19, 23, 29]): """ Generate every prime number in ascending order """ # 2, 3, 5 wheel yield from (2, 3, 5) yield from known_primes # The first time the generator runs, known_primes # contains all primes such that 5 < p < 2 * 3 * 5 # After each wheel cycle the list of known primes # will be added to. # We need to figure out where to continue from, # which is the next multiple of 30 higher than # the last known_prime: base = 30 * (known_primes[-1] // 30 + 1) new_primes = [] while True: # offs is chosen so 30*i + offs cannot be a multiple of 2, 3, or 5 for offs in (1, 7, 11, 13, 17, 19, 23, 29): k = base + offs # next prime candidate for p in known_primes: if not k % p: # found a factor - not prime break elif p*p > k: # no smaller prime factors - found a new prime new_primes.append(k) break if new_primes: yield from new_primes known_primes.extend(new_primes) new_primes = [] base += 30 def is_prime(n): for p in primes(): if not n % p: # found a factor - not prime return False elif p * p > n: # no factors found - is prime return True # search all numbers in [2..limit] for perfect numbers # (ones whose proper divisors sum to the number) # limit = int(input("enter upper limit for perfect number search: ")) limit = 9000000 for p in primes(): pp = 2**p perfect = (pp - 1) * (pp // 2) if perfect > limit: break elif is_prime(pp - 1): print(perfect, "is a perfect number")
23bd8f9abc8622a7fba3ec85097241eacd9f3713
DLLJ0711/friday_assignments
/fizz_buzz.py
1,486
4.21875
4
# Small: add_func(1, 2) --> outputs: __ # More Complex: add_func(500, 999) --> outputs: __ # Edge Cases: add_func() or add_func(null) or add_func(undefined) --> outputs: ___ # Take a user's input for a number, and then print out all of the numbers from 1 to that number. #startFrom = int(input('Start From (1-10): ')) not needed #x = 1 # endOn = int(input('End On (any number): ')) # while(x <= endOn): # print(x) # x +=1 # For any number divisible by 3, print 'fizz' # for i in range(lower, upper+1): # if((i%3==0): # print(i) # For any number divisible by 5, print 'buzz' # for i in range(lower, upper+1): # (i%5==0)): # print(i) # For any number divisible by 3 and 5, print 'fizzbuzz' # for i in range(lower, upper+1): # if((i%3==0) & (i%5==0)): # print(i) #print 1 to user's input NOT NEEDED # while(x <= endOn): # print(x) # x += 1 # HAD TO COMBINE CODE AND REPLACE SYNTAX AND ORDER OF EVALUATION #Starting range x = 1 #user's input endOn = int(input('End On (any number): ')) #for loop and if statment for x in range(x, endOn +1): if x % 3 == 0 and x % 5 == 0: print('fizzbuzz') elif x % 3 == 0: print("fizz") elif x % 5 == 0: print("buzz") else: print(x) #had continue after each statement replaced with else to end.
c41bbc8a0bf4e38e2c4a31459e26a90f6de905fb
aniruddh-acharya/Krypto
/vign.py
895
3.953125
4
#Dont run this. DONT. def key(string, key): s = ""; i = 0 while(len(s) != len(string)): s += key[i%len(key)] i+=1 return s #Just run this for cipher. def encrypt(string, key1): string = string.upper() key1 = key1.upper() key_ = key(string,key1) cipher = "" for i in range(len(key_)): if(string[i] != ' '): p = (ord(string[i]) + ord(key_[i]))%26 p += ord('A') cipher += chr(p) else: cipher += ' ' return cipher #Run to decipher. def decrypt(string, key1): string = string.upper() key1 = key1.upper() key_ = key(string, key1) res = "" for i in range(len(string)): if(string[i] != ' '): p = (ord(string[i]) - ord(key_[i]) + 26)%26 p += ord('A') res += chr(p) else: res += ' ' return res
47f2fb1ed3fcddd40cd542a13adba1cf47addd37
Rahul91/python
/git_gui.py
2,298
3.578125
4
#!/usr/bin/python2.7 import sys import string import base64 from Tkinter import Tk from tkFileDialog import askopenfilename from githubpy import github from bs4 import BeautifulSoup import urllib2 print "For using this app, you need to have Github auth token, please go through the link for more details:\nhttps://help.github.com/articles/creating-an-access-token-for-command-line-use/#creating-a-token\n\nAfter getting your token, just paste in here" token = raw_input("Enter/paste your token : ") #token = '33aa8aec26d79b1843d50385cdea04093b90570f' #Github auth token for authorisation gh = github.GitHub(access_token=token) username = str(gh.user.get()['login']) root = Tk() root.withdraw() root.filename = askopenfilename() filename = str(root.filename) filename_rev = filename[::-1] str_file ='' for i in range(30): if filename_rev[i] == "/": break else: str_file = str_file + filename_rev[i] file_name = str_file[::-1] commit_message = raw_input("Enter your commit Message : ") with open(filename) as f: file_content = f.read() flag1 = 1 j = 0 list = gh.user.repos.get() while (j<=3): repo_name = raw_input("Enter the repo, you want your code to be pushed: ") for dictionary in list: if str(repo_name) != str(dictionary['name']): flag1 = 0 else: flag1 = 1 j = 5 print "got a hit" break if flag1 == 0: print "I think, you have forgotten your repo names, have a look here, and try again." for dictionary in list: print dictionary['name'] j += 1 if j == 3: print "Tumse naa ho payega, Aborting" sys.exit(1) break link = "https://github.com/" + username + "/" + str(repo_name) url = urllib2.urlopen(link) soup = BeautifulSoup(url) con = soup.find_all("a",{"class" : "js-directory-link"}) count = len(con) flag2 = 0 for title in con: if str(file_name) == str(title.text): flag2 = 1 print "You are trying to push a file, which is already there on your remote. This feature is not in this module. Please try later and push a file which is not alrady pushed. Aborting." break if (flag1==1 and flag2==0): encoded_file = base64.b64encode(file_content) gh = github.GitHub(access_token=token) username = str(gh.user.get()['login']) gh.repos(username)(repo_name)('contents')(file_name).put(path=file_content,message=commit_message,content=encoded_file)
27908f6c8668a493e416fc1857ac8fa49e7bb255
s3rvac/talks
/2017-03-07-Introduction-to-Python/examples/22-point.py
353
4.25
4
from math import sqrt class Point: """Representation of a point in 2D space.""" def __init__(self, x, y): self.x = x self.y = y def distance(self, other): return sqrt((other.x - self.x) ** 2 + (other.y - self.y) ** 2) a = Point(1, 2) b = Point(3, 4) print(a.distance(b)) # 2.8284271247461903
43b7db090b104f95554ae7079b0c28379a3c6c39
s3rvac/talks
/2017-03-07-Introduction-to-Python/demos/emails.py
331
3.5
4
# Note: This script is just an illustration. It contains a very simple solution # to the problem, which is far from perfect. import sys import re emails = [] with open(sys.argv[1], 'r') as f: for line in f: for email in re.findall(r'[\w.-]+@[\w.-]+', line): emails.append(email.rstrip('.')) print(emails)
b2aa6c8e73150c89538f50cbe8e848735c28227b
s3rvac/talks
/2020-03-02-Introduction-to-Python/examples/23-properties.py
379
3.734375
4
class Person: def __init__(self, name, age): self.name = name self.age = age @property def age(self): return self._age @age.setter def age(self, new_age): if new_age <= 0: raise ValueError('age has to be positive') self._age = new_age p = Person('John', 30) print(p.age) p.age = -1 # Raises ValueError.
ebb63bb53f8b9ed0e1156bbc0cb6339d72a22f35
s3rvac/talks
/2020-03-02-Introduction-to-Python/examples/23-first-class.py
504
3.859375
4
class Point: ... # Python classes are first-class objects. For example, you can assign them to # variables: P = Point print(P()) # <__main__.Point object at 0x7fc1f458c400> # Pass them to other functions: def create(cls): return cls() p = create(Point) print(p) # <__main__.Point object at 0x7fc6b516d4a8> # Create them during runtime and return them: def foo(): class Point2: ... return Point2 P = foo() print(P()) # <__main__.foo.<locals>.Point2 object at 0x7f5cf0ae3ac8>
7baaca13abcd7fc98fd5d9b78de0bc62557f4b83
s3rvac/talks
/2020-03-26-Python-Object-Model/examples/dynamic-layout.py
666
4.34375
4
# Object in Python do not have a fixed layout. class X: def __init__(self, a): self.a = a x = X(1) print(x.a) # 1 # For example, we can add new attributes to objects: x.b = 5 print(x.b) # 5 # Or even new methods into a class: X.foo = lambda self: 10 print(x.foo()) # 10 # Or even changing base classes during runtime (this is just for illustration, # I do not recommend doing this in practice): class A: def foo(self): return 1 class B(A): pass class C: def foo(self): return 2 b = B() print(b.foo(), B.__bases__) # 1 (<class '__main__.A'>,) B.__bases__ = (C,) print(b.foo(), B.__bases__) # 2 (<class '__main__.C'>,)
04e0458356117f0c0028d0e158edf86e528f43b3
s3rvac/talks
/2021-03-08-Introduction-to-Python/examples/31-arguments.py
217
3.59375
4
def foo(x=[]): x.append(4) return x print(foo([1, 2, 3])) # [1, 2, 3, 4] print(foo()) # [4] print(foo()) # [4, 4] # https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
a0178beb9995c302dc3ebc460b4174995f240f26
s3rvac/talks
/2017-03-07-Introduction-to-Python/examples/23-variables.py
209
3.8125
4
class A: a = 1 def __init__(self, b): self.b = b x = A(1) y = A(1) print(x.a, x.b, y.a, y.b) # 1 1 1 1 x.b = 2 print(x.a, x.b, y.a, y.b) # 1 2 1 1 A.a = 3 print(x.a, x.b, y.a, y.b) # 3 2 3 1
16be02fd8167d8dfc0c82f70c03a94eaf36db41c
s3rvac/talks
/2020-03-26-Python-Object-Model/examples/methods-vs-functions.py
328
3.78125
4
# Methods vs functions. class X: def __init__(self, x): self.x = x def add(self, other): return self.x + other.x a = X(1) b = X(2) print(a.add(b)) # 3 print(X.add(a, b)) # 3 print(X.add) # <function X.add at 0x7f83bb046040> print(a.add) # <bound method X.add of <__main__.X object at 0x7fa9414ee910>>
ea5836406ee848f6fde86e7eda077e6795a91c7d
flyerooo/learnpython27
/qiwsirPython/ex1-8.py
1,089
3.53125
4
#!/usr/bin/env python #coding:utf-8 #Created by Jeff on 2016/3/3 11:12 # 8、获取当前日期,并计算当前日期距离1998年5月1日由多少天、多少周(取整)、多少月(取整)、几个季度(取整)、几年(取整)。 from datetime import date def main(): #获取当前日期 now = date.today() d1 = date(1998, 5, 1) #间隔天数 days_diff = (now - d1).days #间隔星期数 weeks_diff = days_diff / 7 #间隔月数 months_diff = (now.year - d1.year) * 12 + (now.month - d1.month) if now.day >= d1.day else (now.year - d1.year) * 12 + (now.month - d1.month) - 1 #间隔年数 years_diff = months_diff / 12 print r"今天距离1998年 5月 1日共:",days_diff,"天" print r"今天距离1998年 5月 1日共:",weeks_diff,"周" print r"今天距离1998年 5月 1日共:",months_diff,"月" print r"今天距离1998年 5月 1日共:",years_diff,"年" main() #我试着自己用if/else算闰年,有没有二月的情况等,然后再计算,但发现很复杂,就只能这样算了
2bb704c44a69dac025d2d18312b9064011bf0852
flyerooo/learnpython27
/qiwsirPython/ex33.py
1,046
4.03125
4
#!/usr/bin/env python #coding:utf-8 #Created by Jeff on 2016/3/20 9:02 ''' 33、回文(palindrome)是正读或者反读都相同的单词或但与,忽略空格和字母大小写。例如,下面的示例都是回文: warts n straw radar Able was I ere I saw Elba xyzczyx 编写一个程序,判断输入的字符串是否是回文。 ''' def toLetters(string): '''remove non letter character ''' letters = '' for c in string: if c.isalpha(): letters += c return letters def isPalindrome(string): low = 0 #first letter high = len(string) - 1 # last letter while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True if __name__=="__main__": string = raw_input("Enter a string:").lower() if isPalindrome(toLetters(string)): #一个函数要调用另一个函数值这么写吗? 对函数之间的调用不太会 print string,"is a palindrome" else: print string,"is not a palindrome"
e7b44b5c6b2a9490385743f5a4b54aca28ff4728
flyerooo/learnpython27
/qiwsirPython/ex22.py
1,414
3.546875
4
#!/usr/bin/env python #coding:utf-8 #Created by Jeff on 2016/3/13 22:58 # 22、完全数,是对具有某种特征的整数的称呼。维基百科中,对完全数有非常准确的定义和解释。如下: # 完全数,又稱完美數或完備數,是一些特殊的自然数:它所有的真因子(即除了自身以外的约数)的和,恰好等於它本身,完全数不可能是楔形數。 # 例如:第一个完全数是6,它有约数1、2、3、6,除去它本身6外,其余3个数相加,1+2+3=6,恰好等於本身。第二个完全数是28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28,也恰好等於本身。后面的数是496、8128。 # 关于完全数的更多内容,可以阅读:https://zh.wikipedia.org/zh/%E5%AE%8C%E5%85%A8%E6%95%B0 # 要求:编写一段Python程序,用其可以判断一个整数是否是完全数。 def perfectNumber(num): numTemp = num /2 + 1 #因子最大可能值 divisorList = [1] divisor = 2 #while divisor <= numTemp: for divisor in range(2, numTemp): if num % divisor == 0: divisorList.append(divisor) # divisor += 1 print divisorList if num == sum(divisorList): return True else: return False if __name__ == "__main__": num = int(raw_input("请输入数字:")) print num,perfectNumber(num)
42b39efbe438ae62a818b8487aedeb5d71d4cf58
lafleur82/python
/Final/do_math.py
1,022
4.3125
4
import random def do_math(): """Using the random module, create a program that, first, generates two positive one-digit numbers and then displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Ensure your program conducts error-checking on the answer and notifies the user whether the answer is correct or not.""" a = random.randint(1, 9) b = random.randint(1, 9) op = random.randint(1, 3) answer = 0 if op == 1: print("What is", a, "+", b, "?") answer = a + b elif op == 2: print("What is", a, "-", b, "?") answer = a - b elif op == 3: print("What is", a, "*", b, "?") answer = a * b user_input = float(input()) if user_input == answer: print("Correct!") else: print("Incorrect.") if __name__ == '__main__': while True: do_math() print("Another? (y/n)") user_input = input() if user_input != 'y': break