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
4c8921d466f8d85e6327678bf2ea08fe613a2a68
piyus22/AlphaBionix
/Basic_code/element_wise_comparison.py
630
4.09375
4
#By- Piyus Mohanty #Write a NumPy program to create an element-wise comparison (greater, greater_equal, less and less_equal) of two given arrays import numpy as np a=np.random.randint(100,size=(3,4)) b=np.random.randint(100,size=(3,4)) print("array 1 contents are:",a) print("array 2 contents are: ",b) print("The greater between the two array is: \n") print(np.greater(a,b)) print("The position_value equal between the two array is: \n") print(np.greater_equal(a,b)) print("The lower value between the two array is: \n") print(np.less(a,b)) print("The lower position_value equal between the two array is: \n") print(np.less_equal(a,b))
e578a442efdd0a888a2d79c4b93bdbbe2b16e063
meniscus/AtCoder
/ABC/ABC068/B.py
258
3.671875
4
import math N = int(input()) # 実際Nもいらない for i in range(N) : if (N == 1) : # この実装が汚い。。。 print(1) break if (N < math.pow(2,i)) : print(int(math.pow(2,i-1))) break
b2b53a66d1c3fe3767626ddf3343e9c5a42ff3a4
meniscus/AtCoder
/ABC/ABC015/A.py
121
3.5625
4
# あ in_str1 = input() in_str2 = input() if len(in_str1) > len(in_str2) : print(in_str1) else : print(in_str2)
6a39d9c02444a887957b2e07fb3b9144abbb6283
meniscus/AtCoder
/ARC/ARC012/A.py
269
4.25
4
day = input() if (day == "Sunday" or day == "Saturday") : print(0) elif (day == "Monday") : print(5) elif (day == "Tuesday") : print(4) elif (day == "Wednesday") : print(3) elif (day == "Thursday") : print(2) elif (day == "Friday") : print(1)
13cbdc603f01aa7e0b9ff35950866f7a31648b42
meniscus/AtCoder
/ABC/ABC022/A.py
330
3.546875
4
import math # あ read_line = input().split() days = int(read_line[0]) under_limit = int(read_line[1]) upper_limit = int(read_line[2]) best_body_days = 0 weight = 0 for i in range(days) : weight += int(input()) if (under_limit <= weight and weight <= upper_limit) : best_body_days += 1 print(best_body_days)
5ca98b1ff75d93592d2756824fc3eb5ce2395caf
meniscus/AtCoder
/ABC/ABC079/C.py
535
3.75
4
# きたない。。。。 def get_formula(a,b,c,d) : for f1 in range(2) : s = str(a) if (f1 == 0) : s += "+" else : s += "-" s += str(b) for f2 in range(2) : s2 = s if (f2 == 0) : s2 += "+" else : s2 += "-" s2 += str(c) for f3 in range(2) : s3 = s2 if (f3 == 0) : s3 += "+" else : s3 += "-" s3 += str(d) if (eval(s3) == 7) : return s3 a,b,c,d = [int(i) for i in list(input())] print(get_formula(a,b,c,d) + "=7")
44ffcc2491c3125de360b808bb77e39ec4a41d10
meniscus/AtCoder
/ABC/ABC103/B.py
193
3.734375
4
S = input() T = input() is_okay = False for i in range(len(T)) : if (S == T) : is_okay = True break T = T[1:] + T[0] if (is_okay) : print("Yes") else : print("No")
acca4b660e319e5e6ecf8a85a171c1253b86d0dd
meniscus/AtCoder
/ABC/ABC001/B.py
285
3.703125
4
meter=int(input()) kilometer = meter / 1000.0 if meter < 100 : ans=00 elif meter <= 5000 : ans = kilometer * 10 elif meter <= 30000: ans = kilometer + 50 elif meter <= 70000: ans = int((kilometer-30) //5 + 80) else : ans=89 s = '%02d' % ans s = s[0:2] print(s)
52ca8637ddfd548c38794cfd356ea32b617e6611
meniscus/AtCoder
/ABC/ABC011/C.py
756
3.671875
4
def main() : N = int(input()) NG1 = int(input()) NG2 = int(input()) NG3 = int(input()) NG = [NG1,NG2,NG3] if (N in NG) : print("NO") return count = 0 while True : if (N == 0) : break if (N-3 not in NG and N >= 3) : N -= 3 count += 1 continue if (N-2 not in NG and N >= 2) : N -= 2 count += 1 continue if (N-1 not in NG and N >= 1) : N -= 1 count += 1 continue print("NO") return if (count <= 100) : print("YES") else : print("NO") main()
0dc5e8f746b8b47a3713b3d966f932dffe8e0198
meniscus/AtCoder
/ABC/ABC086/B.py
129
3.640625
4
import math a,b = input().split() n = int(a + b) if (math.sqrt(n).is_integer()) : print("Yes") else : print("No")
44ea05fa94fab3758aba1b5e04d258abdfa13d02
meniscus/AtCoder
/ABC/ABC009/B.py
289
3.71875
4
# あ dish_count = int(input()) price_list = [] for i in range(dish_count) : price_list.append(int(input())) price_list.sort() price = price_list[-1] for current_price in price_list[::-1] : if (current_price != price) : price = current_price break print(price)
fa37bcbb0cc8facf64ace865e43b68a91fca7d1d
saurav-singh/CS380-AI
/Assignment 3/connect3.py
9,545
3.578125
4
import math import random import sys import time CONNECT = 3 COLS = 4 ROWS = 3 EMPTY = ' ' TIE = 'TIE' PLAYER1 = 'X' PLAYER2 = 'O' class Connect3Board: def __init__(self, string=None): if string is not None: self.b = [list(line) for line in string.split('|')] else: self.b = [list(EMPTY * ROWS) for i in range(COLS)] def compact_string(self): return '|'.join([''.join(row) for row in self.b]) def clone(self): return Connect3Board(self.compact_string()) def get(self, i, j): return self.b[i][j] if i >= 0 and i < COLS and j >= 0 and j < ROWS else None def row(self, j): return [self.get(i, j) for i in range(COLS)] def put(self, i, j, val): self.b[i][j] = val return self def empties(self): return self.compact_string().count(EMPTY) def first_empty(self, i): j = ROWS - 1 if self.get(i, j) != EMPTY: return None while j >= 0 and self.get(i, j) == EMPTY: j -= 1 return j+1 def place(self, i, label): j = self.first_empty(i) if j is not None: self.put(i, j, label) return self def equals(self, board): return self.compact_string() == board.compact_string() def next(self, label): boards = [] for i in range(COLS): j = self.first_empty(i) if j is not None: board = self.clone() board.put(i, j, label) boards.append(board) return boards def _winner_test(self, label, i, j, di, dj): for _ in range(CONNECT-1): i += di j += dj if self.get(i, j) != label: return False return True def winner(self): for i in range(COLS): for j in range(ROWS): label = self.get(i, j) if label != EMPTY: if self._winner_test(label, i, j, +1, 0) \ or self._winner_test(label, i, j, 0, +1) \ or self._winner_test(label, i, j, +1, +1) \ or self._winner_test(label, i, j, -1, +1): return label return TIE if self.empties() == 0 else None def __str__(self): return stringify_boards([self]) def stringify_boards(boards): if len(boards) > 6: return stringify_boards(boards[0:6]) + '\n' + stringify_boards(boards[6:]) else: s = ' '.join([' ' + ('-' * COLS) + ' '] * len(boards)) + '\n' for j in range(ROWS): rows = [] for board in boards: rows.append('|' + ''.join(board.row(ROWS-1-j)) + '|') s += ' '.join(rows) + '\n' s += ' '.join([' ' + ('-' * COLS) + ' '] * len(boards)) return s # ----------------------------------------------------------------------------------- # AI Players Implementation # ----------------------------------------------------------------------------------- # Player Class class Player: def __init__(self, label): self.label = label # Random Player class RandomPlayer(Player): def __init__(self, label): super().__init__(label) def play(self, board): moves = board.next(self.label) pick = random.randint(0, len(moves)-1) return moves[pick] # Minimax player class MinimaxPlayer(Player): def __init__(self, label): super().__init__(label) # Define Opponent self.opponent = PLAYER1 if self.label == PLAYER1: self.opponent = PLAYER2 # Tree depth reducer self.reducer = 0.7 def maximize(self,board): # Check end state endState = board.winner() if self.terminal_test(endState): return None, self.utility(endState) * self.reducer # Create possible actions to maximize move, value = None, -99999 actions = board.next(self.label) # Compute minimax for each action for action in actions: _, checkValue = self.minimize(action) if checkValue > value: move, value = action, checkValue * self.reducer return move, value def minimize(self, board): # Check end state endState = board.winner() if self.terminal_test(endState): return None, self.utility(endState) * self.reducer # Create possible actions to minimize move, value = None, 99999 actions = board.next(self.opponent) # Compute minimax for each action for action in actions: _, checkValue = self.maximize(action) if checkValue < value: move, value = action, checkValue * self.reducer return move, value def terminal_test(self, endState): if endState != None: return True return False def utility(self, endState): if endState == self.label: return 1000 elif endState == TIE: return 1 else: return -1000 def play(self, board): move, _ = self.maximize(board) return move #Alpha Beta Player class MinimaxAlphaBetaPlayer(MinimaxPlayer): def __init__(self, label): super().__init__(label) def maximize(self,board, alpha, beta): # Check end state endState = board.winner() if self.terminal_test(endState): return None, self.utility(endState) * self.reducer # Create possible actions to maximize move, value = None, -99999 actions = board.next(self.label) # Compute minimax for each action for action in actions: _, checkValue = self.minimize(action, alpha, beta) if checkValue > value: move, value = action, checkValue * self.reducer alpha = max(alpha, value) # Break for beta if beta <= alpha: break return move, value def minimize(self, board, alpha, beta): # Check end state endState = board.winner() if self.terminal_test(endState): return None, self.utility(endState) * self.reducer # Create possible actions to minimize move, value = None, 99999 actions = board.next(self.opponent) # Compute minimax for each action for action in actions: _, checkValue = self.maximize(action, alpha, beta) if checkValue < value: move, value = action, checkValue * self.reducer beta = min(beta, value) # Break for alpha if beta <= alpha: break return move, value def play(self, board): move, _ = self.maximize(board,-99999, 99999) return move # Game AI Class class GameAI: def __init__(self, board, mode): self.board = board self.player1 = None self.player2 = None self.timer = False self.AIname = "" if mode == 'random': self.player1 = RandomPlayer(PLAYER1) self.player2 = RandomPlayer(PLAYER2) if mode == 'minimax': self.player1 = RandomPlayer(PLAYER1) self.player2 = MinimaxPlayer(PLAYER2) self.timer = True self.AIname = "Minimax Player" if mode == 'alphabeta': self.player1 = RandomPlayer(PLAYER1) self.player2 = MinimaxAlphaBetaPlayer(PLAYER2) self.timer = True self.AIname = "AlphaBeta Player" # Gameplay simulation def gameplay(self): gamePlay = [self.board] winner = None timer = [] # Game simulation while True: # Playe 1 makes a move self.board = self.player1.play(self.board) if self.board.winner() != None: break gamePlay.append(self.board) # Player 2 makes a move if self.timer: start = time.time() self.board = self.player2.play(self.board) if self.timer: end = time.time() timer.append(round(end-start, 3)) if self.board.winner() != None: break gamePlay.append(self.board) # Game end result gamePlay.append(self.board) winner = self.board.winner() if winner != TIE: winner += " wins!" # Display result print(stringify_boards(gamePlay)) print("Result =", winner) if self.timer: print("Time by",self.AIname,"in seconds:") for _time in timer: print(str(_time) + "secs", end=" | ") print("\n") # Main function if __name__ == "__main__": if len(sys.argv) > 1: cmd = sys.argv[1] board = Connect3Board(sys.argv[2] if len(sys.argv) > 2 else None) if cmd == 'print': print(board) if cmd == 'next': boards = board.next('o') print(stringify_boards(boards)) if cmd == 'random': gameAI = GameAI(board, "random") gameAI.gameplay() if cmd == 'minimax': gameAI = GameAI(board, "minimax") gameAI.gameplay() if cmd == 'alphabeta': gameAI = GameAI(board, "alphabeta") gameAI.gameplay()
6bafbfbbf5306c1daa9bf05643d7e75c6933f2eb
TonnyL/MyPythonLearnProject
/customized_class.py
7,745
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 定制类 # 看到类似__slots__这种形如__xxx__的变量或者函数名就需要注意,在python中是有特殊用途的 # __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让class作用于len()函数 # 除此之外,python的class中还有很多这样有特殊用途的函数,可以帮助我们定制类 # __str__ # 我们先定义一个Student类 class Student(object): def __init__(self, name): self.name = name print Student('Tony') # <__main__.Student object at 0x02A780B0> # 打印出了对象的地址 # 怎样才能打印出更加好看的信息呢? # 只需要定义好__str__()方法,返回一个好看的字符串就好了 class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name:%s)' % self.name s = Student('Tony') print s # Student object (name:Tony) # 同时也可以将调试时使用的方法__repr__()的方法一同写上 class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name:%s)' % self.name __repr__ = __str__ # __iter__ # 如果一个类想被用于for ... in 循环,类似list和tupel那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象 # 然后,python的for循环就会不断调用该迭代对象的next()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环 # 我们以斐波那契数列为例,写一个Fib类,可以作用于for循环: class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def next(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100: # 退出循环的条件 raise StopIteration(); return self.a # 返回下一个值 # 现在,试试把Fib实例作用于for循环: for n in Fib(): print n # 1 # 1 # 2 # 3 # 5 # 8 # 13 # 21 # 34 # 55 # 89 # __getitem__ # Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行,比如,取第5个元素: # print Fib()[5] # TypeError: 'Fib' object does not support indexing # 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法: class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a # 现在,就可以按下标访问数列的任意一项了: f = Fib() print f[0] print f[1] print f[2] # 1 # 1 # 2 # 但是list有个神奇的切片方法: print range(100)[5:10] # [5, 6, 7, 8, 9] # 对于Fib却报错。原因是__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice,所以要做判断: class Fib(object): def __getitem__(self, n): if isinstance(n, int): a, b = 1, 1 for x in range(n): a, b = b, a + b return a if isinstance(n, slice): start = n.start stop = n.stop a, b = 1, 1 L = [] for x in range(stop): if x >= start: L.append(a) a, b = b, a + b return L # 现在试试Fib的切片: f = Fib() print f[0: 5] # [1, 1, 2, 3, 5] # 但是没有对step参数作处理: print f[:10:2] # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # 也没有对负数作处理,所以,要正确实现一个__getitem__()还是有很多工作要做的。 # 此外,如果把对象看成dict,__getitem__()的参数也可能是一个可以作key的object,例如str。 # 与之对应的是__setitem__()方法,把对象视作list或dict来对集合赋值。最后,还有一个__delitem__()方法,用于删除某个元素。 # 总之,通过上面的方法,我们自己定义的类表现得和Python自带的list、tuple、dict没什么区别 # 这完全归功于动态语言的“鸭子类型”,不需要强制继承某个接口。 # __getattr__ # 正常情况下,当我们调用类的方法或属性时,如果不存在,就会报错。比如定义Student类: class Student(object): def __init__(self): self.name = 'Tony' # 调用name属性,没问题,但是,调用不存在的score属性,就有问题了: s = Student() print s.name # TOny # print s.score AttributeError: 'Student' object has no attribute 'score' # 错误信息很清楚地告诉我们,没有找到score这个attribute。 # 要避免这个错误,除了可以加上一个score属性外,Python还有另一个机制,那就是写一个__getattr__()方法,动态返回一个属性 # 修改如下: class Student(object): def __init__(self): self.name = 'Tony' def __getattr__(self, attr): if attr=='score': return 99 # 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性 # 这样,我们就有机会返回score的值: s = Student() print s.score # 99 # 返回函数也是完全可以的: class Student(object): def __getattr__(self, attr): if attr=='age': return lambda: 25 # 只是调用方式要变为: s = Student() print s.age() # 25 # 注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。 # 此外,注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__默认返回就是None # 要让class只响应特定的几个属性,我们就要按照约定,抛出AttributeError的错误: class Student(object): def __getattr__(self, attr): if attr=='age': return lambda: 25 raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) # 这实际上可以把一个类的所有属性和方法调用全部动态化处理了,不需要任何特殊手段。 # 这种完全动态调用的特性有什么实际作用呢?作用就是,可以针对完全动态的情况作调用。 # __call__ # 一个对象实例可以有自己的属性和方法,当我们调用实例方法时,我们用instance.method()来调用 # 能不能直接在实例本身上调用呢?类似instance()?在Python中,答案是肯定的。 # 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。请看示例: class Student(object): def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name) # 调用方式如下: s = Student('Tony') s() # My name is Tony. # __call__()还可以定义参数 # 对实例进行直接调用就好比对一个函数进行调用一样,所以你完全可以把对象看成函数,把函数看成对象 # 因为这两者之间本来就没啥根本的区别 # 如果你把对象看成函数,那么函数本身其实也可以在运行期动态创建出来,因为类的实例都是运行期创建出来的 # 这么一来,我们就模糊了对象和函数的界限 # 那么,怎么判断一个变量是对象还是函数呢? # 其实,更多的时候,我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象 # 比如函数和我们上面定义的带有__call()__的类实例: print callable(Student('Tony')) print callable(max) print callable([1, 2, 3]) print callable(None) # True # True # False # False # 通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。
92419ef8e44be3168761d2b5b043d4cc22f9b0cf
TonnyL/MyPythonLearnProject
/handle_error.py
6,259
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 错误处理 # 在程序运行过程中,如果发生了错误,可以实现约定返回一个错误代码 # 这样就可以知道是否出错,以及出错的原因 # 用错误码表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起 # 造成调用者必须用大量的代码判断是否出错 # 在java中,可以使用try...catch...finally语句捕获错误 # 在python中也可以try...catch机制 try: print 'try...' r = 10 / 0 print 'result:', r except ZeroDivisionError, e: print 'except:', e finally: print 'finally...' print 'END' # try... # except: integer division or modulo by zero # finally... # END # 当我们认为某些代码可能会出错时,就可以用try来运行这段代码 # 如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块 # 执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕 # 从输出可以看到,当错误发生时,后续语句print 'result:' # r不会被执行,except由于捕获到ZeroDivisionError,因此被执行 # 最后,finally语句被执行。然后,程序继续按照流程往下走。 # 如果把除数0改成2,则执行结果如下 try: print 'try...' r = 10 / 2 print 'result:', r except ZeroDivisionError, e: print 'except:', e finally: print 'finally...' print 'END' # try... # result: 5 # finally... # END # 由于没有错误发生,所以except语句块不会被执行 # 但是finally如果有,则一定会被执行(可以没有finally语句) # 可以有多个except来捕获不同类型的错误: try: print 'try...' r = 10 / int('a') print 'result:', r except ValueError, e: print 'ValueError:', e except ZeroDivisionError, e: print 'ZeroDivisionError:', e finally: print 'finally...' print 'END' # int()函数可能会抛出ValueError,所以我们用一个except捕获ValueError # 用另一个except捕获ZeroDivisionError # 此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句: try: print 'try...' r = 10 / int('a') print 'result:', r except ValueError, e: print 'ValueError:', e except ZeroDivisionError, e: print 'ZeroDivisionError:', e else: print 'no error!' finally: print 'finally...' print 'END' # Python的错误其实也是class,所有的错误类型都继承自BaseException,所以在使用except时需要注意的是 # 它不但捕获该类型的错误,还把其子类也“一网打尽”。比如: # try: # foo() # except StandardError, e: # print 'StandardError' # except ValueError, e: # print 'ValueError' # 第二个except永远也捕获不到ValueError,因为ValueError是StandardError的子类 # 如果有,也被第一个except给捕获了 # 使用try...except捕获错误还有一个巨大的好处,就是可以跨越多层调用 # 比如函数main()调用foo(),foo()调用bar(),结果bar()出错了,这时,只要main()捕获到了,就可以处理 # 也就是说,不需要在每个可能出错的地方去捕获错误,只要在合适的层次去捕获错误就可以了 # 这样一来,就大大减少了写try...except...finally的麻烦 # 记录错误 # 如果不捕获错误,自然可以让Python解释器来打印出错误堆栈,但程序也被结束了 # 既然我们能捕获错误,就可以把错误堆栈打印出来,然后分析错误原因,同时,让程序继续执行下去 # Python内置的logging模块可以非常容易地记录错误信息: # err.py # import logging # # def foo(s): # return 10 / int(s) # # def bar(s): # return foo(s) * 2 # # def main(): # try: # bar('0') # except StandardError, e: # logging.exception(e) # # main() # print 'END' # 同样是出错,但程序打印完错误信息后会继续执行,并正常退出 # $ python err.py # ERROR:root:integer division or modulo by zero # Traceback (most recent call last): # File "err.py", line 12, in main # bar('0') # File "err.py", line 8, in bar # return foo(s) * 2 # File "err.py", line 5, in foo # return 10 / int(s) # ZeroDivisionError: integer division or modulo by zero # END # 通过配置,logging还可以把错误记录到日志文件里,方便事后排查。 # 抛出错误 # 因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的 # Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。 # 如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例: # err.py # class FooError(StandardError): # pass # # def foo(s): # n = int(s) # if n==0: # raise FooError('invalid value: %s' % s) # return 10 / n # 执行,可以最后跟踪到我们自己定义的错误: # $ python err.py # Traceback (most recent call last): # ... # __main__.FooError: invalid value: 0 # 只有在必要的时候才定义我们自己的错误类型。如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError) # 尽量使用Python内置的错误类型 # 最后,我们来看另一种错误处理的方式: # err.py def foo(s): n = int(s) return 10 / n def bar(s): try: return foo(s) * 2 except StandardError, e: print 'Error!' raise def main(): bar('0') main() # 捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误 # 所以,最恰当的方式是继续往上抛,让顶层调用者去处理 # raise语句如果不带参数,就会把当前错误原样抛出 # 此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型: try: 10 / 0 except ZeroDivisionError: raise ValueError('input error!') # 只要是合理的转换逻辑就可以,但是,决不应该把一个IOError转换成毫不相干的ValueError
9cd1139f3d2331ef93f33c0167f986476fc25168
TonnyL/MyPythonLearnProject
/debug.py
3,044
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 调试 # 程序能一次运行成功的概率很小,总是会各种各样的错误 # 有的错误很简单,看看错误信息就能解决,有的bug很复杂,我们需要知道出错时,哪些变量的值时正确的 # 哪些变量的值时错误的,因此,需要以一整套的调试程序来修复bug # 第一种方法简单粗暴有效,就是直接print把可能出错的bug值打印出来 # def foo(s): # n = int(s) # print '>>> n = %d' % n # return 10 / n # # def main(): # foo('0') # # main() # >>> n = 0 # ZeroDivisionError: integer division or modulo by zero # 用print最大的坏处就是将来还得删掉它,程序里到处都是print,运行结果也包含很多的垃圾信息 # 第二种方法,断言 # 凡是能print来辅助查看的地方,都可以用断言assert来替代 # def foo(s): # n = int(s) # assert n != 0, 'n is zero!' # return 10 / n # # def main(): # foo('0') # assert的意思是,表达式n != 0应该是True,否则后面的代码就出错 # 如果断言失败,assert语句本身就会抛出AssertError: # Traceback (most recent call last): # ... # AssertionError: n is zero! # 程序中到处充斥这断言,和print相比好不到哪里去 # 不过,启动python解释器时可以用-o参数来关闭assert # $ python -0 err.py # Traceback (most recent call last): # ... # ZeroDivisionError: integer division or modulo by zero # 关闭后,就可把所有的assert语句当成pass语句来看了 # logging # 把print替换成logging是第三种方式,和assert相比,logging不会抛出错误,而且可以输出到文件 import logging s = '0' n = int(s) logging.info('n = %d' % n) print 10 / n # logging.info()就可以输出一段文本。运行,发现除了ZeroDivisionError,没有任何信息。怎么回事? # 在import logging后添加一行配置就行了 logging.basicConfig(level=logging.INFO) s = '0' n = int(s) logging.info('n = %d' % n) print 10 / n # 输出 # Traceback (most recent call last): # File "D:/PythonProjects/MyPythonLearnProject/debug.py", line 52, in <module> # print 10 / n # ZeroDivisionError: integer division or modulo by zero # 这就是logging的好处,它允许你指定记录信息的级别,有debug,info,warning,error等几个级别 # 当指定level=logging.INFO时,logging.debug就不起作用了 # 同理,指定level=WARNING时,debug和info就不起作用了 # 这样一来,就可以放心地输出不同级别的信息,也不用删除,最后统一指定输出哪个级别的信息 # logging的另一个好处就是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件 # pdb # 第四种方式就是启动python的调试器pdb,让程序单步运行,可以随时查看运行状态 # pdb.set_trace() # 这个方法也是用pdb,但是不需要单步执行,只需要import pdb,然后在可能出错的地方放一个pdb.set_trace() # 就设置了一个断点
66da83e7687f9d598add37baee9aecf6ff44c10a
shfhm/Practice-Python
/Check Power of 2.py
226
4.40625
4
#function that can determine if an input number is a power of 2 import math def sqrtt(x): i=math.sqrt(x) if i**2==x: print('the input is power 2 of %s' %(i) ) else: print('it\'s not the power 2')
6951253d9c50aa9b9c7f7382b3084128cd299c16
shfhm/Practice-Python
/Symmetric binary tree.py
1,151
3.953125
4
#symmetric binary tree. Given a binary tree, check whether it is a mirror of itself. #Runtime: 44 ms from collections import deque class treenode(object): def __init__(self, root): self.val=root self.left=None self.right=None class solution(object): def symmetric(self, root): if (root == None): return True q=deque() #q=[] q.append(root.left) q.append(root.right) while q: left=q.pop() right=q.pop() if (left is None) and (right is None): continue if (left is None) or (right is None): return False if left.val == right.val: q.append(left.left) q.append(right.right) q.append(left.right) q.append(right.left) else: return False return True s=solution() root=treenode(1) root.left=treenode(2) root.right=treenode(2) root.left.left=treenode(3) root.right.right=treenode(3) root.left.right=treenode(4) root.right.left=treenode(4) print(s.symmetric(root))
4ac23cb0e3f3a32bbbb9af3482a830619d358a0f
shfhm/Practice-Python
/Game-Guess.py
305
4.0625
4
__author__ = 'Sahar' from random import randint random_number = randint(1, 8) print(random_number) guesses_left = 3 while guesses_left >= 0: guess=int(input("gues a number: ")) if guess==random_number: print("you win!") break guesses_left = guesses_left -1 else: print ("you lose!")
c4d2a86f4345f182b2f795745239848eea347665
Cjmacdonald/AI-Revised
/AI-Spring2018-HW1/tictactoePy/MyAgent.py
6,901
3.59375
4
import random from Const import Const from Move import Move from State import State """This agent prioritizes consecutive moves by placing marks on spots that are next spots that already have marks on them otherwise it defaults to random playable spots""" class MyAgent: def __init__(self): pass def move(self,state): mark = None if state.getState() == Const.STATE_TURN_O: mark = Const.MARK_O if state.getState() == Const.STATE_TURN_X: mark = Const.MARK_X if mark == None: raise ValueError("state must be playable") board = state.getBoard() playable = [] for row in range(Const.ROWS): for col in range(Const.COLS): if board[row][col] == Const.MARK_NONE: # Added checks to see if next move wins (if there is 2 O's in a row already) # TODO: make win moves work if row+2 < Const.ROWS and board[row+1][col] == Const.MARK_O and board[row+2][col] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move1") return Move(playable[spot][0],playable[spot][1],mark) if row-2 >= 0 and board[row-1][col] == Const.MARK_O and board[row-2][col] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move2") return Move(playable[spot][0],playable[spot][1],mark) if col+2 < Const.COLS and board[row][col+1] == Const.MARK_O and board[row][col+2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move3") return Move(playable[spot][0],playable[spot][1],mark) if col-2 >= 0 and board[row][col-1] == Const.MARK_O and board[row][col-2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move4") return Move(playable[spot][0],playable[spot][1],mark) if col+2 < Const.COLS and row+2 < Const.ROWS and board[row+1][col+1] == Const.MARK_O and board[row+2][col+2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move5") return Move(playable[spot][0],playable[spot][1],mark) if col-2 >= 0 and row-2 >= 0 and board[row-1][col-1] == Const.MARK_O and board[row-2][col-2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move6") return Move(playable[spot][0],playable[spot][1],mark) if col-2 >= 0 and row+2 < Const.ROWS and board[row+1][col-1] == Const.MARK_O and board[row+2][col-2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move7") if col+2 < Const.COLS and row-2 >= 0 and board[row-1][col+1] == Const.MARK_O and board[row-2][col+2] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("win move8") # TODO: add if checks to block opponents win # each of these if checks check to see if an O mark is next to a playable spot in all directions adjacent to the playable spot # Compared to random agentO vs random agentX, this agent should result in more wins for agentO (assumming you assign MyAgent to agentO and Random to agentX) if row+1 < Const.ROWS and board[row+1][col] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move1") return Move(playable[spot][0],playable[spot][1],mark) if row-1 >= 0 and board[row-1][col] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move2") return Move(playable[spot][0],playable[spot][1],mark) if col+1 < Const.COLS and board[row][col+1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move3") return Move(playable[spot][0],playable[spot][1],mark) if col-1 >= 0 and board[row][col-1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move4") return Move(playable[spot][0],playable[spot][1],mark) if row+1 < Const.ROWS and col+1 < Const.COLS and board[row+1][col+1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move5") return Move(playable[spot][0],playable[spot][1],mark) if row+1 < Const.ROWS and col-1 >= 0 and board[row+1][col-1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move6") return Move(playable[spot][0],playable[spot][1],mark) if row-1 >= 0 and col+1 < Const.COLS and board[row-1][col+1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move7") return Move(playable[spot][0],playable[spot][1],mark) if row-1 >= 0 and col-1 >= 0 and board[row-1][col-1] == Const.MARK_O: spot=board[row][col] playable.append([row,col]) print("priority move8") return Move(playable[spot][0],playable[spot][1],mark) # TODO: add if checks to prioritize edge moves over random moves # TODO: add if checks to prioritize center move over random moves else: #defaults to random move if no consecutive move possibility exists playable.append([row,col]) spot=random.randint(0,len(playable)-1) print("random move") return Move(playable[spot][0],playable[spot][1],mark)
2e70910939fedcde1d3c98da05618a8ff871abd0
diego-ponce/code_snippets
/code_challenges/sort_stack.py
1,380
4.15625
4
def pop_until(fromstack, tostack, val): ''' pops from fromstack onto tostack until val is greater than the last value popped. Returns the count of items popped. ''' count = 0 while fromstack: if fromstack[-1] < val: return count pop_val = fromstack.pop() tostack.append(pop_val) count += 1 return count def push_until(fromstack, tostack, n): ''' pushes values from fromstack onto tostack n times ''' for _ in range(n): tostack.append(fromstack.pop()) def sort_stack(astack:list) -> list: ''' sorts elements from astack onto a tmpstack and returns the sorted tmpstack. astack is emptied of values. ''' tmpstack = [] while astack: val = astack.pop() # tmpstack is empty if not tmpstack: tmpstack.append(val) # tmpstack is ordered when appending val elif tmpstack[-1] < val: tmpstack.append(val) # tmpstack is unordered when appending val, so pop tmpstack until # the order is retained, then push popped (previously ordered) values back onto tmpstack else: depth = pop_until(tmpstack, astack, val) tmpstack.append(val) push_until(astack, tmpstack, depth) return tmpstack astack = [1,-11,0,1,2] print(sort_stack(astack))
cf720b2093c9c009d76c3ea8c4bfba9f4f65f80c
sag-coder/python_test
/commend.py
642
3.828125
4
##insert i e: Insert integer at position . ##print: Print the list. ##remove e: Delete the first occurrence of integer . ##append e: Insert integer at the end of the list. ##sort: Sort the list. ##pop: Pop the last element from the list. ##reverse: Reverse the list. #input #12 #insert 0 5 #insert 1 10 #insert 0 6 #print #remove 6 #append 9 #append 1 #sort #print #pop #reverse #print N = int(input()) lis = [] for i in range(N): s = input().split() commend = s[0] argument = s[1:] if commend !="print": commend += "("+ ",".join(argument) +")" eval("lis."+commend) else: print(lis)
dcd7e05257407fdddf7ff13f2fe19a2fe4f50c43
KUHZ/papercode
/vnode.py
1,023
3.84375
4
#video node import turtle import math p1 = math.sqrt(3) p2 = 1 + p1 vpos = []#position of Vnode class VNode(): def __init__(self,level,angle,radius,px,py): self.level = level self.radius = radius self.angle = angle #vision of video node self.px = px #position x self.py = py #position y def draw(self): #window = turtle.Screen() node = turtle.Turtle() node.shape("circle") node.shapesize(0,0,0) node.color("black") node.penup() node.goto(self.px,self.py) #print(node.position()) vpos.append(node.pos()) node.pendown() node.speed(0) node.circle(self.radius) node.penup() node.goto(self.px,self.py-p1*self.radius) #print(node.position()) node.pendown() node.circle(p2*self.radius) #window.exitonclick() #node1 = VNode(1,1,50,0,-50) #node1.draw()
ae56bc91c4fe03e9d6e2066aa43858cf2b3c63b1
houxianxu/learnToProgramCoursera
/week4/a2.py
2,929
4.34375
4
#!/usr/bin/python3.2 def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return get_length(dna1) - get_length(dna2) > 0 def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ res = 0 for i in dna: if i == nucleotide: res += 1 return res def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ res = dna1.find(dna2) if res == -1: return False else: return True def is_valid_sequence(dna): """ (str) -> bool Return True if and only if the DNA sequence is valid (that is, it contains no characters other than 'A', 'T', 'C' and 'G'). >>> is_valid_sequence('ATCGGC') True >>> is_valid_sequence('AFDATCGGC') False """ res = True for i in dna: if i not in 'AGCT': res = False break else: continue return res def insert_sequence(dna1, dna2, index): """(str, str, int) -> str Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index. >>>insert_sequence('CCGG', 'AT', 2) 'CCATGG' """ res = '' len1 = get_length(dna1) len2 = get_length(dna2) if index == 0: res = dna2 + dna1 elif index == len1: res = dna1 + dna2 else: for i in range(index): res += dna1[i] for item in dna2: res += item for i in range(index, len1): res += dna1[i] return res def get_complement(nucleotide): """ (str) -> str Return the nucleotide's complement. >>>get_complement('A') T >>>get_complement('C') G """ if nucleotide == 'A': return 'T' elif nucleotide == 'T': return 'A' elif nucleotide == 'G': return 'C' elif nucleotide == 'C': return 'G' def get_complementary_sequence(dna): """ (str) -> str Return the DNA sequence that is complementary to the given DNA sequence. >>> get_complementary_sequence('ATCG') TAGC """ res = '' for i in dna: res += get_complement(i) return res
31f8f6c8e86fa995259a94e0d0eb8f0f38aa002b
abdulbasit01/hello-pythonists
/final/basic.py
3,885
4.21875
4
#turtle graphics game import os import turtle import math#(when both object snake and their food touches each other then their distance is very small ) import random import time os.system("Main Tere Kabil Hoon ke nahi.mp3&") color_choice=["grey","red","yellow","blue","powder blue","brown","orange"] #launch turtle window wn= turtle.Screen() wn.title(' basic module of turtle GAME') wn.bgcolor("black") #wn.bgpic("tumblr_mduqruzbIc1qktq7uo1_500.gif") #draw border #first define new turtle st=turtle.Turtle() st.penup() mypen=turtle.Turtle() mypen.penup() mypen.setposition(-350,-350) mypen.hideturtle() mypen.color("blue") mypen.down() mypen.pensize(3) mypen.penup for side in range (4): mypen.forward(700) mypen.left(90) score=0 mypen.hideturtle() #we create player in turtle: player=turtle.Turtle() player.color("grey") player.shape("turtle") player.penup()#it can't show the tail of turtle player.speed(0) #create some achivements score=0 achiv=turtle.Turtle() achiv.color(random.choice(color_choice)) achiv.shape("square") achiv.penup() achiv.setposition(random.randint(-200,200),random.randint(-150,230)) speed=1 #it just like the var that in the loop continues the turtle #keyboard binding def left(): player.left(90) def right(): player.right(90) def pause (): global speed speed-=speed def resume(): global speed speed=2 #making function which increase the speed of player def increaseSpeed(): global speed speed+=0.1 if speed==2: speed-=0.2 def decreaseSpeed(): global speed speed-=0.1 if speed==2: speed+=0.2 wn.onkey(resume, "a") wn.onkey(pause, "space") wn.onkey(left, "Left") wn.onkey(right, "Right") wn.onkey(increaseSpeed,"Up") wn.onkey(decreaseSpeed,"Down") wn.listen() while True:#(it continues the turtle whenever this loop true) player.forward(speed) #bowndary checking if player.xcor()> 330 or player.xcor() < -330: player.right(90) if player.ycor()> 330 or player.ycor() < -330: player.right(90) #collision checking d = math.sqrt(math.pow(player.xcor()-achiv.xcor(),2)+math.pow(player.ycor()-achiv.ycor(),2)) if d<15: score+=1 st.undo() st.penup() st.color("lime") st.hideturtle() st.setposition(-340,310) scorestring="score : %s" %score st.write(scorestring) #achiv.hideturtle() achiv.color(random.choice(color_choice)) achiv.setposition(random.randint(-310,310),random.randint(-310,310)) speed+=0.05 if achiv.xcor()> 330 or achiv.xcor() < -330: achiv.right(random.randint(0,360)) if achiv.ycor()> 330 or achiv.ycor() < -330: achiv.right(random.randint(0,360)) score+=1 if player.xcor()> 330 or player.xcor()<-330: player.hideturtle() achiv.hideturtle() mypen.penup() wn.bgcolor("green") new_turtle=turtle.Turtle() new_turtle.write("game over",align="center", font=("classic", 100, "bold")) new_turtle.hideturtle() time.sleep(2) if player.ycor()> 330 or player.ycor()<-330: player.hideturtle() achiv.hideturtle() mypen.penup() wn.bgcolor("green") new_turtle=turtle.Turtle() new_turtle.write("game over",align="center", font=("classic", 100, "bold") ) new_turtle.hideturtle() #move goal '''basically player and echiv are two turtles we find the distance b/w them if distance is very b/w them then achiv will dissapear or move it to a random position'''
02940a7a9b30d9bf8c2587c9168544a40df35063
emmadeeks/CMEECourseWork
/week7/code/LV2.py
4,051
3.859375
4
#!/usr/bin/env python3 #Author: Emma Deeks [email protected] #Script: LV2.py #Desc: Plots Consumer-resource population dybamics and runs the # Lotka-Volterra model for predator prey systems. This script is codifying the Lotka-Volterra model # for predator-prey system in two-dimensional space (e.g. on land). #Arguments: Has default arguments but can input LV model parameters manually: r: is intrinsic growth rate of resource population #a: per-capita "search rate", i.e. the rate at which consumers find resources units: area per time unit #z: mortality rate - units are 'per time' #e" consumer's efficiency (rate in turning mass into its own mass). no units. #Outputs: Plots two models; consumer-resource model and LV model into one subplot called consumer_resource_model_LV2.pdf #Date: Oct 2019 import numpy as np import scipy as sc import sys import matplotlib.pylab as p import scipy.integrate as integrate """ Similar to LV1 but requires inputs into the parameters but does use default values """ """ This script is codifying the Lotka-Volterra model for predator-prey system in two-dimensional space (e.g. on land). A key difference between LV1 and LV2 is LV2 uses a modified equation with constant K which is the carrying capacity Another key difference is that is takes system arguments dR/dt = rR - aCR dC/dt = -zC + eaCR C is consumer population abundance, R is resource population abundance units: number per area unit r is intrinsic growth rate of resource population a is per-capita "search rate", i.e. the rate at which consumers find resources units: area per time unit z is the mortality rate - units are 'per time' e is the consumer's efficiency (rate in turning mass into its own mass). no units. """ def dCR_dt(pops, t=0): """ Defines the Lotka volterra model with carry capacity of population e.g. two dimensional space """ R = pops[0] C = pops[1] dRdt = r * R * (1- (R / K)) - a * R * C dCdt = -z * C + e * a * R * C return sc.array([dRdt, dCdt]) # takes systemarguments as floats so decimals are allowed but if they are not supplied e.g. if there are less than # 5 system arguments inputted then it takes default values if len(sys.argv)== 5: r = float(sys.argv[1]) a = float(sys.argv[2]) z = float(sys.argv[3]) e = float(sys.argv[4]) else: print("Using default arguments:") r = 1 a = 0.1 z = 1.5 e = 0.75 #K used K = 30 # an array of consumer resource is created to be put into the function R0 = 10 C0 = 5 RC0 = sc.array([R0, C0]) #time series t = sc.linspace(0, 15, 1000) #Model is run with array of consumer resorce pops, infodict = integrate.odeint(dCR_dt, RC0, t, full_output=True) # two plots are opened next to each other fig, (ax1, ax2) = p.subplots(1,2) # plots are indexes so both pltos are plotted ont he same time series e.g. consumer and resource compared along #the same time series ax1.plot(t, pops[:,0], 'g-', label='Resource density') # Plot ax1.plot(t, pops[:,1] , 'b-', label='Consumer density') ax1.legend(loc='best') # adds legend ax1.set(xlabel = 'Time', ylabel = 'Population density') # x and y labels are put in p.ylabel('Population density') ax1.set_title('Consumer-Resource population dynamics') p.show()# To display the figure # want the input variables to be displayed on the pltos textstr = ' '.join(("r =", (str(r)))) # textstr1 = ' '.join(("a =", (str(a)))) textstr2 = ' '.join(("z =", (str(z)))) textstr3 = ' '.join(("e =", (str(e)))) final = '\n'.join((textstr, textstr1, textstr2, textstr3)) # append strings into one file props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) #make box ax2.text(0.05, 0.95, final, transform=ax2.transAxes, fontsize=9, verticalalignment='top', bbox=props) #position box props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax2.plot(pops[:,1], pops[:,0] , 'r-') p.legend(loc='best') p.xlabel('Resource density') p.ylabel('Consumer density') p.show()# To display the figure fig.savefig('../results/consumer_resource_model_LV2.pdf') #save figure
a54f2d23123a452a9a4b4ed7be2e1ea6cebf4b5b
emmadeeks/CMEECourseWork
/Week2/Code/lc1.py
2,225
4.65625
5
#!/usr/bin/env python3 #Author: Emma Deeks [email protected] #Script: lc1.py #Desc: List comprehensions compared to for loops #Arguments: No input #Outputs: Three lists containing latin names, common names and mean body masses for each species of birds in a given list of birds #Date: Oct 2019 # Creates a list of bird species, common name and body mass birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) """ Uses List comprehensions to create three lists containing latin names, common names and mean body masses for each species of birds """ #List comprehension for list with latin names first_words = {w[0] for w in birds} #Comprehension that indexes the first line of the list print("The Latin names of the birds using comprehensions: \n", first_words, "\n") #List comprehension for list with common names first_words = {w[1] for w in birds} # common name is second in list print("The common names of the birds using comprehensions:\n ", first_words, "\n") #List comprehension for list with body mass first_words = {w[2] for w in birds} # The body mass is third in the list print("The body mass of the birds using comprehensions: \n", first_words, "\n") #For loop indexing a list of latin names from a list of birds first_words = set() # This is to be appended with the desired latin names, common names and body mass # This is then printed to screen after for loop has run through index of list for w in birds: first_words.add(w[0]) print("The Latin names of the birds using for loops: \n", first_words, "\n") #For loop indexing a list of common names from a list of birds first_words = set() for w in birds: first_words.add(w[1]) print("The common names of the birds using for loops: \n", first_words, "\n") #For loop indexing a list of body mass from a list of birds first_words = set() #Creates empty set that can be appened to in for loop for w in birds: first_words.add(w[2]) print("The body mass of the birds using for loops: \n", first_words, "\n")
3e953d2ae7128c97dcdad05b1f4dd97cbd58f77d
emmadeeks/CMEECourseWork
/Week2/Sandbox/comprehension_test.py
1,903
4.46875
4
## Finds list those taxa that are oak trees from a list of species #There is a range of 10 and i will run throough the range and print the numbers- remember it starts from 0 x = [i for i in range(10)] print(x) #Makes an empty vector (not vector LIST) called x and fils it by running through the range 10 and appending the list x = [] for i in range(10): x.append(i) print(x) #i.lower means print in lower case and so just print the list made in lower case x = [i.lower() for i in ["LIST", "COMPREHENSIONS", "ARE", "COOL"]] print(x) #Makes a list then specifies the range is x and fills it in lower case and prints it x = ["LIST", "COMPREHENSIONS", "ARE", "COOL"] for i in range(len(x)): #explicit loop x[i] = x[i].lower() print(x) #Same as above but just in a different way x = ["LIST", "COMPREHENSIONS", "ARE", "COOL"] x_new = [] for i in x: #implicit loop x_new.append(i.lower()) print(x_new) #This is a nested loop and it makes a matrix. flatten matrix i believe will just ake the matrix less 3d matrix = [[1,2,3], [4,5,6], [7,8,9]] flattened_matrix = [] for row in matrix: for n in row: flattened_matrix.append(n) print(flattened_matrix) #same just in a list comprehension matrix = [[1,2,3], [4,5,6], [7,8,9]] flattened_matrix = [n for row in matrix for n in row] print(flattened_matrix) #create a set of all the first letters in a sequence of words using a loop words = (["These", "are", "some", "words"]) first_letters = set() #creates an empty set object for w in words: first_letters.add(w[0]) #only include the first letter print(first_letters) #Letters are unordered and they need to be put in order so use a comprehension #Note this still doesnt order them just does the same thing words = (["These", "are", "some", "words"]) first_letters = set() for w in words: first_letters.add(w[0]) #adding only the first letter print(first_letters)
0cca2868af0d5c598552626a20bdd749e57e2364
emmadeeks/CMEECourseWork
/Week2/Code/oaks.py
1,565
4.59375
5
#!/usr/bin/env python3 #Author: Emma Deeks [email protected] #Script: oaks.py #Desc: Uses for loops and list comprehensions to find taxa that are oak trees from a list of species. #Arguments: No input #Outputs: Oak species from list #Date: Oct 2019 """ Uses for loops and list comprehensions to find taxa that are oak trees from a list of species. """ ## Finds just those taxa that are oak trees from a list of species taxa = [ 'Quercus robur', 'Fraxinus excelsior', 'Pinus sylvestris', 'Quercus cerris', 'Quercus petraea', ] #find all species that start with quercus def is_an_oak(name): """ Find all the species that start with the name quercus """ return name.lower().startswith('quercus ') ##Using for loops oaks_loops = set() #creates an empty object for species in taxa: #calls upon the taxa list if is_an_oak(species): # calls the function and if it i add the the empty set oaks_loops.add(species) print("List of oaks found in taxa: \n", oaks_loops) #fills out species ##Using list comprehensions oaks_lc = set([species for species in taxa if is_an_oak(species)]) print("List of oaks found in taxa: \n", oaks_lc) ##Get names in UPPER CASE using for loops oaks_loops = set() for species in taxa: if is_an_oak(species): oaks_loops.add(species.upper()) print("List of oaks found in taxa: \n", oaks_loops) ##Get names in UPPER CASE using list comprehensions oaks_lc = set([species.upper() for species in taxa if is_an_oak(species)]) print("List of oaks found in taxa: \n", oaks_lc)
da6312a74a8f3c722e9ec9abece7737a37cc83ca
shruti19/algorithms
/dp/longest_1s_sequence.py
876
3.890625
4
''' Given a binary array, find the index of 0 to be replaced with 1 to get maximum length sequence of continuous ones. Example: [0, 0, 1, 0, 1, 1, 1, 0, 1, 1] #=> position: 7 [0, 1, 1, 1] #=> position: 0 ''' def longest_1s_sequence(arr): length = len(arr) so_far_max_1s = 0 count_0 = new_start = 0 current_substituted_index = best_substituted_index = 0 start_i = end_i = 0 for i in range(length): if arr[i] == 0: count_0 += 1 if count_0 == 2: new_start = current_substituted_index + 1 count_0 -= 1 current_substituted_index = i if so_far_max_1s < (i - new_start + 1): so_far_max_1s = i - new_start + 1 end_i = i start_i = new_start best_substituted_index = current_substituted_index print "substituted index: %s (%s)" % (best_substituted_index,\ arr[start_i:end_i + 1]) print "max 1's sequence length: %s\n" % (so_far_max_1s)
d3ec3a217a17c9ab7963663f0db285dfd80945e7
carinasauter/D04
/D04_ex00.py
2,018
4.25
4
#!/usr/bin/env python # D04_ex00 # Create a program that does the following: # - creates a random integer from 1 - 25 # - asks the user to guess what the number is # - validates input is a number # - tells the user if they guess correctly # - if not: tells them too high/low # - only lets the user guess five times # - then ends the program ########################################################################## # Imports import random # Body def random_guess_game(): x = random.randint(1, 25) count = 0 while count < 5: user_input = '' while user_input == '': try: user_input = int( input("Please guess my number between 1 and 25: ")) if 1 <= user_input < x: print("Too low, you have " + str(4 - count) + " attempts left") count += 1 elif x < user_input <= 25: print("Too high, you have " + str(4 - count) + " attempts left") count += 1 elif user_input == x: print('You guessed correctly!') count = 7 else: print("That integer is not between 1 and 25.\nYou have " + str(4 - count) + " attempts left") count += 1 except: count += 1 if count == 5: print('That was not a valid input.') break else: print("That was not a valid input. Please insert an integer between 1 and 25.\nYou have " + str(5 - count) + " attempts left") if count == 5: print("Sorry, you ran out of attempts") ########################################################################## def main(): return random_guess_game() if __name__ == '__main__': main()
bcb342822398eb8de7542d6d833def1909d5e860
josue-arana/LeetCode_Challenges
/Queue_implementation_using_stacks.py
3,120
4.25
4
# ------ QUEUE IMPLEMENTATION USING TWO STACKS -------- # # By Josue Arana # Python Solution # ------- Personal Analysis --------- # # Time Complexity: push O(1), pop O(n), peek O(n), empty O(1) # Space Complexity: O(2n) ~ O(n) # ------- Leetcode Analysis --------- # # 17 / 17 test cases passed. # Status: Accepted # Runtime: 32 ms, faster than 44.49% of Python3 online submissions for Implement Queue using Stacks. # Memory Usage: 14.1 MB, less than 5.24% of Python3 online submissions for Implement Queue using Stacks. class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack1 = MyStack() self.stack2 = MyStack() def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.stack1.push(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ #If the second stack is empty then we move all the elements from #stack1 to stack2 and then pop. if self.stack2.isEmpty(): #Reverse the stack1 ans save it into stack2 for i in range(0, self.stack1.size()): self.stack2.push(self.stack1.pop()) #if stack2 is not empty, we just pop the last element. return self.stack2.pop() def peek(self) -> int: """ Get the front element. """ #If the second stack is empty then we move all the elements from #stack1 to stack2 and then pop. if self.stack2.isEmpty(): #Reverse the stack1 ans save it into stack2 for i in range(0, self.stack1.size()): self.stack2.push(self.stack1.pop()) #if stack2 is not empty, we just pop the last element. return self.stack2.top() def empty(self) -> bool: """ Returns whether the queue is empty. """ return self.stack1.isEmpty() and self.stack2.isEmpty() # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty() ### This is an implementation of a Stack using arrays ### class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = [] def push(self, x: int) -> None: """ Push element x onto stack. """ self.stack.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.stack.pop() def top(self) -> int: """ Get the top element. """ return self.stack[len(self.stack)-1] def isEmpty(self) -> bool: """ Returns whether the stack is empty. """ return self.stack == [] def size(self) -> int: """ Returns the size of the stack """ return len(self.stack)
098556b0003a35c50a5631496c5d24c38a7c3e12
CODEvelopPSU/Lesson-4
/pythonTurtleGame.py
1,176
4.5
4
from turtle import * import random def main(): numSides = int(input("Enter the number of sides you want your shape to have, type a number less than 3 to exit: ")) while numSides >= 3: polygon(numSides) numSides = int(input("Enter the number of sides you want your shape to have, type a number less than 3 to exit: ")) else: print("Thank you for using the polygon generator!") def polygon(x): sideLength = 600/x colors = ["gold", "red", "blue", "green", "purple", "black", "orange"] shapeColor = random.choice(colors) borderColor = random.choice(colors) borderSize = (x % 20) + 1 makePolygon(x, sideLength, borderColor, borderSize, shapeColor) def makePolygon(sides, length, borderColor, width, fillColor): clear() angle = 360/sides shape("turtle") pencolor(borderColor) fillcolor(fillColor) pensize(width) begin_fill() while True: if sides != 0: forward(length) left(angle) sides -= 1 else: break end_fill() main()
1afc094e86c04fbbafa1dd7d910469975701b87d
JFelipeFloresS/hangman-python
/hangman.py
9,101
3.515625
4
import math from unicodedata import decimal from wordboard import * from getword import * import pygame pygame.init() win_width = 1200 win_height = 440 win = pygame.display.set_mode((win_width, win_height)) pygame.display.update() pygame.display.set_caption("Hangman") source_array = ["urban-dictionary", "vocabulary.com", "animals", "random"] source = "urban-dictionary" min_size = 4 max_size = 10 def get_word(): global source, min_size, max_size if source == "urban-dictionary": return get_word_from_urban_dictionary(min_size, max_size) elif source == "vocabulary.com": return get_word_from_vocabulary(min_size, max_size) elif source == "animals": return get_word_from_animals(min_size, max_size) else: return get_word_from_random_words(min_size, max_size) def restart_game(): draw_text(win, "PRESS ESC TO GO TO MAIN MENU OR ENTER TO START A NEW GAME", 20, (180, 180, 180), (win_width / 2) + 50, win_height - 20) def game_over(word): draw_text(win, "GAME OVER", 50, (255, 0, 0), (win_width / 2) - 100, 50) draw_text(win, "THE WORD WAS ", 35, (180, 180, 180), (win_width / 2) - 100, 100) draw_text(win, word.upper(), 45, (220, 220, 220), (win_width / 2) - 100, 140) restart_game() def game_won(): draw_text(win, "YOU GUESSED IT", 50, (0, 255, 50), (win_width / 2) - 100, 50) restart_game() def draw_meaning(meaning): length = 40 if len(meaning) > length: rows = len(meaning)/length m_array = [] start = 0 end = length for i in range(round(rows) + 1): if end > len(meaning): end = len(meaning) m_array.append(meaning[start:end]) start += length end += length pos_y = 10 for row in m_array: draw_text(win, row, 20, (255, 255, 255), 750, pos_y, False) pos_y += 25 else: draw_text(win, meaning, 25, (255, 255, 255), 700, 60, False) def main(): error_message = "" if source == "urban-dictionary" or source == "vocabulary.com": word, meaning = get_word() board = WordBoard(word) board.meaning = meaning else: word = get_word() board = WordBoard(word) show_meaning = False while True: # draw stuff win.fill((0, 0, 0)) board.draw_man(win) board.draw_blanks(win) board.draw_guessed(win) board.draw_wrong(win) if show_meaning: draw_meaning(board.meaning) # end game if more than 5 wrong guesses if board.size >= 6: game_over(word) draw_meaning(board.meaning) # check if game is won is_guessed = True for guess in board.guessed: if not guess: is_guessed = False if is_guessed: game_won() draw_meaning(board.meaning) # draw error message if error_message is not None: draw_text(win, error_message, 20, (255, 255, 255), 350, 20, False) # draw score draw_text(win, "SCORE: " + str(board.score), 20, (255, 255, 255), 260, win_height - 30) # update window pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: main_menu() if event.key == pygame.K_F1: show_meaning = True elif event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: show_meaning = False if is_guessed: board.score += 1 if source == "urban-dictionary" or source == "vocabulary.com": word, meaning = get_word() board.new_word(word) board.meaning = meaning else: word = get_word() board = WordBoard(word) elif board.size < 6 and not is_guessed: error_message = board.check_input(pygame.key.name(event.key)) if event.type == pygame.KEYUP: if event.key == pygame.K_F1: show_meaning = False def manage_options(pos): global source, min_size, max_size min_colour = (255, 255, 255) max_colour = (255, 255, 255) source_colour = (255, 255, 255) exit_colour = (255, 255, 255) if pos == 0: min_colour = (0, 255, 255) elif pos == 1: max_colour = (0, 255, 255) elif pos == 2: source_colour = (0, 255, 255) elif pos == 3: exit_colour = (0, 255, 255) draw_text(win, "OPTIONS", 50, (255, 255, 255), win_width / 2, 75) draw_text(win, "MIN LETTERS: ", 30, (255, 255, 255), (win_width / 2) - 25, 200) draw_text(win, str(min_size), 30, min_colour, (win_width / 2) + 100, 200) draw_text(win, "MAX LETTERS: ", 30, (255, 255, 255), (win_width / 2) - 25, 250) draw_text(win, str(max_size), 30, max_colour, (win_width / 2) + 100, 250) draw_text(win, "SUBJECT: ", 30, (255, 255, 255), (win_width / 2) - 120, 300) draw_text(win, source.upper(), 30, source_colour, (win_width / 2) + 100, 300) draw_text(win, "BACK TO MAIN MENU", 28, exit_colour, win_width / 2, 400) def options_menu(): global source, min_size, max_size, source_array pos = 0 subject = 0 options = 4 while True: win.fill((0, 0, 0)) source = source_array[subject] manage_options(pos) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return if event.key == pygame.K_UP: if pos > 0: pos -= 1 else: pos = options - 1 if event.key == pygame.K_DOWN: if pos < options - 1: pos += 1 else: pos = 0 if pos == 0: if event.key == pygame.K_LEFT: if min_size > 3: min_size -= 1 if event.key == pygame.K_RIGHT: if min_size < 18 and min_size < max_size: min_size += 1 elif min_size < 18: min_size += 1 max_size += 1 if pos == 1: if event.key == pygame.K_LEFT: if max_size > 3 and max_size > min_size: max_size -= 1 elif max_size > 3: max_size -= 1 min_size -= 1 if event.key == pygame.K_RIGHT: if max_size < 18: max_size += 1 if pos == 2: if event.key == pygame.K_LEFT: if subject > 0: subject -= 1 else: subject = len(source_array) - 1 if event.key == pygame.K_RIGHT: if subject < len(source_array) - 1: subject += 1 else: subject = 0 if pos == 3: if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER: return def manage_menu(pos): new_game = (255, 255, 255) options = (255, 255, 255) exit_game = (255, 255, 255) if pos == 0: new_game = (0, 255, 255) if pos == 1: options = (0, 255, 255) if pos == 2: exit_game = (0, 255, 255) draw_text(win, "HANGMAN", 60, (255, 255, 255), win_width / 2, 50) draw_text(win, "NEW GAME", 45, new_game, win_width / 2, (win_height / 2) - 45) draw_text(win, "OPTIONS", 45, options, win_width / 2, (win_height / 2) + 25) draw_text(win, "EXIT", 45, exit_game, win_width / 2, (win_height / 2) + 90) def main_menu(): pos = 0 options = 3 while True: win.fill((0, 0, 0)) manage_menu(pos) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if pos > 0: if event.key == pygame.K_UP: pos -= 1 if pos < options - 1: if event.key == pygame.K_DOWN: pos += 1 if event.key == pygame.K_RETURN: if pos == 0: main() if pos == 1: options_menu() if pos == options - 1: quit() main_menu()
a1f1e5fc6243d15aea24089d9daeddd5afe444cf
MatteoZambra/dbn-pytorch
/deepbeliefpack/dataload.py
7,252
3.5625
4
import torch from torch.utils.data import DataLoader from torchvision.datasets import MNIST from torchvision import transforms class LoadDataset: """ Class LoadDataset. It serves the purpose of dowloading, preprocessing and fetching the data samples, divided in training set and testing set. Currently, this class is thought only for the MNIST data set. Enhancement in order to fetch different torchvision.datasets items is easy. However, a greater flexibility, to include more classes of data, even custom ones could require more effort and design. """ def __init__(self, batch_size, transforms): """ Constructor. Note that the transform used is that which transforms to tensors the images. Samples are normalized yet. Input: ~ batch_size (integer) : batch size, the number of samples to train the device with, iteratively ~ transforms (list of torchvision.transforms) : how to pre-process the data samples Returns: ~ nothing """ self.batch_size = batch_size self.transforms = transforms #end def yield_data(self, binarize, factor): """ The strategy is the following. Data set is provided by the torchvision.datasets module. MNIST is there available. With the torch.utils.data.DataLoader one can obtain an iterable object out of the MNIST object. Training set and testing set, respectively Xtrain,Ytrain and Xtest,Ytest are obtained by fetching each item from the iterators on the training and testing sets. The whole data set is then available as lists of data batches, which are subsequently used in this compact format. Input: ~ binarize (boolean) : if True, the data samples are transformed in {0,1} numerical matrices ~ factor (float) : if binarize == True, then the numerical values of the features are binarized according to this value Returns: ~ Xtrain and Xtest (list of torch.Tensor) : each tensor has shape [batch_size, num_features] the lists lengths are different ~ Ytrain and Ytest (list of torch.Tensor) : these items have shape [batch_size, 1]. Labels associated with data samples """ transfs = transforms.Compose(self.transforms) train_data = MNIST(r'data/', download = True, train = True, transform = transfs) test_data = MNIST(r'data/', download = True, train = False, transform = transfs) train_load = DataLoader(train_data, batch_size = self.batch_size, shuffle = False) test_load = DataLoader(test_data, batch_size = self.batch_size, shuffle = False) data_iterator = iter(train_load) Xtrain, Ytrain = self.iter_to_list(list(data_iterator)) data_iterator = iter(test_load) Xtest, Ytest = self.iter_to_list(list(data_iterator)) if binarize: Xtrain = self.binarize_digits(Xtrain, factor) Xtest = self.binarize_digits(Xtest, factor) #endif return Xtrain,Ytrain, Xtest,Ytest #end def yield_tensor_data(self): transfs = transforms.Compose(self.transforms) train_data = MNIST(r'data/', download = True, train = True, transform = transfs) test_data = MNIST(r'data/', download = True, train = False, transform = transfs) train_load = DataLoader(train_data, batch_size = self.batch_size, shuffle = False) test_load = DataLoader(test_data, batch_size = self.batch_size, shuffle = False) train_iterator = iter(train_load) test_iterator = iter(test_load) Xtrain = torch.Tensor() Xtest = torch.Tensor() Ytrain = torch.LongTensor() Ytest = torch.LongTensor() for data, labels in train_iterator: Xtrain = torch.cat([Xtrain, data], 0) Ytrain = torch.cat([Ytrain, labels], 0) #end Xtrain = Xtrain.view(-1,28*28) # view(-1,28,28) size_dataset = int(Xtrain.shape[0] / self.batch_size) Xtrain = Xtrain.view(size_dataset, self.batch_size, 28*28) Ytrain = Ytrain.view(size_dataset, self.batch_size, 1) for data, labels in test_iterator: Xtest = torch.cat([Xtest, data], 0) Ytest = torch.cat([Ytest, labels], 0) #end Xtest = Xtest.view(-1,28*28) # view(-1,28,28) size_dataset = int(Xtest.shape[0] / self.batch_size) Xtest = Xtest.view(size_dataset, self.batch_size, 28*28) Ytest = Ytest.view(size_dataset, self.batch_size, 1) Xtrain = Xtrain.cuda() Xtest = Xtest.cuda() return Xtrain, Xtest, Ytrain, Ytest #end @staticmethod def iter_to_list(data_set): """ Transforms iterators to lists. Each list contains the data samples, labels. Input: ~ data_set (torch.utils.data.dataloader._SingleProcessDataLoaderIter) : iterator over the torch.utils.data.dataloader.DataLoader object. Returns: ~ data (list of torch.Tensor) : list of data batches ~ labels (list of torch.Tensor) : list of labels associated with the samples in the data batches in data """ data = [] labels = [] for _data,_labels in data_set: _data = _data.view(-1, _data.shape[2] * _data.shape[3]) data.append(_data) labels.append(_labels) #enddo return data,labels #end @staticmethod def binarize_digits(data_set, factor): """ Images binarization. The threshold value for binarization is set to 1/factor, and the pixels in the image which exceed that value are set to 1, the others are shut to 0. The larger the factor, the less pixels survive. Input: ~ data_set (list of torch.Tensor) : could be Xtrain or Xtest ~ factor (float) : denominator of thethreshold value computation Returns: ~ data_set (list of torch.Tensor) : binarized images of the train/test data samples sets """ threshold = 1.0 / factor for x in data_set: for sample in x: sample[sample <= threshold] = 0. sample[sample > threshold] = 1. #end #end return data_set #end #end
1e8206fcebc5ad8204a66de740ce76f7faae2ac7
Ninwk/coins
/coin_compare.py
2,279
3.703125
4
# coin_dir = [1, 1, 1, 1, 5] def sum_coin(co_list, fom, to): sum_co = 0 for i in range(fom, to+1, 1): sum_co += co_list[i] return sum_co def compare_coin(co_list, fom, to): """ :param co_list: 硬币列表 :param fom: 硬币列表起始位置 :param to: 硬币列表末尾 :return: 假币位置 """ # 硬币数 num = to - fom + 1 # 假币位置 res = 0 if num == 1: if fom == 0: front = co_list[fom] == co_list[fom + 1] back = co_list[fom] == co_list[fom + 2] if back and front: res = 0 elif front and (not back): res = fom + 2 elif (not front) and back: res = fom + 1 else: res = 0 elif fom == len(co_list) - 1: front = co_list[fom] == co_list[fom - 2] back = co_list[fom] == co_list[fom - 1] if back and front: res = 0 elif front and (not back): res = fom - 1 elif (not front) and back: res = fom - 2 else: res = fom else: front = co_list[fom] == co_list[fom - 1] back = co_list[fom] == co_list[fom + 1] if back or front: res = 0 else: res = fom else: # 判断硬币总数是否为偶数 if num % 2 == 0: front = sum_coin(co_list, fom, int(fom + num / 2 - 1)) back = sum_coin(co_list, int(to - num / 2 + 1), to) if front == back: res = 0 else: res1 = compare_coin(co_list, fom, int(fom + num / 2 - 1)) if res1 == 0: res2 = compare_coin(co_list, int(to - num / 2 + 1), to) if res2 != 0: res = res2 else: res = 0 else: res = res1 else: res3 = compare_coin(co_list, fom + 1, to) if res3 == 0: if co_list[fom] != co_list[fom + 1]: res = fom else: res = res3 return res
4a7b9fdc7bb53519db54e26bb719bf42f9dc3a88
nikitosoleil/spos
/sem2/lab2/input/test.py
572
3.53125
4
for i in range(n): l.append(i) l = [] print l # comment s = "a\ns\td" + "q\"w\'e" s += 'z\'x\"c' class Test: def __init__(self): self.name = r"Nikita\n" def print_name(): print self.name f(a = 'b', # test c = 'c') a, b = b, a a, b = \ # test b, a a"asd" b"asd" br"asd" brr"asd" "asd asd" a = true b! b!= $b? a = 5 + 3 b = 1e-3 c = -1.15 d = 1.15e3 e = 1.15e-3-3 c = 15a f = 1.15a g = 1.15e3e h = 100L j = 100A k = 100.j l = 1.15e3J m = 1e15l a = \\\\n b = .5 c = 10. d = .15e-3 f = .15j g = .0E0 g = .0E0E 123asd h = .L k = .a0
b1a1148977a507874e0a6207c7fa2f96fddd3634
PaulGuo5/Leetcode-notes
/notes/0925/0925.py
482
3.640625
4
class Solution: def isLongPressedName1(self, name: str, typed: str) -> bool: it = iter(typed) return all(char in it for char in name) def isLongPressedName(self, name: str, typed: str) -> bool: #2 pointer i = 0 for j in range(len(typed)): if i < len(name) and name[i] == typed[j]: i+=1 elif j == 0 or typed[j-1] != typed[j]: return False return i == len(name)
699784b89934f79c67bfbeec05b9c85ea1f2ab12
PaulGuo5/Leetcode-notes
/notes/1233/1233.py
890
3.703125
4
class TrieNode: def __init__(self): self.children = {} self.isWord = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() node = node.children[c] node.isWord = True def find(self): res = [] def dfs(node, path): if node.isWord: res.append("/"+"/".join(path)) return for c in node.children: dfs(node.children[c], path+[c]) dfs(self.root, []) return res class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: trie = Trie() for f in folder: trie.insert(f.split("/")[1:]) return trie.find()
149d8d49621e091f522decd2c6285cfd9247c7f3
PaulGuo5/Leetcode-notes
/notes/0510/0510.py
963
3.8125
4
""" # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None """ class Solution: def inorderSuccessor(self, node: 'Node') -> 'Node': root = node while root.parent: root = root.parent # nodes = [] # def dfs(node): # nonlocal nodes # if not node: # return # dfs(node.left) # nodes.append(node) # dfs(node.right) # dfs(root) # flag = False # for n in nodes: # if flag: # return n # if n == node: # flag = True res = None while root: if root.val > node.val: res = root root = root.left else: root = root.right return res
96d663f4c42eed9b518de30df4641407924a0490
PaulGuo5/Leetcode-notes
/notes/0079/0079.py
903
3.53125
4
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: if not board: return False def dfs(board, word, d, i, j): if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[d]: return False if d == len(word) - 1: return True # Let the current node out cur = board[i][j] board[i][j] = 0 found = dfs(board, word, d+1, i+1, j) or dfs(board, word, d+1, i-1, j) or dfs(board, word, d+1, i, j+1) or dfs(board, word, d+1, i, j-1) # retore the current value board[i][j] = cur return found m = len(board) n = len(board[0]) for i in range(m): for j in range(n): if dfs(board, word, 0, i, j): return True return False
8b203b94ff89a51de6000a59545ebd5deb0d8143
PaulGuo5/Leetcode-notes
/notes/0160/0160.py
1,614
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not headA or not headB: return None currA, currB = headA, headB countA, countB = 0, 0 start = None while currA.next: currA = currA.next countA += 1 while currB.next: currB = currB.next countB += 1 currA, currB = headA, headB if countA > countB: diff = countA - countB while diff: currA = currA.next diff -= 1 elif countA < countB: diff = countB - countA while diff: currB = currB.next diff -= 1 while currA and currB: if currA is currB: if not start: start = currA else: start = None currA = currA.next currB = currB.next return start def getIntersectionNode(self, headA, headB): ptA, ptB = headA, headB flag = 0 # l1+l2 or l2+l1 while ptA and ptB: if ptA == ptB: return ptA ptA = ptA.next ptB = ptB.next if not ptA and not flag: ptA = headB flag = 1 if not ptB: ptB = headA return None
89912dfc338416f7a985cdd382c4da779d3e200b
PaulGuo5/Leetcode-notes
/notes/0489/0489.py
1,617
3.921875
4
# """ # This is the robot's control interface. # You should not implement it, or speculate about its implementation # """ #class Robot: # def move(self): # """ # Returns true if the cell in front is open and robot moves into the cell. # Returns false if the cell in front is blocked and robot stays in the current cell. # :rtype bool # """ # # def turnLeft(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def turnRight(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def clean(self): # """ # Clean the current cell. # :rtype void # """ class Solution: def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ dirs = ((-1, 0), (0, 1), (1, 0), (0, -1)) def dfs(i, j, vis, di): robot.clean() vis.add((i, j)) for _ in range(4): di = (di+1) % 4 robot.turnRight() if (i+dirs[di][0], j+dirs[di][1]) not in vis and robot.move(): dfs(i+dirs[di][0], j+dirs[di][1], vis, di) robot.turnRight() robot.turnRight() robot.move() robot.turnRight() robot.turnRight() dfs(0, 0, set(), 0)
644ed377fe62329bc292d81f1908370746abc72d
PaulGuo5/Leetcode-notes
/notes/1171/1171.py
991
3.609375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeZeroSumSublists1(self, head: ListNode) -> ListNode: dummy = ListNode(0) dummy.next = head pre, cur = dummy, dummy.next s = 0 table = {s: pre} while cur: s += cur.val if s in table: table[s].next = cur.next else: table[s] = cur pre, cur = cur, cur.next return dummy.next def removeZeroSumSublists(self, head): cur = dummy = ListNode(0) dummy.next = head prefix = 0 seen = collections.OrderedDict() while cur: prefix += cur.val node = seen.get(prefix, cur) while prefix in seen: seen.popitem() seen[prefix] = node node.next = cur = cur.next return dummy.next
06ca5f88badc833510d948f797ba3ffa9d1729b7
PaulGuo5/Leetcode-notes
/notes/0428/0428.py
1,306
3.640625
4
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str """ def write(root): if not root: return res.append(str(root.val)) for child in root.children: write(child) res.append("#") res = [] write(root) return " ".join(res) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node """ if not data: return None data = collections.deque(data.split(" ")) root = Node(int(data.popleft()), []) q = [root] while data: val = data.popleft() if val == "#": q.pop() else: new = Node(int(val), []) q[-1].children.append(new) q.append(new) return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
f93b211cee00a0185c7f70fffcd2883a9973c7ca
PaulGuo5/Leetcode-notes
/notes/0863/0863.py
2,112
3.625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK1(self, root: TreeNode, target: TreeNode, K: int) -> List[int]: def buildParentMap(node, parent, parentMap): if not node: return parentMap[node] = parent buildParentMap(node.left, node, parentMap) buildParentMap(node.right, node, parentMap) parentMap = {} buildParentMap(root, None, parentMap) res = [] visited = set() def dfs(node, dis): if not node or node in visited: return visited.add(node) if K == dis: res.append(node.val) elif K >= dis: dfs(node.left, dis+1) dfs(node.right, dis+1) dfs(parentMap[node], dis+1) dfs(target, 0) return res def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]: def buildGraph(node, parent, graph): if not node: return if parent: graph[node].append(parent) if node.left: graph[node].append(node.left) buildGraph(node.left, node, graph) if node.right: graph[node].append(node.right) buildGraph(node.right, node, graph) graph = collections.defaultdict(list) buildGraph(root, None, graph) visited = set() res = [] q = collections.deque() q.append((target, 0)) while q: node, dis = q.popleft() if node in visited: continue visited.add(node) if dis == K: res.append(node.val) elif dis <= K: for child in graph[node]: q.append((child, dis+1)) return res
564419f966715c913740af2744ed665b30c61305
PaulGuo5/Leetcode-notes
/notes/0276/0276.py
505
3.5
4
class Solution: def numWays(self, n: int, k: int) -> int: if n == 0 or k == 0: return 0 num_same = 0 # the number of ways that the last element has the same color as the second last one num_diff = k # the number of ways that the last element has differnt color from the second last one for i in range(1, n): total = num_diff + num_same num_same = num_diff num_diff = total * (k - 1) return num_same + num_diff
e94a41481beeef420b3cad831090266fb7775f4b
PaulGuo5/Leetcode-notes
/notes/0415/0415.py
710
3.515625
4
class Solution: def addStrings1(self, num1: str, num2: str) -> str: return str(int(num1)+int(num2)) def addStrings(self, num1: str, num2: str) -> str: num1, num2 = list(num1)[::-1], list(num2)[::-1] if len(num1) < len(num2): num1, num2 = num2, num1 carry = 0 res = "" for i in range(len(num2)): carry, r = divmod(int(num1[i]) + int(num2[i]) + carry, 10) res += str(r) if num1[len(num2):]: for i in range(len(num2), len(num1)): carry, r = divmod(int(num1[i])+carry, 10) res += str(r) if carry != 0: res += str(carry) return res[::-1]
c55fdc1ea3e7b95b97c8b67c65c70b51b30455c0
PaulGuo5/Leetcode-notes
/notes/0450/0450.py
1,629
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def deleteNode1(self, root: TreeNode, key: int) -> TreeNode: if not root: return None if root.val < key: root.right = self.deleteNode(root.right, key) elif root.val > key: root.left = self.deleteNode(root.left, key) elif root.val == key: if not root.left: return root.right if not root.right: return root.left if not root.left and not root.right: return None min_node = root.right while min_node.left: min_node = min_node.left root.val = min_node.val root.right = self.deleteNode(root.right, min_node.val) return root def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None elif root.val < key: root.right = self.deleteNode(root.right, key) elif root.val > key: root.left = self.deleteNode(root.left, key) else: if not root.left and not root.right: return None if not root.left: return root.right if not root.right: return root.left left = root.left right = root.right p = right while p.left: p = p.left p.left = left return right return root
75680f7ad61eebf83e2bfd77ff485f05bf5d349c
PaulGuo5/Leetcode-notes
/notes/0241/0241.py
889
3.578125
4
class Solution: def diffWaysToCompute(self, input: str) -> List[int]: memo = {} def helper(s): nonlocal memo if s.isdigit(): return [int(s)] if s in memo: return memo[s] res = [] for i in range(len(s)): if s[i] in "+-*": left = helper(s[:i]) right = helper(s[i+1:]) for l in left: for r in right: if s[i] == "+": res.append(l+r) elif s[i] == "-": res.append(l-r) elif s[i] == "*": res.append(l*r) memo[s] = res return res return helper(input)
9db57a02eacf67e84ed5fe85066bab851ced7dee
PaulGuo5/Leetcode-notes
/notes/0353/0353.py
1,593
4.03125
4
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """ Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. """ self.width = width self.height = height self.food = food self.body = collections.deque([(0,0)]) self.food_ind = 0 def move(self, direction: str) -> int: """ Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. """ i, j = self.body[-1] if direction == "U": i -= 1 elif direction == "D": i += 1 elif direction == "L": j -= 1 elif direction == "R": j += 1 if i >= self.height or i < 0 or j >= self.width or j < 0 or ((i,j) in set(self.body) and (i,j) != self.body[0]): return -1 self.body.append((i, j)) if self.food_ind < len(self.food): x, y = self.food[self.food_ind] if i == x and j == y: self.food_ind += 1 return self.food_ind tmp = self.body.popleft() return self.food_ind # Your SnakeGame object will be instantiated and called as such: # obj = SnakeGame(width, height, food) # param_1 = obj.move(direction)
52c986eff0e4f4344b7cac878c78e9ac1d090dc1
PaulGuo5/Leetcode-notes
/notes/0606/0606.py
1,344
3.75
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def tree2str1(self, t: TreeNode) -> str: if not t: return "" res = "" def dfs(t): nonlocal res if not t: return if not t.left and t.right: res+="("+str(t.val) res += "()" dfs(t.left) dfs(t.right) res+=")" else: res+="("+str(t.val) dfs(t.left) dfs(t.right) res+=")" return res string = dfs(t) ans = "" for i in range(1, len(string)-1): ans += string[i] return ans def tree2str(self, t: TreeNode) -> str: if not t: return "" elif not t.left and not t.right: return "{}".format(t.val) elif not t.left and t.right: return "{}()({})".format(t.val, self.tree2str(t.right)) elif t.left and not t.right: return "{}({})".format(t.val, self.tree2str(t.left)) else: return "{}({})({})".format(t.val, self.tree2str(t.left), self.tree2str(t.right))
c7044b775497fb47b5523da21d9ea81b74c06af4
PaulGuo5/Leetcode-notes
/notes/0261/0261.py
1,177
3.53125
4
class Solution: def validTree1(self, n: int, edges: List[List[int]]) -> bool: if not edges and n == 1: return True if not edges and n > 1: return False def findRoot(x, tree): if tree[x] == -1: return x root = findRoot(tree[x], tree) tree[x] = root return root tree = [-1]*(n) for e in sorted(edges): x = findRoot(e[0], tree) y = findRoot(e[1], tree) if x == y: return False if x < y: tree[y] = x else: tree[x] = y return len(edges) == n-1 def validTree(self, n: int, edges: List[List[int]]) -> bool: def find(nums, i): if nums[i] == -1: return i return find(nums, nums[i]) def union(nums, a, b): aa = find(nums, a) bb = find(nums, b) if aa == bb: return False nums[aa] = bb return True nums = [-1]*n for a, b in edges: if not union(nums, a, b): return False return len(edges) == n-1
e9cd76a7bab4ede9fd83c502936bba8886dbae58
PaulGuo5/Leetcode-notes
/notes/0520/0520.py
744
3.609375
4
class Solution: def detectCapitalUse1(self, word: str) -> bool: def isCaptical(c): return True if ord(c) >= ord("A") and ord(c) <= ord("Z") else False if not word: return True if isCaptical(word[0]): if len(word) > 2: tmp = isCaptical(word[1]) for c in word[2:]: if isCaptical(c) != tmp: return False else: for c in word[1:]: if isCaptical(c): return False return True def detectCapitalUse(self, word: str) -> bool: res = [c.isupper() for c in word] return all(res) or not any(res) or (res[0] and not any(res[1:]))
822f9e35f09fd1753d62fe537b4714332118d983
User9000/100python
/ex79.py
266
4.0625
4
#python PAM while True: password=input("Enter password: ") if any(i.isdigit() for i in password) and any(i.upper() for i in password) and len(password) >= 5: print("Password is fine") break else: print("Password is not fine")
5b33ac0092e1896d53dfd8a3505aa9c8cee3c8e7
User9000/100python
/ex36.2.py
194
3.90625
4
def count_words(filepath): with open(filepath, 'r') as file: strng = file.read() strng_list = strng.split(" ") return len(strng_list) print(count_words("words1.txt"))
801628680f24f1ef38ca3223d958ccffbc501499
User9000/100python
/anyFunction.py
235
3.828125
4
#test the any function list1 = ['0','1','2','l'] if any(i=='2' for i in list1) and any(i=='1' for i in list1): print("found the number 2 and 1 are in list") lst = [-1, True, "X", 0.00001] print (any(lst))
aaf7c0d114a9c949659164425db1730be618abfe
Daksh-404/face-detection-software
/cvTut8.py
517
3.515625
4
import cv2 as cv import numpy as np faceCascade=cv.CascadeClassifier("haarcascade_frontalface_default.xml") img=cv.imread("girls.jpg") img_gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) faces=faceCascade.detectMultiScale(img_gray,1.1,4) for (x,y,w,h) in faces: cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3) #the face recognition works on face cascad xml files created # and compiled over the time by openCV #this is viola and Jones method, for face recognition cv.imshow("Output",img) cv.waitKey(0)
99e85c5259410181914a51738d33b51051e94769
LeafNing/Ng_ML
/ex6/plotData.py
662
3.953125
4
import matplotlib.pyplot as plt import numpy as np def plot_data(X, y): plt.figure() # ===================== Your Code Here ===================== # Instructions : Plot the positive and negative examples on a # 2D plot, using the marker="+" for the positive # examples and marker="o" for the negative examples label0 = np.where(y==0) label1 = np.where(y==1) plt.scatter(X[label0, 0], X[label0, 1], marker='o', color='yellow', label='negative') plt.scatter(X[label1, 0], X[label1, 1], marker='+', color='black', label='positive') plt.legend(['positive', 'negative'], loc=1) plt.show()
3935498828f083754296ad3cb7c587bf75c4870b
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_6.py
3,159
4.46875
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 6 ''' import sys import math #Functions: def is_prime (n): ''' Returns True if the integer 'n' is a prime number. Otherwise, it returns False. To determine if 'n' is not a prime number, it is enough to check if at least one of the numbers from the list <2, 3, 4, ..., int(srqt(n))> divides 'n'. Input : n -> integer Output: result -> bool ''' result = True if n == 1 or n == -1 or n == 0: #Special cases return False limit = int(math.sqrt(abs(n))) #It does not support very large integers because it needs to convert it to float. for number in range(2, limit + 1): if n%number == 0: #'n' is not a prime number. result = False break return result def test(did_pass): ''' Print the result of a test. OBS: Função retirada dos slides Python 1.pptx. ''' linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} is OK.".format(linenum) else: msg = "Test at line {0} FAILED.".format(linenum) print(msg) def test_suite(): ''' Run the suite of tests for code in this module (this file). OBS: Função retirada dos slides Python 1.pptx. ''' test(is_prime(11)) test(not is_prime(35)) test(is_prime(19911121)) test(not is_prime(1)) test(not is_prime(-1)) test(not is_prime(0)) test(is_prime(2)) test(is_prime(-2)) test(is_prime(3)) test(is_prime(-3)) test(not is_prime(4)) test(not is_prime(-4)) test( is_prime(5)) test( is_prime(-5)) #Big prime numbers from http://www.primos.mat.br/2T_en.html test(is_prime(47055831617)) test(not is_prime(47055831614)) test(is_prime(47055808417)) test(is_prime(46813264349)) #Main: if __name__=='__main__': test_suite() #Birthday: ''' (year) -> 4-digit integer from 1990 to 2020. (31 possibilities) (month) -> 2-digit integer from 01 to 12. (12 possibilities) (day) -> 2-digit integer from 01 to 30. (30 possibilities) (year)(month)(day) -> 8-digit integer from 19900101 to 20201230. (31*12*30 = 11160 possibilities) ''' if is_prime(19940423): print('I was born in a prime day.') else: print('I was not born in a prime day.') birth_list = [] for i in range(31): #year for j in range(12): #month for k in range(30): birth_list.append((1990+i)*10**4 + (1+j)*10**2 + (1+k)) number_os_prime_numbers = 0 for n in birth_list: if is_prime(n): number_os_prime_numbers += 1 print('The total number of prime number in birth_list is {}'.format(number_os_prime_numbers)) prob = number_os_prime_numbers/len(birth_list) print('The probability that a student has a prime number birthday is {:<.2%}'.format(prob)) print('We expect that in a class of 100 students we have {} that was born in a prime day.'.format(int(prob*100)))
d62805b6544a217f531eaf387853a7120c479d3f
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_7.py
1,115
4.125
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 7 ''' import sys #Functions: def sum_of_squares (xs): ''' Returns the sum of the squares of the numbers in the list 'xs'. Input : xs -> list (list of integers) Output: result -> integer ''' result = 0 for number in xs: result += number**2 return result def test(did_pass): ''' Print the result of a test. OBS: Função retirada dos slides Python 1.pptx. ''' linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} is OK.".format(linenum) else: msg = "Test at line {0} FAILED.".format(linenum) print(msg) def test_suite(): ''' Run the suite of tests for code in this module (this file). OBS: Função retirada dos slides Python 1.pptx. ''' test(sum_of_squares([2, 3, 4]) == 29) test(sum_of_squares([ ]) == 0) test(sum_of_squares([2, -3, 4]) == 29) #Main: if __name__=='__main__': test_suite()
590591e904740eb57a29c07ba3cf812ac9d5e921
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_4.py
1,580
4.15625
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 4 ''' import sys #Functions: def sum_up2even (List): ''' Sum all the elements in the list 'List' up to but not including the first even number (Is does not support float numbers). Input : List -> list (list of integers) Output: result -> integer or None if no number was added to result. ''' result = None for number in List: if number%2 == 0: break else: if result == None: result = number else: result += number return result def test(did_pass): ''' Print the result of a test. OBS: Função retirada dos slides Python 1.pptx. ''' linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} is OK.".format(linenum) else: msg = "Test at line {0} FAILED.".format(linenum) print(msg) def test_suite(): ''' Run the suite of tests for code in this module (this file). OBS: Função retirada dos slides Python 1.pptx. ''' test(sum_up2even([]) == None) test(sum_up2even([2]) == None) test(sum_up2even([-4]) == None) test(sum_up2even([0]) == None) test(sum_up2even([2, 3, 4, 5, 6]) == None) test(sum_up2even([1, 3, 5, 7, 9]) == 25) test(sum_up2even([27]) == 27) test(sum_up2even([27, 0]) == 27) test(sum_up2even([-3]) == -3) #Main: if __name__=='__main__': test_suite()
8cc600ad07e23adc4d7c9301bb46514e14af1dfa
ArturAssisComp/ITA
/ces22(POO)/Lista4/Questao1.py
1,292
3.78125
4
''' Author : Artur Assis Alves Date : 08/06/2020 Title : Simulador de Estradas ''' import abc #Classes: class VehicleInterface (): ''' Interface class for vehicles.''' def __init__(self, engine_class): self.engine = engine_class def description(self): return '{0}{1}.'.format(self.engine.description, self.__class__.__name__.lower()) class Car (VehicleInterface): pass class Truck (VehicleInterface): pass class Boat (VehicleInterface): pass class Bus (VehicleInterface): pass class Motorcycle (VehicleInterface): pass class EngineInterface (): ''' Interface class for the vehicle's engine.''' @abc.abstractmethod def __init__(self): pass class ElectricMotor (EngineInterface): def __init__(self): self.description = "Electric motor " class CombustionEngine(EngineInterface): def __init__(self): self.description = "Combustion engine " class HybridEngine(EngineInterface): def __init__(self): self.description = "Hybrid engine " if __name__=='__main__': for j in (ElectricMotor(), CombustionEngine(), HybridEngine()): for i in (Car(j), Truck(j), Boat(j), Bus(j), Motocycle(j)): print(i.description())
58c1e655e91256c0e0aed84e0c61f4a7818434d9
zelenyid/amis_python
/km73/Zeleniy_Dmytro/9/task1.py
303
4.15625
4
from math import sqrt # Розрахунок відстані між точками def distance(x1, y1, x2, y2): dist = sqrt((x2-x1)**2 + (y2-y1)**2) return dist x1 = int(input("x1: ")) y1 = int(input("y1: ")) x2 = int(input("x2: ")) y2 = int(input("y2: ")) print(distance(x1, y1, x2, y2))
6a96dd141ed5a13b6db3c5ed99eaff71aa0b520e
PPL-IIITA/ppl-assignment-stark03
/Question9/q9.py
350
3.59375
4
from chooseFromBest import * def main(): """main function for question 9 , creates an object of class 'chooseFromBest' prints the formed couples , the changes are made in the log file 'logGifting.txt' durin the program""" c = formCouples() """here k is taken as 10 , any value can be taken.""" c.makeCouples(10) main()
0018b205b95c996cef5aebd214923a25ea765799
PPL-IIITA/ppl-assignment-stark03
/Question5/boyGenerous.py
1,589
3.671875
4
import operator from Boys import Boy class boyGenerous(Boy): """Boy class for boyType = 'Generous'""" def __init__(self, boy): """constructor , calls the parent constructor and initializes other attributes as:- happiness = happiness of the boy amountSpent = amount spent on gifting gfName = name of the girlfriend """ Boy.__init__(self,boy) self.happiness = 0 self.amountSpent = 0 self.gfName = "" def happinessCalculator(self, gHappiness): "Calculates happiness for Generous boys" self.happiness = gHappiness def gifting(self, gMaintainanceCost, Gifts, giftBasket): "Sets up the gift basket for Generous boys" Gifts.sort(key=operator.attrgetter('price'), reverse=True) if self.budget < Gifts[0].price: temp = [Gifts[0].giftType, Gifts[0].price, Gifts[0].value] self.budget = Gifts[0].price self.amountSpent = self.budget giftBasket.append(temp) else: tempBudget = self.budget i = 0 while(True): if(self.amountSpent < self.budget): if((self.amountSpent + Gifts[i].price) > self.budget): break else: temp = [Gifts[i].giftType, Gifts[i].price, Gifts[i].value] giftBasket.append(temp) self.amountSpent += Gifts[i].price i+=1
120b2ddee0cd72a20792ef669d58142fd7c9ce8b
touyou/CompetitiveProgramming
/codeforces/contest69/A.py
332
3.625
4
#! /usr/bin/env python def solve(n): len = 2^n sum = 0 for i in range(1, len-1): sum += i be = solve(n-1) ol = solve(n-2) sum = sum - (2^(n-1))^2 + be - ((2^(n-2))^2 - ol)*2 return sum def main(): n = int(raw_input()) ans = solve(n) print ans if __name__ == '__main__': main()
e8e8e16d098d51ff7f49bb6e8d51e40e23e8bee9
shruti1502-hub/Detecting-Lanes-for-Self-Driving-cars
/FindingLanes.py
5,006
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import cv2 import numpy as np import matplotlib.pyplot as plt # # Edge Detection # To identify the boundaries in images-identifying sharp changes in intensity in adjacemt pixels or sharp changes in pixels # # At Edge- there is a rapid change in brightness # # Gradient # Measure in change in brightness in adjacent pixels # # Strong Gradient- shows sharp change in brightness like from 0-255 # # Small Gradient- Shows small change in brigthness like from 0-15 # In[2]: #First we need to convert our image to grayscale #This is necessary because a normal image consists of three channels-Red,Green,Blue #Each Pixel is a combination of three intensities #Wheras in grayscale image- only has 1 channel;each pixel has only one intensity ranging from 0-255 #processing a single chnnel image is simpler than processsing a three-channl image # In[3]: #Apply Gaussian Blur: #Reduce Noise #to smoothen a image, we take average of all pixels around a image which is done by kernel # In[4]: #Applying Canny method #applies derivative-we our applying gradient in our image to measure sharp cha ge in intesnities in adjacent pixels in both x and y directions def make_coordinates(image, line_parameters): slope,intercept = line_parameters y1 = image.shape[0] y2 = int(y1*(3/5)) x1 = int((y1-intercept)/slope) x2 = int((y2-intercept)/slope) return np.array([x1, y1, x2, y2]) def average_slope_intercept(image,lines): left_fit = [] right_fit = [] for line in lines: x1,y1,x2,y2=line.reshape(4) parameters = np.polyfit((x1,x2), (y1,y2), 1) slope = parameters[0] intercept = parameters[1] if slope < 0: left_fit.append((slope,intercept)) else: right_fit.append((slope,intercept)) left_fit_average = np.average(left_fit, axis = 0) right_fit_average = np.average(right_fit,axis= 0) left_line = make_coordinates(image, left_fit_average) right_line = make_coordinates(image, right_fit_average) return np.array([left_line, right_line]) def canny(image): gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) blur= cv2.GaussianBlur(gray,(5,5),0) canny = cv2.Canny(blur,50,150) return canny def display_lines(image,lines): line_image=np.zeros_like(image) if lines is not None: for line in lines: x1, y1, x2, y2=line.reshape(4) cv2.line(line_image, (x1,y1), (x2,y2), (255, 0 ,0), 10) return line_image def region_of_interest(image): height= image.shape[0] polygons = np.array([ [(200,height), (1100,height), (550,250)] ]) mask = np.zeros_like(image) cv2.fillPoly(mask, polygons, 255) masked_image = cv2.bitwise_and(image,mask) return masked_image image=cv2.imread('test_image.jpg') lane_image = np.copy(image) canny_image= canny(lane_image) cropped_image = region_of_interest(canny_image) lines=cv2.HoughLinesP(cropped_image, 2, np.pi/180, 100, np.array([]), minLineLength=40, maxLineGap=5) averaged_lines = average_slope_intercept(lane_image, lines) line_image = display_lines(lane_image,averaged_lines) combo_image= cv2.addWeighted(lane_image, 0.8, line_image, 1, 1) cv2.imshow("result",combo_image) #computing the bitwise and of both images takes the bitwise and of each pixel in both arrays,ultimateky masking the canny image to only show the region of interest cv2.waitKey(0) #parameters are low an high threshold--low threshold images are ignored and high threshold are accepted in a certain conditions #image lying brtween low and high threshold is accepted #The output image traces and outline of edges that shows sharp changes in intensities #gradients that exceed the threshold are traceed as high pixels #small change in intesities lying below threshold are not traced at all and are left as black # # # we need to trace our region of interest. # This is done by making a triangle-traced as foloows # 1) 200 pixels along the x-axis, 700 pixels down the y-axis--reaching at a bottom point # # 2) 1100 pixels along x-axis, 700 pixels down y-axis--reaching at a point on the x-axis # # 3) 500 pixels along x-axis and 200 pixels down y-axis, completing the triangle. # In[5]: #Video cap = cv2.VideoCapture(r'test2.mp4') while(cap.isOpened()): _ , frame = cap.read() canny_image = canny(frame) cropped_image = region_of_interest(canny_image) lines = cv2.HoughLinesP(cropped_image , 2 , np.pi/180 , 100 , np.array([]), minLineLength = 40 , maxLineGap = 5) averaged_lines = average_slope_intercept(frame , lines) line_image = display_lines(frame , averaged_lines) combo_image = cv2.addWeighted(frame , 0.8, line_image , 1, 1) cv2.imshow('result', combo_image) if cv2.waitKey(10) & 0xFF== ord('q'): break cap.release() cv2.destroyAllWindows() # In[ ]:
b74253bc3566b35a29767cc23ceb5254cb303441
MailyRa/calculator_2
/calculator.py
1,093
4.125
4
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) print("Welcome to Calculator") #ask the user about the equation def calculator_2(): user_input = (input(" Type your equation ")) num = user_input.split(' ') #if the first letter is a "q" then I kno they want to quit if num == ["q"]: print("Thank you, have a good day") #the rest of the other functions if num[0] == "+": return int(num[1]) + int(num[2]) elif num[0] == "-": return int(num[1]) - int(num[2]) elif num[0] == "*": return int(num[1]) * int(num[2]) elif num[0] == "/": return int(num[1]) / int(num[2]) elif num[0] == "square": return int(num[1]) * int(num[1]) elif num[0] == "cube": return int(num[1]) * int(num[1]) * int(num[1]) elif num[0] == "pow": return int(num[1]) ** int(num[2]) elif num[0] == "mod": return int(num[1]) % int(num[2]) print(calculator_2())
6a9febac0dcf6886c3337991eb7c5dde84ee281b
pdhawal22443/GeeksForGeeks
/GreaterNumberWithSameSetsOFDigit.py
2,055
4.15625
4
'''Find next greater number with same set of digits Given a number n, find the smallest number that has same set of digits as n and is greater than n. If n is the greatest possible number with its set of digits, then print “not possible”. Examples: For simplicity of implementation, we have considered input number as a string. Input: n = "218765" Output: "251678" Input: n = "1234" Output: "1243" Input: n = "4321" Output: "Not Possible" Input: n = "534976" Output: "536479" Algo :: Following is the algorithm for finding the next greater number. I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”. II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6. III) Swap the above found two digits, we get 536974 in above example. IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976. ''' import pdb #ex - 534976 lst = [5,3,4,9,7,6] def arrange(lst): flag = 0 for i in range(len(lst)-1,0,-1): if lst[i] > lst[i-1]: flag = 1 #this is to check that such number found break if flag == 0: print("Not Possible") exit(0) x = lst[i-1] #step-1 of algo #algo step2 temp = lst[i] small = i for k in range(i+1,len(lst)): if lst[k-1] > x and lst[small] > lst[k]: small = k #step 3 lst[i-1],lst[small] = lst[small],lst[i-1] pdb.set_trace() res = lst[0:i] + sorted(lst[i:]) print(''.join(map(str,res))) arrange(lst)
f3062465da0ac2bff8ce22f8dcff7bafd74057f7
pdhawal22443/GeeksForGeeks
/MaximumIntervalOverLap.py
1,068
3.9375
4
''' https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/ Consider a big party where a log register for guest’s entry and exit times is maintained. Find the time at which there are maximum guests in the party. Note that entries in register are not in any order. Example : Input: arrl[] = {1, 2, 9, 5, 5} exit[] = {4, 5, 12, 9, 12} First guest in array arrives at 1 and leaves at 4, second guest arrives at 2 and leaves at 5, and so on. Output: 5 There are maximum 3 guests at time 5. ''' def maximumOverlap(entry,exit): temp_arr = [] time = 0 max_guests = 1 guest = 1 for i in range(0,len(entry)): temp_arr.append([entry[i],exit[i]]) temp_arr = sorted(temp_arr) for i in range(1,len(temp_arr)): if temp_arr[i][0] < temp_arr[i-1][1] and temp_arr[i][1] > temp_arr[i-1][1]: guest += 1 if guest > max_guests: max_guests = guest time = temp_arr[i-1][0] return ([time,max_guests]) print(maximumOverlap([1, 2, 9, 5, 5],[4, 5, 12, 9, 12]))
e70705f03982835e2c1c4a1a4a5e34fd34129ee0
richardfearn/advent-of-code-2020
/day4/parser.py
657
3.546875
4
def parse_input(lines): if isinstance(lines, str): lines = lines.strip().split("\n") passports = [[]] for line in lines: if line == "": passports.append([]) else: passports[-1].append(line) passports = [create_passport_from_lines(passport) for passport in passports] return passports def create_passport_from_lines(passport_lines): line = " ".join(passport_lines) key_value_pairs = line.split(" ") passport_lines = dict(split_pair(pair) for pair in key_value_pairs) return passport_lines def split_pair(text): bits = text.split(":") return bits[0], bits[1]
6309ae5b9fd4a10573e61423afa5a7ef873a1531
richardfearn/advent-of-code-2020
/day9/__init__.py
1,677
3.53125
4
from collections import OrderedDict def is_valid(previous_numbers, number): for other in previous_numbers: complement = number - other if (other != complement) and (complement in previous_numbers): return True return False def part_1(numbers, preamble_length): numbers = convert(numbers) preamble = numbers[:preamble_length] numbers = numbers[preamble_length:] previous_numbers = OrderedDict.fromkeys(preamble) while len(numbers) > 0: number = numbers.pop(0) if not is_valid(previous_numbers, number): return number # noinspection PyArgumentList previous_numbers.popitem(last=False) previous_numbers[number] = None def part_2(numbers, invalid_number): numbers = convert(numbers) nums_in_range = find_range(numbers, invalid_number) return min(nums_in_range) + max(nums_in_range) def find_range(numbers, invalid_number): numbers = convert(numbers) sums = cumulative_sums(numbers) sums.append(0) # small trick so that if i == 0 below, sums[i - 1] returns 0 for i in range(0, len(numbers)): for j in range(i + 1, len(numbers)): range_sum = sums[j] - sums[i - 1] if range_sum == invalid_number: return numbers[i:j + 1] def cumulative_sums(numbers): sums = [numbers[0]] for i in range(1, len(numbers)): sums.append(sums[i - 1] + numbers[i]) return sums def convert(numbers): if isinstance(numbers, str): numbers = numbers.strip().split("\n") if isinstance(numbers[0], str): numbers = [int(n) for n in numbers] return numbers
73c52ebae85664b4145f09bf65d63bd2ed7fb090
ashwin4ever/Kaggle
/Competitions/digit_recognizer/digit_prediction_tf.py
2,238
3.765625
4
''' https://www.kaggle.com/c/digit-recognizer/data Digit Recognizer Kaggle This approach uses SVM to classify the digits Reference: https://www.kaggle.com/ndalziel/beginner-s-guide-to-classification-tensorflow/notebook ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import os import warnings warnings.filterwarnings('ignore') import seaborn as sns sns.set(style="darkgrid") import tensorflow as tf from tensorflow.python.framework import ops def elapsed(sec): ''' This function returns the elapsed time ''' if sec < 60: return str(round(sec)) + ' secs' elif sec < 3600: return str(round(sec / 60)) + ' mins' else: return str(round(sec / 3600)) + ' hrs' def plotImage(df , n): ''' This funcion plots the MNIST images given by n ''' labels = df['label'] print(labels) for i in range(1 , n): plt.subplot(1 , 10 , i) img_arr = df.iloc[i , 1 : ].values.reshape(28 , 28) plt.imshow(img_arr) plt.title(labels[i]) plt.show() def featureEngineering(train , test): ''' This function performs selection of features and handles missing,null values if applicable Return the target label and train data ''' x_train = train.iloc[ : , 1 : ] y_train = train['label'].values # rows = 42000 , cols = 784 r , c = x_train.shape print(x_train.shape) # Split into trainin and Cross Val set # Use 40000 records for training # Use 2000 records for CV # Train data x_tr = x_train[ : 40000].T.values y_tr = y_train[ : 40000] y_tr = pd.get_dummies(y_tr).T.values # print(y_tr , y_tr.shape) # CV data x_tr_cv = x_train[40000 : 4200000].T.values y_tr_cv = y_train[40000 : 420000] y_tr_cv = pd.get_dummies(y_tr_cv).T.values if __name__ == '__main__': start_time = time.time() # Read train data train = pd.read_csv('train.csv') # read test data test = pd.read_csv('test.csv') #plotImage(train , 10) featureEngineering(train , test) elapsed_time = time.time() - start_time print('Elapsed Time: ' , elapsed(elapsed_time))
9c843dcb57fce440936c61bd2a7b6cc7518cd748
notnew/sous-vide
/blinker.py
3,706
3.703125
4
from gpio import gpio from threading import Thread import queue import time class Blinker(): """ Blink an input pin on and off """ def __init__(self, pin_num): self.pin_num = pin_num self._messages = queue.Queue() self._thread = None self._hi_time = -1 self._low_time = 0 def set_cycle(self, hi_time, low_time=None): """ set period for the blinker if only `hi_time` is passed, that value is used for `off_time` as well if `hi_time` is positive, it's value is the length of time the pin should be set high, in seconds if `hi_time` is zero, the pin should be turned on indefinitely if `hi_time` is negative, the pins should be turned off indefinitely""" if hi_time > 0: if low_time is None: low_time = hi_time if low_time <= 0: raise ValueError(low_time, "low_time duration must be positive") (self._hi_time, self._low_time) = (hi_time, low_time) self._messages.put( (hi_time, low_time) ) def set_on(self): self.set_cycle(0) def set_off(self): self.set_cycle(-1) def run(self): def _run(): (hi,low) = (self._hi_time, self._low_time) def msg_or_timeout(duration=None): try: start = time.time() msg = self._messages.get(timeout=duration) if msg is None: raise StopIteration elapsed = time.time() - start return (msg, elapsed) except queue.Empty: return ((hi, low), duration) with gpio(self.pin_num, "out") as pin: try: while True: if hi < 0: # off until new message arrives pin.set(False) ((hi,low),_) = msg_or_timeout() elif hi == 0: # on until new message arrives pin.set(True) ((hi,low),_) = msg_or_timeout() else: pin.set(True) ((hi,low),elapsed) = msg_or_timeout(hi) while ( hi > 0 and hi > elapsed): ((hi,low),elapsed2) = msg_or_timeout(hi-elapsed) elapsed += elapsed2 if hi <= 0: continue pin.set(False) ((hi,low), elapsed) = msg_or_timeout(low) while ( hi > 0 and low > 0 and low > elapsed): ((hi,low),elapsed2) = msg_or_timeout(low-elapsed) elapsed += elapsed2 except StopIteration: pass if not self.is_running(): self._thread = Thread(target=_run) self._thread.start() def stop(self): if self.is_running(): self._messages.put(None) self._thread.join() def is_running(self): return self._thread and self._thread.is_alive() def __enter__(self): self.run() return self def __exit__(self, exc_type=None, exc_val=None, exc_tb=None): self.stop() return False if __name__ == "__main__": (red,green,blue) = (18,27,22) blinker = Blinker(red) blinker.run() blinker.set_cycle(0.9,0.1) try: blinker._thread.join() except: print("stopping blinker") blinker.stop()
d9de9c735a24f6256383bc7177d51ac9dfada273
ARTINKEL/Array-of-Integers-to-Array-of-Letters
/array-to-letters.py
514
3.84375
4
# Austin Tinkel # 11/29/2018 import string import random array = [] new_array = [] done = False counter = 0 def convert_array(array): for x in array: s = "" for _ in range(x): s += (random.choice(string.ascii_letters)) new_array.append(s) return new_array while (not done): number = input(("Enter Element " + str(counter) + ": ")) try: array.append(int(number)) except ValueError: done = True print(convert_array(array)) counter += 1
99b88d0e90e10a4dce49beb5bbcedae95d246273
zhng1456/M-TA-Prioritized-MAPD
/ta_state.py
1,037
3.625
4
""" Created on Sat Apr 18 10:45:11 2020 @author: Pieter Cawood """ class Location(object): def __init__(self, col, row): self.col = col self.row = row def __eq__(self, other): return self.col == other.col and self.row == other.row def __hash__(self): return hash(str(self.col) + str(self.row)) def __str__(self): return str((self.col, self.row)) class State(object): def __init__(self, time, location): self.time = time self.location = location self.g = 0 self.f = 0 def __eq__(self, other): return self.time == other.time and self.location == other.location def __hash__(self): return hash(str(self.time) + str(self.location.col) + str(self.location.row)) def __str__(self): return str((self.time, self.location.col, self.location.row)) def __lt__(self, other): if self.f < other.f: return True else: return False
4c3c61ec0353feb7821188778870f572c0728265
dward2/BME547Class
/analysis.py
198
3.671875
4
# analysis.py import calculator seconds_in_hour = calculator.multiply(60, 60) second_in_day = calculator.multiply(seconds_in_hour, 24) print("There are {} seconds in a day".format(second_in_day))
1e0fefcd119ee2e1fe1587667b2bf410f1d22549
Cyzerx/Scripts
/Emails/scrap1.py
1,980
3.515625
4
# -*- coding: utf-8 -*- """ Python script to bulk scrape websites for email addresses """ import urllib.request, urllib.error import re import csv import pandas as pd import os import ssl # 1: Get input file path from user '.../Documents/upw/websites.csv' user_input = input("Enter the path of your file: ") # If input file doesn't exist if not os.path.exists(user_input): print("File not found, verify the location - ", str(user_input)) # 2. read file df = pd.read_csv(user_input) # 3. create the output csv file with open('Emails.csv', mode='w', newline='') as file: csv_writer = csv.writer(file, delimiter=',') csv_writer.writerow(['Website', 'Email']) # 4. Get websites for site in list(df['Website']): try: # print(site) gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) req = urllib.request.Request("http://" + site, headers={ 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1", # 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive' }) # 5. Scrape email id with urllib.request.urlopen(req, context=gcontext) as url: s = url.read().decode('utf-8', 'ignore') email = re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", s) print(email) # 6. Write the output with open('Emails.csv', mode='a', newline='') as file: csv_writer = csv.writer(file, delimiter=',') [csv_writer.writerow([site, item]) for item in email] except urllib.error.URLError as e: print("Failed to open URL {0} Reason: {1}".format(site, e.reason))
3cd646626ff4c5aa84e4161f76230552a076e25d
syedyshiraz/Hackerearth
/jadoo vs koba.py
280
3.59375
4
ch=str(input()) st='' for i in ch: if(i=='G'): st=st+'C' elif(i=='C'): st=st+'G' elif(i=='A'): st=st+'U' elif(i=='T'): st=st+'A' else: print('Invalid Input') st='' break print(st)
13833a9668f6038c37c212e04021c8173aa4f798
sklagat45/ml_Algorithms
/perceptron.py
1,847
3.90625
4
# P15/101552/2017 # SAMUEL KIPLAGAT RUTTO import numpy as np # initialise the weights, learning rate and bias np.random.seed(42) # Ensures that we get the same random numbers every time weights = np.random.rand(3, 1) # Since we have three feature in the input, we have a vector of three weights bias = np.random.rand(1) learn_rate = 0.05 # Inputs and expected output training_set = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]]) classes = np.array([[1, 0, 0, 1, 1]]) classes = classes.reshape(5, 1) # rows by columns # Sigmoid function is used for the activation function def activ_func(x): return 1/(1+np.exp(-x)) # Derivative of the activation function which is used in finding the derivative of the cost function def activ_func_deriv(x): return activ_func(x) * (1 - activ_func(x)) # Training the neural network for epoch in range(20000): # Number of times the algorithm should run in order to minimize the error inputs = training_set # Feed-forward # Dot product of input and weights plus bias input_weights = np.dot(training_set, weights) + bias # Pass the dot product through the activ_func function z = activ_func(input_weights) # Back-pass # Print error error = z - classes print(error.sum()) # Use chain-rule to find derivative of cost function dcost_dpred = error dpred_dz = activ_func_deriv(z) z_delta = dcost_dpred * dpred_dz inputs = training_set.T weights -= learn_rate * np.dot(inputs, z_delta) for num in z_delta: bias -= learn_rate * num # Use a single instance to test which category the input falls under # single_point = np.array([1, 0, 0]) # result = activ_func(np.dot(single_point, weights) + bias) # print(result)
e27c1d39c34b9dcb5391eb9ec24497ee34412e95
rizkisadewa/MachineLearningA-Z
/Part 2 - Regression/Section 6 - Polynomial Regression/polynomial_regression.py
2,302
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 22 10:28:44 2019 @author: rizky """ # Polynomial Regression # Import the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import the dataset dataset = pd.read_csv('Position_Salaries.csv') # Make a matrix feature of the three independent variables X = dataset.iloc[:,1:2].values # Create the dependent variable vector Y = dataset.iloc[:,2].values # Splitting the dataset into Trainning set and Testing set from sklearn.model_selection import train_test_split # a library for splitting a dataset X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.2, random_state = 0) ''' the remark will be updated soon ''' # Feature Scaling """ from sklearn.preprocessing import StandardScaler # import class from library sc_X = StandardScaler() # an object from the class above X_train = sc_X.fit_transform(X_train) # fit the object and transform it X_test = sc_X.transform(X_test) # we only transfer the object as it's already fitted in train set """" ''' for the dependent variable vector do not have to be scalled due to the the value represent as category with 2 value "yes" or "no" ''' # Fitting Linear Regression to the dataset from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X, Y) # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg2 = LinearRegression() lin_reg2.fit(X_poly, Y) # Visualising the Linear Regression plt.scatter(X, Y, color='red') plt.plot(X, lin_reg.predict(X), color='blue') plt.title('Truth or Bluff (Linear Regression)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() # Visualising the Polynomial Regression X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, Y, color='red') plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)), color='blue') plt.title('Truth or Bluff (Polynomial Regression)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() # Predict a new result with Linear Regression lin_reg.predict(6.5) # Predict a new result with Polynomial Regression lin_reg2.predict(poly_reg.fit_transform(6.5))
58c58dbaf3ad230ec20eded8beed69a34cb0d5bf
PawelKapusta/Python-University_Classes
/Lab10/queue_lib.py
544
3.75
4
class Queue: def __init__(self, elems=None): if elems is None: elems = [] self.items = elems def __str__(self): return str(self.items) def __eq__(self, other): return self.items == other.items def is_empty(self): return not self.items def is_full(self): return False def put(self, data): if self.is_full(): raise OverflowError("Queue is full!") self.items.append(data) def get(self): if self.is_empty(): raise ValueError("Queue is empty!") return self.items.pop(0)
4f52547a0a15a57c72290bf61d21eb11a18668f2
PawelKapusta/Python-University_Classes
/Lab8/task1.py
590
3.8125
4
def solve1(a, b, c): if a == 0: if b == 0: if c == 0: print("identity equation") else: print("No solutions") else: if c == 0: print("Solution: y = 0") else: print("Solution: y =", -c / b) else: if b == 0: if c == 0: print("Solution: x = 0") else: print("Solution: x =", -c / a) else: if c == 0: print("Solution: y =", -a / b, "* x") else: print("Solution: y =", -a / b, "* x +", -c / b) print("Solution for equation 5x + 10y + 50 = 0: ") solve1(5, 10, 50)
2d3272a23f8cb49bc5dfa00f5fb27286adff493e
PawelKapusta/Python-University_Classes
/Lab2/task14.py
624
3.921875
4
def replaceChar(word): return str(word).replace('.', '').replace(',', '') def theLongest(words): return max(words,key=len) line = "Python is a high-level programming language designed to be easy to read and simple to implement.\n" \ "It is open source, which means it is free to use, even for commercial applications.\n" \ "Python can run on Mac, Windows, and Unix systems and has also been ported to Java and .NET virtual machines." words = line.split() results = list(map(replaceChar, words)) long = theLongest(results) print("The longest string in line is:",long,"and its length equals:",len(long))
51a2e174e5c69fb89bdb07708a86c774c972a659
PawelKapusta/Python-University_Classes
/Lab3/task6.py
581
4.03125
4
output = "" try: firstSide = int(input("Write first side of rectangle: ")) secondSide = int(input("Write second side of rectangle: ")) except ValueError: print("Check your input, maybe you do not write a number") else: for index in range(2 * firstSide + 1): if index % 2 == 0: output += "+" for i in range(secondSide): output += "---+" output += "\n" else: output += "|" for j in range(secondSide): output += " |" output += "\n" print(output)
490b309f4fed53ab48b914a9a1b8c6fa8934e45f
PawelKapusta/Python-University_Classes
/Lab4/task7.py
259
3.875
4
returned = [] def flatten(seq): for item in seq: if isinstance(item, (list, tuple)): flatten(item) else: returned.append(item) return returned seq = [1, (2, 3), [], [4, (5, 6, 7)], 8, [9]] print(flatten(seq))
52fc107624d46f57e2b99394196053e444eb7136
PawelKapusta/Python-University_Classes
/Lab8/task4.py
387
4.15625
4
import math def area(a, b, c): if not a + b >= c and a + c >= b and b + c >= a: raise ValueError('Not valid triangle check lengths of the sides') d = (a + b + c) / 2 return math.sqrt(d * (d - a) * (d - b) * (d - c)) print("Area of triangle with a = 3, b = 4, c = 5 equals = ", area(3, 4, 5)) print("Area of triangle with a = 15, b = 4, c = 50 equals = ", area(15, 4, 50))
8f8253c2114c5029661eb2660d200314bb7eacff
lucasrcz/Python-Exercises
/Python-01/exercicio 20.py
742
4.09375
4
# O mesmo professor do desafio anterior quer sortear a ordem #de apresentação do trabalho dos alunos. Faça um programa que #leia o nome dos quatro alunos e mostre a ordem sorteada import random from random import shuffle print('Bem vindo ao gerador de Listas Randômicas 1.0.') a1 = str(input('Digite o nome do segundo Aluno: ')) a2 = str(input('Digite o nome do segundo Aluno: ')) a3 = str(input('Digite o nome do terceiro Aluno: ')) a4 = str(input('Digite o nome do quarto Aluno: ')) lista=[a1,a2,a3,a4] random.shuffle(lista) #Cria-se a lista e logo após embaralha a mesma para que a lista saia de forma aleatória no print print('A ordem da lista gerada randômicamente é a seguinte: {}'.format(lista)) #Se você para selecionar
5614aa22786c0c72c3e4ec96a77904a54b67de3e
lucasrcz/Python-Exercises
/Python-01/exercicio 17.py
251
3.84375
4
from math import hypot oposto = float(input('Digite o comprimento do cateto oposto em M: ')) adj = float(input('Digite o comprimento do cateto adjacente em M: ')) print('O comprimento da hipotenusa é igual á {:.2f} M '.format(hypot(oposto, adj)))
023229ca86719b66aa7d8e1834631f284db9a88f
lucasrcz/Python-Exercises
/Python-01/Exercicio 28.py
259
3.984375
4
from random import randint print('Bem vindo ao jogo de adivinhação') n = int(input('Digite um número de 0 a 5: ')) m = randint(0, 5) if m == n: print('Você adivinhou o número, parabéns!') else: print('Você perdeu :(, tente novamente')
788b70df4320be219682ba0abd8697be77f8e3a6
Adinaytalalantbekova/pythonProject1
/homework_3.py
599
3.953125
4
letters = [] numbers = [] data_tuple = ('h', 6.13, 'C', 'e', 'T', True, 'K', 'e', 3, 'e', 1, 'G') for element in data_tuple: if(type(element)==str): letters.append(element) else: numbers.append(element) print(letters) print(numbers) numbers.remove(6.13) true = numbers.pop(0) letters.append(true) print(letters) print(numbers) numbers.insert(1, 2) print(numbers) numbers = sorted(numbers) print(numbers) letters.reverse() print(letters) letters[4] = 'k' letters[7] = 'c' print(letters) numbers = tuple(numbers) letters = tuple(letters) print(letters) print(numbers)
c2f0c2eb520f18c5235b3bef3ff87ca289723eb5
Adinaytalalantbekova/pythonProject1
/homework_2.py
773
4.03125
4
while True: number = int(input("Назавите код региона: ")) if number == 1: print('Бишкек') elif number == 2: print('Ош') elif number == 3: print('Баткен') elif number == 4: print('Жалал-Абад') elif number == 5: print('Нарын') elif number == 6: print('Ошская область') elif number == 7: print('Таласская область') elif number == 8: print('Чуйская область') elif number == 9: print('Иссык-Кульская область') elif number == 0: print('выйти из цикла') break else: print("Такого региона нет")
fa1200aaf3d92da9b51a6c124967ab88c94378e5
Adinaytalalantbekova/pythonProject1
/lesson_2..py
922
3.765625
4
# Условные конструкции и Операторы сравнения, Булеаны, Циклы # !=, <,>, <=, >=, not, and, or count = 0 rounds = 12 while not count == rounds: count += 1 if count == 6: print('knock down, finish') continue print(count) # bool() # zero = False # one = True # number = 5 # user = int(input('Enter the number: ')) # if number > user: # print('greater') # if number < user: # print('less') # if number == user: # print('equal') # else: # print('finish') # while True: # signal = input('Enter signal: ') # if signal == 'green' or signal == 'зеленый': # print('Go!') # elif signal == 'yellow' or signal == 'желтый': # print('ready') # elif signal == 'red' or signal == 'красный': # print('stop') # else: # print('look at the situation') # break
cfa1a3bd23631be1d067659f5d8ebf674341cad5
soon-h/BaekJoon
/BaekJoonBasic/5622.py
234
3.890625
4
dial = ['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ'] word = input() time = 0 for unit in dial : for i in unit: for x in word : if i == x : time += dial.index(unit) +3 print(time)
f81eb55666cfbe6f99b59ddca4df58f3dfe04140
soon-h/BaekJoon
/BaekJoonBasic/2884.py
284
3.75
4
Hour,Min = input().split() Hour = int(Hour) Min = int(Min) if Min < 45: if Hour == 0: Hour = 23 Min = 60 - (45 - Min) print(Hour,Min) else: Hour -= 1 Min = 60 - (45 - Min) print(Hour,Min) else: Min -= 45 print(Hour,Min)
849402be8f503d46883dc5e8238821566b33598b
Rajatku301999mar/Rock_Paper_Scissor_Game-Python
/Rock_paper_scissor.py
2,350
4.21875
4
import random comp_wins=0 player_wins=0 def Choose_Option(): playerinput = input("What will you choose Rock, Paper or Scissor: ") if playerinput in ["Rock","rock", "r","R","ROCK"]: playerinput="r" elif playerinput in ["Paper","paper", "p","P","PAPER"]: playerinput="p" elif playerinput in ["Scissor","scissor", "s","S","SCISSOR"]: playerinput="s" else: print("I dont understand, try again.") Choose_Option() return playerinput def Computer_Option(): computerinput=random.randint(1,3) if computerinput==1: computerinput="r" elif computerinput==2: computerinput="p" else: computerinput="s" return computerinput while True: print("") playerinput=Choose_Option() computerinput=Computer_Option() print("") if playerinput=="r": if computerinput=="r": print("You choose Rock, Computer choose Rock, Match Tied...") elif computerinput=="p": print("You choose Rock, Computer choose Paper, You Lose...") comp_wins+=1 elif computerinput=="s": print("You choose Rock, Computer choose Scissor, You Win...") player_wins+=1 elif playerinput=="p": if computerinput=="r": print("You choose Paper, Computer choose Rock, You Win...") player_wins+=1 elif computerinput=="p": print("You choose Paper, Computer choose Paper, Match Tied...") elif computerinput=="s": print("You choose Paper, Computer choose Scissor, You Lose...") comp_wins+=1 elif playerinput=="s": if computerinput=="r": print("You choose Scissor, Computer choose Rock, You Lose...") comp_wins+=1 elif computerinput=="p": print("You choose Scissor, Computer choose Paper, You Win...") player_wins+=1 elif computerinput=="s": print("You choose Scissor, Computer choose Scissor, Match Tied...") print("") print("Player wins: "+ str(player_wins)) print("Computer wins: " + str(comp_wins)) print("") playerinput=input("Do you want to play again? (y,n)") if playerinput in ["Y","y","Yes","yes"]: pass elif playerinput in ["N","n","No","no"]: break else: break
f9ac9c75d756a1548225c139265206ffb70e3bfc
manzeelaferdows/week3_homework
/data_types.py
1,481
4.1875
4
str = 'Norwegian Blue', "Mr Khan's Bike" list = ['cheddar', ['Camembert', 'Brie'], 'Stilton', 'Brie', 'Brie'] tuples = (47, 'spam', 'Major', 638, 'Ovine Aviation') tuples2 = (36, 29, 63) set = {'cheeseburger', 'icecream', 'chicken nuggets'} dict = {'Totness': 'Barber', 'BritishColumbia': 'Lumberjack'} print(len(list)) print(min(tuples2)) print(max(tuples2)) print(sum(tuples2)) a = 'Mash Potato' b = 'Gravy' print(a, b) a, b = b, a print(a, b) Gouda, Edam, Caithness = range(3) print(range) Belgium = 'Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German' Belgium2 = Belgium*2 print(Belgium2) thing = 'Hello' print(type(thing)) thing = ('Hello',) print(type(thing)) list[:0] = ['Newham', 'Hackney'] print(list) list += ['Southwark', 'Barking'] print(list) list.extend(['Dagenham', 'Croydon']) print(list) list.insert(5, 'Tottenham') print(list) list[5:5] = ['Edmonton'] print(list) list2 = list.pop(1) print(list2) list3 = list.pop(3) print('the two items we removed:', list2, 'and', list3, "Now the list is shorter:", list) list.remove('Edmonton') print(list) print(list.count('Brie')) print(list.index('Brie')) list.reverse() print(list) set1 = {5, 6, 7, 8, 9} set2 = {10, 11, 12, 13} print(set1) print(set2) set1.remove(9) print(set1) set2.add(9) print(set2) print(len(set2)) list4 = [1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5] list4b = ["cat", "dog", "cat", "dog"] list4_set = set(list4) list4 = list(list4_set) print(list4)
e36f1118cfbfd8ac36951fe666b499717c5a22b5
manzeelaferdows/week3_homework
/lotto.py
685
3.984375
4
import random #print(help(random)) lucky_numbers = input('please type in your 6 lucky numbers') lotto_numbers = [] for i in range(0, 6): number = random.randint(1, 50) while number in lotto_numbers: number = random.randint(1, 50) lotto_numbers.append(number) print(lotto_numbers) if lotto_numbers == lucky_numbers: print("You win as the lottery numbers {} matches your lucky numbers{}".format(lotto_numbers, lucky_numbers)) else: print("Better luck next time. The lottery numbers {} didn't match your lucky numbers{}".format(lotto_numbers, lucky_numbers))
f4222eae8a9be74bd2a743bbb7ab0bb8c4300887
Gabyluu/Python-Proyectos
/#clasesObjetos.py
867
3.515625
4
#clasesObjetos.py class MixinsData(object); def__init__(self, user="anonimo", password="patito", port="1234", ost="localhost", db="sqlite3"); self.user = user self.password = password self.port = port self.ost = host self.db = db #metodos para recuperar datos def get_username(self): return self.user def get_password(self): return self.password def get_port(self): return self.port def get_host(self): return self.host def get_db(self): return self.db #atributos usuario= str(input("Nombre del usuario? :_____")) password = str(input("Password?:___ ")) obj = MixinsData(password= password, user=usuario) print(obj.user) print(obj.password) print(obj.get_username()) user = obj.get_username() print(user*10)
446c481634d6cf1cebf897533cfe9baaacce2c3e
plaetzaw/htx-immersive-01-20
/01-week/4-Thursday/lectureNotes/class.py
3,142
4.125
4
# Hello # Hello # Hello # count = 0 # while count < 3: # print('Hello') # count += 1 # alphabet = [1, 2, 3, 4, 5, 6, 7] # new_list = alphabet[2:5] # myVar = 1 # mvVar2 = 2 # def greeting(): # print("hello world") # if (myVar == 1): # print('Hello') # greeting() # def print_students(): # print("Shu Pei") # print("Thomas") # print("Gustavo Fette") # print("Alim") # print("Day 1: Students in SRE class") # print("lecture: git 101") # print_students() # print("Day 2: Students in SRE class") # print("lecture: git 102") # print_students() # print("Day 3: Students in SRE class") # print("lecture: python 101") # print_students() # def myFunction(): # for i in range(10): # print(i) # def greeting(): # print('hello') # for i in range(10): # greeting() # def separateRuns(): # print('******************') # print() # def getGroceries(): # print('milk') # print('flour') # print('sugar') # print('butter') # separateRuns() # for i in range(3): # getGroceries() # def greeting(person): # print(f'hello {person}') # greeting('Kazim') # def add(num1, num2): # sum = num1 + num2 # return sum # result = add(4, 5) # # print(result) # def concat_lists(list1, list2): # concat = list1 + list2 # return concat # c_result = concat_lists([1, 4, 6], [7, 9, 0]) # print(c_result) # def cal_avg(param1, param2, param3, parm4): # sum = param1 + param2 + param3 + parm4 # avg = sum / 4 # return avg # result = cal_avg(4, 6, 9, 0) # print(result) # print(cal_avg(6, 8, 22, 11)) # def myFunction(num1, num2, num3): # return num1*2, num2*3, num3*4 # c1, c2, c3 = myFunction(4, 7, 9) # print(c1) # print(c2) # print(c3) # def addTwo(startingValue): # endingValue = startingValue + 2 # print('The sum of', startingValue, 'and 2 is:', endingValue) # return endingValue # result = addTwo(5) # print(result) # print("hello") # def greeting(name): # print(f'hello {name}') # students = ['Kazim', "Matt", "Alina", "Mary", "Alex"] # for name in students: # greeting(name) # print("bye") # TAX_RATE = .09 # 9 percent tax # COST_PER_SMALL_WIDGET = 5.00 # COST_PER_LARGE_WIDGET = 8.00 # def calculateCost(nSmallWidgets, nLargeWidgets): # TAX_RATE = 7 # subTotal = (nSmallWidgets * COST_PER_SMALL_WIDGET) + (nLargeWidgets * COST_PER_LARGE_WIDGET) # taxAmount = subTotal * TAX_RATE # totalCost = subTotal + taxAmount # return totalCost # total1 = calculateCost(4, 8) # 4 small and 8 large widgets # print('Total for first order is', total1) # total2 = calculateCost(12, 15) # def dance2(): # print("I want to do a %s dance" % kind) # def dance(): # kind = "silly" # print("I am doing a %s dance" % kind) # dance2() # dance() # def dance(kind="silly"): # print("I am doing a %s dance" % kind) # dance("funky") # Totally OK. # print(kind) # Error! def dance(kind="silly"): print(f'I am doing a {kind} dance') dance("funky") # Totally OK.