blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bab5047463f263311de080b527a017f76ea9680b
ksaubhri12/ds_algo
/practice_450/graph/05_cycle_undirected_graph.py
732
3.640625
4
def is_cyclic(graph: [[]], v): visited = [False] * v for i in range(v): if not visited[i]: if dfs_util(i, visited, graph, -1): return True return False def dfs_util(vertex: int, visited: [], graph: [[]], parent: int): visited[vertex] = True for neighbour in graph[vertex]: if not visited[neighbour]: if dfs_util(neighbour, visited, graph, vertex): return True else: if neighbour != parent: return True if __name__ == '__main__': graph_edge = [[1], [0, 2, 4], [1, 3], [2, 4], [1, 3]] print(is_cyclic(graph_edge, 5)) graph_edge = [[], [2], [1, 3], [2]] print(is_cyclic(graph_edge, 4))
a7fe6382d8f6f8bdcf40227bfbdcc8ddee87929d
SoftwareDojo/Katas
/Python/Katas/WordWrap/wordwrap.py
600
3.625
4
class wordwrap(object): def wrap(text, length): result = "" currentLength = 0 for value in str(text).split(" "): if currentLength > 0: result += wordwrap.__newline_or_whitespace(currentLength, len(value), length) currentLength += len(value) result += value return result def __newline_or_whitespace(currentLength, wordLength, maxLength): if currentLength + wordLength < maxLength: currentLength += 1 return " " currentLength = 0 return "\n"
d0dba32ca24ebce454a8c35c6d936274741c896d
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Tree_Revisited/Binary_Search_Tree.py
9,222
4.15625
4
# this code makes the tree that we'll traverse from collections import deque class Queue(): def __init__(self): self.q = deque() def enq(self, value): self.q.appendleft(value) def deq(self): if len(self.q) > 0: return self.q.pop() else: return None def __len__(self): return len(self.q) def __repr__(self): if len(self.q) > 0: s = "<enqueue here>\n_________________\n" s += "\n_________________\n".join([str(item) for item in self.q]) s += "\n_________________\n<dequeue here>" return s else: return "<queue is empty>" class Node(object): def __init__(self, value=None): self.value = value self.left = None self.right = None def set_value(self, value): self.value = value def get_value(self): return self.value def set_left_child(self, left): self.left = left def set_right_child(self, right): self.right = right def get_left_child(self): return self.left def get_right_child(self): return self.right def has_left_child(self): return self.left != None def has_right_child(self): return self.right != None # define __repr_ to decide what a print statement displays for a Node object def __repr__(self): return f"Node({self.get_value()})" def __str__(self): return f"Node({self.get_value()})" class Tree(): def __init__(self): self.root = None def set_root(self, value): self.root = Node(value) def get_root(self): return self.root def compare(self, node, new_node): """ 0 means new_node equals node -1 means new node less than existing node 1 means new node greater than existing node """ if new_node.get_value() == node.get_value(): return 0 elif new_node.get_value() < node.get_value(): return -1 else: return 1 """ define insert here can use a for loop (try one or both ways) """ def insert_with_loop(self, new_value): node = self.get_root() new_node = Node(new_value) if node is None: self.root = new_node return while True: if node.get_value() > new_value: if node.has_left_child() is False: node.left = new_node break node = node.left continue elif node.get_value() < new_value: if node.has_right_child() is False: node.right = new_node break node = node.right continue else: node.set_value = new_value break """ define insert here (can use recursion) try one or both ways """ def insert_recursion(self,node,new_node): if self.compare(node,new_node) == -1: if node.has_left_child() is False: node.left = new_node return else: self.insert_recursion(node.left,new_node) elif self.compare(node,new_node) == 1: if node.has_right_child() is False: node.right = new_node return else: self.insert_recursion(node.right,new_node) else: node.set_value = new_node.get_value return def insert_with_recursion(self, value): if self.root is None: self.root = Node(value) return node = self.root new_node = Node(value) return self.insert_recursion(node,new_node) ### Delete Cases def delete_case_2_l(self,node,node_delete): # node to be deleted has a left child pass def delete_case_2_r(self,node,node_delete): pass def delete_case_3_l(self,node,node_delete): pass def delete_case_3_r(self,node,node_delete): pass def delete(self,val): if self.search(val) is False: return -1 new_node = Node(val) node = self.root if node.get_value() == val: # Delete root if not node.has_left_child() and not node.has_right_child(): return None elif node.has_left_child() and not node.has_right_child(): self.root = node.get_left_child() return elif node.has_right_child() and not node.has_left_child(): self.root = node.get_right_child() return else: return self.delete_case_3(node,new_node) left_right = 0 # -1 when left node has to be deleted and +1 when the right node has to be deleted while True: if node is None: break compare = self.compare(node,new_node) if compare == 1: compare_right = self.compare(node.get_right_child(),new_node) if compare_right == 0: left_right = 1 break else: node = node.get_right_child() elif compare == -1: compare_left = self.compare(node.get_left_child(),new_node) if compare_left == 0: left_right = -1 break else: node = node.get_left_child() else: return -1 if left_right == -1: # left child case node_delete = node.get_left_child() if node_delete.has_left_child() and node_delete.has_right_child(): return self.delete_case_3(node,node_delete) elif node_delete.has_left_child() and not node_delete.has_right_child(): return self.delete_case_2_l(node,node_delete) elif node_delete.has_right_child() and not node_delete.has_left_child(): return self.delete_case_2_r(node,node_delete) else: node.set_left_child(None) elif left_right == 1: # Right child case node_delete = node.get_right_child() if node_delete.has_right_child() and node_delete.has_left_child(): return self.delete_case_3(node,node_delete) elif node_delete.has_right_child() and not node_delete.has_left_child(): return self.delete_2_r(node,node_delete) elif node_delete.has_left_child() and not node_delete.has_right_child(): return self.delete_2_l(node,node_delete) else: node.set_right_child(None) return """ implement search """ def search(self, value): node = self.root new_node = Node(value) while True: if node is None: break compare = self.compare(node,new_node) if compare == -1: if node.has_left_child() is False: return False else: node = node.get_left_child() continue if compare == 1: if node.has_right_child() is False: return False else: node = node.get_right_child() continue else: return True return False def __repr__(self): level = 0 q = Queue() visit_order = list() node = self.get_root() q.enq((node, level)) while (len(q) > 0): node, level = q.deq() if node == None: visit_order.append(("<empty>", level)) continue visit_order.append((node, level)) if node.has_left_child(): q.enq((node.get_left_child(), level + 1)) else: q.enq((None, level + 1)) if node.has_right_child(): q.enq((node.get_right_child(), level + 1)) else: q.enq((None, level + 1)) s = "Tree\n" previous_level = -1 for i in range(len(visit_order)): node, level = visit_order[i] if level == previous_level: s += " | " + str(node) else: s += "\n" + str(node) previous_level = level return s # tree = Tree() # tree.insert_with_loop(5) # tree.insert_with_loop(6) # tree.insert_with_loop(4) # tree.insert_with_loop(2) # tree.insert_with_loop(5) # insert duplicate # print(tree) tree = Tree() tree.insert_with_recursion(5) tree.insert_with_recursion(3) tree.insert_with_recursion(4) tree.insert_with_recursion(7) tree.insert_with_recursion(6) tree.insert_with_recursion(10) # insert duplicate tree.insert_with_recursion(9) tree.insert_with_recursion(8) tree.insert_with_recursion(8.5) # print(tree) tree.delete(7.5) print(f""" search for 8: {tree.search(8)} search for 2: {tree.search(2)} search for 5: {tree.search(5)} """) print(tree)
839d70176ecfb9f5d9edf407e541266c8f6b9b17
petushoque/spa-django-rest-nuxtjs
/section3lesson1step4.py
662
3.71875
4
# решение с подключением дополнительной библиотеки import roman; s = input() print(roman.fromRoman(s)) # готовая функция для перевода def romanToInt(s): result=0 f={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} i=0 while i < len(s)-1: if f[s[i+1]] > f[s[i]]: result+=f[s[i+1]]-f[s[i]] i+=2 else: result+=f[s[i]] i+=1 if i<len(s): result+=f[s[len(s)-1]] return result print(romanToInt('III'))
37e9440da26eb15bd1ea1a74b329e3f220b71891
AdarshNamdev/Python-Practice-Files
/Constructor&Method_Overriding_Super().py
1,391
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 10 20:02:15 2021 @author: adars """ class father(object): def __init__(self, name, age, prop): self.prop = prop self.name = name self.age = age def getpropdetails(self): print("Father's Property: ", self.prop) class son(father): """ Here we are writing the derived class- 'son' and also Overriding the Constructor !! """ def __init__(self): self.prop = 85000 # Constructor Overriding def getpropdetails(self): """ Here the method- 'getpropdetails' are Overridden """ print("Son's Property: ", self.prop) # Method Overriding class daughter(father): def __init__(self, name, age, prop = 0, Dprop= 0): super().__init__(name, age, prop) # "super()" method to inherit variables and Methods from Base/Super Class- 'Father' self.Dprop = Dprop def getpropdetails(self): print("Father's Name: ", self.name) print("Father Age: ", self.age) print("Father's property: ", self.prop) print("Daughter's property: ", self.Dprop) print("Daughter's total property: ", self.Dprop + self.prop) sonny = son() sonny.getpropdetails() beti = daughter("Siraj-ud-daullah", 78, 70000, Dprop = 5000) beti.getpropdetails()
ab091a745c0a10c082ba1400d4156da47ed19823
CauchyPolymer/teaching_python
/python_intro/24_recursion.py
1,566
3.703125
4
def func_1(): #function은 정의를 하고 call을 하여 재활용을 한다. 중요한 개념 #일반적으로는 함수가 있고 글로벌에서 함수를 불러서 쓰는데, 함수 안에서 함수를 call 할 수 있다. print('hello') def func_2(): func_1() print('hello again')#func1이 끝나야 프린트 가능. func_2 #top-level -> func_2 -> func_1 #function call chain/ function call stack #call stack 이 넘치게 되면 에러가 남. print('-' * 40) import random def func_3(): print('in func 3') f = random.randrange(1, 10) * 100 b = func_4() return f + b def func_4(): print('in func 4') return random.randrange(1, 10) r = func_3() # print(r) # print('-' * 40) # # def recurse(n): #자기 스스로를 call할수가 있도록 되어있다. 그래서 재귀함수 'RECURSION' 이라고 칭한다! # print('hi-{}'.format(n)) # recurse(n+1) #최대 call stack 의 깊이가 1000이다. 메모리의 최대값. #recurse(1) #stack over flow ERROR print('-' * 40) def recurse_2(n): #STOFE가 안남. 이유는 print('hi-{}'.format(n)) if n == 25: #24까지 가고 recurse_2(25)는 n 이 25기 떄문에 끝나버림. return else: #스스로를 call 해도 상관이 없음. recurse_2(n + 1) recurse_2(1) print('-' * 40) def recurse_3(n): print('hi-{}'.format(n)) #call stack 이 올라갔다가 내려기는 피라미드 순서로 진행됨. if n == 0: return else: recurse_3(n - 1) print('returing - {}'.format(n)) recurse_3(10)
77c87985e22259462264afcfb4dc85d61617226e
AECassAWei/dsc80-wi20
/discussions/07/disc07.py
958
3.765625
4
import requests def url_list(): """ A list of urls to scrape. :Example: >>> isinstance(url_list(), list) True >>> len(url_list()) > 1 True """ url_list = [] for num in range(0, 26): url_list.append('http://example.webscraping.com/places/default/index/' + str(num)) return url_list def request_until_successful(url, N): """ impute (i.e. fill-in) the missing values of each column using the last digit of the value of column A. :Example: >>> resp = request_until_successful('http://quotes.toscrape.com', N=1) >>> resp.ok True >>> resp = request_until_successful('http://example.webscraping.com/', N=1) >>> isinstance(resp, requests.models.Response) or (resp is None) True """ if N==0: return None rq = requests.get(url) if rq.status_code != 200 and N>0: return request_until_successful(url, N-1) return rq
4f335b651346f568077bae94423995055976c730
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/meetup/92908cd0e4a24bf7986d6688dbd0c57a.py
1,706
3.765625
4
from datetime import date, timedelta def meetup_day(year, month, weekday_name, happens): weekday_number = __to_weekday_number__(weekday_name) if happens == '1st': return __first__(year, month, weekday_number) elif happens == 'teenth': return __teenth__(year, month, weekday_number) elif happens == 'last': return __last__(year, month, weekday_number) else: first_weekday = __first__(year, month, weekday_number) weeks = __ordinal_to_number__(happens) - 1 days = weeks * 7 day = first_weekday.day + days return date(year, month, day) def __to_weekday_number__(weekday_name): weekday_numbers = __weekday_numbers__() if weekday_numbers.has_key(weekday_name): return weekday_numbers[weekday_name] def __weekday_numbers__(): return { 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6, } def __first__(year, month, weekday_number): first_week = range(1,8) for day in first_week: meetup_date = date(year, month, day) if meetup_date.weekday() == weekday_number: return meetup_date def __teenth__(year, month, weekday_number): teens = range(13,20) for teen in teens: meetup_date = date(year,month,teen) if meetup_date.weekday() == weekday_number: return meetup_date def __ordinal_to_number__(simple_ordinal): return int(simple_ordinal[0]) def __last__(year, month, weekday_number): last_week = range(7) last_day = date(year, month+1, 1) - timedelta(days=1) day = last_day.day for days in last_week: meetup_date = date(year, month, day-days) if meetup_date.weekday() == weekday_number: return meetup_date
e9aafdc489d49887636a445d1f0276c0fb5e8c79
SaiSarathVattikuti/practice_programming
/s30-problem1.py
584
3.65625
4
import sys class Node: def __init__(self,value=None): self.value=value self.right_child=None self.left_child=None def validate_Bst(root,min=-sys.maxsize,max=sys.maxsize): if root==None: return True if(root.value>min and root.value<max and validate_Bst(root.left_child,min,root.value) and validate_Bst(root.right_child,root.value,max)): return True else: return False root=Node(5) r=Node(6) l=Node(5) root.left_child=l root.right_child=r print(validate_Bst(root))
ca9cd34a1999a714dc4902e9dd32a5f59d997376
ger-hernandez/UTP-backup
/week3/string3.py
441
3.765625
4
# #Solicitar el ingreso de una clave por teclado y almacenarla en una cadena de caracteres. #controlar que el string ingresado tenga entre 10 y 20 caracteres para que sea válido, # en caso contrario mostrar un mensaje de error. def clave(): c = input('ingrese una clave entre 10 y 20 caracteres de largo: \n') if len(c) < 10 or len(c) > 20: print('Ingresa bien esa monda care verga no sabes contar es animal!') clave()
c310fb05ea9c5ed702a0f61dc6ef137518282ff9
jxie0755/Learning_Python
/ProgrammingCourses/MIT6001X/week2/function_3.py
648
3.984375
4
def f(y): x = 1 x += 1 print(x) x = 5 f(x) print(x) # f(5), 重新定义x=1, 然后x+1=2 # 所以函数输出就是2 # 但是本身的print(x)依然输出5,因为x=2在函数内,不能影响函数外 def g(y): print(x) print(x + 1) n = 5 g(x) print(x) # g(5)首先寻找x,发现函数内没有,所以找函数外发现x=5 # 函数输出5和6 # print(x)依然不受函数影响还是输出5 def h(y): x = x + 1 x = 5 h(x) print(x) # h(5)报错, 同样是找不到函数内的x,继而使用函数外的x=5 # 然而,函数内将改变x的赋值,这是不允许的,因为函数内无法改变函数外的全局x的赋值
a1895a28eb09357b6e91d3045a5472671835ea10
daniel-reich/turbo-robot
/HBuWYyh5YCmDKF4uH_4.py
1,366
4.15625
4
""" An **almost-sorted sequence** is a sequence that is **strictly increasing** or **strictly decreasing** if you remove a **single element** from the list (no more, no less). Write a function that returns `True` if a list is **almost- sorted** , and `False` otherwise. For example, if you remove `80` from the first example, it is perfectly sorted in ascending order. Similarly, if you remove `7` from the second example, it is perfectly sorted in descending order. ### Examples almost_sorted([1, 3, 5, 9, 11, 80, 15, 33, 37, 41] ) ➞ True almost_sorted([6, 5, 4, 7, 3]) ➞ True almost_sorted([6, 4, 2, 0]) ➞ False // Sequence is already sorted. almost_sorted([7, 8, 9, 3, 10, 11, 12, 2]) ➞ False // Requires removal of more than 1 item. ### Notes * Completely sorted lists should return `False`. * Lists will always be **> 3** in length (to remove ambiguity). * Numbers in each input list will be unique - don't worry about "ties". """ def almost_sorted(lst): count_1=0 count_2=0 magic=0 i=1 while i<len(lst): if (lst[i-1]<lst[i]): count_1+=0 else: count_1+=1 i+=1 i=1 while i<len(lst): if lst[i-1]>lst[i]: count_2+=0 else: count_2+=1 i+=1 if count_1==1 or count_2==1: magic=True else: magic=False return(magic)
5d262e371c6b75e199d5de61cb953f1c157e4fe7
rajatmishra3108/Daily-Flash-PYTHON
/25 aug 2020/prog5.py
406
3.9375
4
from time import clock start = clock() history = {'French Revolution' : 1789, 'Industrial Revolution' : 1760, "Greek Revolution" : 1821, "Serbian Revolution" : 1748} n1 = input("Enter first event\n") n2 = input("Enter second event\n") for i in history : if n1 == i: year1 = history[i] elif n2 == i: year2 = history[i] print(abs(year1-year2)) end = clock() print(end - start)
87dd046d4ce79d4d8b2da655375889a6fc78d6a8
FawenYo/NTU_Programming-for-Business-Computing
/Assistant/1029/problem2.py
395
3.78125
4
import math def main(): mode = int(input()) number = int(input()) answer = calculate(mode=mode, number=number) print(answer) def calculate(mode, number): if mode == 1: result = math.log(number, 2) elif mode == 2: result = math.log(number, math.e) else: result = number ** 2 return float(result) if __name__ == "__main__": main()
06229817c1120a8b213f0eee2619800f85587bb8
liyingying1105/selenium7th
/day4/CsvFileManager3.py
1,012
3.59375
4
import csv #每个测试用例对应着不同的CSV文件,每条测试用例都会打开一个CSV文件,所以每次也应该关闭该文件 class CsvFileManger3: @classmethod def read(self): path=r'C:\Users\51Testing\PycharmProjects\selenium7th\data\test_data.csv' file=open(path,'r') try: #尝试执行一下代码 #通过CSV代码库读取打开的CSV文件,获取文件中所有数据 data_table=csv.reader(file) a=[1,2,3,4,5] a[7] #程序执行过程中是否报错,都能正常关闭打开的文件 for item in data_table: print(item) finally: #无论程序是否有错,finally是最终结果 file.close() #方法最后应该天机close()方法 if __name__ == '__main__': #csvr=CsvFileManger2() #csvr.read() #方法上面加上@classmethod ,表示这个方法可以直接用类调用.. 不需要先实例化对象后才能调用 CsvFileManger3.read()
638fa04ea7e66daa2202a0ed60f67d64a2077fb3
Yellow-Shadow/SICXE
/LinkingLoader2021/LinkingLoader/pass2.py
4,795
3.515625
4
import objreader def hexDig2hexStr(hexDig, length): hexDig = hexDig.upper() hexStr = hexDig[2:] # 0xFFFFF6 => FFFFF6 for i in range(0, length - len(hexStr)): # 位數不足補零 hexStr = '0' + hexStr return hexStr # Hex String => Dec Int Digit def hexStr2decDig(hexStr, bits): decDig = int(hexStr, 16) # 0xFFFFF6 => 16777206 if decDig & (1 << (bits-1)): # 2^0 << (bits-1) = 0x800000 => 8388608 decDig -= 1 << (bits) # Threshold Of Negative Number:Negative decDig > 7FFFFF >= Positive decDig # 2^0 << (bits) = 0x1000000 => 16777216 # if decDig >= int(pow(2, bits-1)): # decDig -= int(pow(2, bits)) return decDig # Dec Int Digit => Hex Int Digit def decDig2hexDig(decDig, bits): return hex((decDig + (1 << bits)) % (1 << bits)) # e.g. hex[(-10 + 256) % 256] = 0xF6 # e.g. hex[( 10 + 256) % 256] = 0x0A # Text Record # Col. 2-7: Starting address for object code in this record # Col. 8-9: Length of object code in this record in bytes # e.g. 0A: 10 bytes (20 half-bytes) # Col.10-69: Object code def processTRecord(Tline, CSADDR, PROGADDR, MemoryContent): TADDR = int(f'0x{Tline[1:7]}', 16) # 將 Address 從 string 更改成 hex digit TADDR += CSADDR TADDR -= PROGADDR TADDR *= 2 # 將 1byte (Binary) 用 2個 數字(HEX)表示, 故需要將 Address 兩倍 # e.g. 1011 0110 => B6 length = int(f'0x{Tline[7:9]}', 16) # 將 Length 從 string 更改成 hex digit for i in range(0, length * 2): # bytes = half-bytes * 2 MemoryContent[TADDR] = Tline[9 + i] # 將 Object code 照著 TADDR 的順序, 依序填入 MemoryContent 中 TADDR += 1 # Modification Record # Col. 2-7: Starting location of the address field to be modified, relative to the beginning of the program # Col. 8-9: Length of the address field to be modified (half-bytes) # Col. 10: Modification flag (+ or -) # Col. 11-16: External symbol whose value is to be added to or subtracted from the indicated field def processMRecord(Mline, CSADDR, PROGADDR, MemoryContent, ESTAB): MADDR = int(f'0x{Mline[1:7]}', 16) # 將 Address 從 string 更改成 hex digit MADDR += CSADDR MADDR -= PROGADDR MADDR *= 2 # 將 1byte (Binary) 用 2個 數字(HEX)表示, 故需要將 Address 兩倍 # e.g. 1011 0110 => B6 length = int(f'0x{Mline[7:9]}', 16) # 將 Length 從 string 更改成 hex digit if (length == 5): # "05"代表除了需要跳過 First Byte(OPCODE + n,i) MADDR += 1 # 還需要跳過 Second Half-Byte(x,b,p,e) # e.g."77100004" 跳過 "77" 與 "1", address field 才是 "00004" # FFFFF6 = ['F', 'F', 'F', 'F', 'F', '6'] current = "".join(MemoryContent)[MADDR:MADDR + length] # -10 = hexStr2decDig(0xFFFFF6, 24) decDig = hexStr2decDig(f'0x{current}', length * 4) # Mline 以 '\n' 結尾,故 token 的擷取位置是從 10 到 len(Mline)-1 key = Mline[10:len(Mline)-1] if Mline[9] == '+': decDig += ESTAB[key] else: decDig -= ESTAB[key] modifiedHexStr = hexDig2hexStr(decDig2hexDig(decDig, length * 4), length) for i in range(0, length): # 將更改後的 modifiedHexStr 照著 MADDR 的順序, 依序填入 MemoryContent 中 MemoryContent[MADDR] = modifiedHexStr[i] MADDR += 1 def execute(ESTAB, PROGADDR, PROG, MemoryContent): # Control Section Address CSADDR = PROGADDR for i in range(0, len(PROG)): lines = objreader.readOBJFiles(PROG[i]) # Header Record # Col. 2-7: Program name # Col. 8-13: Starting address (hexadecimal) # Col. 14-19 Length of object program in bytes Hline = objreader.readRecordWithoutSpace(lines[0]) # Replace All Space for Header Line # CSNAME = Hline[1:6] CSLTH = int(f'{Hline[12:18]}', 16) # 將 Address 從 string 更改成 hex digit for j in range(1, len(lines)): # Text Record if lines[j][0] == 'T': processTRecord(lines[j], CSADDR, PROGADDR, MemoryContent) # Modification Record if lines[j][0] == 'M': processMRecord(lines[j], CSADDR, PROGADDR, MemoryContent, ESTAB) CSADDR += CSLTH
97651d29357feb05578d80921320d53e1b07bd92
doraemon1293/Leetcode
/archive/592. Fraction Addition and Subtraction.py
943
3.75
4
import re class Solution: def fractionAddition(self, expression): """ :type expression: str :rtype: str """ def gcd(a, b): while a % b: a, b = b, a % b return b def add(a, b, c, d): x = a * d + b * c y = b * d if x == 0: return (0, 1) temp = gcd(x, y) return (x // temp, y // temp) nums = [x for x in re.split("[+-]", expression) if x] symbols = (["+"] if expression[0] != "-" else []) + [x for x in expression if x == "-" or x == "+"] print(nums) print(symbols) a, b = 0, 1 for i in range(len(nums)): c, d = nums[i].split("/") c = int(c) if symbols[i] == "+" else int("-" + c) d = int(d) x, y = add(a, b, c, d) a, b = x, y return str(a) + "/" + str(b)
afd7678af6043e8098f508bd56a3aa912ff848ce
GMBAMorera/OC_projet_3
/Labyrinths.py
2,361
3.578125
4
from random import randrange from constants import OBJECT_TILES from Exceptions import InvalidLabyrinth class Labyrinth: def __init__(self, lab): self.path_to_array(lab) self.column_length = len(self.lab) self.row_length = len(self.lab[0]) self.compare() self.haystacking() def haystacking(self): """Put the needle and other objects into the labyrinth.""" temp = self.array_to_list() for obj in OBJECT_TILES[2:]: # Choose a floor tile loc = temp.count('0') loc = randrange(loc) # Et put it the object for i, _ in enumerate(temp): if temp[:i+1].count('0') == loc: temp[i] = obj break self.list_to_array(temp) def compare(self): """Check if the labyrinth will function.""" # Check if the labyrinth is a rectangel for line in self.lab: if len(line) != self.row_length: raise InvalidLabyrinth( 'toutes les lignes de votre labyrinthe \ doivent avoir la même taille') # Check if all the good letters have been used temp = self.array_to_list() count = temp.count if count('K') != 1 or count('M') != 1: raise InvalidLabyrinth("Il doit y avoir exactement un \ gardien et un mac_gyver!") if not count('0') + count('1') + count('\n') == len(temp) - 2: raise InvalidLabyrinth('seuls les charactères 0,1,K et M \ doivent être utilisé pour le labyrinthe') def path_to_array(self, lab): """Transform a folder to a labyrinth to an array.""" with open(lab) as lab: self.lab = lab.readlines() # delete all new lines typo for i, line in enumerate(self.lab): if line.endswith('\n'): self.lab[i] = line[:-1] def array_to_list(self): """Transform a labyrinth-array to a labyrinth-list.""" # Plac new line typo in order to easily cut the list again latter return list('\n'.join(self.lab)) def list_to_array(self, temp): """Transform a labyrinth-list to a labyrinth-array.""" self.lab = (''.join(temp)).split()
3e79e6ebd06b6d665c798279a6a4b29f09f33507
emilea12/Python-
/Panda_Tutorial.py
1,884
4.5625
5
import pandas as pd import numpy as np #The primary data structures in pandas are implemented as two classes: #DataFrame, which you can imagine as a relational data table, with rows and named columns. #Series, which is a single column. A DataFrame contains one or more Series and a name for each Series. california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",") california_housing_dataframe.describe(include='all') california_housing_dataframe.head california_housing_dataframe.hist('housing_median_age') #print(california_housing_dataframe) #DataFrame objects can be created by passing a dict mapping string column names to their respective Series. If the Series don't match in length, missing values are filled with special NA/NaN values. Example: city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) cities = pd.DataFrame({ 'City name': city_names, 'Population': population }) print (cities['City name']) np.log(population) #Modifying DataFrames is also straightforward. For example, the following code adds two Series to an existing DataFrame: cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92]) cities['Population density'] = cities['Population'] / cities['Area square miles'] # The example below creates a new Series that indicates whether population is over one million: population.apply(lambda val: val > 1000000) #Modify the cities table by adding a new boolean column that is True if and only if both of the following are True: #The city is named after a saint. #The city has an area greater than 50 square miles. cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San')) cities.reindex([2, 0, 1]) print(cities)
e26204aaed58da7c765ef06c2be8f9931e837d68
bjfletc/Learning-Python-4th-Edition
/Chapter 4, Introducing Python Object Types/userDefinedClasses.py
759
3.828125
4
''' We’ll study object-oriented programming in Python—an optional but powerful feature of the language that cuts development time by supporting programming by customization— in depth later in this book. In abstract terms, though, classes define new types of objects that extend the core set, so they merit a passing glance here. Say, for example, that you wish to have a type of object that models employees. Although there is no such specific core type in Python, the following user-defined class might fit the bill: ''' class Worker: def __init__(self, name, pay): self.name = name self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1.0 + percent)
0fda531a0602f48c6ae385baeeb358542b211555
runningshuai/jz_offer
/33.丑数.py
1,621
3.890625
4
""" 题目描述 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 思路: 从1开始,我们只用比较3个数:u2:用于乘2的数,u3:乘3的数,u5:乘5的数,然后取最小的数 最小的数取完之后,更新当前的数,例如u2 * 2 一直循环,直到取N个 """ class Solution: def GetUglyNumber_Solution(self, index): # write code here if index < 7: return index ugly = [1] # 初始化待比较的三个数,这三个数都是乘的同一个数,只有这个数消费掉,才可以乘下一个 # 2, 3, 5需要乘的序列就是丑数序列,即第一次都乘1,第二次都乘2, 第三次都乘3 # 需要注意的是,不是同时乘的,是当前这个数被消费掉才去乘的 u2, u3, u5 = 2, 3, 5 # 记录乘了第几个 i2, i3, i5 = 0, 0, 0 while len(ugly) < index: temp = min(u2, u3, u5) ugly.append(temp) # 需要找到哪一个最小的数被取走了,然后开始乘下一个数,并更新 if temp == u2: i2 += 1 u2 = 2 * ugly[i2] if temp == u3: i3 += 1 u3 = 3 * ugly[i3] if temp == u5: i5 += 1 u5 = 5 * ugly[i5] return ugly[-1] if __name__ == '__main__': s = Solution() print(s.GetUglyNumber_Solution(11))
b84cda4022254d68719da575fbb73fa14704ef6f
vkagwiria/thecodevillage
/Python week 1/Python day 4/exercise4.py
213
4.1875
4
num=int(input("Insert your number here: ")) numsquare = num**2 if (num>10): print(" The square of your number {} is {}.".format(num, numsquare)) else: print("Your number needs to be greater than 10.")
220eb07259efae7dcfead7551527549a11a14e21
RichLuna/g-challenge
/g-challenge.py
2,126
3.5625
4
#Abrimos el documento con el numero e. Puedes ingorar completamente esta parte def open_e(): e_file = open("euler.txt") e = e_file.read() return e ######################################################################### #Start challenge here ######################################################################## """ Encuentra la primer cifra de 10 dígitos que sea un numero primo dentro de los digitos de el número de Euler. Los números primos son aquellos que solo pueden dividirse entre 1 y ellos mismos. Ejemplo: El número e es: 2.718281828459045235360287471352662497757... La primer cifra de 10 dígitos es 7182818284 y no es primo. La segunda cifra es 1828182845 y tampoco es primo etc La función "open_e()" regresa el número e con aproximadamente un millón de dígitos de precisión. PRO TIPS 1. Primero resuelve el probema. Después optimiza, pero solo si es necesario 2. Las cadenas son iterables como listas. Eso quiere decir que puedes iterar sobre ellas con un for 3. Igualmente puedes usar slices con cadenas 4. Divide y vencerás. Si separas tareas en funciones puede que el ejercicio sea mas claro 5. Python está muy bien documentado. Si lo necesitas consulta: https://docs.python.org/3/library/string.html 6. La repsuesta es 7427466391. Lo importante es el código, no la repsuesta. """ #Obtenemos el número e e = open_e() def removeWhiteSpaces(eulerString): return "".join(eulerString.split()) def isPrime(n): for i in range(2,n): if n % i == 0: return False return True def findPrimeNumber (eulerNumberListWithSpace): eulerNumberList = removeWhiteSpaces(eulerNumberListWithSpace) indexStart = 2 indexFinal = 12 indexEuler = len(eulerNumberList) while(indexFinal <= indexEuler): listEuler = eulerNumberList[indexStart:indexFinal] checkPrime = isPrime(int(listEuler)) if(checkPrime): return listEuler indexStart+=1 indexFinal+=1 return "Not Found" output = findPrimeNumber(e) print("Result: " + str(output))
4c0a69994f609c42e8aafa21172185da9f8ef352
shunjizhan/Gradient-Descent
/gd.py
3,336
3.625
4
import numpy as np from random import randint import matplotlib.pyplot as plt import matplotlib.ticker as ticker from sklearn.preprocessing import normalize def n(v): return normalize(v[:, np.newaxis], axis=0).ravel() class GradientDescent: def __init__(self): self.n, self.d = 6000, 100 self.X = np.random.normal(size=(self.n, self.d)) self.beta_real = np.random.rand(self.d) self.Y = self.X.dot(self.beta_real) self.main() def main(self): beta_rand = np.random.rand(self.d) # initial beta for GD errors_GD = self.GD(np.copy(beta_rand)) errors_NAGD = self.NAGD(np.copy(beta_rand)) errors_SGD = self.SGD(np.copy(beta_rand)) print errors_GD[:5] print errors_NAGD[:5] print errors_SGD[:5] # set y axis to display integer # fig, ax = plt.subplots() # ax.yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) plt.xlabel('iterations') plt.ylabel('f(x)') X = np.arange(50) plt.plot(X, errors_GD, 'r-', label='GD') plt.plot(X, errors_NAGD, 'b-', label='NAGD') plt.legend(loc='upper right') plt.show() plt.plot(errors_SGD, label='SGD') plt.legend(loc='upper right') plt.show() # I view the function f(x) as the squared error function for: # Y = X*beta, so in gradient descent we calculates beta # self.sqr_error() calculate f(x) in the question, which is: # (2/n)*(X*beta - b) def GD(self, beta): step = 0.025 errors = [] for i in range(50): sqr_error_ = self.sqr_error(beta) errors.append(sqr_error_) # update beta beta -= step * self.gradient(beta) return errors def NAGD(self, beta): y, z = np.copy(beta), np.copy(beta) step = 0.025 errors = [] for i in range(50): sqr_error_ = self.sqr_error(beta) errors.append(sqr_error_) # update beta g = self.gradient(beta) a = 2.0 / (i + 3) y = beta - step * g z -= ((i + 1) / 2) * step * g beta = (1 - a) * y + a * z return errors def SGD(self, beta): step = 0.005 errors = [] for i in range(300): sqr_error_ = self.sqr_error(beta) errors.append(sqr_error_) # update beta beta = beta - step * self.stochastic_gradient(beta) return errors # gradient of f(X) = (X*Beta - y) ^ 2 / N def gradient(self, beta): X, Y = self.X, self.Y g = np.zeros(X.shape[1]) for i in range(X.shape[0]): xi = X[i, :] yi = Y[i] g += xi * (xi.dot(beta) - yi) return g * 2 / X.shape[0] # estimator of gradient of f(X) = (X*Beta - y) ^ 2 / N def stochastic_gradient(self, beta): X, Y = self.X, self.Y i = randint(0, X.shape[0]) xi_T = X[i, :] xi = np.transpose(xi_T) yi = Y[i] return xi * (xi_T.dot(beta) - yi) * 2 # squared error def sqr_error(self, beta): X, Y = self.X, self.Y N = X.shape[0] temp = X.dot(beta) - Y return temp.dot(temp) / N if __name__ == '__main__': lm = GradientDescent()
6aee4a08f9364faad53bffab4a9ebbf90f3cc012
Untamanei/Sudoku-AI-Problem
/sudoku4.py
5,761
4.15625
4
''' Exercise4.1: Apply Constraint Propagation to Sudoku problem Now that you see how we apply Constraint Propagation to this problem, let's try to code it! In the following quiz, combine the functions eliminate and only_choice to write the function reduce_puzzle, which receives as input an unsolved puzzle and applies our two constraints repeatedly in an attempt to solve it. Some things to watch out for: - The function needs to stop if the puzzle gets solved. How to do this? - What if the function doesn't solve the sudoku? Can we make sure the function quits when applying the two strategies stops making progress? ''' # 1. utils.py ---------------------------- # 1.1 define rows: rows = 'ABCDEFGHI' # 1.2 define cols: cols = '123456789' # 1.3 cross(a,b) helper function to create boxes, row_units, column_units, square_units, unitlist def cross(a, b): return [s + t for s in a for t in b] # 1.4 create boxes boxes = cross(rows, cols) # 1.5 create row_units row_units = [cross(r, cols) for r in rows] # 1.6 create column_units column_units = [cross(rows, c) for c in cols] # 1.7 create square_units for 9x9 squares square_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')] # 1.8 create unitlist for all units unitlist = row_units + column_units + square_units # 1.9 create peers of a unit from all units units = dict((s, [u for u in unitlist if s in u]) for s in boxes) peers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes) # 1.10 display function receiving "values" as a dictionary and display a 9x9 suduku board def display(values): """ Display the values as a 2-D grid. Input: The sudoku in dictionary form Output: None """ width = 1 + max(len(values[s]) for s in boxes) line = '+'.join(['-' * (width * 3)] * 3) for r in rows: print(''.join(values[r + c].center(width) + ('|' if c in '36' else '') for c in cols)) if r in 'CF': print(line) return def grid_values(grid): """Convert grid string into {<box>: <value>} dict with '123456789' value for empties. Args: grid: Sudoku grid in string form, 81 characters long Returns: Sudoku grid in dictionary form: - keys: Box labels, e.g. 'A1' - values: Value in corresponding box, e.g. '8', or '123456789' if it is empty. """ ''' Your solution here ''' chars = [] for c in grid: chars.append(c) assert len(chars) == 81 return dict(zip(boxes, chars)) values = grid_values('..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..') print("\n") print("The original Sudoku board is **********************************************") display(values) def eliminate(values): """Eliminate values from peers of each box with a single value. Go through all the boxes, and whenever there is a box with a single value, eliminate this value from the set of values of all its peers. Args: values: Sudoku in dictionary form. Returns: Resulting Sudoku in dictionary form after eliminating values. """ ''' Your solution here ''' for key, value in values.items(): if (len(value) == 1): for key_peer in peers[key]: values[key_peer] = values[key_peer].replace(value, '') return values eliminate(values) print("\n") print("After implement eliminate(values) method **********************************") display(values) def only_choice(values): """Finalize all values that are the only choice for a unit. Go through all the units, and whenever there is a unit with a value that only fits in one box, assign the value to this box. Input: Sudoku in dictionary form. Output: Resulting Sudoku in dictionary form after filling in only choices. """ ''' Your solution here ''' new_values = values.copy() for unit in unitlist: for digit in '123456789': dplaces = [box for box in unit if digit in values[box]] if len(dplaces) == 1: new_values[dplaces[0]] = digit return new_values new_values = only_choice(values) print("\n") print("After implement only_choice(values) method **********************************") display(new_values) # 2. function.py ---------------------------- # 2.1 combine the functions eliminate and only_choice to write the function reduce_puzzle # from utils import * def reduce_puzzle(values): """ Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False. If the sudoku is solved, return the sudoku. If after an iteration of both functions, the sudoku remains the same, return the sudoku. Input: A sudoku in dictionary form. Output: The resulting sudoku in dictionary form. """ ''' Your solution here ''' solved_values = [box for box in values.keys() if len(values[box]) == 1] stalled = False while not stalled: solved_values_before = len([box for box in values.keys() if len(values[box]) == 1]) values = eliminate(values) values = only_choice(values) solved_values_after = len([box for box in values.keys() if len(values[box]) == 1]) stalled = solved_values_before == solved_values_after if len([box for box in values.keys() if len(values[box]) == 0]): return False return values new_values = reduce_puzzle(values) print("\n") print("After applying constrint propagaton (both eliminate and only_choice strategies)*****************") display(new_values)
c7896ffcdf6dc1fd41863efa3dcf6d280fb32cbc
mapleeit/Python
/anti_vowel_v1.py
194
4
4
def anti_vowel(text): items = ['a', 'A', 'E', 'e', 'i', 'I', 'o', 'O', 'u', 'U'] for item in items: if item in text: text = text.replace(item,'') return text
7e53bad9d9719ddf01204d65e741721ab1df32bc
davll/practical-algorithms
/LeetCode/99-recover_binary_search_tree.py
857
3.71875
4
# https://leetcode.com/problems/recover-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def inorder(root): if not root: return yield from inorder(root.left) yield root yield from inorder(root.right) def recover_bst_v1(root): a = list(inorder(root)) b = a[:] b.sort(key=lambda t: t.val) # find mismatch for x, y in zip(a, b): if x.val != y.val: x.val, y.val = y.val, x.val break def recover_bst_v2(root): raise NotImplementedError() class Solution: def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ recover_bst_v1(root)
7c400216f0d7687b4cb15a031ad7f392f9526376
Murgowt/hacktoberfest-2021
/python/palindrome_checker.py
597
4.21875
4
''' Palindrome checker by python ''' #Palindrome check for String inputs. def palindrome (s): r=s[::-1] if(r==s): print("Yes It is a palindrome") else: print("No It is not a palindrome") s = input("Enter a String to check whether it is palindrome or not") palindrome(s) #Palindrome check for Number (Integer) inputs. num=int(input("Enter a number:")) temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 if(temp==rev): print("The number is Palindrome!") else: print("The number is Not a palindrome!")
30b1aaeb35332f3dd2e372292a323f545a047147
tomboxfan/PythonExample
/exercise/014_3/P014Solution2.py
949
3.96875
4
# From Yixuan / Natalie import math def factorise(n): print(n, '=', end = ' ') m = int(math.sqrt(n)) + 1 # this is not possible # origianl = a * b * c * d * e # sqr root < d and e # # if it is prime, then output should be n = 1 * n is_prime = True # loop from 2 to square root m for i in range(2, m): # 0 -> False # not 0 -> True # n % i 取余数 # if n % i == 0, it means n is divisble by i # if n % i != 0, it means n is NOT divisble by i # n % i == 0, 0 is False # not (n % i) : 只要i 是n的prime factor, 我就一直loop while not (n % i): is_prime = False print(i, end = ' ') n = n / i if n > 1: print("*", end = ' ') if is_prime: print("1 *", end = ' ') # 14 = 2 * 7 if n != 1: print(n, end =' ') print() factorise(1000)
e1959421c27e002400728fc541c84c1701866134
adityapande-1995/DSA
/LinkedLists/main.py
1,788
4.03125
4
#!PYTHON3 class Node: def __init__(self, num): self.content = num self.prev = None self.next = None def addNext(self, other): self.next = other other.prev = self def addPrev(self,other): self.prev = other other.next = self class LL: def __init__(self, head): self.head = head self.last = head self.length = 1 def pushback(self,node): self.last.addNext(node) self.last = node self.length += 1 def pushfront(self,node): self.head.addPrev(node) self.head = node self.length += 1 def insert_after(self, other, index0): temp = self.head for i in range(index0): temp = temp.next other.addNext(temp.next) temp.addNext(other) self.length += 1 def get(self, index): temp = self.head for i in range(index): temp = temp.next return temp def delete(self, index): if index !=0 and index != (self.length -1): temp = self.head for i in range(index): temp = temp.next temp.prev.addNext(temp.next) self.length -= 1 def show(self): i = 0 temp = self.head while temp: print("Node, index : ",temp.content,i) temp = temp.next i += 1 print("Head node : ", self.head.content) print("Last node : ", self.last.content) print("Length : ", self.length) # Main a = LL( Node("A") ) a.pushback( Node("B") ) a.pushback( Node("C") ) a.insert_after( Node(100), 1) a.pushback( Node("E") ) a.show() print("\nFurther operations") a.delete(3) a.pushfront( Node("Alpha") ) a.show()
3c76d16a9bda2041a0f8a5a9a4f23eb463bf215d
CrisofilaxDives/Python-Practica
/practicaspropias2.0.py
4,525
3.96875
4
# Tipos de datos y condicionales str_1 = "Pescado" str_2 = "Mariscos y cefalopodos" int_1 = 56 int_2 = 89 flt_1 = 1.9 flt_2 = 2.5 bool_f = False none_1 = None list_1 = list(("Azul", "Verde", "Morado")) list_2 = list(range(1,4)) tuple_1 = tuple((12, 13, 14)) tuple_2 = tuple((20,)) set_1 = {"Perros", 3, True} dict_1 = { "Especie":"Mamifero", "Tamaño":5.6, "ID":4555656456 } print(type(flt_1)) # Str print(str_1.upper()) print(str_2.lower()) print(str_1.swapcase()) print(str_2.replace("y", "And").capitalize()) print(str_1.count("s")) print(str_2.find("f")) print(str_1.index("c")) print(len(str_2)) print(str_1.startswith("Pescado")) print(str_2.endswith("cefalopodos")) print(str_1.isalpha()) print(str_2.isnumeric()) print(str_2.split()) print(str_1.split("c")) print(str_2[3]) print(str_1, ", ", str_2) print(f"{str_1}, {str_2}") print("{0}, {1}".format(str_1, str_2).capitalize()) # Int y Float operacion = ((int_1 + flt_1) * (int_2 - flt_2) / flt_1) print(operacion) print(int_1 // int_2) print(int_2 % int_1) # Concatenación print(str_1 + ", ", str_2) # Bool y None print("Pruebas del funcionamiento del dióxido de cloro en el cuerpo humano") print(bool_f) print("Pruebas de que el 5G causa COVID_19") print(none_1) # List print(list_1[1]) print(len(list_2)) print("Azul" in list_1) list_2[2] = 9 print(list_2) list_1.append("Cafe") print(list_1) list_2.extend((15, 48 , 79)) print(list_2) list_1.pop() print(list_1) list_2.pop(4) print(list_2) list_1.remove("Azul") print(list_1) # list_2.clear() # print(list_2) list_1.sort() print(list_1) list_1.sort(reverse = True) print(list_1) print(list_2.index(2)) print(list_1.count("Verde")) # Tuples y Sets # print(dir(set_1)) # print(dir(tuple_1)) print(tuple_1[1]) # del tuple_1 set_1.add("Limón") print(set_1) set_1.remove(3) print(set_1) # set_1.clear() # print(set_1) # Dict for keys, values in dict_1.items(): print(keys, "=", values) print(dict_1.items()) print(dict_1.keys()) print(dict_1.values()) # del dict_1 # dict_1.clear() # print(dict_1) # Condicionales y loops nombre = input("Ingrese su nombre: ") if nombre == "Gustav" or nombre == "Helena": print(f"Welcome Commander, {nombre}") elif nombre == "Hector": print(f"Welcome Capitan, {nombre}") else: print(f"Welcome Soldier, {nombre}") while True: try: ID = int(input("Escriba su número de usuario: ")) if ID >= 0 and ID < 10: print("Bienvenido Diamante") elif ID >= 10 and ID < 50: print("Bienvenido Oro") elif ID >= 50 and ID < 100: print("Bienvenido Plata") else: print("Bienvenido Bronce") break except: print("Erro. Escriba de nuevo su número de usuario.") try: ahorros = int(input("Ingrese sus ahorros: ")) if (not(ahorros == 0)): if ahorros < 100000: print("Siga ahorrando") elif ahorros >= 100000 and ahorros < 1000000: print("Tiene buenos ahorros") elif ahorros >= 1000000 and ahorros < 10000000: print("Puede invertir en bolsa") else: print("Puede invertir en bienes raices") except: print("Ahorros no validos") # Funciones def imc(peso = 0, altura = 0): while True: try: peso = float(input("Ingrese su peso en Kg: ")) break except: print("Peso no valido, intentelo de nuevo.") while True: try: altura = float(input("Ingrese su altura en m: ")) break except: print("Altura no valido, intentelo de nuevo.") imc = peso / (altura ** 2) print(f"Su IMC es de {imc:.1f}") #Use formart() ":." "un numero de decimales"f para hacer que me mostrara solo 1 decimal print("Eso significa: ") if imc < 18.5: print("Bajo peso") elif imc >= 18.5 and imc < 25: print("Peso normal") elif imc >= 25 and imc < 30: print("Sobrepeso") else: print("Obesidad") imc() resta = lambda n1 = 0, n2 = 0: n1 - n2 print(resta(2, 8)) # Modulos ## Recordad que los modulos son tuyos, de otros o de python ## Propios ## Python ### Usa import "nombre del modulo" o con from "modulo" import "funcion_1", "funcion_2", "..." ## Otros ### Usa la funcion en consola de windows pi install "nombre del modulo"
7301647ec241cedae05a63daeffb6417f45dcc91
lalitkapoor112000/Python
/Removing Data from list.py
215
3.953125
4
fruits=['apple','orange','grapes','mango','peach'] fruits.remove('orange') print(fruits) fruits.pop() print(fruits) del fruits[1] print(fruits) fruits.pop(1) print(fruits) for i in fruits: print(i)
83a04887f1aa5f422e446bcbc3a204663c264c4c
vincek59/qcm-exo7
/bin/braces.py
1,550
4.0625
4
#!/usr/bin/env python3 from re import * # Find the first well-balanced string in brace # Usage : find_braces(string) # Example find_braces("Hello{ab{c}d}{fg}"") returns "ab{c}d", "Hello{", "}{fg}" def find_braces(string): """return the first string inside a well-balanced expression with {}""" res = "" open_brace = False count = 0 start = -1 end = -1 for i in range(len(string)): s = string[i] # Not a first "{" if open_brace and s == "{": count += 1 # First "{" if not open_brace and s == "{": open_brace = True count += 1 start = i if open_brace and s == "}": count += -1 if open_brace and count==0: end = i break if not open_brace: return string, -1, -1 return string[start+1:end], start+1, end # Test # string = "\\feedback{$2^{10}=1024$}blabla" # string = "rien du tout" # string = "{au début{}}blaba" # string = "blabla{à la fin {{}{}{}}xxx}" # print(find_braces(string)) def find_command(command,string): trouve = search(command,string) if not trouve: return None c_start = trouve.start() find_res = find_braces(string[c_start:]) c_end = c_start + find_res[2] + 1 return string[c_start:c_end], c_start, c_end # Test # string = r"coucou \feedback{$2^{10}=1024$}blabla" # string = r"coucou {$2^{10}=1024$}blabla" # command = "\\\\feedback" # print(find_command(command,string))
de42580f9b5234004f293bba16ed85fd37946939
SunatP/Python
/Hello World/Hello world.py
176
3.84375
4
print("Hello World") print(2+2) name = 'chawna' test = name +' '+ "Hi" print(test) print(name[3]) print(name[0:3]) a = b = pow(2,5) print(a+b) a = 5 a += 5 b = 10 print(a==b)
a22fc4ecde52331b464b7c5e7a09de0e43a69621
manuelF/Encuestas2015
/ways.py
928
3.671875
4
def linspace(a,b,step): res =[] while(a<=b): res.append(a) a+=step return res def solve(): fun = linspace step = 1 a=set(fun(0,50,step)) #macri b=set(fun(0,50,step)) #massa c=set(fun(0,50,step)) #scioli d=set(fun(0,20,step)) #binner e=set(fun(0,0,step)) #otro f=set(fun(0,0,step)) #otro suma = 100 ways=0 # print a # print f # print c # print d # print e for _a in a: suma = 100-_a for _b in b: if suma-_b<0: break suma-=_b for _c in c: if suma-_c<0: break suma-=_c for _d in d: if suma-_d<0: break suma-=_d for _e in e: if suma-_e<0: break suma-=_e if suma in f: ways+=1 suma+=_e suma+=_d suma+=_c suma+=_b suma+=_a return ways def main(): print solve() main()
52969bf9e2292f7e5feb4d047c1e2c0c204bcdc3
Ratnakarmaurya/Data-Analytics-and-visualization
/working with data 02/10_Renaming_index.py
1,109
4.125
4
import numpy as np import pandas as pd from pandas import Series, DataFrame # Making a DataFrame dframe= DataFrame(np.arange(12).reshape((3, 4)), index=['NY', 'LA', 'SF'], columns=['A', 'B', 'C', 'D']) dframe # Just like a Series, axis indexes can also use map #Let's use map to lowercase the city initials dframe.index.map(str.lower) dframe # If you want to assign this to the actual index, you can use index #we can save it dframe.index = dframe.index.map(str.lower) dframe # Use rename if you want to create a transformed version withour modifying the original! #str.title will capitalize the first letter, lowercasing the columns dframe.rename(index=str.title,columns = str.lower) # We can also use rename to insert dictionaries providing new values for indexes or columns! dframe.rename(columns={"A":"Alpha"},index={"ny":"NEW YORK"}) dframe #note orignal is not changed # If you would like to actually edit the data set in place, set inplace=True dframe.rename(columns={"A":"Alpha"},index={"ny":"NEW YORK"},inplace=True) dframe
c104ec2c8725418a90a626d011c72429af1f1cbd
theishansri/Python_Codes
/Python/segment_tree_1.py
2,554
3.65625
4
# import sys # def segment_tree(tree,a,index,start,end): # if(start>end): # return # if(start==end): # tree[index]=a[start] # return # mid=(start+end)//2 # segment_tree(tree,a,2*index,start,mid) # segment_tree(tree,a,2*index+1,mid+1,end) # left=tree[2*index] # right=tree[2*index+1] # tree[index]=min(left,right) # def query(tree,s,e,index,qs,qe): # if(qs>e or qe<s): # return sys.maxsize # if(s>=qs and e<=qe): # return tree[index] # mid=(s+e)//2 # left=query(tree,s,mid,2*index,qs,qe) # right=query(tree,mid+1,2*index+1,qs,qe) # return min(left,right) # def update(tree,s,e,index,i,value): # if(i<s or i>e): # return # if(s==e): # tree[index]=value # return # mid=(s+e)//2 # update(tree,s,mid,2*index,i,value) # update(tree,mid+1,e,2*index+1,i,value) # tree[index]=min(tree[2*index],tree[2*index+1]) # return # n=6 # a=[1,3,2,-2,4,5] # tree=[None]*(4*n+1) # index=1 # segment_tree(tree,a,index,0,n-1) # print(tree) ''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' # Write your code here import sys def segment_tree(tree,a,index,start,end): if(start>end): return if(start==end): tree[index]=a[start] return mid=(start+end)//2 segment_tree(tree,a,2*index,start,mid) segment_tree(tree,a,2*index+1,mid+1,end) left=tree[2*index] right=tree[2*index+1] tree[index]=min(left,right) def query(tree,s,e,index,qs,qe): if(qs>e or qe<s): return sys.maxsize if(s>=qs and e<=qe): return tree[index] mid=(s+e)//2 left=query(tree,s,mid,2*index,qs,qe) right=query(tree,mid+1,e,2*index+1,qs,qe) return min(left,right) def update(tree,s,e,index,i,value): if(i<s or i>e): return if(s==e): tree[index]=value return mid=(s+e)//2 update(tree,s,mid,2*index,i,value) update(tree,mid+1,e,2*index+1,i,value) tree[index]=min(tree[2*index],tree[2*index+1]) return n,k=map(int,input().split()) l=list(map(int,input().split())) tree=[None]*(n*4+1) segment_tree(tree,l,1,0,n-1) print(tree) for _ in range(n): p,q,r=input().split() q=int(q) r=int(r) if(p=='q'): print(query(tree,0,n-1,1,q,r)) else: update(tree,0,n-1,q,r)
f52b7cafb68a4e6c33d0a618ce785847c02e568e
shubham14/Coding_Contest_solutions
/target_difference.py
1,481
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 29 10:12:55 2018 @author: Shubham """ # Python program to find if there are # two elements wtih given sum # function to check for the given sum # in the array def cutSticks(lengths): count_sticks = [] while len(lengths) != 0: count_sticks.append(len(lengths)) m = min(lengths) lengths =list(map(lambda x: x - m, lengths)) lengths = list(filter(lambda x: x != 0, lengths)) return count_sticks def kDifference(a, k): s = set() count = 0 for i in range(len(a)): temp = a[i] - k if (temp>=0 and temp in s): count += 1 s.add(a[i]) else: s.add(a[i]) return count def kDifference1(a, k): c = dict() count = 0 for ele in a: if ele in list(c.keys()): c[ele] += 1 else: c[ele] = 1 for i in range(len(a)): temp = a[i] - k if temp >= 0 and temp in c.keys(): count += min(c[temp], c[a[i]]) return count def kDifference2(a, k): c = 0 for ele in a: a =list(map(lambda x: x - ele, a)) print('Here') c += len(list(filter(lambda x: x == abs(2), a))) a = list(filter(lambda x: x != abs(2), a)) return c # driver program to check the above function A = [1,5,3,4,2] B = [5,4,4,2,2,8] k = 1 ans = kDifference2(A, k) ans1 = cutSticks(B) print(ans1)
37162fca54b1643080d961e1bec751e782deed36
pranavchandran/Key-Exploit
/exploit/generator_exp.py
776
3.578125
4
import random import string def excel_format(num): res = "" while num: mod = (num - 1) % 26 # res = chr(65 + mod) + res num = (num - mod) // 26 return res def full_format(num, d=3,stringLength=7): letters = string.ascii_uppercase random_string = ''.join(random.choice(letters) for i in range(stringLength)) chars = num // (10**d-1) + 1 # this becomes A..ZZZ digit = num % (10**d-1) + 1 # this becomes 001..999 return random_string + excel_format(chars) + "0{:0{}d}".format(digit, d) global otp_list otp_list = [] for i in range(101,1000): nums = (full_format(i, d=2)) otp_list.append(nums) def check1(): global otp_list for i in otp_list: yield i exp = check1() print(next(exp))
b0dd784ab9bc2790b2d4591dc41d156d0d9b25f0
8sagh8/Python
/Isha_Prayer_Qaza_Time/isha_qaza_time.py
2,157
3.75
4
# -*- coding: utf-8 -*- """ title: ISHA QAZA TIME CALCULATOR created by: SAMMAR ABBAS """ def hr_mint(time): pos = time.find(":") hr = int(time[0:pos]) mint = int(time[pos+1:]) lst = [] lst.append(hr) lst.append(mint) return lst def accurate_time(time, event): new_time = "" while time[0] < 0 or time[0] > 24 or time[1] < 0 or time[1] > 60 or (time[0] == 24 and time[1] > 0): new_time = input (f"INVALID TIME: enter correct {event} time: ") time = hr_mint(new_time) return time def diff_time (fajr_time, magrib_time): fj_hr = fajr_time[0] mg_hr = magrib_time[0] while not(fj_hr == mg_hr): fj_hr -= 1 if not(fj_hr == mg_hr): if fj_hr == 0: fj_hr = 24 if not (fj_hr == mg_hr): mg_hr += 1 if not(fj_hr == mg_hr): if mg_hr == 24: mg_hr = 0 mid_hr = fj_hr fj_hr = ((mid_hr + 1) * 60) + fajr_time[1] mg_hr = ((mid_hr - 1) * 60) + magrib_time[1] while not(fj_hr == mg_hr): fj_hr -= 1 if fj_hr == 0: fj_hr = 12 * 60 mg_hr += 1 mid = fj_hr lst = [] lst.append(mid // 60) lst.append(mid % 60) return lst ####### MAIN PART ######## magrib_time = [] fajr_time = [] time = [] magrib = input("Please enter Magrib time: ") time = hr_mint(magrib) time[0] = time[0] + 12 magrib_time = accurate_time(time, "Magrib") fajr = input("Please enter Fajr time: ") time = hr_mint(fajr) fajr_time = accurate_time(time, "Fajr") time = diff_time (fajr_time, magrib_time) if magrib_time[0] < 12: magrib_time[0] = magrib_time[0] - 12 print() print(f"fajr is at {fajr_time[0]}:{fajr_time[1]} am and magrib is at {magrib_time[0]}:{magrib_time[1]} pm") print print(f"Esha will Qaza at {time[0]}:{time[1]}", end='') if time[0] < 12: print("pm.") else: print("am.") ###################################### ##### NEW FEATURE ############ import datetime now = datetime.datetime.now() print ("Current date and time : ") print (now.strftime("%H:%M:%S"))
4b6ac6383a17d443ca59f24965af5c6a21f880fd
Anakinliu/PythonProjects
/book/others/test_for.py
241
3.5
4
# coding: utf-8 sf = [] # 空列表 for i in range(1, 11): square = i ** 2 sf.append(square) print (sf) sf = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print (min(sf)) # 最大值 print (max(sf)) # 最小值 print (sum(sf)) # 求和
bc1f037aa465d63247329b3639827e272bffcdf0
caron1211/Computer-Vision-image-processing--exercises
/Ex1/ex1_utils.py
9,346
3.609375
4
""" '########:'##::::'##::::'##::: ##.....::. ##::'##:::'####::: ##::::::::. ##'##::::.. ##::: ######:::::. ###::::::: ##::: ##...:::::: ## ##:::::: ##::: ##:::::::: ##:. ##::::: ##::: ########: ##:::. ##::'######: ........::..:::::..:::......:: """ from typing import List LOAD_GRAY_SCALE = 1 LOAD_RGB = 2 import cv2 import numpy as np import matplotlib.pyplot as plt import sys def imReadAndConvert(filename: str, representation: int) -> np.ndarray: """ Reads an image, and returns and returns in converted as requested :param filename: The path to the image :param representation: GRAY_SCALE or RGB :return: The image object The function used cv2.imread function to read the image. It distinguished the case where the image is GRAYSCALE and RGB by representation param In the case where the representation is RGB i convert from BGR to RGB After converting to the matrix, I normalized all pixels to values between 0 and 1 by cv2.normalize """ if (representation == LOAD_GRAY_SCALE): img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) else: img_bgr = cv2.imread(filename) img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # convert from BGR to RGB # normalize norm_image = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) return norm_image def imDisplay(filename: str, representation: int): """ Reads an image as RGB or GRAY_SCALE and displays it :param filename: The path to the image :param representation: GRAY_SCALE or RGB :return: None The function call to 'imReadAndConvert' and then use 'matplotlib.pyplot' library to show the image """ img = imReadAndConvert(filename, representation) if (representation == LOAD_GRAY_SCALE) : plt.imshow(img,cmap='gray') else: plt.imshow(img) plt.show() def transformRGB2YIQ(imgRGB: np.ndarray) -> np.ndarray: """ Converts an RGB image to YIQ color space :param imgRGB: An Image in RGB :return: A YIQ in image color space The function does dot product with the image and the matrix """ yiq_from_rgb = np.array([[0.299, 0.587, 0.114], [0.59590059, -0.27455667, -0.32134392], [0.21153661, -0.52273617, 0.31119955]]) return np.dot(imgRGB, yiq_from_rgb.T.copy()) # transposed def transformYIQ2RGB(imgYIQ: np.ndarray) -> np.ndarray: """ Converts an YIQ image to RGB color space :param imgYIQ: An Image in YIQ :return: A RGB in image color space The function does dot product with the image and the matrix """ rgb_from_yiq = np.array([[1.00, 0.956, 0.623], [1.0, -0.272, -0.648], [1.0, -1.105, 0.705]]) return np.dot(imgYIQ, rgb_from_yiq.T.copy()) # transposed def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray): """ Equalizes the histogram of an image :param imgOrig: Original Histogram :return: imgEq:image after equalize , histOrg: the original histogram, histEq: the new histogram The function get image performing a histogram calculation, I used the numpy function and then computed the histogram cdf and then mapped the pixels in the image to the optimal cdf """ imgOrigCopy = imgOrig.copy() # if the image is rgb convert to YIQ and them continue if len(imgOrig.shape) == 3: imgYiq = transformRGB2YIQ(imgOrig) imgOrig = imgYiq[:, :, 0] imgOrig = normalizeTo256(imgOrig) histOrg , bins = np.histogram(imgOrig.flatten(), 256, [0, 256]) # Original Histogram: plt.subplot(2, 1, 1) histOrig, bins = np.histogram(imgOrig.flatten(), 256, [0, 255]) cdf = histOrig.cumsum() # cumulative cdf_normalized = cdf * histOrig.max() / cdf.max() plt.title('Original image histogram with CDF') plt.plot(cdf_normalized, color='b') plt.hist(imgOrig.flatten(), 256, [0, 255], color='r') plt.xlim([0, 255]) plt.legend(('cdf - ORIGINAL', 'histogram - ORIGINAL'), loc='upper left') # plt.show() cdf = histOrg.cumsum() # cdf_normalized = cdf * histOrg.max() / cdf.max() cdf_m = np.ma.masked_equal(cdf, 0) cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min()) cdf = np.ma.filled(cdf_m, 0).astype('uint8') imgEq = cdf[imgOrig] histEq, bins = np.histogram(imgEq.flatten(), 256, [0, 256]) # histogram for equalized image: histEq, bins = np.histogram(imgEq.flatten(), 256, [0, 255]) cdf = histEq.cumsum() # cumulative cdf_normalized = cdf * histEq.max() / cdf.max() plt.subplot(2, 1, 2) plt.title('Equalized image histogram with CDF ') plt.plot(cdf_normalized, color='b') plt.hist(imgEq.flatten(), 256, [0, 255], color='r') plt.xlim([0, 255]) plt.legend(('cdf - EQUALIZED', 'histogram - EQUALIZED'), loc='upper right') # if the original image was RGB return back to RGB if len(imgOrigCopy.shape) == 3: imgEq = cv2.normalize(imgEq.astype('double'), None, 0.0, 1.0, cv2.NORM_MINMAX) imgYiq [:, :, 0]= imgEq imgEq = transformYIQ2RGB(imgYiq) imgEq = normalizeTo256(imgEq) # plt.savefig('histoOfhsitogramEqualize.png') # saveImageWithCv2('hsitogramEqualizeRes.jpg',imgEq) return imgEq, histOrg, histEq def quantizeImage(imOrig: np.ndarray, nQuant: int, nIter: int) -> (List[np.ndarray], List[float]): """ Quantized an image in to **nQuant** colors :param imOrig: The original image (RGB or Gray scale) :param nQuant: Number of colors to quantize the image to :param nIter: Number of optimization loops :return: (List[qImage_i],List[error_i]) I divided the histogram into nQuant equal parts and then found the average in each section. After finding the average, I changed all the pixels in that range to their average. Repeat this process nIter times and at each stage find the mistake between the image we calculated and the original image """ imgOrigCopy = imOrig.copy() if len(imOrig.shape) == 3: imgYiq = transformRGB2YIQ(imOrig) imOrig = imgYiq[:, :, 0] imgnew = normalizeTo256(imOrig) hist, bins = np.histogram(imgnew.flatten(), 256, [0, 256]) init = 255 / nQuant qImage_lst = [] err_lst = [] k = int(256 / nQuant) borders = np.arange(0, 257, k) borders[nQuant] = 255 # print("borders{}".format(borders)) for i in range(0, nIter): imgQuant = imgnew # print("borders_n{}".format(borders)) weightedMean = np.zeros(nQuant) for j in range(0, nQuant): low_bound = int(borders[j]) # print("low_bound{}".format(low_bound)) high_bound = int (borders[j+1] +1) # print("high_bound{}".format(high_bound)) weightedMean[j] = getWeightedMean(range(low_bound,high_bound), hist[low_bound:high_bound]) # print("means{}".format(weightedMean)) for j in range(0, nQuant): bool_pixels = (imgQuant >= borders[j]) & (imgQuant <= borders[j + 1]) imgQuant[bool_pixels] = weightedMean[j] imgQuant = np.rint(imgQuant).astype(int) # Round elements of the array to the nearest integer. borders = (weightedMean[:-1] + weightedMean[1:]) / 2 # get the middle between 2 avg borders = np.insert(borders, 0, 0) # add 0 to begin borders = np.append(borders, 255) # add 255 to end borders = np.rint(borders).astype(int) mse = getMse(imgnew, imgQuant) err_lst.append(mse) # add err to list if len(imgOrigCopy.shape) == 3: imgQuant = cv2.normalize(imgQuant.astype('double'), None, 0.0, 1.0, cv2.NORM_MINMAX) imgYiq[:, :, 0] = imgQuant imgQuant = transformYIQ2RGB(imgYiq) imgQuant = normalizeTo256(imgQuant) qImage_lst.append(imgQuant) # add the image to list # saveImageWithCv2('quantimageRes.jpg',imgQuant) return qImage_lst, err_lst # normalize fron [0,1] to [0,255] def normalizeTo256(imgOrig: np.ndarray) -> np.ndarray: imgOrig = cv2.normalize(imgOrig, None, 0, 255, cv2.NORM_MINMAX) imgOrig = np.ceil(imgOrig) imgOrig = imgOrig.astype('uint8') return imgOrig # WeightedMean of np def getWeightedMean(intens: np.ndarray, vals: np.ndarray) -> int: # print("intens {}".format(intens)) # print("vals{}".format(vals)) weightedMean = np.average(intens, weights=vals) return weightedMean # I used https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/ def getMse(imageA, imageB): # the 'Mean Squared Error' between the two images is the # sum of the squared difference between the two images; # NOTE: the two images must have the same dimension err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2) err /= float(imageA.shape[0] * imageA.shape[1]) # return the MSE, the lower the error, the more "similar" # the two images are return err # Save img with cv2 (BGR) def saveImageWithCv2(filename , img:np.ndarray): if len(img.shape) == 3: img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) cv2.imwrite(filename, img)
0711c87aa327a0c297060c145042cc4d3be85ed0
abhi0987/DeepLearning-ML
/Hand_Written_digit_prediction/classify.py
7,639
3.53125
4
#import tensorflow and other libraries import matplotlib.pyplot as plt import os import sys from tensorflow.examples.tutorials.mnist import input_data import numpy as np import pandas as pd from scipy import ndimage from sklearn.metrics import accuracy_score import tensorflow as tf from scipy.misc import imread from PIL import Image, ImageFilter import cv2 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) seed=128 rng = np.random.RandomState(seed) # Let's create the graph input of tensorflow by defining the 'Place Holders' data_img_shape = 28*28 # 784 input units digit_recognition = 10 # 10 classes : 0-9 digits or output units hidden_num_units = 500 # hidden layer units x = tf.placeholder(tf.float32,[None,data_img_shape]) y = tf.placeholder(tf.float32,[None,digit_recognition]) epochs = 5 batch_size = 128 learning_rate = 0.01 training_iteration = 50 # Let's define weights and biases of our model # weights are the probablity that affects how data flow in the graph and # it will be updated continously during training # so that our results will be closer to the right solution weights = { 'hidden' : tf.Variable(tf.random_normal([data_img_shape,hidden_num_units],seed=seed)), 'output' : tf.Variable(tf.random_normal([hidden_num_units,digit_recognition],seed=seed)) } # bias is to shift our regression line to better fit the data biases = { 'hidden' : tf.Variable(tf.random_normal([hidden_num_units],seed=seed)), 'output' : tf.Variable(tf.random_normal([digit_recognition],seed=seed)) } # let's create our neural network computaional graph hidden_layer = tf.add(tf.matmul(x,weights['hidden']),biases['hidden']) hidden_layer = tf.nn.relu(hidden_layer) output_layer = tf.add(tf.matmul(hidden_layer,weights['output']),biases['output']) # let's define our cost function # cost function minimize our erroe during training # we will use cross entropy method to define the cost function cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = output_layer, labels = y)) # let's set the optimizer i.e our backpropagation algorithim # Here we use Adam, which is an efficient variant of Gradient Descent algorithm # optimizer makes our model self improve through the training optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # We finish the architecture of our neural network # nOw we will initialize all the variables # Let's create an session and run our neural network in that session to train it checkpoint_dir = "cps_py/" saver = tf.train.Saver() sess = tf.InteractiveSession() tf.global_variables_initializer().run() ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) else: print("No checkpoint found ! Train the data") for iteration in range(1000): avg_cost = 0 total_batch = int(mnist.train.num_examples/batch_size) for i in range(50): batch_x,batch_y = mnist.train.next_batch(total_batch) # create pre-processed batch _,c = sess.run([optimizer,cost],feed_dict = {x:batch_x , y:batch_y}) # feed the batch to optimizer avg_cost += c / total_batch #find cost and reiterate to minimize print ("iteration :", (iteration+1), "cost =", "{:.5f}".format(avg_cost)) print ("\nTraining complete!") #saving the session for later use saver.save(sess, checkpoint_dir+'model.ckpt') pred_temp = tf.equal(tf.argmax(output_layer,1),tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(pred_temp,'float')) #print ("Validation Accuracy:", accuracy.eval({x:mnist.test.images, y: mnist.test.labels})) print ("Validation Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})*100) import math # get the best shift value for shifting def getBestShift(img): cx,cy = ndimage.measurements.center_of_mass(img) rows,cols = img.shape shiftX = np.round(cols/2.0-cx).astype(int) shiftY = np.round(rows/2.0-cy).astype(int) return shiftX,shiftY # shift the img to the center def shift(img,shiftx,shifty): rows,cols = img.shape M = np.float32([[1,0,shiftx],[0,1,shifty]]) shifted = cv2.warpAffine(img,M,(cols,rows)) return shifted def imageprepare(X,Y,data): #create an array to store the eight images images = np.zeros((1,784)) #array to store correct values correct_vals = np.zeros((1,10)) gray = cv2.imread(data,0) # resize the images and invert it (black background) gray = cv2.resize(255-gray,(28,28)) #Okay it's quite obvious that the images doesn't #look like the trained ones. These are white digits on a gray background and not on a black one. (thresh, gray) = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) """All images are size normalized to fit in a 20x20 pixel box and there are centered in a 28x28 image using the center of mass. These are important information for our preprocessing.""" """First we want to fit the images into this 20x20 pixel box. Therefore we need to remove every row and column at the sides of the image which are completely black""" while np.sum(gray[0]) == 0: gray = gray[1:] while np.sum(gray[:,0]) == 0: gray = np.delete(gray,0,1) while np.sum(gray[-1]) == 0: gray = gray[:-1] while np.sum(gray[:,-1]) == 0: gray = np.delete(gray,-1,1) rows,cols = gray.shape """Now we resize our outer box to fit it into a 20x20 box. Let's calculate the resize factor:""" if rows > cols: factor = 20.0/rows rows = 20 cols = int(round(cols*factor)) gray = cv2.resize(gray, (cols,rows)) else: factor = 20.0/cols cols = 20 rows = int(round(rows*factor)) gray = cv2.resize(gray, (cols, rows)) """But at the end we need a 28x28 pixel image so we add the missing black rows and columns using the np.lib.pad function which adds 0s to the sides.""" colsPadding = (int(math.ceil((28-cols)/2.0)),int(math.floor((28-cols)/2.0))) rowsPadding = (int(math.ceil((28-rows)/2.0)),int(math.floor((28-rows)/2.0))) gray = np.lib.pad(gray,(rowsPadding,colsPadding),'constant') """ Here comes the shift operation """ #shiftx,shifty = getBestShift(gray) #shifted = shift(gray,shiftx,shifty) #gray = shifted cv2.imwrite("data.png", gray) """ all images in the training set have an range from 0-1 and not from 0-255 so we divide our flatten images (a one dimensional vector with our 784 pixels) to use the same 0-1 based range """ flatten = gray.flatten() / 255.0 """The next step is to shift the inner box so that it is centered using the center of mass.""" """ we need to store the flatten image and generate the correct_vals array correct_val for the first digit (9) would be [0,0,0,0,0,0,0,0,0,1] """ images[0] = flatten #correct_val = np.zeros((10)) #correct_val[0] = 1 #correct_vals[0] = correct_val prediction = tf.argmax(output_layer,1) """ we want to run the prediction and the accuracy function using our generated arrays (images and correct_vals) """ pred = prediction.eval({X: images}) print("The prdicted number is : "+ str(pred)) #print (sess.run(accuracy, feed_dict={X: image_, Y: image_.labels})*100) image = sys.argv[1] imageprepare(x,y,image)
ff3572f28a2492c6dad001c0b7064b85d51bf9e8
pod1019/python_learning
/第3章 序列/my_dict/字典新增键值对.py
795
3.625
4
'''''' ''' 1、给字典新增“键值对”。①如果“键”已经存在,则覆盖旧的键值对;②如果“键”不存在, 则新增“键值对”。 ''' dict1 = {'name':'小白','age':18, 'job':'QA'} dict1['age'] = 27 # ①如果“键”已经存在,则覆盖旧的键值对; dict1['addr'] = '和平饭店' # ②如果“键”不存在, 则新增“键值对” print(dict1) ''' 2. 使用update()将新字典中所有键值对全部添加到旧字典对象上。如果 key 有重复,则直接覆盖。 ''' dict2 = {'name':'小白','age':18, 'job':'QA'} dict3 = {'name':'小黑白','age':18, 'job':'QA','sex':'男','salary':9000.0} dict2.update(dict3) #将欣字典dict3的所有键值对添加到旧字典dict2上,如果key重复,则直接覆盖 print(dict2)
4ec44b7c7dc24d2434e7d3bdd0c62141b4ae32ae
CeciliaPYY/road2beEngineer
/duNiang/binarySearchforSqrt.py
2,741
3.890625
4
# 问题:现在没有开根号这个运算符,你如何写一个函数,即 y^2 = x, # 在已知 x 的情况下,求得 y 的值。 # 以下是我面试的时候写的伪代码,回来 run 了一下是跑不通的, # 可能是递归没写好的关系 import numbers def binarySearchforSqrt(start, end, num): if not isinstance(num, numbers.Number): return elif num < 0: return elif num == 0: return 0 elif num < 1: mid = 1/2 if mid * mid > num: binarySearchforSqrt(0, mid, num) elif mid * mid < num: binarySearchforSqrt(mid, 1, num) elif abs(mid * mid - num) < 0.00000001: return mid else: mid = (num + 1) / 2 if mid * mid > num: binarySearchforSqrt(1, mid, num) elif mid * mid < num: binarySearchforSqrt(mid, num, num) elif abs(mid * mid - num) < 0.00000001: return mid # 在网上查阅了一下别人写的 # 首先先简单说一下思想,求平方根的算法主要有两种,分别是二分法和牛顿法 # 举个栗子,比如 x = 9 > 1 # 那么 (1 + 9)/2 = 5.0,而5.0 * 5.0 = 25.0 > 9 # 因此我会开始向下搜索,即 [1, 5.0],继续折半 # 5.0 / 2 = 2.5,而 2.5 * 2.5 = 6.25 < 9,那我则开始向上搜索 # 即[2.5, 5],这么一直做下去直到我找到的数字 abs(y * y - x) < delta # 其中 delta 是一个很小的数字,比如十的负六次方 # 网上的很多代码都没有考虑被开方数小于1的情况,下面的代码是面试 # 的时候面试官提示之后在网上的版本上进行的一个修改 def mySqrt(num): if not isinstance(num, numbers.Number): return elif num < 0: return elif num < 1: _max = 1.0 else: _max = num _min = 0.0 delta = 0.00000001 mid = (_max + _min) / 2.0 while((abs(mid * mid - num)) > delta): print(mid) if mid * mid < num: _min = mid elif mid * mid > num: _max = mid else: return mid mid = (_max + _min) / 2.0 return mid print(mySqrt(0.04)) # 0.199999988079 print(mySqrt(9)) # 3.0000000014 # 思路二:牛顿法求近似解 # 开根号的问题可以看做是求 f(x) = x^2 - a = 0 的根 def mySqrtNewton(num): if not isinstance(num, numbers.Number): return elif num < 0: return else: delta = 0.00000001 x = 1.0 while (abs(x*x - num) > delta): x = (x + num/x) / 2.0 return x print(mySqrtNewton(0.04)) # 0.200000000002 print(mySqrtNewton(9)) # 3.0000000014 # 以上代码参考:https://blog.csdn.net/u012348774/article/details/79804369
5b3c01a03cf8453d185bfefe378c1c9c2b2ad03a
league-python-student/level2-module0-dencee
/_01_file_io/_c_sudoku/sudoku.py
10,698
4.1875
4
""" Create a Sudoku game! """ import random from pathlib import Path import tkinter as tk from tkinter import messagebox # TODO 1) Look at the sudo_grids.txt file. There are multiple starting sudoku # grids inside. Complete the function below with the following requirements: # 1. Open the sudoku_grids_file file for reading # 2. Select a random sudoku grid # 3. Read the random grid picked that was picked and return each row as an # element in a list of strings (not integers), for example: # ['003020600', # '900305001', # '001806400', # '008102900', # '700000008', # '006708200', # '002609500', # '800203009', # '005010300] def open_sudoku_file(sudoku_grids_file): return None # TODO 2) Complete the function below with the following requirements: # 1. Give the save_file input variable a default string # 2. Open the save_file input variable for writing. # If the file already exists, overwrite it. # 3. Write the contents of the sudoku_grid_list to the file, where each # element in the list is a new line in the file. The file should look # similar to this: # 003020600 # 900305001 # 001806400 # 008102900 # 700000008 # 006708200 # 002609500 # 800203009 # 005010300 # *NOTE: DON'T forget the new line ('\n') at the end! def on_save_button(sudoku_grid_list, save_file='saved.txt'): return None # TODO 3) Complete the function below with the following requirements: # 1. Give the saved_file input variable a default string # 2. Open the saved_file input variable for reading. # 3. Return a list of strings containing the integers (as strings!) for # each row, similar to TODO 1) open_sudoku_file() # 4. If the file could not be found, return None and an error message def on_load_button(saved_file='saved.txt'): return None class Sudoku(tk.Tk): sudoku_grids_file = 'sudoku_grids.txt' def __init__(self): super().__init__() # Window size needs to be updated immediately here so the # window width/height variables can be used below self.geometry('800x600') self.update_idletasks() self.sudoku_grid = None # # Setup cells to hold the numbers # self.entries = list() self.entries_rows = [list(), list(), list(), list(), list(), list(), list(), list(), list()] self.entries_cols = [list(), list(), list(), list(), list(), list(), list(), list(), list()] self.entries_per_row = 9 self.entries_per_col = 9 num_frames = 9 cols_per_frame = 3 rows_per_frame = cols_per_frame entries_per_frame = cols_per_frame * rows_per_frame # +1 to leave room on the right for the load and solve buttons entry_width = float(self.winfo_width() / (self.entries_per_col + 1)) entry_height = float(self.winfo_height() / self.entries_per_row) # # Setup and build 3x3 cell frames # frame_width = cols_per_frame * entry_width frame_height = rows_per_frame * entry_height self.frames = list() for i in range(num_frames): frame_x = (i % cols_per_frame) * frame_width frame_y = int(i / rows_per_frame) * frame_height frame = tk.Frame(self, highlightbackground="black", highlightthickness=1) frame.place(x=frame_x, y=frame_y, width=frame_width, height=frame_height) self.frames.append(frame) # # Build cells inside 3x3 frames # for k in range(entries_per_frame): row_num = int(k / cols_per_frame) col_num = int(k % rows_per_frame) row_y = row_num * entry_height col_x = col_num * entry_width # %d = action (insert=1, delete=0), %P = key value, %s = current value # https://tcl.tk/man/tcl8.6/TkCmd/entry.htm#M16 validate_cmd = (self.register(self.num_check), '%d', '%P', '%s') entry = tk.Entry(frame, justify='center', validate='key', vcmd=validate_cmd, fg='blue', font=('arial', 24, 'bold')) entry.place(x=col_x, y=row_y, width=entry_width, height=entry_height) self.entries.append(entry) row_index = (3 * int(i / 3)) + int(k / 3) col_index = (3 * int(i % 3)) + int(k % 3) self.entries_rows[row_index].append(entry) self.entries_cols[col_index].append(entry) # # Setup and build menu buttons # self.new_game_button = tk.Button(self, text='New Game') self.check_answer_button = tk.Button(self, text='Check Answer') self.save_button = tk.Button(self, text='Save') self.load_button = tk.Button(self, text='Load') self.new_game_button.bind('<ButtonPress>', self.on_new_game_button) self.check_answer_button.bind('<ButtonPress>', self.on_check_answer_button) self.save_button.bind('<ButtonPress>', lambda event: self.on_save_button()) self.load_button.bind('<ButtonPress>', lambda event: self.on_load_button()) menu_x = 3 * frame_width menu_width = self.winfo_width() - menu_x menu_button_height = 50 self.new_game_button.place(x=menu_x, y=0, w=menu_width, h=menu_button_height) self.check_answer_button.place(x=menu_x, y=menu_button_height, w=menu_width, h=menu_button_height) self.save_button.place(x=menu_x, y=2*menu_button_height, w=menu_width, h=menu_button_height) self.load_button.place(x=menu_x, y=3*menu_button_height, w=menu_width, h=menu_button_height) def on_save_button(self): on_save_button(self.entries_to_list()) def on_load_button(self): string_list = on_load_button() # Remove new lines at the end string_list = [row[0 : len(row)-1] for row in string_list] if len(string_list) != 9: messagebox.showerror('ERROR', 'ERROR: ' + str(len(string_list)) + 'rows in loaded file, expected 9') for row, row_string in enumerate(string_list): for offset, value in enumerate(row_string): entry = self.entries_rows[row][offset] entry.configure(state='normal', bg='white') entry.delete(0, 'end') if value == '0': entry.insert(0, '') else: entry.insert(0, value) self.update_idletasks() def entries_to_list(self): string_list = list() for entries_row in self.entries_rows: row_str = str() for entry in entries_row: if entry.get() == '': row_str += '0' else: row_str += entry.get() string_list.append(row_str) return string_list def num_check(self, action, value_if_allowed, prior_value): # Allow deleting characters if action == '0': return True # Don't allow more than 1 number in the text field if prior_value == '': try: int(value_if_allowed) return True except ValueError: return False else: return False def on_new_game_button(self, event): print('new game button pressed') # # Clear all the sudoku cells # for entry in self.entries: entry.configure(state='normal', bg='white') entry.delete(0, 'end') # # Load a starting grid to play # self.sudoku_grid = open_sudoku_file(Sudoku.sudoku_grids_file) # # Set the tk.entries with the starting numbers from the read grid # for row_num, row_entries in enumerate(self.entries_rows): row = self.sudoku_grid[row_num] for offset in range(self.entries_per_row): value = row[offset] if value != '0': row_entries[offset].insert(0, str(value)) row_entries[offset].configure(state='disabled') def on_check_answer_button(self, event): print('check answer button pressed') # Reset tk.entry colors for entry in self.entries: entry.configure(state='normal', bg='white') # # Check all 3x3 frames # success = self.check_frames() # # Check all rows # if success: success = self.check_rows() # # Check all columns # if success: success = self.check_cols() if success: messagebox.showinfo('Win', "You win!!!") def check_cols(self): for col_list in self.entries_cols: success = self.check_entries(col_list) if not success: break return success def check_rows(self): for row_list in self.entries_rows: success = self.check_entries(row_list) if not success: break return success def check_frames(self): for frame in self.frames: success = self.check_entries(frame.children.values()) if not success: break return success def check_entries(self, entries): success = True digits = list() entry_sum = 0 for i, entry in enumerate(entries): try: value = int(entry.get()) if value in digits: print('ERROR: Duplicate digit: ' + str(value)) success = False break digits.append(value) entry_sum += int(entry.get()) except ValueError: print('ERROR: No number in cell: ' + str(i)) success = False break if success: if len(digits) != 9: print('ERROR: not all digits 0-9 used, actual number used: ' + str(len(digits))) success = False if success: if entry_sum != 45: print('ERROR: entry sum not 45, actual sum: ' + str(entry_sum)) success = False if not success: for entry in entries: entry.configure(state='normal', bg='red') return success if __name__ == '__main__': game = Sudoku() game.title('League Sudoku') game.mainloop()
80848618b709bec18f0397f771209de5e5a19530
yukan97/python_essential_mini_tasks
/004_Iterators_Generators/Task2.py
306
3.9375
4
def my_reverse(input_list): step = -1 while -step <= len(input_list): yield input_list[step] step = step - 1 test_list = [1, 2, 3] generator = my_reverse(test_list) print(next(generator)) print(next(generator)) print(next(generator)) print(next(generator))
bb44506dc687761122e59ebb732560f35206cc4a
ordinary-developer/education
/py/m_lutz-learning_py-5_ed/code/part_04-functions_and_generators/ch_17-scopes/04-the_nonlocal_statement/main.py
2,362
3.546875
4
def example_1(): def tester(start): state = start def nested(label): print(label, state) return nested F = tester(0) F('spam') F('ham') def example_2(): def tester(start): state = start def nested(label): nonlocal state print(label, state) state += 1 return nested F = tester(0) F('spam') F('ham') F('eggs') G = tester(42) G('spam') G('eggs') F('bacon') def example_3(): def tester(start): def nested(label): global state state = 0 print(label, state) return nested F = tester(0) F('abc') print(state) def example_4(): def tester(start): global state state = start def nested(label): global state print(label, state) state += 1 return nested F = tester(0) F('spam') F('eggs') G = tester(42) G('toast') G('bacon') F('ham') def example_5(): class tester: def __init__(self, start): self.state = start def nested(self, label): print(label, self.state) self.state += 1 F = tester(0) F.nested('spam') F.nested('ham') G = tester(42) G.nested('toast') G.nested('bacon') F.nested('eggs') print(F.state) def example_6(): class tester: def __init__(self, start): self.state = start def __call__(self, label): print(label, self.state) self.state += 1 H = tester(99) H('juice') H('pancakes') def example_7(): def tester(start): def nested(label): print(label, nested.state) nested.state += 1 nested.state = start return nested F = tester(0) F('spam') F('ham') print(F.state) G = tester(42) G('eggs') F('ham') print(F.state) print(G.state) print(F is G) def example_8(): def tester(start): def nested(label): print(label, state[0]) state[0] += 1 state = [start] return nested if __name__ == '__main__': example_1() example_2() example_3() example_4() example_5() example_6() example_7() example_8()
ec9a80d07436752997c94939effa009be6bbd554
wasjediknight/python
/exercicios/week7/conta_primos.py
597
3.625
4
def EsteNumeroEPrimo(numero): numeroDeDivisores = 0 for divisor in range(1, numero + 1): if numero % divisor == 0: numeroDeDivisores += 1 if numeroDeDivisores > 2: return False return True def ContarNumerosPrimos(numeroInicial, numeroFinal): quantidadeDeNumerosPrimos = 0 for numeroCorrente in range(numeroInicial, numeroFinal + 1): if EsteNumeroEPrimo(numeroCorrente): quantidadeDeNumerosPrimos += 1 return quantidadeDeNumerosPrimos def n_primos(numero): return ContarNumerosPrimos(2, numero)
b703203ee52fde3d0f91d46b7824e746867699a8
zdzjiuge/TestCode
/UnittestTest/demo_03.py
512
3.8125
4
""" unittest的测试结果 """ import unittest class TestCaseResultDemo(unittest.TestCase): def test_01_pass(self): # pass 所有代码都执行完了/断言通过 self.assertEqual(1, 1) def test_02_failed(self): # 断言失败了 self.assertEqual(1, 2) def test_03_error(self): # 代码报错了抛出了异常 nums = [123,1,2] nums[4] if __name__ == "__main__": # 这种写法通常用来调试脚本 unittest.main()
5a0be0d063b062975a0c9169d2ca89f915c26fc3
archanadeshpande/codewars
/Sum of intervals.py
1,856
4.28125
4
# -*- coding: utf-8 -*- """ Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. Overlapping Intervals List containing overlapping intervals: [ [1,4], [7, 10], [3, 5] ] The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. Examples: sumIntervals( [ [1,2], [6, 10], [11, 15] ] ); // => 9 sumIntervals( [ [1,4], [7, 10], [3, 5] ] ); // => 7 sumIntervals( [ [1,5], [10, 20], [1, 6], [16, 19], [5, 11] ] ); // => 19 """ def sum_of_intervals(intervals): #sorting the list on first elements dist = sorted(intervals,key= lambda ele: ele[0]) interval=0 while len(dist) != 1: i=-1 j=0 while i < len(dist): i+=1 if i>=len(dist)-1: break #check if last element of current list is greater than first element of next list if dist[i][-1] >= dist[i+1][0]: #replace second item of current element with max of second item from current and next element of the list dist dist[i]=[(dist[i][0]),max(dist[i+1][-1],dist[i][-1])] #pop out the next element dist.pop(i+1) j+=1 #repeat until no more elements can be merged if j == 0: break for i in range(0,len(dist)): interval += (dist[i][1]-dist[i][0]) return interval
ea2db29b964f64e51d936af9ea3227a93e3230a9
Arya16ap/c-1oo3oo1oo3
/103/bar.py
175
3.609375
4
import pandas as pd import plotly.express as px #reading data from csv files df = pd.read_csv("data.csv") fig = px.line(df,x = "Country",y = "InternetUsers") fig.show()
88cdf9bb74cd720bf359a43ab3e5a054b5e6be1b
rubenspgcavalcante/python-para-padawans
/ep2/q3/main.py
474
4.46875
4
# coding=utf-8 # Faça uma função que receba um número n e que imprima uma pirâmide invertida de números: # 1, 2, 3, ... n # ... # 1, 2, 3 # 1, 2 # 1 def piramide(altura): # Recebe as larguras das linhas em ordem crescente linhas = range(1, altura + 1) # Porém, é utilzado a ordem invertida para a piramide invertida for linha in linhas[::-1]: for base in range(1, linha + 1): print "%d, " % base, print "" piramide(5)
9be6f1bc1ff7ac8e242109c7ac3bfc95a4597628
lucasgarciabertaina/hackerrank-python3
/set/introduction.py
307
4
4
# https://www.hackerrank.com/challenges/py-introduction-to-sets/problem def average(array): s = set(array) print(s) total = 0 for i in s: total += i return '%.3f' % float(total/len(s)) n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
e9b5ba9d36993c731d2d2cdf1fd1c8b8ff1aacf0
BBode11/CIT228
/Project1/laser.py
1,016
3.578125
4
import pygame from pygame.sprite import Sprite class Laser(Sprite): # A class to manage the lasers fired from the cat def __init__(self, cm_game): #Create a laser object at the cats current position super().__init__() self.screen = cm_game.screen self.settings = cm_game.settings self.color = self.settings.laser_color #Create a bullet rect at (0,0) and then set correct laser position self.rect = pygame.Rect(0, 0, self.settings.laser_width, self.settings.laser_height) self.rect.midtop = cm_game.cat.rect.midtop #store the lasers position as a decimal value self.y = float(self.rect.y) def update(self): #update the laser up the screen towards aliens self.y -= self.settings.laser_speed #update the rect position self.rect.y = self.y def draw_laser(self): #Draw the laser onto screen pygame.draw.rect(self.screen, self.color, self.rect)
d88edb25b8e0a48ec18d525e97dbc7b7c2ae39a9
t0ri-make-school-coursework/cracking-the-coding-interview
/stacks-and-queues/queue_via_stacks.py
722
4.375
4
# 3.4 # Implement a MyQueue class which implements a queue using two stacks. class MyQueue: def __init__(self): self.stack1 = [] self.stack2 = [] def enqueue(self, item): # Shift all elements from stack1 to stack2 while len(self.stack1) is not 0: self.stack2.append(self.stack1[-1]) self.stack1.pop() # Push item into self.stack1 self.stack1.append(item) # Shift everything back to stack1 while len(self.stack2) is not 0: self.stack1.append(self.stack2[-1]) self.stack2.pop() def dequeue(self): item = self.stack1[-1] self.stack1.pop() return item
18c7ed211f34eb41deed26a142801329e5fbbed6
sglim/inno-study
/baekjoon/problem_4673/self_number.py
1,069
3.828125
4
# function d(n) : sum n and its each order's number # for example, d(75) = 75 + 7 + 5 = 87 def d(n): result = n while n != 0: result += (n % 10) n = n // 10 return result # has_n() function will check out if certain number 'num' has 'n' such that d(n) = num def has_n(num): exp = 0 copy = num while copy != 0: exp += 1 copy = copy // 10 # if 'num' has 'n', 'n' shall be located in range of (num itself - 1, certain minimum) # and that minimum shall be 'num - 9 * order of num'. due to maximum number of each order is '9' min_range = num - 9 * exp for n in range(num - 1, min_range - 1 , -1): # if n goes negative, there is no n if n < 0: return False if d(n) == num: return True return False # if certain number 'num' has no number 'n' such that d(n) = num, than 'num' is 'self number' # check out and print self numbers within range of [1,10000] for test_num in range(1,10001): if has_n(test_num) is False: print(test_num)
4fa0d5dfa3c8c5beb9215e7186e0877abe45d0d3
pangyouzhen/data-structure
/linked_list/141 hasCycle.py
438
3.578125
4
from base.linked_list.ListNode import ListNode class Solution: def hasCycle(self, head: ListNode) -> bool: dummy_head1 = ListNode(0, head) dummy_head2 = ListNode(0, dummy_head1) fast, slow = head, dummy_head2 while fast != slow: if fast and fast.next: fast, slow = fast.next.next, slow.next else: return False return True
d020e72a17666b5c6d06305241dd059ea44fbf56
NealGross1/PythonChess
/test_ChessPiecesandBoard.py
12,246
3.59375
4
import unittest from ChessPiecesandBoard import * class TestChessPiece(unittest.TestCase): def test_init(self): newPiece = ChessPiece([0,3],'white') self.assertEqual(newPiece.color, 'white') self.assertEqual(newPiece.boardPosition,[0,3]) del newPiece class TestChessBoard(unittest.TestCase): def test_init(self): newBoard = ChessBoard() boardContents = newBoard.boardSpaces #assert all chess pieces are in the correct locations for col in range(8): #row 1 white backline expectedClasses=[Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook] boardContentsRow=boardContents[0] self.assertIsInstance(boardContentsRow[col],expectedClasses[col]) self.assertEqual(boardContentsRow[col].color,'white') #row 2 white pawns boardContentsRow=boardContents[1] self.assertIsInstance(boardContentsRow[col],Pawn) self.assertEqual(boardContentsRow[col].color,'white') #row 7 black pawns boardContentsRow=boardContents[6] self.assertIsInstance(boardContentsRow[col],Pawn) self.assertEqual(boardContentsRow[col].color,'black') #row 8 black backline boardContentsRow=boardContents[7] self.assertIsInstance(boardContentsRow[col],expectedClasses[col]) self.assertEqual(boardContentsRow[col].color,'black') #all others 0 for row in range(2,6): boardContentsRow=boardContents[row] self.assertEqual(boardContentsRow[col],0) newBoard.destructor() def test_getPieceAtPosition(self): newBoard = ChessBoard() tarPiece = newBoard.getPieceAtPosition([0,0]) self.assertIsInstance(tarPiece, Rook) self.assertEqual(tarPiece.color,'white') tarPiece = newBoard.getPieceAtPosition([4,4]) self.assertEqual(tarPiece,0) newBoard.destructor() def test__addPiece(self): newBoard = ChessBoard() newPiece = Pawn([4,4], 'white') newBoard._addPiece(newPiece) newBoard._addPiece(newPiece, [2,4]) tarPiece = newBoard.getPieceAtPosition([4,4]) self.assertIs(tarPiece,newPiece) tarPiece = newBoard.getPieceAtPosition([2,4]) self.assertIs(tarPiece,newPiece) self.assertEqual(tarPiece.boardPosition, [2,4]) newBoard.destructor() def test__removePiece(self): newBoard = ChessBoard() newPiece = Pawn([4,4], 'white') newBoard._addPiece(newPiece) newBoard._addPiece(newPiece, [2,4]) newBoard._removePiece(newPiece, currPosition=[4,4]) tarPiece = newBoard.getPieceAtPosition([4,4]) self.assertEqual(tarPiece,0) tarPiece = newBoard.getPieceAtPosition([2,4]) self.assertIsInstance(tarPiece, Pawn) self.assertEqual(tarPiece.color, 'white') newBoard._removePiece(newPiece, deletePiece=True) tarPiece = newBoard.getPieceAtPosition([2,4]) self.assertEqual(tarPiece,0) newBoard.destructor() def test_chessPiecePropertiesAtPosition(self): newBoard = ChessBoard() pieceProperties = newBoard.chessPiecePropertiesAtPosition([0,1]) self.assertEqual(pieceProperties,(1,'white')) pieceProperties = newBoard.chessPiecePropertiesAtPosition([4,4]) self.assertEqual(pieceProperties,(0,None)) newBoard.destructor() def test_clearBoard(self): newBoard=ChessBoard() newBoard.clearBoard() for row in range(8): for col in range(8): tarPiece = newBoard.getPieceAtPosition([row,col]) self.assertEqual(tarPiece, 0) def test__clearPathToMoveToPositionGivenDirection(self): #create board with obstructed paths newBoard = ChessBoard() newBoard.clearBoard() #piece to move wQ1 = Queen([4,4],'white') #pieces to block wQ2 = Queen([1,4],'white') wQ3 = Queen([5,4],'white') wQ4 = Queen([4,1],'white') wQ5 = Queen([4,6],'white') wQ6 = Queen([5,5],'white') wQ7 = Queen([2,2],'white') wQ8 = Queen([2,6],'white') wQ9 = Queen([5,3],'white') #pieces to take bQ1 = Queen([0,4],'black') bQ2 = Queen([4,0],'black') bQ3 = Queen([7,7],'black') bQ4 = Queen([1,7],'black') piecesToAdd = [wQ1,wQ2,wQ3,wQ4,wQ5,wQ6,wQ7,wQ8,wQ9,bQ1,bQ2,bQ3,bQ4] for i in range(len(piecesToAdd)): newBoard._addPiece(piecesToAdd[i]) #unclear paths for 4 diagonals and 4 Dpad directions pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [0,4],0,-1) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [4,0],-1,0) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,4],0,1) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [4,7],1,0) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,7], 1,1) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [0,0], -1,-1 ) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [1,7], 1,-1 ) self.assertFalse(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,1], -1,1 ) self.assertFalse(pathClear) #clear paths for 4 diagonals and 4 Dpad directiosn piecesToRemove = [wQ2,wQ3,wQ4,wQ5,wQ6,wQ7,wQ8,wQ9] for i in range(len(piecesToRemove)): newBoard._removePiece(piecesToRemove[i],deletePiece=True) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [0,4],0,-1) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [4,0],-1,0) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,4],0,1) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [4,7],1,0) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,7], 1,1) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [0,0], -1,-1 ) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [1,7], 1,-1 ) self.assertTrue(pathClear) pathClear = newBoard._clearPathToMoveToPositionGivenDirection([4,4] , [7,1], -1,1 ) self.assertTrue(pathClear) newBoard.destructor() def test_clearPathToMoveToPosition(self): #_clearPathToMoveToPositionGivenDirection already tested for obstruction, need to test directional normalization only newBoard = ChessBoard() newBoard.clearBoard() wQ1 = Queen([4,4],'white') newBoard._addPiece(wQ1) endPathPoints=[[0,4], [4,4], [7,4], [4,7], [0,0],[7,7],[1,7],[7,1]] for i in range(len(endPathPoints)): clearPath = newBoard.clearPathToMoveToPosition([4,4],endPathPoints[i]) self.assertTrue(clearPath) class TestPawn(unittest.TestCase): print("running pawn tests") def test_possibleMoves(self): pawnCenterOfBoard = Pawn([4,4], 'white') pawnBlackInfrontOfPawn = Pawn([2,4],'black') pawnBlackInfrontOfPawn2 = Pawn([2,2],'black') newBoard = ChessBoard() newBoard._addPiece(pawnCenterOfBoard) newBoard._addPiece(pawnBlackInfrontOfPawn) newBoard._addPiece(pawnBlackInfrontOfPawn2) #black movement tarPiece = newBoard.getPieceAtPosition([6,4]) self.assertIsInstance(tarPiece,Pawn) possibleMoves = tarPiece.getPossibleMoves(newBoard) self.assertEqual(possibleMoves, [[5,4]]) #diagnal movement and white movement tarPiece = newBoard.getPieceAtPosition([1,3]) self.assertIsInstance(tarPiece,Pawn) possibleMoves = tarPiece.getPossibleMoves(newBoard) self.assertEqual(len(possibleMoves),3) expectedMoves =[[2,4],[2,3],[2,2]] for i in range(len(possibleMoves)): self.assertIn(expectedMoves[i],possibleMoves) #off the board movement tarPiece = newBoard.getPieceAtPosition([7,7]) newBoard._removePiece(tarPiece) tarPiece = newBoard.getPieceAtPosition([1,3]) newBoard._addPiece(tarPiece,[7,7]) possibleMoves = tarPiece.getPossibleMoves(newBoard) self.assertEqual(possibleMoves, []) #blocked by piece newBoard._addPiece(pawnBlackInfrontOfPawn,[5,0]) tarPiece = newBoard.getPieceAtPosition([6,0]) possibleMoves = tarPiece.getPossibleMoves(newBoard) self.assertEqual(possibleMoves, []) newBoard.destructor() class TestKnight(unittest.TestCase): print("running knight tests") def test_possibleMoves(self): newBoard=ChessBoard() newBoard.clearBoard() testKnight = Knight([4,4],'white') newBoard._addPiece(testKnight) #all 8 knight moves expectedMoves=[[6,3],[6,5],[5,2],[5,6],[3,2],[3,6],[2,3],[2,5]] actualMoves = testKnight.getPossibleMoves(newBoard) self.assertEqual(len(actualMoves),len(expectedMoves)) for i in range(len(expectedMoves)): self.assertIn(expectedMoves[i],actualMoves) #moves off the board and allied pieces blocking newBoard.destructor() newBoard = newBoard=ChessBoard() testKnight = Knight([5,7],'white') testPawn = Pawn([3,6],'white') newBoard._addPiece(testKnight) newBoard._addPiece(testPawn) actualMoves = testKnight.getPossibleMoves(newBoard) expectedMoves=[[7,6],[6,5],[4,5]] self.assertEqual(len(actualMoves),len(expectedMoves)) for i in range(len(expectedMoves)): self.assertIn(expectedMoves[i],actualMoves) newBoard.destructor() class TestBishop(unittest.TestCase): print("running bishop tests") def test_possibleMoves(self): newBoard=ChessBoard() #at position 4,6 Bishop can potentially move off the board to the right, and goes through multiple enemies and allies on the left testBishop = Bishop([4,6],'white') newBoard._addPiece(testBishop) actualMoves = testBishop.getPossibleMoves(newBoard) expectedMoves = [[6,4],[5,5],[5,7],[3,5],[3,7],[2,4]] self.assertEqual(len(actualMoves), len(expectedMoves)) for i in range(len(expectedMoves)): self.assertIn(expectedMoves[i],actualMoves) class TestQueen(unittest.TestCase): print("running queen tests") def test_possibleMoves(self): newBoard=ChessBoard() blockingTestPawn = Pawn([4,2],'white') testQueen = Queen([4,6],'white') newBoard._addPiece(testQueen) newBoard._addPiece(blockingTestPawn) actualMoves = testQueen.getPossibleMoves(newBoard) expectedMoves = [[6,4],[5,5],[5,7],[3,5],[3,7],[2,4],[4,3],[4,4],[4,5],[4,7],[6,6],[5,6],[3,6],[2,6]] self.assertEqual(len(actualMoves), len(expectedMoves)) for i in range(len(expectedMoves)): self.assertIn(expectedMoves[i],actualMoves) class TestRook(unittest.TestCase): print("running rook tests") def test_possibleMoves(self): newBoard=ChessBoard() blockingTestPawn = Pawn([4,2],'white') testRook = Rook([4,6],'white') newBoard._addPiece(testRook) newBoard._addPiece(blockingTestPawn) actualMoves = testRook.getPossibleMoves(newBoard) expectedMoves = [[4,3],[4,4],[4,5],[4,7],[6,6],[5,6],[3,6],[2,6]] self.assertEqual(len(actualMoves), len(expectedMoves)) for i in range(len(expectedMoves)): self.assertIn(expectedMoves[i],actualMoves) if __name__ == '__main__': unittest.main()
22594d9ac41c808537f74574c0e23af762d5b436
zhiweiguo/my_leetcode
/offer/62.py
1,505
3.53125
4
# 每日打卡 day8 : offer 62 ''' 圆圈中最后剩下的数字 0,1,,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字。 求出这个圆圈里剩下的最后一个数字。 例如: 0、1、2、3、4这5个数字组成一个圆圈, 从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1, 因此最后剩下的数字是3。 ''' class Solution: def lastRemaining(self, n: int, m: int) -> int: ''' 构建数组,计算索引依次删除,时间复杂度较高,待优化 ''' num = [i for i in range(n)] # 起始索引初始化 start = 0 # 长度>1,则一直循环 while len(num) > 1: # 计算待删除元素索引 idx = (start + m - 1) % len(num) # 删除该索引元素 num.pop(idx) # 更新起始索引为删除元素位置 start = idx return num[0] def lastRemaining_2(self, n: int, m: int) -> int: ''' 数学+递归 ''' def f(n, m): if n == 1: return 0 x = f(n-1, m) return (m+x) % n return f(n, m) def lastRemaining_3(self, n: int, m: int) -> int: ''' 数学+迭代:基于方法2优化而来,节省了空间 ''' x = 0 for i in range(2, n+1): x = (m+x) % i return x
ded66d21c781404ae382a530dc68d318568654c3
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/tmpste002/question4.py
1,371
4.25
4
""" Print a graph of a function using ASCII art """ __author__ = 'Stephen Temple - TMPSTE002' __date__ = '2014/04/13' import math # set x axis range and increment X_MIN = -10 X_MAX = 10 X_INC = 1 x_multiplier = int(1 / X_INC) # required if increment is a floating point number to convert to whole number # set y axis range and increment Y_MIN = -10 Y_MAX = 10 Y_INC = 1 y_multiplier = int(1 / Y_INC) # required if increment is a floating point number to convert to whole number function = input("Enter a function f(x):\n") # iterate through each row, y axis for y in range(int(y_multiplier*Y_MAX), int(y_multiplier*(Y_MIN-Y_INC)), int(-y_multiplier*Y_INC)): y /= y_multiplier # convert back to floating point # iterate through each column, x axis for x in range(int(x_multiplier*X_MIN), int(x_multiplier*X_MAX+X_INC), int(x_multiplier*X_INC)): x /= x_multiplier # convert back to floating point if eval(function) - (Y_INC / 2) < y < eval(function) + (Y_INC / 2): # where y = x (within bounds) print('o', end='') elif x == 0 and y == 0: # point of origin print('+', end='') elif x == 0: print('|', end='') # y-axis elif y == 0: print('-', end='') # x-axis else: print(' ', end='') # need a space character to fill empty space on graph print()
9dbf87a85158d3834ea278ead08d04895c450802
dcyoung23/data-analyst-nd
/data-wrangling/lessons/Lesson_3_Problem_Set/01-Auditing_Data_Quality/audit.py
3,609
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ In this problem set you work with cities infobox data, audit it, come up with a cleaning idea and then clean it up. In the first exercise we want you to audit the datatypes that can be found in some particular fields in the dataset. The possible types of values can be: - 'NoneType' if the value is a string "NULL" or an empty string "" - 'list', if the value starts with "{" - 'int', if the value can be cast to int - 'float', if the value can be cast to float, but is not an int - 'str', for all other values The audit_file function should return a dictionary containing fieldnames and a SET of the types that can be found in the field. e.g. {"field1: set([float, int, str]), "field2: set([str]), .... } The audit_file function should return a dictionary containing fieldnames and the datatypes that can be found in the field. All the data initially is a string, so you have to do some checks on the values first. """ import codecs import csv import json import pprint #fieldname = "name" CITIES = 'cities.csv' FIELDS = ["name", "timeZone_label", "utcOffset", "homepage", "governmentType_label", "isPartOf_label", "areaCode", "populationTotal", "elevation", "maximumElevation", "minimumElevation", "populationDensity", "wgs84_pos#lat", "wgs84_pos#long", "areaLand", "areaMetro", "areaUrban"] #for field in FIELDS: # print field def skip_lines(input_file, skip): for i in range(0, skip): next(input_file) def is_float(s): try: s = s.replace(",","") float(s) return True except ValueError: return False def is_int(s): try: s = s.replace(",","") int(s) return True except ValueError: return False ''' - 'NoneType' if the value is a string "NULL" or an empty string "" - 'list', if the value starts with "{" - 'int', if the value can be cast to int - 'float', if the value can be cast to float, but is not an int - 'str', for all other values Test = set(["A", "B"]) print Test Test.add("C") print Test Test.add("A") print Test ''' def audit_file(filename, fields): fieldtypes = {} for field in fields: fieldtypes[field] = set() input_file = csv.DictReader(open(filename)) skip_lines(input_file, 3) nrows = 0 for row in input_file: for fieldname, value in row.iteritems(): v = value.strip() if fieldname in fieldtypes: if v == "NULL" or v == "": fieldtypes[fieldname].add('NoneType') elif v[:1] == "{": fieldtypes[fieldname].add('list') elif is_int(v) == True: fieldtypes[fieldname].add('int') elif is_float(v) == True: fieldtypes[fieldname].add('float') else: fieldtypes[fieldname].add('str') nrows += 1 return fieldtypes def test(): fieldtypes = audit_file(CITIES, FIELDS) pprint.pprint(fieldtypes) #assert fieldtypes["areaLand"] == set([type(1.1), type([]), type(None)]) #assert fieldtypes['areaMetro'] == set([type(1.1), type(None)]) if __name__ == "__main__": test() ''' v = row[fieldname] v = v.strip() #print v #print fieldname + ": " + v if v == "NULL" or v == "": new_set.add('NoneType') elif v[:1] == "{": new_set.add('list') elif is_int(v) == True: new_set.add('int') elif is_float(v) == True: new_set.add('float') else: new_set.add('str') fieldtypes[fieldname] = new_set print fieldtypes '''
e3a75ce0183c1bde6705ae2a14ea94ce5e4f6f03
CodingDojoOnline-Nov2016/al-lakshmanan
/python/flask/starterproj/python basics/oddeven.py
292
4.1875
4
def oddeven(): sum = 0 for val in range(1,2001,1): if val % 2 == 0: print "Number is ", val, ".This is even Number." else: print "Number is ", val, ".This is odd Number." sum = sum + val return sum result = oddeven() print result
f753ebd1a22146d354346a879cab467561df3d80
rafaelperazzo/programacao-web
/moodledata/vpl_data/116/usersdata/164/25963/submittedfiles/al1.py
181
3.71875
4
from __future__ import division #INICIE AQUI SEU CODIGO R=float(input('Digite o raio da lata: ')) A=float(input('Digite a altura da lata: ')) V= 3.14159*(R**2)*A print('%.2f' %V)
bfe72d8fbf4f6a01f7ec2557b59f3b27b2d76e67
olivierverdier/polynomial
/polynomial.py
5,741
3.84375
4
# -*- coding: utf-8 -*- from __future__ import division # to avoid the mess with integer divisions # determine what is imported during a `from polynomial import *` __all__ = ['Polynomial', 'Zero', 'One', 'X'] """ Classes to model polynomials. It also defines a Zero and One polynomials """ import numpy as np import numpy.linalg as nl import functools def cast_scalars(method): """ Decorator used to cast a scalar to a polynomial """ def newMethod(self, other): if np.isscalar(other): other = Polynomial(other) return method(self, other) return newMethod class Polynomial (object): """ Model class for a polynomial. Features ======== * The usual operations (``+``, ``-``, ``*``, ``**``) are provided * Comparison between polynomials is defined * Scalars are automatically cast to polynomials * Trailing zeros are allowed in the coefficients Examples ======== :: Polynomial(3) Polynomial([3,4,1]) Polynomial([3,4,1,0,0]) P = 3 + 4*X + X**2 P(3) # value at 3 P[10] # 10th coefficient (zero) P[10] = 1 # setting the tenth coefficient """ def __init__(self, coeffs): """ Create a polynomial from a list or array of coefficients There may be additional trailing zeros. """ # we allow the creation of polynomials from scalars: if np.isscalar(coeffs): coeffs = [coeffs] elif not list(coeffs): # empty coeff list coeffs = [0] self.coeffs = np.array(coeffs) def str_power(self, d, X='X'): if d == 0: return '' if d == 1: return X return X+'^{}'.format(d) def __str__(self): """ Pretty presentation. """ return ' + '.join(str(coeff)+self.str_power(index) for (index, coeff) in enumerate(self.coeffs[:self.length()]) if coeff != 0) def __repr__(self): """ Make it easy to create a new polynomial from of this output. """ return "%s(%s)" % (type(self).__name__, str(list(self.coeffs[:self.length()]))) def __getitem__(self, index): """ Simulate the [] access and return zero for indices out of range. """ # note: this method is used in the addition and multiplication operations try: return self.coeffs[index] except IndexError: return 0. def __setitem__(self, index, value): """ Change an arbitrary coefficient (even out of range) """ try: self.coeffs[index] = value except IndexError: newcoeffs = np.append(self.coeffs, np.zeros(index-len(self.coeffs)+1)) newcoeffs[index] = value self.coeffs = newcoeffs def length(self): """ "Length" of the polynomial (degree + 1) """ for index, coeff in enumerate(reversed(list(self.coeffs))): if coeff != 0: break return len(self.coeffs)-index def degree(self): """ Degree of the polynomial (biggest non zero coefficient). """ return self.length() - 1 @cast_scalars def __add__(self, other): """ P1 + P2 """ maxLength = max(self.length(), other.length()) return Polynomial([self[index] + other[index] for index in range(maxLength)]) __radd__ = __add__ def __neg__(self): """ -P """ return Polynomial(-self.coeffs) def __pos__(self): return Polynomial(self.coeffs) def __sub__(self, other): """ P1 - P2 """ return self + (-other) def __rsub__(self, other): return -(self - other) @cast_scalars def __mul__(self, other): """ P1 * P2 """ # length of the resulting polynomial: length = self.length() + other.length() newCoeffs = [sum(self[j]*other[i-j] for j in range(i+1)) for i in range(length)] return Polynomial(newCoeffs) __rmul__ = __mul__ def __div__(self, scalar): return self * (1/scalar) __truediv__ = __div__ def __pow__(self, n): """ P**n """ def mul(a,b): return a*b return functools.reduce(mul, [self]*n, 1.) class ConstantPolynomialError(Exception): """ Exception for constant polynomials """ def companion(self): """ Companion matrix. """ degree = self.degree() if degree == 0: raise self.ConstantPolynomialError("Constant polynomials have no companion matrix") companion = np.eye(degree, k=-1, dtype=complex) companion[:,-1] = -self.coeffs[:degree]/self.coeffs[degree] return companion def zeros(self): """ Compute the zeros via the companion matrix. """ try: companion = self.companion() except self.ConstantPolynomialError: if self: # non zero return [] else: raise self.ConstantPolynomialError("The zero polynomial has infinitely many zeroes") else: return nl.eigvals(companion).tolist() def __call__(self, x): """ Numerical value of the polynomial at x x may be a scalar or an array """ # note: the following technique certainly obfuscates the code... # # Notice how the following "sub-function" depends on x: def simpleMult(a, b): return a*x + b # the third argument is to take care of constant polynomials! return functools.reduce(simpleMult, reversed(self.coeffs), 0) epsilon = 1e-10 def __bool__(self): """ Test for difference from zero (up to epsilon) """ # notice the use of a generator inside the parenthesis # the any function will return True for the first True element encountered in the generator return any(abs(coeff) > self.epsilon for coeff in self.coeffs) __nonzero__ = __bool__ # compatibility Python 2 def __eq__(self, other): """ P1 == P2 """ return not (self - other) def __ne__(self, other): """ P1 != P2 """ return not (self == other) def differentiate(self): """ Symbolic differentiation """ return Polynomial((np.arange(len(self.coeffs))*self.coeffs)[1:]) # just for a cleaner import we delete this decorator del cast_scalars Zero = Polynomial([]) # the zero polynomial (extreme case with an empty coeff list) One = Polynomial([1]) # the unit polynomial X = Polynomial([0,1])
f18c8cbc60d927953bfd23c303e9ff9158b4d88f
lucianthorr/traffic-simulation
/trafficsimulation/car.py
3,548
3.890625
4
from blackbox import Blackbox import random class Car: """ The Car is the workhorse class of this project. Each car keeps track of its location, speed, and uses a Road object to get changes in the environment. Also, each car has a Car attribute that points to the car ahead of it. This is used to manage moving.""" def __init__(self,length=5,speed=0,location=0, current_time=0,road=None,number=-1): self.number = number self.length = length self.speed = speed self.location = location self.next_car = 0 self.max_speed = (100/3) #meters/second self.distance_from_car_ahead = 0 self.blackbox = Blackbox(-1,self.location,self.speed) self.road = road self.road_length = len(self.road.road) def __str__(self): print("Location: {} Speed: {}".format(self.location,self.speed)) def check_for_pass(self): # If self is ahead of next (>0) # but not so far that its really behind (<500) if 0 < (self.location - self.next_car.location) < 500: return True, self.next_car.location - self.location elif (self.road_length - self.next_car.location < 50 and self.location < 50): return True, -1 * ((self.road_length - self.next_car.location) + self.location) else: return False, None @property def distance(self): return self.distance_to_next_car() def distance_to_next_car(self): """ Distance to next car is the distance from next car's location minus this location MINUS the length of the next car. This will return a negative distance if we have accidentally passed the car ahead. """ distance = (self.next_car.location - self.location) if distance < 0: distance = ((self.road_length - self.location) + self.next_car.location) distance %= self.road_length passed, pass_distance = self.check_for_pass() if passed: return pass_distance else: return distance def accelerate(self): """ Accelerate uses the Road object to change its probability of slowing. """ road_condition = self.road.get_chance_of_slowing(int(self.location)) if random.random() < (0.1 * road_condition): self.speed -= 2 elif self.speed < self.max_speed: self.speed += 2 if self.speed > self.max_speed: self.speed = self.max_speed elif self.speed < 0: self.speed = 0 return self.speed def move(self): """ Moves the car ahead and looks for conflict. If so, moves back to the original location and moves again at a slower rate. """ self.speed = self.accelerate() dist_speed = self.distance - 5 min_speed = min([x for x in [dist_speed, self.next_car.speed] if x >= 0]) # Tentatively move the car ahead and check for conflict original_location = self.location if (self.speed) <= self.distance - 5: self.location = (original_location + self.speed) % self.road_length if self.distance < self.length * 5: self.location = (original_location + min_speed) % self.road_length self.speed = min_speed else: self.location = (original_location + min_speed) % self.road_length self.speed = min_speed
b199d3d6336ccb77d090afe4f2be3048ada29091
pulinghao/LeetCode_Python
/647. 回文子串.py
905
3.796875
4
#!/usr/bin/env python # _*_coding:utf-8 _*_ """ @Time    :2020/8/19 10:04 下午 @Author  :pulinghao@baidu.com @File :647. 回文子串.py  @Description : """ class Solution(object): def __init__(self): self.cnt = 0 def countSubstrings(self, s): """ :type s: str :rtype: int """ # cnt = 0 # for i in range(0,len(s)): # for j in range(i + 1,len(s) + 1): # if s[i:j] == s[i:j][::-1]: # cnt += 1 # return cnt def count(s, start, end): while start >= 0 and end < len(s) and s[start] == s[end]: self.cnt += 1 start -= 1 end += 1 for i in range(len(s)): count(s, i, i) count(s, i, i + 1) return self.cnt if __name__ == '__main__': print Solution().countSubstrings("aaa")
fb53f49b5607af41d9d89924d89c55bae6295e9e
SushantiThottambeti/Assignment-10
/Thottambeti.Sushanti.Assignment-10.py.py
4,117
3.546875
4
""" File: Python Programming Author: Sushanti Thottambeti DU ID: 873406925 Date: 06/05/2020 Title: Adding Functions to the Stock Problem Description: This program creates a line graph with Matplotlib for stock data imported from a JSON file. The graph shows variation in closing price for each stock over time.Also uploading in GitHub """ # -*- coding: utf-8 -*- # Import Packages import json from datetime import datetime as dt import matplotlib.pyplot as plt # File path for the json data source file filepath = r"C:\Users\Desktop\Sushanti\Week 8\AllStocks (1).json" # Read data in the json file and assign a variable # Using json.load() since the source data is from a file rather than a variable with open(filepath) as jsonData: stock_data = json.load(jsonData) # Initialize dictionaries to save all the extracted data from the json file AIG = {} F = {} FB = {} GOOG = {} M = {} MSFT = {} RDSA = {} # Data extraction from assigned variable and transferring to # the dictionaries that have been initialized for item in stock_data: while item['Symbol'] == 'AIG': closing_price = item.get('Close') AIG.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() AIG.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'F': closing_price = item.get('Close') F.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() F.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'FB': closing_price = item.get('Close') FB.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() FB.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'GOOG': closing_price = item.get('Close') GOOG.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() GOOG.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'M': closing_price = item.get('Close') M.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() M.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'MSFT': closing_price = item.get('Close') MSFT.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() MSFT.setdefault('date_value', list()).append(parse_date) break while item['Symbol'] == 'RDS-A': closing_price = item.get('Close') RDSA.setdefault('closing_value', list()).append(closing_price) date_field = item.get('Date') parse_date = dt.strptime(date_field, "%d-%b-%y").date() RDSA.setdefault('date_value', list()).append(parse_date) break # Generate plots utilizing dictionaries fig = plt.figure(dpi=128, figsize=(10,6)) plt.plot(AIG['date_value'],AIG['closing_value']) plt.plot(F['date_value'],F['closing_value']) plt.plot(FB['date_value'],FB['closing_value']) plt.plot(GOOG['date_value'],GOOG['closing_value']) plt.plot(M['date_value'],M['closing_value']) plt.plot(MSFT['date_value'],MSFT['closing_value']) plt.plot(RDSA['date_value'],RDSA['closing_value']) plt.title('Assignment 8', fontsize=16) plt.xlabel('Dates', fontsize=14) plt.ylabel("Closing values", fontsize=12) fig.autofmt_xdate() plt.tick_params(axis='both',which='major',labelsize='16') plt.savefig('outputGraph.png') plt.show()
f80f48bac7426249948893a7c03f32af7c69df0b
1751660300/lanqiaobei
/基础练习/01.py
403
3.671875
4
# -*- coding:utf-8 -*- n = int(input()) a = input().split(" ") def i(s): return int(s) if n < 2: print(a[0]) else: a.pop() a.sort(key=i) for b in a: print(b, end=' ') # 问题:n大于1时,a的分割会多出一个空出来,所以要把列表的最后一个元素删除 # 技术:使用了列表的排序 # 想起了字符的提取 re lxml bs4 jsonpath
0f5c8f5dd26de8f01e477ddaca90b431da5fab10
Daividao/interview
/topological_sort.py
1,177
3.859375
4
# Topological sort is applied to Directed Acyclic Graph to # find a a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u # comes before v in the ordering from utils import build_adjacency_list_directed from collections import deque # time complexity: O(N+M) # space: O(N) def topological_sort(total_nodes, edges): # build graph graph = build_adjacency_list_directed(total_nodes, edges) # calculate the indegree of all nodes indegrees = dict() for node in graph.keys(): indegrees[node] = 0 for node in graph.keys(): for neighbor in graph[node]: indegrees[neighbor] += 1 # find nodes with indegree == 0 queue = deque([]) for node in graph.keys(): if indegrees[node] == 0: queue.append(node) result = [] while queue: node = deque.popleft() result.append(node) for neighbor in graph[node]: indegrees[neighbor] -= 1 if indegrees[neighbor] == 0: queue.append(neighbor) if len(result) != len(graph.keys()): # there is a cycle return [] return result
54348692e73a2732236255ecc6d908c211504359
enrique-martinez95/Python
/DayOfTheWeek.py
1,997
4.25
4
# File: DayOfTheWeek.py # Description: A program that asks the user for a date and returns the day # of the week the day falls on. # Student's Name: Enrique Martinez # Student's UT EID: egm657 # Course Name: CS 303E # Unique Number: 50191 # # Date Created: 2/23/2020 # Date Last Modified: 2/23/2020 def main(): # Ask the user for a date in year, month, day format year = int(input("Please enter the year (an integer): ")) month = input("Please enter the month (a string): ") day = int(input("Please enter the day (an integer): ")) # calculate value for a given the month if month == "January": a = 11 elif month =="February": a=12 elif month =="March": a = 1 elif month == "April": a= 2 elif month == "May": a = 3 elif month =="June": a = 4 elif month == "July": a = 5 elif month == "August": a = 6 elif month == "September": a = 7 elif month == "October": a = 8 elif month == "November": a = 9 else: a = 10 # assign value for b b = day # calculate the value for c and d if a == 11 or a == 12: year = year-1 if year <= 1999: c= year % 1900 d = 19 elif year <= 2099: c = year % 2000 d = 20 else: c = 0 d = 21 # Zeller's Congruence w = (13 * a - 1) // 5 x = c//4 y = d // 4 z = w + x + y + b + c - 2 * d r = z%7 r = (r+7) % 7 if r == 0: dotw = "Sunday" elif r == 1: dotw = "Monday" elif r == 2: dotw = "Tuesday" elif r == 3: dotw = "Wednesday" elif r == 4: dotw = "Thursday" elif r == 5: dotw = "Friday" else: dotw = "Saturday" # print the day of the week print("The day of the week is " + dotw +".") main()
747f77dc55afb73fd7a74c4e18f023ddcd9a03a0
nadavpeled/automudo
/automudo/browsers/base.py
937
3.65625
4
class Browser(object): """ An interface representing a browser. Provides functions for getting bookmarks from it. """ # When inheriting this class, you should define a module-level # constant named "name", containing the browser's name def get_all_bookmarks(self): """ Returns all of the user's bookmarks in the browser. """ raise NotImplementedError() def get_music_bookmarks(self): """ Returns the user's music bookmarks. """ all_bookmarks = self.get_all_bookmarks() return [b for b in all_bookmarks if 'music' in map(str.lower, b[0])] def get_music_bookmarks_titles(self): """ Returns the titles that were given to the user's music bookmarks. """ return [bookmark_path[-1] for (bookmark_path, bookmark_url) in self.get_music_bookmarks()]
b675b047dea080792425c8c74b72abaf6ba42094
brlala/Educative-Grokking-Coding-Exercise
/Leetcode/138. Copy List with Random Pointer.py
1,508
3.9375
4
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': """ O(2n) """ dic = dict() m = n = head # Create old node to new node while m: dic[m] = Node(m.val) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = n.next return dic.get(head) def copyRandomList(self, head: 'Node') -> 'Node': """ dict with old Nodes as keys and new Nodes as values. Doing so allows us to create node's next and random as we iterate through the list from head to tail. Otherwise, we need to go through the list backwards. defaultdict() is an efficient way of handling missing keys """ map_new = collections.defaultdict(lambda: Node(0, None, None)) map_new[ None] = None # if a node's next or random is None, their value will be None but not a new Node, doing so removes the if-else check in the while loop nd_old = head while nd_old: map_new[nd_old].val = nd_old.val map_new[nd_old].next = map_new[nd_old.next] map_new[nd_old].random = map_new[nd_old.random] nd_old = nd_old.next return map_new[head]
b368a98a8df737b29ec0fd2cba2eb5f9a276957a
Edgarlv/Tarea_03
/Magnitud.py
300
3.890625
4
#encoding: UTF-8 #author: Edgar Eduardo Alvarado Duran #Problema 5 import math x= int(input("Dame el valor de x")) y= int(input("Dame el valor de y")) r= math.sqrt((x**2)+ (y**2)) angulo= math.atan2(x,y) grados= math.degrees(angulo) grados= 90-grados print ("La magnitud de r es:",r) print ("Angulo:", grados)
3c07168bd1f7c1721ef54198f9903df50cad4942
dwz1011/spider
/data_spider/bs_spider.py
415
3.5
4
# -*- coding: utf-8 -*- import urllib2 from bs4 import BeautifulSoup def bs_spider(html): soup = BeautifulSoup(html, 'lxml') tr = soup.find(attrs={'id':'places_area__row'}) td = tr.find(attrs={'class':'w2p_fw'}) area = td.text return area if __name__ == '__main__': url = 'http://example.webscraping.com/view/United-Kingdom-239' html = urllib2.urlopen(url).read() print bs_spider(html)
dce5092b88efb9c64696709897fb2809e133013e
otoolebrian/Challenges
/cryptanalysis/crypto.py
3,515
3.859375
4
# Vigenere Cipher Challenge Code # # This script is used to create ciphertext from plaintext in a file # and to decrypt ciphertext to plaintext using a user supplied key # # Source code is available at https://github.com/otoolebrian/Challenges/ import sys import re # I will use the alphabet for encrypting and decrypting letters, # I will also be able to use the alphabet to create the ciphertext # TODO: Implement Number Handling and special chars handling # Ignore these characters for the moment & jump over them in the # Cipher ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Hardcode the password into the file, it might make it easier # than having to remember to add a key at runtime. It's not in the # top 24 passwords of the year, so that should be ok # PASSWORD = Removed the password from here, it's not great to have # it hardcoded, no matter how easy it makes it def main(): if(len(sys.argv) == 4): textfile = open(sys.argv[3], "r") text = textfile.read() if(len(text) == 0): print("No Data in Textfile") exit() else: # I don't want to worry about lowercase letters in the key # so I will just convert the key to uppercase key = sys.argv[3].upper() # I am also worried about memory usage, so I have decided to # only take the first 5 chars of the key. This still leaves a # potential keyspace of like nearly 12 million passwords # TODO: Any special chars in the key cause me issues, so strip # them out. When I implement number handling, I'll put it back in fixed_key = re.sub('[ !@#$%^&*123456789]', '', sys.argv[2])[:5] if(sys.argv[1] == 'e'): print(encrypt(fixed_key, text)) elif(sys.argv[1] == 'd'): print(decrypt(fixed_key, text)) else: print("Supported modes are e for encryption or d for decryption") exit() else: print('USAGE: ./crypto.py <mode:e|d> <key> <textfile> ') exit() return() #Function to encrypt plaintext to ciphertext def encrypt(key, message): cipher = [] index=0 #Loop through the message for char in message: num = ALPHABET.find(char.upper()) #Check if it's a supported character, otherwise jump it if num != -1: num += ALPHABET.find(key[index].upper()) num %= len(ALPHABET) if char.isupper(): cipher.append(ALPHABET[num]) else: cipher.append(ALPHABET[num].lower()) else: cipher.append(char) # Move on to the next part of the key, or go back to the # start of the key if needed # We rotate through the key, even if the character is # unencryptable. I'd say that's more secure. IDK. Probably? # TODO: Check if this is more secure??? index += 1 if index == len(key): index = 0 return ''.join(cipher) #Function to decrypt ciphertext to plaintext def decrypt(key, message): plaintext = [] index=0 #Loop through the message for char in message: num = ALPHABET.find(char.upper()) #Check if it's a supported character, otherwise jump it if num != -1: num -= ALPHABET.find(key[index].upper()) num %= len(ALPHABET) if char.isupper(): plaintext.append(ALPHABET[num]) else: plaintext.append(ALPHABET[num].lower()) else: plaintext.append(char) # Move on to the next part of the key, or go back to the # start of the key if needed # Why are we rotating through the key? This is a terrible # idea # TODO: Tell the guy who wrote the encrypt function to change this index += 1 if index == len(key): index = 0 return ''.join(plaintext) if __name__ == '__main__': main()
2df22607e0b3c4d1b65c6356c157afba1f8d6e41
jonghwanchoi/python
/PracticePython/practice.py
2,387
4.0625
4
# 참 / 거짓 -->boolean # print(5 < 10) # print(not (5>10)) # station = "사당" # print(station + "행 열차가 들어오고 있습니다") # print(1+1) # print(2**3) #2^3 = 8 # print(5%3) # 나머지 구하기 2 # print(5/3) #소수점까지 나옴 # print(5//3) # 몫 =1 # print(10>3) #True # print(4 >= 7) #False # print(5 <= 5) #True # print(3 == 3) #True # print(3 != 4) #True # print(not(1 != 3)) #False # print((3>0)and(3<5)) #True # print((3>0) & (3<5)) #True # print((3>0) or (3>5)) #True # print((3>0) | (3>5)) #True # print(5>4>3) #True # print(2+3*4) # number = 2 + 3 * 4 # print(number) # number = number+2 # print(number) # number += 2 # print(number) # print(abs(-5)) # print(pow(4, 2)) #4^2 = 16 # print(max(5, 12)) # print(round(3.14)) # 3 반올림 # from math import * # print(floor(4.99)) #내림, 4 # print(ceil(3.14)) #올림, 4 # print(sqrt(16)) #제곱근, 4 # from random import * # #include랑 비슷한 역할 # day = randint(4, 28) # print("오프라인 스터디 모임 날짜는 매월"+ str(day) + "일로 선정되었습니다. ") # sentence = '나는 소년입니다' # print(sentence) # sentence2 = "파이썬은 쉬워요" # print(sentence2) # sentence3 = """ # 나는 소년이고, # 파이썬은 쉬워요 # """ # print(sentence3) # jumin = "990120-1234567" #배열과 같다 # print("성별 : " + jumin[7]) # print("연 : "+ jumin[0:2]) #0부터 2번째자리 직전까지..0,1 # print("월 : "+ jumin[2:4]) # print("일 : "+ jumin[4:6]) # print("생년월일 : "+ jumin[:6]) #처음부터 6 직전까지 # print("뒤 7자리 : "+jumin[7:]) #7부터 끝까지 # print("뒤 7자리 : " + jumin[-7:]) #맨 뒤에서 7번째부터 끝까지 # python = "Python is Amazing" # print(python.lower()) #소문자로 출력 # print(python.upper()) # print(python[0].isupper()) #문자열 0번째 값이 대문자인지? True or False # print(len(python)) #문자열 길이 구하기 # print(python.replace("Python", "Java")) #원하는 글자로 대체 # index = python.index("n") #해당 문자 첫 위치(index) 찾기 # index = python.index("n", index+1) #해당 문자의 두번째 위치 # print(index) # print(python.find("Java")) #원하는 값이 없을때 -1반 # # print(python.index("Java")) #원하는 값이 없을때 오류 및 종료 # print(python.count("n")) #해당 문자 개수 # print(index) # print("hello world")
83dfd350ac59374e05a0fb7a4bdd6b4f0aae3ab1
lobsterkatie/CodeFights
/Arcade/LoopTunnel/candles.py
1,957
4.34375
4
""" LOOP TUNNEL / CANDLES When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers? Example For candlesNumber = 5 and makeNew = 2, the output should be candles(candlesNumber, makeNew) = 9. Here is what you can do to burn 9 candles: burn 5 candles, obtain 5 leftovers; create 2 more candles, using 4 leftovers (1 leftover remains); burn 2 candles, end up with 3 leftovers; create another candle using 2 leftovers (1 leftover remains); burn the created candle, which gives another leftover (2 leftovers in total); create a candle from the remaining leftovers; burn the last candle. Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer. Input/Output [input] integer candlesNumber The number of candles you have in your possession. Constraints: 1 ≤ candlesNumber ≤ 15. [input] integer makeNew The number of leftovers that you can use up to create a new candle. Constraints: 2 ≤ makeNew ≤ 5. [output] integer """ def candles(num_candles, num_leftovers_to_make_new): num_leftovers = 0 total_burned = 0 #while you have candles left to burn... while num_candles > 0: #burn the candles you have, and turn them into leftovers num_burned = num_candles num_leftovers += num_burned total_burned += num_burned num_candles = 0 #make as many leftovers as you can into new candles candles_made = num_leftovers / num_leftovers_to_make_new num_candles += candles_made num_leftovers -= candles_made * num_leftovers_to_make_new return total_burned
3c9670e3bf58b60e5e26c15a1703430c1d440e68
inaciofabricio/python-para-iniciantes
/aula 10.py
268
4.09375
4
numero=20 while True: numero=numero-1 print(numero) if(numero==2): break print('---') numero=10 while True: numero=numero-1 if(numero==4): continue print(numero) if(numero==2): break for x in range(0,5): pass
4960366c9893866db32d1dada0af773a10b2ce0a
membriux/Wallbreakers-Training
/week1/Arrays/transpose_matrix.py
628
4.15625
4
# Problem 2: Transpose Matrix # Given matrix A, return transpose of A # Transpose = matrix flipped over it's main diagonal, # switching the row and column indices of the matrix ''' Example: Input: [[1,2,3], [4,5,6], [7,8,9]] Output: [[1,4,7], [2,5,8], [3,6,9] ] Input [[1,2,3], [4,5,6]] Output [[1,4], [2,5], [3,6]] ''' class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: transpose = [] for r in range(len(A[0])): temp = [] for c in range(len(A)): temp.append(A[c][r]) transpose.append(temp) return transpose
4617259b96130bc9ddca55f020042a5776b1a291
rgerk/PythonFiap
/variavel_numero.py
330
4.03125
4
nota1 = int( input("Digite a nota 1: ")) nota2 = int( input("Digite a nota 2: ")) media = (nota1 + nota2) / 2 if media >= 6: print("VOCE FOI APROVADO: " + "MEDIA: ", media) elif media < 4: print("VOCE ESTA EM REPROVADO:" + "MEDIA: ", media) else: print("VOCE ESTA EM RECUPERACAO: " + "MEDIA: ", media)
6bc3a9fbfef9373938df4528b1a26552a912d28d
realitycrysis/htx-immersive-08-2019
/01-week/3-thursday/labs/8-29-19 python exercises Scott/exercise6.py
100
3.796875
4
celcius = int(input('Temperature in Celsius?')) farenheit = 9.0/5.0 * celcius + 32 print(farenheit)
33acc5ba71e88c38e5642e55fae5c2162843f651
Elkasitu/advent-of-code
/day-07/tower.py
932
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def parse(raw): lines = [line for line in raw.split('\n') if line.find('->') > 0] supporting = [] supported = [] for line in lines: splitted = line.split('->') supporting.append(splitted[0].split()[0]) supported += splitted[1].strip().split(', ') return supporting, supported def find_root(supporting, supported): for node in supporting: if node not in supported: return node def test(): data = [ ['fwft', 'padx', 'tknk', 'ugml'], ['ktlj', 'cntj', 'xhth', 'pbga', 'havc', 'qoyq', 'ugml', 'padx', 'fwft', 'gyxo', 'ebii', 'jptl'] ] assert find_root(*data) == 'tknk', "Test input failed!" def main(): test() with open("input.txt", "r") as f: buf = f.read() print("Bottom program is %s" % find_root(*parse(buf))) if __name__ == '__main__': main()
d92d1f79415a7003720a374c94ffe6968b9ff982
Computer-engineering-FICT/Computer-engineering-FICT
/I семестр/Програмування (Python)/Лабораторні/Лисенко 6116/Python/Презентації/ex23/Ex8.py
242
3.53125
4
class Base: tb=10 class One(Base): to=20 class Two(Base): tt=30 x=Base() y=One() z=Two() L=[(x,"tb"),(y,"to"),(z,"tt")] #Атрибути задаємо як рядки for i,j in L: print(getattr(i,j), end=" ")
3d151510991e6d9f59053ca094ea17e3b7bb2bb8
boknowswiki/mytraning
/lintcode/python/1315_summary_ranges.py
4,821
3.609375
4
#!/usr/bin/python -t # array no duplicated number case class Solution: """ @param nums: a sorted integer array without duplicates @return: the summary of its ranges """ def summaryRanges(self, nums): # Write your code here n = len(nums) ret = [] if n == 0: return ret index = 0 i = 0 while i < n: start = i end = i while end < n -1 and (nums[end]+1 == nums[end+1]): end = end + 1 if end > start: s = str(nums[start]) + "->" + str(nums[end]) #ret.append(s) else: s = str(nums[start]) ret.append(s) i = end + 1 return ret class Solution: """ @param nums: a sorted integer array without duplicates @return: the summary of its ranges """ def summaryRanges(self, nums): # Write your code here n = len(nums) ret = [] if n == 0: return ret if n == 1: ret.append(str(nums[0])) return ret i = 0 while i < n: start = nums[i] while i +1 < n and nums[i+1]-nums[i] == 1: i += 1 if nums[i] != start: ret.append(str(start) + "->" + str(nums[i])) else: ret.append(str(start)) i += 1 return ret # array # cover duplicated numbers class Solution: """ @param nums: a sorted integer array without duplicates @return: the summary of its ranges """ def summaryRanges(self, nums): # Write your code here un_dup_l = set(nums) un_dup_l = list(un_dup_l) un_dup_l.sort() #print un_dup_l # get length n = len(un_dup_l) # no element, return empty list if n == 0: return [] # one element, return this value if n == 1: return [str(un_dup_l[0])] ret = [] # get start value start = str(un_dup_l[0]) # get start index index = un_dup_l[0] # start from second one for i in range(1, n): prev = un_dup_l[i-1] # not the last element if i != n-1: # not continue #print un_dup_l[i], index if un_dup_l[i] != index+1: if int(start) == index: ret.append(start) #print un_dup_l[i], start, index else: tmp = start + "->" + str(index) ret.append(tmp) start = str(un_dup_l[i]) index = un_dup_l[i] else: index += 1 else: #print index if un_dup_l[i] != index+1: if int(start) != index: tmp = start + "->" + str(index) ret.append(tmp) ret.append(str(un_dup_l[i])) else: ret.append(start) ret.append(str(un_dup_l[i])) else: tmp = start + "->" + str(un_dup_l[i]) ret.append(tmp) return ret # cover duplicated case class Solution: """ @param nums: a sorted integer array without duplicates @return: the summary of its ranges """ def summaryRanges(self, nums): # Write your code here n = len(nums) ret = [] if n == 0: return ret if n == 1: ret.append(str(nums[0])) return ret i = 0 while i < n: start = nums[i] while i+1 < n and nums[i+1] == nums[i]: i += 1 while i +1 < n and nums[i+1]-nums[i] == 1: i += 1 while i+1 < n and nums[i+1] == nums[i]: i += 1 if nums[i] != start: ret.append(str(start) + "->" + str(nums[i])) else: ret.append(str(start)) i += 1 return ret if __name__ == '__main__': ss = [0, 5, 9] print "input %s" % ss s = interview() print "answer is " print s.combin(ss)
e0d711e342dad3eba5762540a287db35e70538d9
ghostklart/python_work
/08.07.1.py
263
3.5
4
def make_album(): prompt_0 = "Please, specify the album: " prompt_1 = "Please, specify the artist: " res_album = input(prompt_0) res_artist = input(prompt_1) album_info = {'album': res_album, 'res_artist': res_artist} print(album_info) make_album()
ccc7ea3b924ea01ce43a8f9150eb3f76556f93c3
manondesclides/ismrmrd-python-tools
/ismrmrdtools/ndarray_io.py
2,452
3.640625
4
import numpy as np from struct import unpack def write_ndarray(filename,ndarray): '''Writes simple ndarray format. This format is mostly used for debugging purposes The file name extension indicates the binary data format: '*.float' indicates float32 '*.double' indicates float64 '*.cplx' indicates complex64 '*.dplx' indicatex complex128 :param filename: Name of file containing array (extension appended automatically) :param ndarray: Numpy array ''' datatype = ndarray.dtype if datatype == np.dtype(np.float32): fullfilename = filename + str('.float') elif datatype == np.dtype(np.float64): fullfilename = filename + str('.double') elif datatype == np.dtype(np.complex64): fullfilename = filename + str('.cplx') elif datatype == np.dtype(np.complex128): fullfilename = filename + str('.dplx') else: raise Exception('Unsupported data type') f = open(fullfilename,'wb') dims = np.zeros((ndarray.ndim+1,1),dtype=np.int32) dims[0] = ndarray.ndim; for d in range(0,ndarray.ndim): dims[d+1] = ndarray.shape[ndarray.ndim-d-1] f.write(dims.tobytes()) f.write(ndarray.tobytes()) def read_ndarray(filename): '''Reads simple ndarray format. This format is mostly used for debugging purposes The file name extension indicates the binary data format: '*.float' indicates float32 '*.double' indicates float64 '*.cplx' indicates complex64 '*.dplx' indicatex complex128 :param filename: Name of file containing array :returns arr: Numpy ndarray ''' datatype = None if filename.endswith('.float'): datatype = np.dtype(np.float32) elif filename.endswith('.double'): datatype = np.dtype(np.float64) elif filename.endswith('.cplx'): datatype = np.dtype(np.complex64) elif filename.endswith('.dplx'): datatype = np.dtype(np.complex128) else: raise Exception('Unknown file name extension') f = open(filename,'rb') ndims = f.read(4) ndims = unpack('<I', ndims)[0] dims = np.zeros((ndims),dtype=np.int32) for d in range(0,ndims): di = f.read(4) di = unpack('<I', di)[0] dims[ndims-1-d] = di dims = tuple(dims) by = f.read(np.prod(dims)*datatype.itemsize) arr = np.frombuffer(by,datatype); arr = arr.reshape(dims) return arr
a4c4d2d41a314c6be75e3c908dea6231b458ee43
TurusovMaxim/newrepository
/Pyramid for Mario.py
1,218
4.0625
4
element = input('Enter the data: ') def pyramid(element): if element.isdigit(): while int(element) > 23: element = input('Enter a number less than 23: ') while int(element) < 0: element = input('enter a number greater than 0: ') if int(element) >= 0 and int(element) <= 23: for j in range(int(element)): print(' ' * (int(element) - j - 1) + '#' * (j + 2)) else: try: float(element) while int(element) < 0: element = input('Enter a number greater than 0: ') while int(element) > 23: element = input('Enter a number less than 23: ') if int(element) >= 0 and int(element) <= 23: for j in range(int(element)): print(' ' * (int(element) - j - 1) + '#' * (j + 2)) except ValueError: element = input('Enter an integer greater than 0 but less than 23: ') if int(element) >= 0 and int(element) <= 23: for j in range(int(element)): print(' ' * (int(element) - j - 1) + '#' * (j + 2)) print(pyramid(element)) input('Press "enter" for close program ')
61878d94877c03611996947c648ceeb8e6318326
jobiaj/Problems-from-Problem-Solving-with-Algorithms-and-Data-Structures-
/Chapter_02/deque.py
505
3.8125
4
class Deque: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0, item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) def size(self): return len(self.items) d = Deque() d.add_front("athul") d.add_front("ravi") d.add_front("shibin") d.add_rear("chalu") d.add_rear("ansab") print d.remove_rear() print d.size()
2c5d289e36c119f9c2973a8126477e9e6337896f
hubieva-a/lab19
/l19z1.py
1,370
3.546875
4
from tkinter import * def func_sum(event): s1 = entry1.get() s1 = float(s1) s2 = entry2.get() s2 = float(s2) result1 = s1 + s2 result1 = str(result1) label1['text'] = ' '.join(result1) def func_difference(event): s1 = entry1.get() s1 = float(s1) s2 = entry2.get() s2 = float(s2) result2 = s1 - s2 result2 = str(result2) label1['text'] = ' '.join(result2) def func_multiplication(event): s1 = entry1.get() s1 = float(s1) s2 = entry2.get() s2 = float(s2) result3 = s1 * s2 result3 = str(result3) label1['text'] = ' '.join(result3) def func_splitting(event): s1 = entry1.get() s1 = float(s1) s2 = entry2.get() s2 = float(s2) result4 = s1 / s2 result4 = str(result4) label1['text'] = ' '.join(result4) root = Tk() entry1 = Entry(width=20) entry2 = Entry(width=20) but1 = Button(width=20,text=" + ") but2 = Button(width=20,text=" - ") but3 = Button(width=20,text=" * ") but4 = Button(width=20,text=" / ") label1 = Label(width=20) but1.bind('<Button-1>', func_sum) but2.bind('<Button-1>', func_difference) but3.bind('<Button-1>', func_multiplication) but4.bind('<Button-1>', func_splitting) entry1.pack() entry2.pack() but1.pack() but2.pack() but3.pack() but4.pack() label1.pack() root.mainloop()
73f72fd4a7cd11b57c082330384bf6aba37cb3fe
3Thiago/Competition-Toolbox
/longest_sequence.py
526
4.0625
4
def longest_sequence(N): ''' Find longest sequence of zeros in binary representation of an integer. The solution is straight-forward! Use of binary shift. ''' cnt = 0 result = 0 found_one = False i = N while i: if i & 1 == 1: if (found_one == False): found_one = True else: result = max(result,cnt) cnt = 0 else: cnt += 1 i >>= 1 return result
a303f16dda7121ad44c087c9fba0e9001ddebab3
JoseAntonioVelasco/2DAM_Workspaces
/Python/ejercicio5JoseantonioVelasco.py
1,190
4.0625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 18 09:00:16 2020 @author: ADMIN """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- listaLetras = ['T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E'] class DNI: def __init__(self,numero,letra): self.numero = numero self.letra = letra def mostrarInformacion(self): print("El dni introducido es el siguiente: ",self.numero,"-",self.letra) def calcularLetra(self): resto = self.numero % 23 letra = listaLetras[resto] return letra def comprobarValidez(self): if(self.letra==self.calcularLetra()): return True else: return False numdni = int(input("Introduce el numero del DNI: ")) letra = input("Introduce la letra del DNI: ") dni = DNI(numdni,letra) print("--------RESULTADOS--------") dni.mostrarInformacion() print("El numero del DNI es: ",dni.numero) print("La letra del DNI es: ",dni.letra) if(dni.comprobarValidez()): print("El DNI introducido es correcto") else: print("El DNI introducido NO es correcto. La letra correcta deberia ser la ",dni.calcularLetra())
d0473a3f9139951de0051eea70f98eb98011b387
GauravBhardwaj/pythonDS
/28questionsbyArdenDertat/2LargetsContinuousSum.py
864
4.09375
4
#Given an array of integers (positive and negative) find the largest continuous sum #return the largest sum, start and end import timeit def largest_sum1(arr): ''' We will keep swapping the maxsum with cureent sum while traversing the array. This doesnt work for negative numbers, so add an extra condition to check that. Time Complexity:O(n) Space Complexity:O(1) ''' if len(arr)==0: return currsum = 0 maxsum = 0 for i in range(0,len(arr)): currsum += arr[i] if currsum < 0: currsum = 0 elif currsum > maxsum: maxsum = currsum return maxsum #test print largest_sum1([-2, -3, 4, -1, -2, 1, 5, -3]) t1 = timeit.Timer("largest_sum1([-2, -3, 4, -1, -2, 1, 5, -3])", "from __main__ import largest_sum1") print "algo1: ", t1.timeit() #results #algo1: 1.3080239296
2fbd11a100c8fd3b6b9223b37841b7b74df742be
Maidno/Muitos_Exercicios_Python
/exe14.py
142
3.984375
4
c = float(input('Informe a temperatura em ºC: ')) fa = 9 * c / 5 + 32 print('A temperatura de {} ºC corresponde a {} ºF!' .format(c,fa))
a43210129bccc5794ea060bd7fb90564093b0b2f
binfen1/PythonWithHardware
/CyberPi V1/Python with CyberPi 043(read 阅后即焚).py
1,440
3.5625
4
"""" 名称:043 阅后即焚 硬件: 童芯派 功能介绍:读取文件的信息后,就会自动将读取到的信息进行删除。 难度:⭐⭐⭐⭐ 支持的模式:仅支持在线模式 使用到的API及功能解读: 1.read()函数 python的内建函数,通过read函数可以读取到文件中的数据 """ # ---------程序分割线----------------程序分割线----------------程序分割线---------- import cyberpi import time cyberpi.led.off() cyberpi.console.clear() while True: if cyberpi.controller.is_press("a"): chatfile = open("chatrecord.txt", 'r', encoding='utf-8') # 打开文件为追加模式,解码为utf-8,并存放在chatfile变量下。 message = chatfile.read() # 用变量存放 读取(read)所打开文件中的数据 for i in message: # 将读取的数据逐字在屏幕上进行打印。 cyberpi.console.print(i) time.sleep(0.01) cyberpi.console.println("消息即将抹除") chatfile.close() chatfile = open("chatrecord.txt", 'w', encoding='utf-8') # 打开文件为写入模式,解码为utf-8,并存放在chatfile变量下。 chatfile.write("404 Not Found") # 写入模式会先将文件内的数据进行清空,再写入。 cyberpi.console.clear() chatfile.close()
82a13e6438bde9c9bb840eb8b9bfc3a200d8e3cb
KennedyOdongo/Time_Series
/LSTM.py
6,127
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import LSTM from keras.layers import Dense from keras.layers import Flatten import math from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt import pandas_datareader as pdr import warnings warnings.filterwarnings('ignore') # In[3]: data=pd.read_csv(r'Downloads\shampoo.csv') data.head() # In[4]: def data_prep(series,n_features): """ given a data series and the number of periods you want use to forecast, this function returns a value""" X,y=[],[] for i in range(len(series)): next_prediction=i+n_features if next_prediction> len(series)-1: break seq_x,seq_y=series[i:next_prediction],series[next_prediction] X.append(seq_x) y.append(seq_y) return np.array(X),np.array(y) # In[5]: X,y=data_prep(data['Sales'],3) # In[6]: X # In[7]: y # #### Whenever you are using an LSTM you have to reshape your data into a 3 dimensional data set # In[8]: ## We do a reshape from samples and time steps to samples, timestps and features # In[9]: X=X.reshape((X.shape[0],X.shape[1],1)) # In[10]: n_steps=3 n_features=1 # In[11]: model=Sequential() model.add(LSTM(50, activation='relu', return_sequences=True, input_shape=(n_steps,n_features))) model.add(LSTM(50, activation='relu')) #layer with 50 neurons model.add(Dense(1)) # we'll need only one output model.compile(optimizer='adam',loss='mse') model.fit(X,y,epochs=200,verbose=0) # Setting verbose to 1 shows you all the epochs # In[12]: x_input=np.array(data['Sales'][-3:]) temp_input=list(x_input) lst_output=[] i=0 while (i<20): # This depends on how far into the future you eant to predict, 10 periods ahead here if (len(temp_input)>3): x_input=np.array(temp_input[1:]) print("{} day input {}".format(i,x_input)) x_input=x_input.reshape((1, n_steps, n_features)) yhat=model.predict(x_input,verbose=0) print("{} day output {}".format(i, yhat)) temp_input.append(yhat[0][0]) temp_input=temp_input[1:] lst_output.append(yhat[0][0]) i=i+1 else: x_input=x_input.reshape((1, n_steps, n_features)) yhat=model.predict(x_input,verbose=0) print(yhat[0]) temp_input.append(yhat[0][0]) lst_output.append(yhat[0][0]) i=i+1 print(lst_output) # In[13]: new=np.arange(1,21) pred=np.arange(20,40) # In[14]: plt.plot(new,data["Sales"][-20:]) plt.plot(pred,lst_output) # In[15]: df=pdr.get_data_tiingo('AAPL',api_key='2616ae4c299d778e6ad7cc4a129f2a495322a5e8') # In[16]: df.to_csv('AAPL.csv') # In[17]: df1=df.reset_index()['close'] # In[18]: df1.shape # In[19]: import matplotlib.pyplot as plt plt.plot(df1) # In[20]: ## LSTMS are very sensitive to the scales of the data # In[21]: import numpy as np from sklearn.preprocessing import MinMaxScaler scaler=MinMaxScaler(feature_range=(0,1)) df1=scaler.fit_transform(np.array(df1).reshape(-1,1)) # In[22]: training_size=int(len(df1)*0.65) test_size=len(df1)-training_size train_data, test_data=df1[0:training_size,:],df1[training_size:len(df1),:1] # In[23]: def create_dataset(dataset, time_step=1): dataX, dataY=[],[] for i in range(len(dataset)-time_step-1): a=dataset[i:(i+time_step),0] dataX.append(a) dataY.append(dataset[i+timestep,0]) return np.array(dataX),np.array(dataY) # In[24]: timestep=100 xtrain,ytrain=create_dataset(train_data, timestep) xtest,ytest=create_dataset(test_data,timestep) # In[25]: xtrain # In[26]: xtrain=xtrain.reshape(xtrain.shape[0],xtrain.shape[1],1) xtest=xtest.reshape(xtest.shape[0],xtest.shape[1],1) # In[27]: model=Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(100,1))) model.add(LSTM(50, return_sequences=True)) #layer with 50 neurons model.add(LSTM(50)) model.add(Dense(1)) # we'll need only one output model.compile(optimizer='adam',loss='mse') # In[28]: model.summary() # In[29]: model.fit(xtrain,ytrain,validation_data=(xtest,ytest),epochs=100,batch_size=64,verbose=0) # In[30]: train_predict=model.predict(xtrain) test_predict=model.predict(xtest) # In[31]: train_predict=scaler.inverse_transform(train_predict) test_predict=scaler.inverse_transform(test_predict) # In[32]: math.sqrt(mean_squared_error(ytrain,train_predict)) # In[33]: math.sqrt(mean_squared_error(ytest,test_predict)) # In[34]: look_back=100 trainPredictPlot=np.empty_like(df1) trainPredictPlot[:,:]=np.nan trainPredictPlot[look_back:len(train_predict)+look_back,:]=train_predict testPredictPlot=np.empty_like(df1) testPredictPlot[:,:]=np.nan testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1,:]=test_predict plt.plot(scaler.inverse_transform(df1)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() # In[35]: len(test_data) # In[36]: x_input=test_data[341:].reshape(1,-1) x_input.shape # In[37]: temp_input=list(x_input) temp_input=temp_input[0].tolist() # In[38]: lst_output=[] n_steps=100 i=0 while(i<30): #for the next 30 days if (len(temp_input)>100): x_input=np.array(temp_input[1:]) print("{} day input {}".format(i,x_input)) x_input=x_input.reshape(1,-1) x_input=x_input.reshape(1,n_steps,1) yhat=model.predict(x_input,verbose=0) print("{} day output {}".format(i, yhat)) temp_input.extend(yhat[0].tolist()) temp_input=temp_input[1:] lst_output.extend(yhat.tolist()) i+=1 else: x_input=x_input.reshape((1, n_steps, 1)) yhat=model.predict(x_input,verbose=0) print(yhat[0]) temp_input.extend(yhat[0].tolist()) print(len(temp_input)) lst_output.extend(yhat.tolist()) i+=1 #print(lst_output) # In[39]: day_new=np.arange(1,101) day_pred=np.arange(101,131) # In[40]: plt.plot(day_new,scaler.inverse_transform(df1[1158:])) plt.plot(day_pred,scaler.inverse_transform(lst_output))
47201e22b61833e6b2ec0a46b81f400bdacb311f
piyush18184/Student-Management-System
/student_enrollement.py
4,856
3.921875
4
from Course import * from ListOfCourses import CourseList as c from ListOfMajors import * from Course import * from ListOfStudents import * from Major import * from ListOfParticularCourses import * from Student import * import sys if __name__ == '__main__': while True: print() print("1:Student name") print("2:Available Courses") print("3. Add Courses") print("4:Remove Courses") print("5. Show Cart") print("Press any other key to exit") print() print("Enter choice:") num = int(input()) print() if num == 1: print("Student's List from the records:") print("Roll Number", " Student Name"," ", "ID") for i in Student.list_students: print(i.GetStudentRollNumber()," ",i.GetStudentName(),i.GetStudentID()) elif num == 2: print("S.No.", "Course Name", "Course ID", "Course Price") c=1 for i in Courses.list_course: print(c," ",i.GetCourseName()," ",i.GetCourseID()," ",i.GetCoursePrice()) c=c+1 elif num == 3: while True: print("Enter the roll number of student whose cart needs to be modified(press 0 to exit):") roll=input() if int(roll) == 0: break else: print("Enter the Course Number to be added") print("Press any other key apart from 1-6 to exit") s=int(input()) if s==1: student1.BuyCourse(course1,roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s==2: student1.BuyCourse(course2,roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s==3: student1.BuyCourse(course3, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s==4: student1.BuyCourse(course4, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s==5: student1.BuyCourse(course5, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s==6: student1.BuyCourse(course6, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() else: print("Invalid Input") break elif num== 4: while True: print("Enter the roll number of student whose cart needs to be removed(press 0 to exit):") roll = input() if int(roll) == 0: break else: print("Enter the Course Number to be removed") print("Press any other key apart from 1-6 to exit") s = int(input()) if s == 1: student1.Remove(course1, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s == 2: student1.Remove(course2, roll) print("%s" % student1.GetCart().ShowCart()) #student1.AddCart() elif s == 3: student1.Remove(course3, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s == 4: student1.Remove(course4, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s == 5: student1.Remove(course5, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() elif s == 6: student1.Remove(course6, roll) print("%s" % student1.GetCart().ShowCart()) student1.AddCart() else: print("Invalid Input") break elif num==5: print(student1.GetCart().ShowCart()) else: sys.exit()
de3034b0cddf4768cd21c45d24f7e8e3c266b892
CharlesBasham132/com404
/second-attempt-at-tasks/1-basics/3-decision/2-nested-decisions/1-nested/bot.py
596
4
4
print("what type of book cover is that?(soft/hard)") book_cover_hardness = str(input()) if (book_cover_hardness == "soft"): print("is the cover perfect bound?(yes/no)") book_cover_bound = str(input()) if (book_cover_bound == "yes"): print("soft cover, perfect bound books are popular") elif (book_cover_bound == "no"): print("soft covers with coils or stiches are great for short books") else: print("incorect input") elif (book_cover_hardness == "hard"): print("hard cover books can be more expensive!") else: print("incorect input")
ae34f58be95bb422ed47b5b1a3065e4f006f100f
sanderheieren/in1000
/oblig2/utskriftsfunksjon.py
521
3.53125
4
# Sander Heieren, Oblig 2, IN1000 # Dette programmet skal ta inn navn og bosted fra terminalen (brukeren) # Vi skal også brukte prosedyrer for å bli bedre kjent med kodeflyt, her er det bare om utskrifter # 1, 2 får navn og bosted og legger all logikk inn i en egen prosedyre. Denne skal kalles 3 ganger. def navnOgBosted(): navn = input('Skriv inn navn: ') bosted = input('Hvor kommer du fra? ') print(f'Hei {navn}! Du er fra {bosted}.') # Kaller på prosedyren 3 ganger for x in range(3): navnOgBosted()
81c5335d0b90373381d5f94aee11d78c38e0e6ca
itsbritt/python_practice
/conditionals.py
436
3.9375
4
myList = [1,2,3,4] myTuple = (1,2,3,4) if 1 in myList: print 'Do I print?' if 4 in myTuple: print 'yo' if 5 not in myTuple: print 'no' aList = ['apples', 'oranges', 'pineapples'] whatIsRange = range(1,10) whatIsRangeAgain = range(20,30) print whatIsRange print whatIsRangeAgain for i in range(len(aList)): print 'value is %s' % aList[i] for index, value in enumerate (aList): print 'the index is %d' % index