text
stringlengths
37
1.41M
import random class Account: # 클래스를 완성하세요 """ - 보안문제로 외부에서 내부의 정보를 수정할 수 없도록 변수를 설정해야함 - 계좌번호와 잔고의 경우 표시된 결과와 다를 수 있음 - def __init__(name: str, birthday: str) - def __str__() -> 계좌정보 - def deposit(amount:int) :입금 함수 - def withdraw(amount:int) 출금 함수 - 필요시 random() 함수 사용 가능 - 안전코딩 : 입금은 0원 미만일 수 없고, 출금은 잔고 이상일 수 없음 """ def __init__(self, name: str, birthday: str): self.__name = name self.__birthday = birthday self.__account = str(random.randint(0,999)).zfill(3) + "-" + str(random.randint(0,99)).zfill(2) + "-" + str(random.randint(0,999999)).zfill(6) self.__balance = random.randint(0,1000) def __str__(self): return "이름: {}\n생년월일: {}\n계좌번호: {}\n잔고: {}".format(self.__name, self.__birthday,self.__account,self.__balance,) def show_balance(self): return print("잔고: {}".format(self.__balance)) def deposit(self, amount:int): if amount >0 : self.__balance = self.__balance + amount return print("{}원 입금".format(amount)) else: return print("입금불가") def withdraw(self, amount:int): if 0 < amount <= self.__balance: self.__balance = self.__balance - amount return print("{}원 출금".format(amount)) else: print('출금불가') ###### do not edit here ####### person = Account("김성균", "990218") print(person) print("#####") person.deposit(100) person.deposit(-1) person.show_balance() person.withdraw(500) person.withdraw(0) person.show_balance()
import tkinter from PIL import Image, ImageTk root = tkinter.Tk() cv = tkinter.Canvas(root, width = 500, height = 300) def click(event): print("Click Location: ", event.x, event.y) r, g, b = img.getpixel((event.x, event.y)) print("R:%d, G:%d, B:%d" % (r,g,b)) cv.bind("<Button-1>", click) cv.pack() img = Image.open("cat.jpg") img_tk = ImageTk.PhotoImage(img) cv.create_image(250, 250, image=img_tk) root.mainloop()
""" Задача на программирование: точки и отрезки """ import random import bisect def partition(array, start, end): x = array[start] # j # | x | <= x | > x | j = start for i in range(start + 1, end + 1): if array[i] <= x: j += 1 array[i], array[j] = array[j], array[i] array[start], array[j] = array[j], array[start] return j def rand_partition(array, start, end): rand_elem = random.randint(start, end) array[rand_elem], array[start] = array[start], array[rand_elem] x = array[start] # j # | x | <= x | > x | j = start for i in range(start + 1, end + 1): if array[i] <= x: j += 1 array[i], array[j] = array[j], array[i] array[start], array[j] = array[j], array[start] return j def rand_partition_3parts(array, start, end): rand_elem = random.randint(start, end) array[rand_elem], array[start] = array[start], array[rand_elem] x = array[start] # j # | x | <= x | > x | j = start i = start + 1 end_iter = end while i < end_iter + 1: if array[i] < x: j += 1 array[i], array[j] = array[j], array[i] elif array[i] > x: array[end_iter], array[i] = array[i], array[end_iter] end_iter -= 1 i -= 1 i += 1 array[start], array[j] = array[j], array[start] return j, end_iter def quick_sort(array, start, end): if start >= end: return mid, mid1 = rand_partition_3parts(array, start, end) quick_sort(array, start, mid - 1) quick_sort(array, mid1 + 1, end) num_of_sections, num_of_points = map(int, input().split()) sections_start = [] sections_end = [] for i in range(num_of_sections): start, end = map(int, input().split()) sections_start.append(start) sections_end.append(end) points = [int(i) for i in input().split()] quick_sort(sections_start, 0, len(sections_start) - 1) quick_sort(sections_end, 0, len(sections_end) - 1) for point in points: it_start = bisect.bisect_right(sections_start, point, 0, len(sections_start)) it_end = bisect.bisect_left(sections_end, point, 0, len(sections_start)) print(it_start - it_end, end=' ') print()
# -*-coding:Latin-1 -* """Classe Etudiant""" class Etudiant: # Attributs nom = "" prenom = "" numCarte = 0 # constructeur def __init__(self, nom, prenom): self.nom = nom self.prenom = prenom """ Ajout des tudiants du fichier la liste """ def importFichier(liste, fichier): with open (fichier, "r") as f: # Ouvre le fichier et le ferme proprement la fin de la boucle # Rcupre le fichier sous forme de string et la dcoupe (tous les blancs) en tableau args=f.read().split() i=0 while i < len(args): # Ajoute les lts du tableau la liste des tudiants liste+=[Etudiant(args[i],args[i+1])] i+=2 # Fermeture fichier return liste """ Ajout du numro tudiant """ def ajoutNumCarte(liste, nom, numeroCarte): for etu in liste: # Cherche le bon tudiant et lui attribue son numro de carte if etu.nom == nom: etu.numCarte = numeroCarte return liste """ Enlve de la liste des absents l'leve au numro numeroCarte """ def retraitAbsent(absents, numeroCarte): for i in range(len(absents)): if absents[i].numCarte == numeroCarte: absents.remove(absents[i]) break # sort pour viter un dbordement de liste cause du remove return absents
# -*-coding:Latin-1 -* """Classe Etudiant""" class Etudiant: # Attributs nom = "" prenom = "" numCarte = 0 # constructeur def __init__(self, nom, prenom): self.nom = nom self.prenom = prenom """ Ajout des tudiants du fichier la liste """ def importFichier(liste, fichier): with open (fichier, "r") as f: # Ouvre le fichier et le ferme proprement la fin de la boucle # Rcupre le fichier sous forme de string et la dcoupe (tous les blancs) en tableau args=f.read().split() i=0 while i < len(args): # Ajoute les lts du tableau la liste des tudiants liste+=[Etudiant(args[i],args[i+1])] i+=2 # Fermeture fichier return liste """ Ajout du numro tudiant """ def ajoutNumCarte(liste, nom, numeroCarte): return liste
ten=int(input("Enter the Ten Rs. coins quantity: ")) five=int(input("Enter the Five Rs. coins quantity: ")) two=int(input("Enter the Two Rs. coins quantity: ")) one=int(input("Enter the One Rs. coins quantity: ")) total=((10*ten)+(5*five)+(2*two)+(1*one)) print("Total amount of money: ",total)
from tkinter import * from tkinter import messagebox import random as playerfind def button(window): b = Button(window, padx=1, bg="#856ff8", width=3, text=" ", font=('times new roman', 60, 'bold')) return b def change_a(): global turn for i in ['O', 'X']: if not (i == turn): turn = i break def reset(): global turn for i in range(3): for j in range(3): box_played[i][j]["text"] = " " box_played[i][j]["state"] = NORMAL turn = playerfind.choice(['O', 'X']) def check(): for i in range(3): if box_played[i][0]["text"] == box_played[i][1]["text"] == box_played[i][2]["text"] == turn: messagebox.showinfo("Congrats!!", "'" + turn + "' has won") reset() elif box_played[0][i]["text"] == box_played[1][i]["text"] == box_played[2][i]["text"] == turn: messagebox.showinfo("Congrats!!", "'" + turn + "' has won") reset() if box_played[0][0]["text"] == box_played[1][1]["text"] == box_played[2][2]["text"] == turn: messagebox.showinfo("Congrats!!", "'" + turn + "' has won") reset() elif box_played[0][2]["text"] == box_played[1][1]["text"] == box_played[2][0]["text"] == turn: messagebox.showinfo("Congrats!!", "'" + turn + "' has won") reset() elif box_played[0][0]["state"] == box_played[0][1]["state"] == box_played[0][2]["state"] == box_played[1][0]["state"] == box_played[1][1]["state"] == box_played[1][2][ "state"] == box_played[2][0]["state"] == box_played[2][1]["state"] == box_played[2][2]["state"] == DISABLED: messagebox.showinfo("Tied!!", "The match ended in a draw") reset() def click(row, col): box_played[row][col].config(text=turn, state=DISABLED, disabledforeground=colour[turn]) check() change_a() label.config(text=turn + "'s Chance") parent = Tk() parent.title("Tic Tac Toe With GUI") turn = playerfind.choice(['O', 'X']) colour = {'O': "deep sky blue", 'X': "Red"} box_played = [[], [], []] for i in range(3): for j in range(3): box_played[i].append(button(parent)) box_played[i][j].config(command=lambda row=i, col=j: click(row, col)) box_played[i][j].grid(row=i, column=j) label = Label(text=turn + "'s Chance", font=('sans', 25, 'bold')) label.grid(row=3, column=0, columnspan=3) parent.mainloop()
def test(n,e): if e>1 and e<n: ct=int(input("Enter the cipher test ct = ")) if e<=5: sm_e(ct,n,e) else: test2(ct,n,e) else: print("Wrong values Exiting") def sm_e(ct,n,e): from resources.nthroot import nth res=nth(ct,e) while(res!=0): if res == 1: print("Seems like we found it.\n1.Exit\n2.Continue Testing") selection=int(input()) if selection==1: exit() elif selection==2: res=0 else: print("Invalid selection Try again:\n") test2(ct,n,e) def test2(ct,n,e): from Crypto.Util.number import inverse from resources.decrypt import decrypt if e>65537: from resources import owiener d=owiener.attack(e,n) if d is None: pass else: decrypt(ct,d,n) from resources.fermant import fer val=fer(n) if val!=0: d=inverse(e,val) decrypt(ct,d,n) exit() from resources.pollard import pollards val=pollards(n) if val!=0: d=inverse(e,val) decrypt(ct,d,n) exit()
def biggest_collatz(x): longest_seq, test = [], [] for i in range(1, x+1): test.append(i) while i > 1: if i % 2 == 0: i //= 2 else: i = i*3+1 test.append(i) if len(test) > len(longest_seq): longest_seq = test test = [] return longest_seq print(biggest_collatz(1000))
# -*- coding: utf-8 -*- """ Created on Sun Sep 16 19:45:00 2018 @author: Yahia Bakour, OOG """ def find_Median(A,B): if(len(A) > len(B)): Arr1 , n = B, len(B) Arr2 , m = A, len(A) else: Arr1 , n = A, len(A) Arr2 , m = B, len(B) Min, Max = 0 , n while(Min <= Max): #Setting Partitions Partition_1 = (Min + Max) // 2 Partition_2 = (n + m + 1) // 2 - Partition_1 #For maxleft1 if(Partition_1 != 0): Max_Left_1 = Arr1[Partition_1 - 1] else: Max_Left_1 = float("-inf") #For minRight1 if(Partition_1 != n): Min_Right_1 = Arr1[Partition_1] else: Min_Right_1 = float("inf") #For maxLeft2 if(Partition_2): Max_Left_2 = Arr2[Partition_2 - 1] else: Max_Left_2 = float("-inf") #For MinRight2 if(Partition_2 != m): Min_Right_2 = Arr2[Partition_2] else: Min_Right_2 = float("inf") #WE Know We Found The Median if(Max_Left_1 <= Min_Right_2 and Max_Left_2 <= Min_Right_1): if((m+n)%2): return max(Max_Left_1,Max_Left_2) else: return (max(Max_Left_1,Max_Left_2) + min(Min_Right_1,Min_Right_2)) / 2.0 elif Max_Left_1 <= Min_Right_2: Min = Partition_1 + 1 else: Max = Partition_1 - 1 Array1 = [1,3,5,7,9,11] Array2 = [2,4,6,8,10,12] Median = find_Median(Array1, Array2) print("MEDIAN OF ARR 1 And ARR 2 is : " + str(Median))
# -*- coding: utf-8 -*- """ Created on Fri Sep 14 18:00:53 2018 @author: yahia """ def DictionarySearch(A,Left,Right,key): if (Right >= Left): y = (key - A[Left]) / (A[Right] - A[Left]) mid = Left + y * (Right - Left) mid = int(mid) if (A[mid] == key): return mid if (A[mid] > key): return DictionarySearch(A, Left, mid - 1, key) else: return DictionarySearch(A, mid + 1, Right, key) return -1 list1 = [0,1,2,10,100,2000,10000,200000,1000000,200000000] print("NUMBER 2000 FOUND IN : " + str(DictionarySearch(list1,0,len(list1)-1,2000)))
class Node: def __init__(self, data): self.left = None self.right = None self.parent = None self.data = data self.color = 'R' class RB_Tree: def __init__(self,N): self.root = N self.root.color = 'B' def search(self,currnode, data): if currnode.data == data: return (True) elif currnode.data < data: if currnode.right is None: return (False) else: return(self.search(currnode.right,data)) elif currnode.data > data: if currnode.left is None: return (False) else: return(self.search(currnode.left,data)) def PrintTree(self,root): #Inorder Traversal currnode = root print(currnode.data) if(currnode.parent is not None): print("parent IS : " + str(currnode.parent.data),end="-->") if(currnode is not None): print("Color IS : " + str(currnode.color)) if currnode.left: self.PrintTree(currnode.left) if currnode.right: self.PrintTree(currnode.right) def insert(self,data): currnode = self.root newnode = Node(data) self.insert_Recursive(currnode,newnode,data) if(newnode.parent is None): newnode.color = 'B' return self.fix_Violations(newnode) def insert_Recursive(self,currnode, newnode,data): if currnode.data: if data < currnode.data: if currnode.left is None: newnode.parent= currnode currnode.left = newnode else: self.insert_Recursive(currnode.left,newnode,data) else: if currnode.right is None: newnode.parent = currnode currnode.right = newnode else: self.insert_Recursive(currnode.right,newnode,data) def fix_Violations(self,Pointer): N = Pointer if(self.root == N): N.color = 'B' return while(N.parent is not None and N.parent.color == 'R'): if(N.parent.parent.left == N.parent): if(N.parent.parent.right is not None): if(N.parent.parent.right.color == 'R'): N.parent.color = 'B' N.parent.parent.right.color = 'B' N.parent.parent.color = 'R' N = N.parent.parent else: if(N.parent.right == N): N = N.parent self.leftRotate(N,N.right) N.parent.color = 'B' N.parent.parent.color = 'R' self.rightRotate(N.parent.parent,N.parent.parent.left) else: if(N.parent.parent.left is not None): if(N.parent.parent.left.color == 'R'): N.parent.color = 'B' N.parent.parent.left.color = 'B' N.parent.parent.color = 'R' N = N.parent.parent else: if(N.parent.left == N): N = N.parent self.rightRotate(N,N.left) N.parent.color = 'B' N.parent.parent.color = 'R' self.leftRotate(N.parent.parent,N.parent.parent.right) self.root.color = 'B' def leftRotate(self, G,P) : if P is None: return else: if P.left is not None: G.right = P.left P.left.parent = G else: G.right = None if G.parent is not None: P.parent = G.parent if G.parent is None: self.root = P self.root.parent = None else: if G == G.parent.left: G.parent.left = P else: G.parent.right = P P.left = G G.parent = P def rightRotate(self, G,P) : if P is None: return else: if P.right is not None: G.left = P.right P.right.parent = G else: G.left = None if G.parent is not None: P.parent = G.parent if G.parent is None: self.root = P self.root.parent = None else: if G == G.parent.left: G.parent.left = P else: G.parent.right = P P.right = G G.parent = P root = Node(10) RB = RB_Tree(root) RB.insert(11) RB.insert(12) RB.insert(13) RB.insert(14) RB.insert(15) RB.insert(1) RB.insert(3) RB.insert(4) RB.insert(5) RB.PrintTree(RB.root) if(RB.search(RB.root,10)): print("FOUND ")
__author__ = 'Eder Xavier Rojas' from collections import Counter events = [] fechas = [] events_file = raw_input("Nombre del archivo: ") print "you entered", events_file try: f = open(events_file,'r') line = f.readline() while line: try : #Set the whole string #remove enter if(not line.startswith('#')): line = line.rstrip('\n').rstrip('\r') line = ','.join(line.split(',')[3:]) try: if line: #print(line) #dividir las lineas por sus espacios en blanco pieces = line.split(',') #rearmar las lineas a partir de la segunda posicion key = pieces[0].strip('"')+","+pieces[1].strip('"') fechas.append(pieces[2].split()[1]) key = key.strip('"') events.append(key) except: pass line = f.readline() except: pass events_count = Counter(events) total = 0 for key in events_count: total += events_count[key] print(key+","+str(events_count[key])) print("TOTAL EVENTOS:"+str(total)) print("------------------------------------") fachas_count = Counter(fechas) for key in fachas_count: print(key+","+str(fachas_count[key])) except Exception,e: print("Error: No fue posible leer el archivo [ " + events_file+" ]") print(e)
import turtle from random import * for i in range(0,100,1): turtle.right(randint(0,360)) turtle.forward(randint(0,100))
# 1. List Comprehensions print('--' * 40) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(f"Numbers: {numbers}") print('--' * 40) def square(): squares = [] for i in numbers: squares.append(i ** 2) print(f"Squares - Traditional way: {squares}") print('--' * 40) squares = list(map(lambda x: x ** 2, numbers)) print(f"Squares - Map Function: {squares}") print('--' * 40) squares = [i ** 2 for i in numbers] print(f"Squares - List Comprehension: {squares}") print('--' * 40) even_squares = [i ** 2 for i in numbers if i % 2 == 0] print(f"Even Squares - List Comprehension: {even_squares}") print('--' * 40) odd_squares = [i ** 2 for i in numbers if i % 2 != 0] print(f"Odd Squares - List Comprehension: {odd_squares}") print('--' * 40) # square() def square_cube(): squares_cubes = [] for i in numbers: if i < 6: squares_cubes.append(i ** 2) else: squares_cubes.append(i ** 3) print(f"Square & Cube - Traditional Way: {squares_cubes}") print('--' * 40) squares_cubes = list(map(lambda x: x ** 2 if x < 6 else x ** 3, numbers)) print(f"Square & Cube - Map Function: {squares_cubes}") print('--' * 40) # [ <evaluation expression> for in <collection> <filter expression> ] squares_cube = [i ** 2 if i < 6 else i ** 3 for i in numbers] print(f"Square & Cube - List Comprehension: {squares_cubes}") print('--' * 40) num = [-1, -2, -3, -4, -5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(f"Num: {num}") odd_cubes_gt0 = [i ** 3 if i > 0 else -9999 for i in num if i % 2 != 0] print(f"Odd Cube, gt 0 - List Comprehension: {odd_cubes_gt0}") print('--' * 40) print('**' * 40) result = [] for i in num: if i % 2 != 0: if i > 0: result.append(i ** 3) else: result.append(-9999) print(f"Result: {result}") print('**' * 40) # square_cube() # ----------------------------------------------------------- # Dictionary Comprehensions # ----------------------------------------------------------- def func1(): num_sq = {num: num ** 2 for num in range(11) if num > 0} even_sq = {num: num ** 2 for num in range(11) if num % 2 == 0 and num > 0} odd_sq = {num: num ** 2 for num in range(11) if num % 2 != 0} print(f"num_sq: {num_sq}, and type of num_sq = {type(num_sq)}") print(f"even_sq: {even_sq}, and type of even_sq = {type(even_sq)}") print(f"odd_sq: {odd_sq}, and type of odd_sq = {type(odd_sq)}") func1()
# -------------------------------------------------------------------------- """ Root Class: object Every class in Python is inherited directly or indirectly from Root class i.e 'object'. """ # -------------------------------------------------------------------------- class NewPerson(object): def __init__(self, name, age, city): self._name = name self._age = age self._city = city class Person: def __init__(self, name, age, city): self._name = name self._age = age self._city = city class Employee(Person): def __init__(self, empid, name, age, city): Person.__init__(self, name, age, city) self.__empid = empid def run(): print(f"Employee Base Class: {Employee.__base__}") print('--' * 40) print(f"Person Base Class: {Person.__base__}") print('--' * 40) print(f"NewPerson Base Class: {Person.__base__}") # run() # -------------------------------------------------------------------------- """ Polymorphism: a. Early Binding or Static Resolution or Compile Time Polymorphism - Achieved via Method Overloading - Not possible, as data types are inferred automatically in Python. - Also, we have Default Arguments and Variable Length arguments in method definition. b. Late Binding or Dynamic Resolution or RunTime Polymorphism - Achieved via Method Over-riding and inheritance - Possible, derived class methods have first preference, if not found then it searches in Base Class until it founds in ROOT Class. This phenomenon of dynamically resolving the method name is called DYNAMIC RESOLUTION, which is possible in Runtime Polymorphism only. """ # -------------------------------------------------------------------------- # Method Overriding class Person: def __init__(self, name, age, city): self._name = name self._age = age self._city = city def print_info(self): print(f"Name: {self._name}") print(f"Age: {self._age}") print(f"City:{self._city}") class Student(Person): def __init__(self, name, age, city, rollno, marks): Person.__init__(self, name, age, city) self.__rollno = rollno self.__marks = marks def print_info(self): Person.print_info(self) print(f"Roll No: {self.__rollno}") print(f"Marks: {self.__marks}") def run1(): person1 = Person('Manoj', 29, 'Mumbai') person1.print_info() print('--' * 40) student1 = Student('Esha', 3, 'Pune', 10, 89) student1.print_info() print('--' * 40) # run1() def run2(): print('--' * 40) print('print() --> returns different output for primitive and non-primitve datypes. \n' '\t\tTherefore, to standardize the return value of them, we have to override the __str__() method for non-primitive types.') print('--' * 40) num1 = 100; num2 = 200 print(num1); print(num1.__str__()) print(num2) print(num2.__str__()) print('--' * 40) person1 = Person('Manoj', 29, 'Mumbai') student1 = Student('Esha', 3, 'Pune', 10, 89) print(person1) print(person1.__str__()) print(student1) print(student1.__str__()) # run2() class NewPerson: def __init__(self, name, age, city): self._name = name self._age = age self._city = city def __str__(self): return f" Name: {self._name}\n Age: {self._age}\n City:{self._city}" class NewStudent(Person): def __init__(self, name, age, city, rollno, marks): Person.__init__(self, name, age, city) self.__rollno = rollno self.__marks = marks def __str__(self): return f"{NewPerson.__str__(self)}\n Roll No: {self.__rollno}\n Marks: {self.__marks}" def run3(): print('--' * 40) print('After overriding __str__() method') print('--' * 40) person2 = NewPerson('Manoj', 29, 'Mumbai') print(person2) print('--' * 40) student2 = NewStudent('Esha', 3, 'Pune', 10, 89) print(student2) # run3() # -------------------------------------------------------------------------- # Operator Overloading """ == --> __eq__ != --> __ne__ > --> __gt__ >= --> __ge__ < --> __lt__ <= --> __le__ + --> __add__ - --> __sub__ * --> __mul__ / --> __truediv__ // --> __floordiv__ ** --> __pow__ % --> __mod__ We have to explicitly implement/override above methods like __eq__(), as it is not part of the reference/non-primitve type, else it says 'NotImplemented' when called. This method is called implicitly when we use the above operators. Also, there is no need to explicitly implement Complementary Operators(== and !=, monly one is enough), python takes acare of the another operation. """ # -------------------------------------------------------------------------- class Person(object): def __init__(self, name, age): # object.__init__(self) self._name = name self._age = age def __eq__(self, other): return self._name == other._name and self._age == other._age def __gt__(self, other): return self._age > other._age class Number: def __init__(self, value): self.__value = value def __eq__(self, other): return self.__value == other.__value def __add__(self, other): return Number(self.__value + other.__value) def __str__(self): return str(self.__value) def run(): num1 = 10 num2 = 10 print(num1, num2) # Value Type/ Primitive DataType print(f"num1 == num2: {num1 == num2}") print(f"num1.__eq__(num2): {num1.__eq__(num2)}") print('--' * 40) num1 = Number(10) num2 = Number(10) print(num1, num2) # Reference Type/ Non-Primitive Data Type print(f"num1 == num2: {num1 == num2}") print(f"num1.__eq__(num2): {num1.__eq__(num2)}") print(f"num1 + num2: {num1 + num2}") print('--' * 40) person1 = Person('Manoj', 29) person2 = Person('Manoj', 29) person3 = Person('Esha', 3) print(person1, person2) # Reference Type/ Non-Primitive Data Type print(f"person1 == person2: {person1 == person2}") print(f"person1.__eq__(person2): {person1.__eq__(person2)}") print(f"person1 > person3: {person1 > person3}") run()
def func(): nums = [1, 2, 3, 4, 5] a = list(map(lambda num: num ** 2, nums)) print(a) # func() def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 def execute(func): print(f"Parameter is: {func}, and type of the parameter is {type(func)}") print(f"Result: {func(10, 20)}") # execute(add) # execute(subtract) # execute(multiply) # execute(divide) # FILTER def func2(): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_nos = list(filter(lambda x: x % 2 == 0, numbers)) print(f"Even numbers are: {even_nos}") # func2() # Squares of Even numbers def func3(): numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(f"Squares of Even numbers: {list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))}") print(f"Cube of Odd numbers: {list(map(lambda x: x ** 3, filter(lambda x: x % 2 != 0, numbers)))}") for even_num in filter(lambda x: x % 2 == 0, numbers): print(even_num) # func3() def func4(): cars = [ {'name': 'i20', 'company': 'hyundai', 'price': 7.5, 'year': 2010}, {'name': 'nano', 'company': 'tata', 'price': 2.5, 'year': 2006}, {'name': 'laura', 'company': 'skoda', 'price': 17, 'year': 2011}, {'name': 'x5', 'company': 'bmw', 'price': 40, 'year': 2014}, {'name': 'gld350', 'company': 'mercedes', 'price': 85, 'year': 2018} ] car_price = list(map(lambda car: {'car': car['name'], 'price': car['price']}, cars)) print(car_price) affordable_cars = list(map( lambda car: {'car': car['name'], 'price': car['price']}, filter(lambda car: car['price'] < 10, cars))) print(f"Affordable cars: {affordable_cars}") # Model and Company of Non-affordable cars print(f"Non-affordable car name and company information: " f"{list(map(lambda car: {'car': car['name'], 'company': car['company']}, filter(lambda car: car['price'] > 20, cars)))}") func4()
''' Basic Operations Exercise in Matrix Operations ''' import numpy as np gene_list = np.array([['a2m', 'fos', 'brca2', 'cpox']]) times_list = np.array(['4h','12h','24h','48h']) values0 = np.array([[.12,0.08,0.06,0.02]]) values1 = np.array([[0.01,0.07,0.11,0.09]]) values2 = np.array([[0.03,0.04,0.04,0.02]]) values3 = np.array([[0.05,0.09,0.11,0.14]]) x = np.vstack([values0, values1, values2, values3]) print(x) ######################################################## ## which gene has the maximum mean expression value? ######################################################## #print("\nQuestion 4") #gene_means = X.mean(axis=1) #gene_mean_ind = np.argmax(gene_means) #print("gene with max mean expression value: %s (%s)"%(row_names[gene_mean_ind],gene_means[gene_mean_ind])) ######################################################## ## sort the gene names by the max expression value ######################################################## #gene_names = row_names #print("sorted gene names: %s"%(gene_names[np.argsort(np.max(X,axis=1))]))
from math import sqrt maximum = 0 def prime(num): #tests if the number is prime p = True for i in range(2, int(sqrt(num))+1): if num % i == 0: p = False break return p for a in range(-991, 1000, 2): #looping through all possible values of a and b for b in range(-991, 1000, 2): n=0 while True: result = n**2 + a*n + b if result > 0: pr = prime(result) if pr == False: break n += 1 #n is the number of consectuve primes else: break if n > maximum: maximum = n fa,fb=a,b print(maximum,fa,fb) print(fa*fb)
from math import sqrt from time import time start = time() def prime(n): if n == 1: return False for i in range(3, int(sqrt(n)) + 1, 2): if n % i == 0: return False return True side, primes = 3, 0 diagonal = [1] while True: for i in range(4): n = diagonal[-1] + (side - 1) diagonal.append(n) if prime(n): primes += 1 percent = primes / (len(diagonal)) if percent < 0.1: break side += 2 print(side) print("Runtime =", time() - start)
from math import sqrt def tree(n): pf = [] while n % 2 == 0: pf.append(2) n = n / 2 for i in range(3, int(sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = n / i if n > 2: pf.append(int(n)) return pf con = 0 for n in range(100000, 1000000): pf = tree(n) l = len(set(pf)) if l == 4: con += 1 if con == 4: print(n - 3) break else: con = 0
class Solution: def bitwiseComplement(self, N: int) -> int: value = N if(N==0) : return 1 result="" while value >= 1: if(value%2 == 0): result="0"+result else: result = "1"+result value//=2 result2="" for a in result: if(a=="0"): result2= result2+"1" else: result2= result2+"0" result=result2[::-1] index = 0 value=0 for e in result: if(e=="1"): value += 2**index index+=1 return value
sal = float(input('Digite seu salário:')) aumento10 = (sal/100 * 10) + sal aumento15 = (sal/100 * 15) + sal if sal > 1250.00: print('Você vai ter um aumento de 10% e seu salário vai passar a ser R${}'.format(aumento10)) if sal <= 1250.00: print('Você vai ter um aumento de 15% e seu salário vai passar a ser R${}'.format(aumento15))
n = int(input('digite um número?')) ant = (n-1) suc = (n+1) print('analisando o valor {}, o antecessor dele é {} e o sucessor é {}.'.format(n,ant,suc))
temperatura = float(input("Qual é a temperatura:")) resultado = ((temperatura * 1.8) + 32) print('A temperatura {}C para Fahrenheit é {}F'.format(temperatura,resultado))
v = int(input('Digite a velocidade do seu carro em KM/h:')) a = v - 80 if v > 80: print('MULTADO! ,o senhor estava a {}km/h acima do limite'.format(a)) print('Sua multa custará R${} reais'.format(a*7)) print('TENHA UM BOM DIA DIRIJA COM SEGURANÇA!') else: print('Parabéns você estava dentro do limite de 80km/h')
# 二つの整数値を昇順にソート(その3) a = int(input('整数a:')) b = int(input('整数b:')) a,b = sorted([a,b]) # 昇順にソート print('a≦bとなるようにソートしました。') print('変数aの値は',a,'です。') print('変数bの値は',b,'です。')
# 文字列に含まれる文字列を探索 txt = input('文字列txt:') ptn = input('文字列ptn:') c = txt.count(ptn) if c == 0: print('ptnはtxtに含まれません') elif c ==1: print('ptnがtxtに含まれるインデックス:',txt.find(ptn)) else: print('ptnがtxtに含まれる先頭インデックス:',txt.fint(ptn)) print('ptnがtxtに含まれる末尾インデックス:',txt.rfind(ptn))
# 点数を読み込んで合計点・平均点を表示(その1) print('合計点と平均点を求めます。') number = int(input('学生の人数:')) tensu = [None] * number for i in range(number): tensu[i] = int(input('{}番の点数:'.format(i+1))) total = 0 for i in range(number): total += tensu[i] print('合計は{}点です。'.format(total)) print('平均は{}点です。'.format(total/number))
# 読み込んだ整数値以下の全約数を列挙 n = int(input('整数値:')) for i in range (1,n+1): if n % i == 0: print(i,end=' ') print()
# 人数と点数を読み込んで最低点・最高点を表示(その2:組み込み関数を利用) print('最低点と最高点を求めます。') number = 0 tensu = [] while True: s = input('{}番の点数:'.format(number+1)) if s == 'End': break tensu.append(int(s)) number += 1 minimum = min(tensu) maximum = max(tensu) print('最低点は{}点です。'.format(minimum)) print('最高点は{}点です。'.format(maximum))
# 小さいほうの値と大きいほうの値を求めて表示(その2) a=int(input('整数a')) b=int(input('整数b')) if a < b: min2 = a; max2 = b; else: min2 = b; max2 = a; print('小さいほうの値は',min2,'です。') print('大きいほうの値は',max2,'です。')
# 5人の点数を読み込んで合計点と平均点を求めます。 print('5人の点数の合計点と平均点を求めます。') tensu1 = int(input('1番の点数:')) tensu2 = int(input('2番の点数:')) tensu3 = int(input('3番の点数:')) tensu4 = int(input('4番の点数:')) tensu5 = int(input('5番の点数:')) total = 0 total += tensu1 total += tensu2 total += tensu3 total += tensu4 total += tensu5 print('合計は{}点です。'.format(total)) print('平均は{}点です。'.format(total/5))
# 小さいほうの値と大きいほうの値を求めて表示(その5:min関数とmax関数) a = int(input('整数a')) b = int(input('整数b')) min2 = min(a,b) max2 = max(a,b) print('小さいほうの値は',min2,'です。') print('大きいほうの値は',max2,'です。')
#!/usr/bin/env python # coding=utf-8 # @file solve.py # @brief solve # @author Anemone95,x565178035@126.com # @version 1.0 # @date 2019-05-10 16:08 def solve(): with open('./Welcome.txt') as f: content=f.read() table={ '蓅烺計劃': 'A', '洮蓠朩暒': 'B', '戶囗': 'C', '萇條': 'D', '洮蓠朩暒戶囗': 'BC', '洮蓠朩暒蓅烺計劃': 'BA', '萇條蓅烺計劃': 'DA', '萇條戶囗':'DC' } # table={ # '蓅烺計劃': '.', # '洮蓠朩暒': '.', # '戶囗': '.', # '萇條': '.', # '洮蓠朩暒戶囗': '_', # '洮蓠朩暒蓅烺計劃': '_', # '萇條蓅烺計劃': '_', # '萇條戶囗':'_' # } arr=content.split() print(set(arr)) res=[] for e in arr: res.append(table[e]) print(" ".join(res)) if __name__ == '__main__': solve()
#!/usr/bin/env python3 """ Class NeuralNetwork Defines a neural network with one hidden """ import numpy as np class NeuralNetwork: """ Performing binary classification On 2 layers Neural Network """ def __init__(self, nx, nodes): if not isinstance(nx, int): raise TypeError("nx must be a integer") if nx < 1: raise ValueError("nx must be positive") if not isinstance(nodes, int): raise TypeError("nodes must be a integer") if nodes < 1: raise ValueError("nodes must be positive") self.W1 = np.random.normal(size=(nx, 1)) self.b1 = np.zeros(nodes) self.A1 = 0 self.W2 = np.random.normal(size=(nodes, 1)) self.b2 = 0 self.A2 = 0
#!/usr/bin/env python3 """ Class DeepNeuralNetwork Defines a deep multiple layers neural network """ import numpy as np import matplotlib.pyplot as plt class DeepNeuralNetwork: def __init__(self, nx, layers): if not isinstance(nx, int): raise TypeError("nx must be a integer") if nx < 1: raise ValueError("nx must be positive") if not isinstance(layers, list): raise TypeError("layers must be a list of positive integers") if min(layers) < 1: raise TypeError("layers must be a list of positive integers") self.__L = len(layers) self.__cache = {} self.__weights = {"W1": np.random.randn(layers[0], nx), "b1": np.zeros((layers[0], 1))} for i in range(1, self.__L): self.__weights[("W{}".format(i+1))] = np.random.randn(layers[i], layers[i-1]) * np.sqrt(2/layers[i-1]) self.__weights[("b{}".format(i+1))] = np.zeros((layers[i], 1)) @property def L(self): """ Number of layers of NN """ return self.__L @property def cache(self): """ Intermediary values of the NN """ return self.__cache @property def weights(self): """ Weights and biases dict """ return self.__weights def forward_prop(self, X): """ Calculates the forward propagation of the NN """ self.__cache = {"A0": X} self.z = {} for i in range(1, self.__L + 1): self.z["z{}".format(i)] = (self.__weights["W{}".format(i)] @ self.__cache["A{}".format(i-1)]) + self.__weights["b{}".format(i)] self.__cache["A{}".format(i)] = 1/(1+np.exp(-(self.z["z{}".format(i)]))) return self.__cache["A{}".format(i)], self.__cache def cost(self, Y, A): """ Calculates the cost of the model using logistic regression """ cost = (-Y * np.log(A) - (1 - Y) * np.log(1 - A)).mean() return cost def evaluate(self, X, Y): """ Evaluates the neuron’s predictions """ self.forward_prop(X) A = self.__cache["A{}".format(self.__L)] cost = self.cost(Y, A) pred_labels = np.where(A >= 0.5, 1, 0) return pred_labels, cost def gradient_descent(self, Y, cache, alpha=0.05): """ Calculates one pass of gradient descent on the neural network """ """ forward propagation """ self.forward_prop(self.cache["A0"]) """ back propagation """ m = Y[0].shape cache["dz{}".format(self.__L)] = cache["A{}".format(self.__L)] - Y cache["dw{}".format(self.__L)] = cache["dz{}".format(self.__L)] @ cache["A{}".format(self.__L - 1)].T / m cache["db{}".format(self.__L)] = np.sum(cache["dz{}".format(self.__L)], axis=1, keepdims=True) / m self.__L = self.__L + 1 for i in range(1, self.__L - 1): cache["dz{}".format(self.__L - i - 1)] = self.__weights["W{}".format(self.__L - i)].T @ cache["dz{}".format(self.__L - i)] * cache["A{}".format(self.__L - i - 1)] cache["dw{}".format(self.__L - i - 1)] = cache["dz{}".format(self.__L - i - 1)] @ (cache["A{}".format(self.__L - i - 2)]).T / m cache["db{}".format(self.__L - i - 1)] = np.sum(cache["dz{}".format(self.__L - i - 1)], axis=1, keepdims=True) / m self.__weights["b{}".format(self.__L - i)] = self.__weights["b{}".format(self.__L - i)] - (alpha * cache["db{}".format(self.__L - i)]) self.__weights["W{}".format(self.__L - i)] = self.__weights["W{}".format(self.__L - i)] - (alpha * cache["dw{}".format(self.__L - i)])
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt np.random.seed(5) student_grades = np.random.normal(68, 15, 50) bin = np.arange(0, max(student_grades), 10) plt.hist(student_grades, bins=bin, edgecolor='black') ybin = np.arange(0, len(student_grades), 5) plt.yticks(ybin) plt.xlabel('Grades') plt.ylabel('Number of Students') plt.title('Project A') plt.show()
#!/usr/bin/env python3 """ Calculates the weighted moving average of a data set """ import numpy as np def moving_average(data, beta): """ Returns: a list containing the moving averages of data """ # beta - weight avg_list = [] mov_avg = 0 for i in range(len(data)): mov_avg = ((mov_avg * beta) + ((1 - beta) * data[i])) mov_avg_cor = mov_avg / (1 - beta ** (i + 1)) avg_list.append(mov_avg_cor) return avg_list
#!/usr/bin/env python3 """ performs matrix multiplication """ def mat_mul(mat1, mat2): """ Return a new matrix Multiplication of all elements of 2 matricies """ if len(mat1[0]) != len(mat2): return None res = [[0 for i in range(len(mat2[0]))] for j in range(len(mat1))] for i in range(len(mat1)): for j in range(len(mat2[0])): for x in range(len(mat2)): res[i][j] += mat1[i][x] * mat2[x][j] return(res)
#!/usr/bin/env python3 """ Calculates the accuracy of a prediction """ import tensorflow as tf def calculate_accuracy(y, y_pred): """ Returns a tensor containing the decimal accuracy """ pred = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(pred, tf.float32)) return accuracy
NofP = eval(input()) for i in range(NofP): line = input() stringList = line.split() number1 = eval(stringList[0]) number2 = eval(stringList[2]) number3 = eval(stringList[4]) operator = stringList[1] if operator == "+": answer = number1 + number2 elif operator == "-": answer = number1 - number2 elif operator == "*": answer = number1 * number2 elif operator == "/": answer = number1 // number2 if answer == number3: print("correct") else: print("wrong answer")
x=eval(input()) if x == 1: y=eval(input()) if 0<=y<=100: if y>=60: print("pass") else: print("fail") else: print("score error") elif x==2: y=eval(input()) if 0<=y<=100: if y>=70: print("pass") else: print("fail") else: print("score error") else: print("roll error")
n=input() n=n.lower() lst=[] while True: m=input() if m=="q": break lst.append(m) if n in lst: a=lst.index(n)+1 print('Yes',a) else: b=len(lst) print('No',b)
n=eval(input()) for j in range(1,n,2): a=int((n-j)/2) print(" "*(a)+"*"*j,end='') print() for j in range(n,0,-2): a=int((n-j)/2) print(" "*(a)+"*"*j,end='') print()
#2.Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. nome = input("Informe seu nome: ") senha = input("Informe sua senha: ") while (nome == senha): print("O nome não pode ser igual a senha") nome = input("Informe seu nome: ") senha = input("Informe sua senha: ")
#9.Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50. for i in range (1, 51): if(i%2 != 0): print(i) for i in range (1, 51, 2): print(i)
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês. valorHora = float(input("Informe o valor que você ganha por hora: ")) horaMes = float(input("Informe quantas horas foram trabalhadas esse mês: ")) salario = round(valorHora*horaMes,2) print(f"O salário total do referido mês é R${salario}")
#Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00. #Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações: #comprar apenas latas de 18 litros; #comprar apenas galões de 3,6 litros; #misturar latas e galões, de forma que o desperdício de tinta seja menor. Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias. import math metro = float(input("Informe o tamanho em m² da área a ser pintada: ")) metroLata = metro / 6 if (metroLata <= 0): metroLata = 1 quantidadeLata = math.floor(metroLata / 18+(18*0.10)) quantidadeGalao = math.floor(metroLata / 3.6+(3.6*0.10)) quantidadeFinalLata = math.floor(metroLata / 18) resto = metroLata % 18 if(resto > 0 and resto <= 3.6): quantidadeFinalGalao = 1 elif(resto==0): quantidadeFinalGalao = 0 else: quantidadeFinalGalao = math.floor(resto / 3.6 + (3.6*0.10)) if (quantidadeLata <= 0 or quantidadeGalao <= 0 or quantidadeFinalGalao < 0): quantidadeGalao=1 quantidadeLata=1 quantidadeFinalGalao=1 precoLata = quantidadeLata * 80 precoGalao = quantidadeGalao * 25 precoLataFinal = quantidadeFinalLata * 80 precoGalaoFinal = quantidadeFinalGalao * 25 precoFinal = precoLataFinal + precoGalaoFinal print(f"\nQuantidade de latas: {quantidadeLata} latas. Preço latas: R${precoLata:.2f} reais.\nQuantidades galões: {quantidadeGalao} galões. Preço galões: R${precoGalao:.2f}.\nSolução com menos desperdício, latas: {quantidadeFinalLata} e galões: {quantidadeFinalGalao} Valor: R${precoFinal:.2f}")
print("Multiplicação de Dois Números") print("=============================\n") num1 = int(input("Por favor, informe um número: ")) num2 = int(input("Agora informe outro número: ")) multiplicacao = num1 * num2; print(num1, " x ", num2, " = ", multiplicacao, sep="")
#5.Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: #A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; #A mensagem "Reprovado", se a média for menor do que sete; #A mensagem "Aprovado com Distinção", se a média for igual a dez. n1 = float(input("Informe a primeira parcial: ")) n2 = float(input("Informe a segunda parcial: ")) media = (n1 + n2) / 2 if(media >= 7 and media < 10): print("Aprovado!") elif(media < 7): print("Reprovado!") elif(media == 10): print("Aprovado com Distinção!")
#!/usr/bin/python3 """ Queries Reddit API and prints the titles of the first 10 hot posts a given subreddit """ import requests def top_ten(subreddit): """Prints titles of first 10 hot posts of a given subreddit""" url = 'https://api.reddit.com/r/{}/hot?limit=10'.format(subreddit) headers = {'user-agent': 'linux:api_advanced:v1.2 (by /u/miguel-dev)'} r = requests.get(url, headers=headers, allow_redirects=False) if (r.status_code != requests.codes.ok): print('None') else: dict_hot = r.json() hot_posts = dict_hot.get("data").get('children') for post in hot_posts: print(post.get('data').get('title'))
Name = input("Enter your full name: ") print("You are welcome" + "," + Name) variable = input("Enter number of inputs: ") if variable >= "3": repr("Enter another number:") number1 = float(input("Enter first number: ")) sign = input("Operator: ") number2 = float(input("Enter another number: ")) if sign == "+": print(number1 + number2) elif sign == "-": print(number1 - number2) elif sign == "/": print(number1 / number2) elif sign == "*": print(number1 * number2) elif sign == "**": print(number1 ** number2) elif sign == "%": print(number1 % number2) else: print(SyntaxError) var = exit == input("End program")
# n^2 solution # def h_index(A): # index = 0 # prev_index = 0 # while True: # curr_papers = 0 # for i in A: # if i >= index: # curr_papers += 1 # if curr_papers < index: # return prev_index # else: # prev_index = index # index += 1 # divide and conquer def h_index(A): middle = len(A) // 2 h_index = len(A) - middle while h_index < A[middle]: middle += 1 h_index += 1 while h_index > A[middle]: middle -= 1 h_index -= 1 return h_index print(h_index([6,5,3,1,0]))
total_attempt=0 while total_attempt<3: username=input(“enter your user name: ”) password=input(“enter your password ”) If username==’Michal' and password==’e3$WT89x': print(“you are successfully loged in") else: print(“you entered wrong login id. Please check again\n”) print(‘you have’ ,3-total_attempt) total_attempt+=1 if total_attempt==3: print(“account blocked")
attempt=0 while attempt<3: user_name=input("Enter the username: ") password =input("Enter the password :") if user_name =="Micheal" and password =="e3$WT89x": print("You have successfully logged in") else: attempt+1 print("Invalid username or password") print("Account Locked") # your code has bug Enter the username: Micheal Micheal Enter the password :e3$WT89x You have successfully logged in Enter the username: jas Enter the password :23 Invalid username or password Enter the username:
"""Statistics and out-of-vocabulary words identification""" import re # Author: Thales Bertaglia <thalesbertaglia@gmail.com> def identify_oov(lex, tokens, force_list=[]): """Returns a list containing all indexes of out-of-vocabulary words in ``text``. Args: lex (dict): The lexicon dictionary. force_list (dict): A dictionary containing words that will be considered incorrect, regardless of any other lexicon. tokens (list (str)): The preprocessed and sanitized text (i.e, no punctuation etc). Returns: list (int): Indexes of all out-of-vocabulary words in ``text``. """ oov = [] p = re.compile("(kk)+|(ha)+|(rs)+|(ks)+|(he)+|(hua)+|(hau)+|(hue)+") placeholders = ["username", "url", "number", "emoji"] for i in range(len(tokens)): t = tokens[i].lower() if ( str.isalpha(t) and not p.match(t) and not t in placeholders and len(t) < 15 and (t not in lex or t in force_list) ): oov.append(i) """return [i for i in range(len(tokens)) if (tokens[i].lower() not in lex and str.isalpha(tokens[i])) or (tokens[i].lower() in ignore_list)]""" return oov
year=int(input()) if(year%400==0): print ("yes") elif(year%4==0): print ("yes") else: print ("no")
from __future__ import division import sys sys.path.append(r"C:\Users\dhruv\Documents\Learning\Data\Data-Science-Scratch\Chapter_3") from linear_algebra import sum_of_squares from linear_algebra import dot from collections import Counter import matplotlib.pyplot as plt import random import math num_friends = random.choices(range(101),k=200) friend_counts = Counter(num_friends) """ xs=range(max(num_friends)+1) ys=[friend_counts[x] for x in xs] plt.bar(xs,ys) plt.title("Histogram of Friend Counts") plt.xlabel('# of friends') plt.ylabel('# of people') plt.show() """ def mean(x): return sum(x)/len(x) def median(v): n=len(v) sorted_v=sorted(v) midpoint=n//2 if n%2==1: return sorted_v[midpoint] else: lo=midpoint-1 hi=midpoint return(sorted_v[lo]+sorted_v[hi])/2 def quantile(x,p): p_index = int(p*len(x)) return sorted(x)[p_index] def data_range(x): return max(x)-min(x) def de_mean(x): x_bar=mean(x) return [x_i - x_bar for x_i in x] def variance(x): n=len(x) deviatations = de_mean(x) return sum_of_squares(deviatations)/(n-1) def standard_deviation(x): return math.sqrt(variance(x)) def interquartile_range(x): return quantile(x,0.75)-quantile(x,0.25) def covariance(x,y): n=len(x) return dot(de_mean(x)-de_mean(y))/(n-1) def correlation(x,y): sd_x=standard_deviation(x) sd_y=standard_deviation(y) return covariance(x,y)/(sd_x*sd_y)
import numpy as np from helpers import sigmoid def learn_complex_net(X, y): # This function learns the weights for a neural net that calculates one set # of "intermediate inputs" and then uses those inputs to make a prediction. # The multiplications are set up so that in each iteration, the weights are # indeed updated in the correct direction. To understand why, follow the # arguments here: http://sethweidman.com/neural_net_post_2 np.random.seed(2) V = np.random.randn(3, 4) W = np.random.randn(4, 1) for j in range(50000): A = np.dot(X,V) B = _sigmoid(A) C = np.dot(B,W) P = _sigmoid(C) L = 0.5 * (y - P) ** 2 dLdP = -1.0 * (y-P) dPdC = _sigmoid(C) * (1-_sigmoid(C)) dLdC = dLdP * dPdC dCdW = B.T dLdW = np.dot(dCdW, dLdC) dCdB = W.T dLdB = np.dot(dLdC, dCdB) dBdA = _sigmoid(A) * (1-_sigmoid(A)) dLdA = dLdB * dBdA dAdV = X.T dLdV = np.dot(dAdV, dLdA) W -= dLdW V -= dLdV return V, W def predict_with_complex_net(X, V, W): # This function takes in the weights of a neural net that has been trained # using the 'learn_simple_net' function above and returns the prediction # that the function makes using these weights. A = np.dot(X, V) B = _sigmoid(A) C = np.dot(B, W) P = _sigmoid(C) return P if __name__ == "__main__": # initialize X as a 1 x 3 matrix X = np.array([[0,0,1]]) # initialize y as a 1 x 1 matrix y = np.array([[1]]) # learn the weights V, W = learn_complex_net(X, y) # predict 'X' using the computed weights prediction = predict_with_complex_net(X, V, W) print "Prediction: %s" % prediction print "y: %s" % y
class Termometro(): def __init__(self): self.__unidadM = 'C' self.__temperatura = 0 def __str__(self): return"{}º {}".format(self.__temperatura, self.__unidadM) def unidadMedida(self, uniM=None): # Aquí hay un getter y un setter if uniM == None: return self.__unidadM else: if uniM == 'F' or uniM == 'C': self.__unidadM = uniM def temp(self, temperatura=None): # Aquí hay un getter y un setter if temperatura == None: return self.__temperatura else: self.__temperatura = temperatura def __conversor(self, temperatura, unidad): # Este es un método interno que devuelve la conversión if unidad == 'C': return "{}º F".format(temperatura * 9/5 + 32) if unidad == 'F': return "{}º C".format((temperatura -32) * 5/9) else: return "unidad incorrecta" def mide(self, uniM=None): if uniM == None or uniM == self.unidadM: # Si coincide o no está informado me das lo que ya tengo, return self.__str__() else: if uniM == 'F' or uniM == 'C': return self.__conversor(self.__temperatura, self.__unidadM) # y si no coincide me haces la conversión else: return self.__str__()
# should_continue = True # if should_continue: # print("hello") # # known_people = ["John", "Ana", "Mary"] # person = input("Enter the name of the person you know:\n") # # if person in known_people: # print("Você conhece alguem") # else: # print("Você conhece ngm") ## Exercise def who_do_you_know(): # Ask the user for a list of people you know # Split the string into a list # Return that list people = input("Digite o nome das pessoas que você conhece separado por espaços (apenas primeiro nome):\n").split( " " ) people = [p.strip().lower() for p in people] return people def ask_user(): # Ask user for a name # See if their name is in the list of people they know # Print out that they know the person people_you_know = who_do_you_know() person = input("Digite o nome da pessoa:\n") if person in people_you_know: print("You know {}".format(person)) else: print("Unfortunately, you dont know {}".format(person)) ask_user()
from xml.dom import minidom # Open XML document using minidom parser DOMTree = minidom.parse("bookstore.xml") # print(DOMTree.toxml()) print("Node type is: ", DOMTree.nodeType) # Number 9 means DOCUMENT_NODE print("The list of nodes for the root:") print(DOMTree.firstChild.childNodes) print("") for node in DOMTree.firstChild.childNodes: # Process only element nodes (type 1) if node.nodeType == 1: print("Find one element with the name: " + node.nodeName) for n in node.childNodes: if n.nodeType == 1: print("Find one element with the name: " + n.nodeName) print(" and its value is: " + n.childNodes[0].nodeValue)
# Author : Harrison Toppen-Ryan # Description : Password Checker, HW5, CSCI 141 # Date : November 21st, 2020 #Function to create a list and check if each password is valid or not def validatePassword(): #empty list passwordList = [ ] #length of the password list lenthPasswordList = len(passwordList) #when the user wants to end, 'i' searches for eachpassword index in the list and checks if they are valid or not. i = 0 while True: #while loop that takes inouts and puts them into the list total_passwords = str(input()) passwordList.append(total_passwords) if total_passwords == "END": for i in range(5): #if any digit in a password does not have a digit in it if (any(c.isdigit() for c in passwordList[i])) == False: print("password", passwordList[i], "is bad. It has no digits." ) i += 1 #if any digit in a password does not have a uppercase letter in it elif (any(c.isupper() for c in passwordList[i])) == False: print("password", passwordList[i], "is bad. It has no upper case letters." ) i += 1 #if any digit in a password does not have a loweercase letter in it elif (any(c.islower() for c in passwordList[i])) == False: print("password", passwordList[i], "is bad. It has no lower case letters." ) i += 1 #if any digit in a password has a space in it elif ' ' in passwordList[i]: print("password", passwordList[i], "is bad. It has a space in it." ) i += 1 #if the password is good and can be used else: print("password", passwordList[i], "is good.") i += 1 # main function that calls the vaidatePassword function after printing the text. def main(): print("Please input passwords one-by-one for validation.") print("Input END after you've entered your last password") validatePassword() #call the main function main()
# Student ID : 1201201025 # Student Name : Tai Jun Ping litre = 0.15 print("Natural Mineral Water Dispener") print("------------------------------\n") amount = int(input("Enter amount of liters : ")) print("\nPrice per litre : RM 0.15") print("Number of litre :",amount) total = amount * 0.15 print("Total : RM {:.2f}".format(total))
''' start = 0 stop = 5 (n-1) = 4 step = +1 ''' for var in range(5): #print(var) print(var, end=', ') print("Inside Loop") print("Outside Loop")
num = int(input("Enter a number : ")) reverse = 0 temp = num while(num > 0) { digit = num % 10 reverse = reverse * 10 + digit num = num // 10 if(temp == reverse): print("Palindrome Number") else: print("Not Palindrome")
a,b,c = 10,20,30 # Logical Operators - and (&), or (|), not (!) if a > b and a > c: print("A is greatest") elif b > a and b > c: print("B is greatest") else: print("C is greatest") print("Odd Even Program...............") num = 10 if num % 2 == 0: print("Even") else: print("Odd") num = 10 if num % 2 == 0:print("Even") else:print("Odd") print("If Else Expression") result = "Even" if num % 2 == 0 else "Odd" print(result) print("Greatest of 3 Using Expression") result = "A" if a > b and a > c else "B" if b > a and b > c else "C" print(result,"is greatest")
min_range = int(input("Enter the min range : ")) max_range = int(input("Enter the max range : ")) for num in range(min_range, max_range): for i in range(2, num//2): if num % i == 0: #print(num,"is not a prime number") break else: print(num,"is a prime number")
# las excepciones son errores que se producen en tiempo de ejecución # estas provocan que el programa se detenga si no se controlan # las excepciones son causadas por comportamientos inesperados en el programa # de los cuales el programa mismo no se puede recuperar por si mismo si no se le ha programado para ello def numeric_fail(numero): resultado = 0 try: resultado = 500 / numero except ZeroDivisionError: resultado = 0 else: print("todo salio bien") finally: return resultado def cast_fail(): try: return int('palabras') except ValueError: return 1 def access_fail(): lista = [1, 2, 3] try: return lista[8] except IndexError: return 0 # para controlar las excepciones tenemos las estructuras: # try-except # try=except-finally # try-except-else-finally # # dentro del bloque try se coloca el código que puede ocasionar una excepción # # dentro del bloque except se coloca el código a ejecutar en acaso de que una excepción surja # se pueden incluir tantos bloques except como excepciones se quieran controlas individualmente # # el bloque else es opcional, aquí se coloca código que solo se ejecutará si no se presento ninguna excepción # # así mismo, el bloque finally es opcional y aquí se incluye el código que se debe ejecutar # independientemente de si hubo o no una excepción, normalmente se suelen liberar recursos if __name__ == '__main__': access_fail() cast_fail() numeric_fail(0)
# tenemos estructuras para repetir código conocidas como ciclos number = 5 list_numbers = [45, 51, 87, 72, 18, 62, 5, 38, 21, 19] # while # esta estructura repite n bloque de código mientras se cumpla la condición evaluada while number > 0: print('se cumple') number -= 1 # for # esta estructura repite el código del bloque una vez or cada elemento de una colección # al mismo tiempo, los elementos se van evaluando uno a uno y se pueden usar dentro del bloque de código for number in list_numbers: print(number) # para conseguir el funcionamiento clasico de un 'for' en otros lenguajes # se usa una función especial llamada range # esta función recibe de 1 a 3 parámetros # un parámetro indica que se quiere recorrer de uno en uno los números del 0 al numero anterior al parámetro var1 = range(12) # 0,1 2,3,4,5,6,7,8,9,10,11 # dos parámetros indican que se iniciara desde el primer parámetro, avanzando de uno en uno hasta el número # anterior al segundo parámetro var2 = range(4, 10) # 4,5,6,7,8,9 # tres parámetros indican que se iniciara desde el primero, avanzando el numero del tercer parámetro # hasta el numero anterior al segundo parámetro dentro de la serie var3 = range(2, 12, 2) # 2,4,6,8,10 # el 'for' indexado se escribe entonces asi for i in range(number): print(list_numbers[i]) # además este ciclo también puede recorrer los caracteres de un 'string' for character in "esto es una cadena de texto": print(character)
# ya observamos el poder de las funciones # sin embargo eso no es lo único que tienen por ofrecernos # # python también soporta el paradigma de programación funcional # este paradigma se centra en las funciones para transformar datos de entrada en datos de salida # y una de las características mas versátiles son las funciones de alto orden # # estas son funciones que aceptan otras funciones como parámetros, o regresan funciones desde ellas # # son útiles para extender algunas funciones predefinidas # o construir nuevas de forma dinámica def multiples_veces(f, *args): for arg in args: f(arg) # para poder regresar funciones desde dentro de una función, podemos definir funciones anidadas # esta última tiene acceso a todas las variables de la función que la contiene, pero también puede recibir parámetros # y definir sus propias variables, esta solo tendrá nombre dentro de la función contenedora # fuera de esta, el nombre no existirá def decir_(palabra): # esta función genera mas funciones que dirán lo que necesitemos def interna(nombre): print(f"{palabra} {nombre}") # hacemos uso de variables internas y de la función contenedora return interna # la función interna se regresa sin los paréntesis # de otra forma se estaría llamando a la función y regresando su resultado # pero deseamos retornar la función no su resultado # después podemos usar pocas funciones para hacer mucho mas if __name__ == '__main__': decir_hola = decir_("hola") # las funciones también se pueden asignar a variables y guardar en colecciones multiples_veces(decir_hola, "Horacio", "Gonzalo", "Daniel") print() lista_saludos = [decir_(saludo) for saludo in ( "hola", "buenos dias", "buenas tardes", "como estas?" )] nombres = ( "Fernando", "Ramon", "Saul", "Antonio", "Gustavo" ) for saludo in lista_saludos: multiples_veces(saludo, *nombres)
# crear un programa que pida una lista de números al usuario desde la linea de comandos # cada numero debera ir separado por una coma "," # después de ingresar su lista de números al usuario se le pedirá que elija # entre 4 opciones # 1) quiere sumarlos todos # 2) quiere multiplicarlos todos # 3) quiere imprimirlos todos # 4) quiere salir del programa # # si el usuario teclea una opción incorrecta mandar el mensaje "opción no valida" # # el programa principal estará codificado, solamente deberán escribirse las funciones: # "sumar_todos" # esta función debe regresar la suma de los números (un número) # "multiplicar_todos" # esta función debe regresar la multiplicación de los números (un número) # "imprimir_todos" # No regresa nada # "imprimir_error" # No regresa nada # # defina aquí el mensaje donde se muestran las opciones (Menu de opciones)} MENU = """ MENU DE OPCIONES 1.- SUMAR 2.- MULTIPLICAR 3.- QUIERE SUPRIMIR TODOS 4.-QUIERE SALIR DEL PROGRAMA 5.-ERROR """ # fin de la zona de definición de menú # defina aquí sus funciones def sumar_todos(*numeros): resultado=0 for numero in numeros: resultado += numero return resultado def multiplicar_todos(*numeros): resultado=1 for numero in numeros: resultado *= numero return resultado def imprimir_todos(*numeros): for numero in numeros: print(numero) def imprimir_error(): print("Opcion no Valida") # fin de la zona de definición de funciones # no modificar la siguiente sección del programa if __name__ == '__main__': number_list = tuple( float(number) for number in input("ingrese una lista de números separados por coma: ").strip(" ").split(",") ) while True: print(MENU) option = input("ingrese una opción") if option == "1": print(f"la suma de los números es: {sumar_todos(*number_list)}") elif option == "2": print(f"la multiplicación de los números es: {multiplicar_todos(*number_list)}") elif option == "3": imprimir_todos(*number_list) elif option == "4": break else: imprimir_error()
import csv voter_id = [] candidate = [] with open("election_data.csv.csv") as file: reader = csv.reader(file) next(reader) for row in reader: voter_id.append(row[0]) candidate.append(row[2]) #Write "Election Results" with total votes done print("Election Results") print("---------------------------") print(f"Total Votes: {len(voter_id)}") print("---------------------------") # Get list of candidates values of specific candidates cands = list(set(candidate)) cands.sort() # Get a vote count of candidates vote_candidates = [] for cand in cands: vote_candidates.append(candidate.count(cand)) # Write code to list out pertectange and totals of votes with the winner of candidates for i in range(len(cands)): print(f"{cands[i]}: {'{:.2%}'.format(vote_candidates[i]/len(candidate))} ({vote_candidates[i]})") print("--------------------") print(f"Winner: {cands[vote_candidates.index(max(vote_candidates))]}") print("-------------------\n") #
import math def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result def area(radius): temp = math.pi * radius**2 return temp def circle_area(xc, yc, xp, yp): print(area(distance(xc, yc, xp, yp))) return circle_area(4,5,6,7)
from PyPDF2 import PdfFileMerger import os from tkinter import * from tkinter import filedialog root = Tk() root.columnconfigure(0, weight=1) root.title("PDF Merger") root.resizable(False, False) def mergePDF(): DIRECTORY_NAME = filedialog.askdirectory() if(len(DIRECTORY_NAME)>1): locError.config(text=DIRECTORY_NAME, fg="green") else: locError.config(text="Please Choose Folder", fg="red") return try: merger = PdfFileMerger() for item in os.listdir(DIRECTORY_NAME): if item.endswith('.pdf'): merger.append(DIRECTORY_NAME + "/" + item) merger.write(DIRECTORY_NAME + "/merged_pdf.pdf") merger.close() locError.config(text="Successfully Merged the PDFs", fg="green") except: locError.config(text="Cannot Merge the PDFs", fg="red") label = Label(root, text="Select the Folder", font=('jost', 15)) label.grid() selectFolder = Button(root, width=10, bg="red", fg="white", text="Choose Path", command=mergePDF) selectFolder.grid() locError = Label(root, text="Error Message Of Path", fg="red", font=('jost', 10)) locError.grid() root.mainloop()
import turtle colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] pen = turtle.Pen() pen.speed(10) turtle.bgcolor('black') for x in range(200): pen.pencolor(colors[x%6]) pen.width(x/100 + 1) pen.forward(x) pen.left(59) turtle.done()
def sawp(s1, s2): return (s2, s1) a = float(input('a=:')) b = float(input('b=:')) print(sawp(a,b))
import argparse def gumarum(a,b): c = a+b return c def Main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-v","--verbose",action="store_true") group.add_argument("-q","--quiet",action="store_true") parser.add_argument("num",help="the fibonacci number you wish to calculate.",type=int) parser.add_argument("num1",help="the fibonacci number you wish to calculate.",type=int) parser.add_argument("-o","--output",help="output result to a file",action="store_true") args = parser.parse_args() result = gumarum(args.num,args.num1) if args.verbose: print("The " +str(args.num)+" + "+str(args.num1)+" = "+str(result)) elif args.quiet: print(result) else: print("fib("+str(args.num)+") = "+str(result)) if __name__=="__main__": Main()
''' Moduuli, jonka funktioilla tarkistetaan syötteen järkevyys Sisältää joukon funktioita, jota käyttämällä saadaan: 1. virhekoodi (int),2. virhesanoma (string) ja 3. arvo (float) Funktiot palauttavat nämä tiedot listana ''' # Kirjastojen lataukset # Luokkien ja funktioiden määritykset def liukuluku_syote(syote): """Tutkii onko syöte sopiva liukiluvuksi Args: syote (string): näppäimistöltä syötetty arvo Returns: list: virhekoodi (int),sanoma (string), arvo (float) """ syote = syote.strip() # Poistetaan tulostumattomat merkit molemmista päistä if syote.find(',') !=-1: # Katsotaan sisältääkö pilkkuja syote = syote.replace(',', '.') # Korvataan pilkut pisteellä if syote.find(',') ! = -1: # Katsottan löytyykö pistettä osat = syote.split('.') # Luodaan lista jossa pisteellä erotetut osat syötteellä if len(osat) > 2: arvo = 0 virhekoodi = 1 virhesanoma = 'Syötteessä useita desimaalierottimia' else: osa = str(osa[0]) if osa.isnumeric(): osa = str(osat{1}) if osa.isnumeric(): arvo = float(syote) virhekoodi = 0 virhesanoma = 'Syöte OK' else : if syote.isnumeric() arvo = float(syote) virhekoodi = 0 virhesanoma = 'Syöte OK' return tulokset # Koodi, joka suoritetaan vain jos tämä tiedosto käynnistetään konsolista, esim "testit"
""" This is a controller that instantiates a SharedMemory core and builds a wrapper around it to make it programmable. This is exposed to the programmer. The function calls accepted: load <src> <dst> store <src> <dst> """ import Queue import sys from shared_memory import SharedMemory class SharedMemoryController: def __init__(self): """ Initialize controller with an instance of SharedMemory Args: None Returns: None """ # configuration of L2 cache and DRAM are pre-defined in SharedMemory constructor self.bank = SharedMemory() self.read_queue_0 = Queue.Queue() self.read_queue_1 = Queue.Queue() self.write_queue_0 = Queue.Queue(maxsize=2) self.write_queue_1 = Queue.Queue(maxsize=2) # dictionary for cycle count for each active memory access self.cycles_left = dict() # FIX ME IN DEPENDENCY MANAGER LATER # create fields for each channel to allow reads and writes to the same address to happen simulatenously self.cycles_left['read_channel0'] = dict() self.cycles_left['write_channel0'] = dict() self.cycles_left['read_channel1'] = dict() self.cycles_left['write_channel1'] = dict() # dictionary for storing address for active memory access self.channel = dict() self.channel['read_channel0'] = 0 self.channel['write_channel0'] = 0 self.channel['read_channel1'] = 0 self.channel['write_channel1'] = 0 # store read response for each channel till cycle completion self.total_cycles = 0 def run_cycle(self, read_channel0, write_channel0, read_channel1, write_channel1): """ This is the main function to call the read/write request """ # inputs araddr0, arvalid0 = read_channel0 waddr0, wdata0, wvalid0 = write_channel0 araddr1, arvalid1 = read_channel1 waddr1, wdata1, wvalid1 = write_channel1 # outputs rdata0 = 0 rvalid0 = 0 readID0 = None rdata1 = 0 rvalid1 = 0 readID1 = None read_cycles_channel0 = (None, 0, False) write_cycles_channel0 = (None, 0, False) read_cycles_channel1 = (None, 0, False) write_cycles_channel1 = (None, 0, False) ######### CHANNEL 0-1 ######### #### WRITE #### # clear any previous completed accesses # check if a memory access is ongoing in the channel # if yes, decrement cycle count otherwise # pop write requests if any # debug #print("self.cycles_left: ", self.cycles_left) #print("self.channel['write_channel0']: ", self.channel['write_channel0']) if((self.channel['write_channel0'] != 0) and (self.cycles_left['write_channel0'][self.channel['write_channel0']] == 0)): # clear channel self.cycles_left['write_channel0'].pop(self.channel['write_channel0']) self.channel['write_channel0'] = 0 if(self.channel['write_channel0'] != 0): self.cycles_left['write_channel0'][self.channel['write_channel0']] -= 1 else: if(not self.write_queue_0.empty()): addr, data = self.write_queue_0.get() cycles_write_queue_0 = self.bank.write(data, addr) self.channel['write_channel0'] = addr # do not run one cycle of mem access now # this allows us to stay in sync with the corresponding store unit self.cycles_left['write_channel0'][addr] = cycles_write_queue_0 # add cycles left to cycle channel of write_channel0 with valid signal write_cycles_channel0 = (addr, self.cycles_left['write_channel0'][addr], True) # debug print("Write Queue 0 -> addr: ", str(addr), ", data: ", str(data), ", write cycles : ", str(cycles_write_queue_0), "write_cycles_channel0: ", write_cycles_channel0) else: pass if((self.channel['write_channel1'] != 0) and (self.cycles_left['write_channel1'][self.channel['write_channel1']] == 0)): # clear channel self.cycles_left['write_channel1'].pop(self.channel['write_channel1']) self.channel['write_channel1'] = 0 if(self.channel['write_channel1'] != 0): self.cycles_left['write_channel1'][self.channel['write_channel1']] -= 1 else: if(not self.write_queue_1.empty()): addr, data = self.write_queue_1.get() cycles_write_queue_1 = self.bank.write(data, addr) self.channel['write_channel1'] = addr # do not run one cycle of mem access now # this allows us to stay in sync with the corresponding store unit self.cycles_left['write_channel1'][addr] = cycles_write_queue_1 # add cycles left to cycle channel of write_channel1 with valid signal write_cycles_channel1 = (addr, self.cycles_left['write_channel1'][addr], True) # debug print("Write Queue 1 -> addr: ", str(addr), ", data: ", str(data), ", write cycles : ", str(cycles_write_queue_1), "write_cycles_channel1: ", write_cycles_channel1) else: pass # load write requests into the queue if(wvalid0): self.write_queue_0.put((waddr0, wdata0)) if(wvalid1): self.write_queue_1.put((waddr1, wdata1)) #### READ #### # no logic of outstanding reads in SharedMemory # clear any previous completed accesses # check if a memory access is ongoing in the channel # if yes, decrement cycle count otherwise # pop read requests if any valid_response_0 = False valid_response_1 = False if((self.channel['read_channel0'] != 0) and (self.cycles_left['read_channel0'][self.channel['read_channel0']] == 0)): # clear channel self.cycles_left['read_channel0'].pop(self.channel['read_channel0']) self.channel['read_channel0'] = 0 if(self.channel['read_channel0'] != 0): self.cycles_left['read_channel0'][self.channel['read_channel0']] -= 1 if(self.cycles_left['read_channel0'][self.channel['read_channel0']] == 0): # reperform load to update readID, rdata, rvalid values rvalid0, rdata0, readID0, cycles_read_queue_0 = self.bank.read(self.channel['read_channel0']) valid_response_0 = True else: if(not self.read_queue_0.empty()): addr, data = self.read_queue_0.get() rvalid0, rdata0, readID0, cycles_read_queue_0 = self.bank.read(addr) self.channel['read_channel0'] = addr # do not run one cycle of mem access now # this allows us to stay in sync with the corresponding load unit self.cycles_left['read_channel0'][addr] = cycles_read_queue_0 # add cycles left to cycle channel of read_channel0 with valid signal read_cycles_channel0 = (addr, self.cycles_left['read_channel0'][addr], True) # debug print("Read Queue 0 -> addr: ", str(addr), ", read cycles to wait : ", str(cycles_read_queue_0), "read_cycles_channel0: ", read_cycles_channel0) else: pass if((self.channel['read_channel1'] != 0) and (self.cycles_left['read_channel1'][self.channel['read_channel1']] == 0)): # clear channel self.cycles_left['read_channel1'].pop(self.channel['read_channel1']) self.channel['read_channel1'] = 0 if(self.channel['read_channel1'] != 0): self.cycles_left['read_channel1'][self.channel['read_channel1']] -= 1 if(self.cycles_left['read_channel1'][self.channel['read_channel1']] == 0): # reperform load to update readID, rdata, rvalid values rvalid1, rdata1, readID1, cycles_read_queue_1 = self.bank.read(self.channel['read_channel1']) valid_response_1 = True else: if(not self.read_queue_1.empty()): addr, data = self.read_queue_1.get() rvalid1, rdata1, readID1, cycles_read_queue_1 = self.bank.read(addr) self.channel['read_channel1'] = addr # do not run one cycle of mem access now # this allows us to stay in sync with the corresponding load unit self.cycles_left['read_channel1'][addr] = cycles_read_queue_1 # add cycles left to cycle channel of read_channel1 with valid signal read_cycles_channel1 = (addr, self.cycles_left['read_channel1'][addr], True) # debug print("Read Queue 1 -> addr: ", str(addr), ", read cycles : ", str(cycles_read_queue_1), "read_cycles_channel1: ", read_cycles_channel1) # push requests to the queue if(arvalid0): self.read_queue_0.put((araddr0, 0)) if(arvalid1): self.read_queue_1.put((araddr1, 1)) #### RESPONSE #### # combine results and respond # return load value only when cycles complete if(not valid_response_0): rvalid0 = 0 if(not valid_response_1): rvalid1 = 0 read_resp_channel0 = readID0, rdata0, rvalid0 read_resp_channel1 = readID1, rdata1, rvalid1 # combine all read/write_cycles_channels into one single tuple for ease of management # (r0,w0,r1,w1) cycles_resp_channel = (read_cycles_channel0, write_cycles_channel0, read_cycles_channel1, write_cycles_channel1) # increment total cycle count self.total_cycles += 1 # debug #print("==== System status ====") #print("Total cycles: ", self.total_cycles) #print("Read Queue 0 : ", list(self.read_queue_0.queue)) #print("Read Queue 1 : ", list(self.read_queue_1.queue)) #print("Write Queue 0 : ", list(self.write_queue_0.queue)) #print("Write Queue 1 : ", list(self.write_queue_1.queue)) #print("Read Channel 0 : ", self.channel['read_channel0']) #print("Read Channel 1 : ", self.channel['read_channel1']) #print("Write Channel 0 : ", self.channel['write_channel0']) #print("Write Channel 1 : ", self.channel['write_channel1']) #for i in self.cycles_left.keys(): # print("addr: ", i," => ", self.cycles_left[i]) return read_resp_channel0, read_resp_channel1, cycles_resp_channel if __name__ == "__main__": # instantiate a shared memory controller shmem_controller = SharedMemoryController() # initialize channels to something read_channel0 = 0,0 read_channel1 = 0,0 write_channel0 = 0,0,0 write_channel1 = 0,0,0 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1) print("CYCLE 0") print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n") read_channel0 = 0,0 read_channel1 = 0,0 write_channel0 = 1234,10,1 write_channel1 = 0,0,0 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1) print("CYCLE 1") print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n") read_channel0 = 2232,1 read_channel1 = 0,0 write_channel0 = 0,0,0 write_channel1 = 0,0,0 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1) print("CYCLE 2") print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n") read_channel0 = 0,0 read_channel1 = 0,0 write_channel0 = 0,0,0 write_channel1 = 1336,12,1 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0,write_channel0, read_channel1, write_channel1) print("CYCLE 3") print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n") read_channel0 = 0,0 read_channel1 = 1500,1 write_channel0 = 1260,11,1 write_channel1 = 0,0,0 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1) print("CYCLE 4") print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n") # modify range of iterator to see different accesses getting to completion for i in range(0,85): read_channel0 = 0,0 read_channel1 = 0,0 write_channel0 = 0,0,0 write_channel1 = 0,0,0 read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1) print("CYCLE ", shmem_controller.total_cycles) print("READ RESP CHANNEL0 (ID, DATA, VALID): ", read_resp_channel0) print("READ RESP CHANNEL1 (ID, DATA, VALID): ", read_resp_channel1) print("CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: ", cycles_resp_channel) print("\n-----------------------------\n\n")
turns=0 board = [["0", "0", '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0']] board[int(random(0,5))][int(random(0,5))] = "1" def setup(): size(500,500) background(0) img = loadImage("CarltonDance.gif") def draw(): global img global turns global board for i in range(len(board)): for j in range(len(board)): if board[i][j] == "0" or board[i][j] == "1": fill(255,255,255) rect(i*100,j*100,100,100) elif board[i][j] == "H": fill(0,0,0) rect(i*100,j*100,100,100) img = loadImage("CarltonDance.gif") image(img, 0, 0) image(img, 0, 0, 0,0) background(255); fill(0); textSize(80) text("YOU WIN",100,100) print(board[i][j]) else: fill(255,255,0) rect(i*100,j*100,100,100) def mousePressed(): global turns mx = int(mouseX/100) my = int(mouseY/100) if board[mx][my] == "1": print("You Win") board[mx][my] = "H" textSize(50) text("YOU WON",255,0,0) print("you win") elif board[mx][my] == "0": board[mx][my] = "M" print("you missed) if turns>4: background(255); fill(0); textAlign(CENTER,CENTER); text("GAME OVER",width/2,height/2)
""" fibonacci_algorithm.py Returns the reduced uncertainty interval containing the minimizer of the function func - anonimous function interval0 - initial uncertainty interval N_iter - number of iterations """ import numpy as np def fibonacci_algorithm_calc_N_iter(interval0, uncertainty_range_desired): F = np.empty(shape = (10000), dtype = int); F[0] = 0; F[1] = 1; F[2] = 1; N = 1; epsilon = 10e-6; while F[N + 1] < (1 + 2 * epsilon) * (interval0[1] - interval0[0]) / uncertainty_range_desired: F[N + 2] = F[N + 1] + F[N]; N += 1; N_iter = N - 1; return (N_iter, F); def fibonacci_algorithm(func, interval0, N_iter, F): epsilon = 10e-6; left_limit = interval0[0]; right_limit = interval0[1]; smaller = 'a'; a = left_limit + (F[N_iter] / F[N_iter + 1]) * (right_limit - left_limit); f_at_a = func(a); for iter_no in range(N_iter): if (iter_no != N_iter): rho = 1 - F[N_iter + 1 - iter_no] / F[N_iter + 2 - iter_no]; else: rho = 0.5 - epsilon; if (smaller == 'a'): c = a; f_at_c = f_at_a; a = left_limit + rho * (right_limit - left_limit); f_at_a = func(a); else: a = c; f_at_a = f_at_c; c = left_limit + (1 - rho) * (right_limit - left_limit); f_at_c = func(c); if (f_at_a < f_at_c): right_limit = c; smaller = 'a'; else: left_limit = a; smaller = 'c'; interval = (left_limit, right_limit); return interval;
# LCD Test Script # Script to test the input and output of the Raspberry Pi GPIO # # Author: Kevin Wong # With some code from a Raspberry Pi tutorial from: # http://www.youtube.com/watch?v=KM4n2OtwGl0 # # Date: 11/10/2013 # The wiring for the LCD is as follows: # 1 : GND # 2 : 5V # 3 : Contrast (0-5V)* # 4 : RS (Register Select) # 5 : R/W (Read Write) - GROUND THIS PIN! We do not want the LCD to send anything to the Pi @ 5v # 6 : Enable or Strobe # 7 : Data Bit 0 - NOT USED # 8 : Data Bit 1 - NOT USED # 9 : Data Bit 2 - NOT USED # 10: Data Bit 3 - NOT USED # 11: Data Bit 4 # 12: Data Bit 5 # 13: Data Bit 6 # 14: Data Bit 7 # 15: LCD Backlight +5V # 16: LCD Backlight GND #import import RPi.GPIO as GPIO import time # Define GPIO to LCD mapping LCD_RS = 25 LCD_E = 24 LCD_D4 = 23 LCD_D5 = 17 LCD_D6 = 27 LCD_D7 = 22 #Define GPIO to buttons BTN1 = 4 BTN2 = 18 #Define some device constants LCD_FILLER = "--------------------" LCD_WIDTH = 20 LCD_CHR = True LCD_CMD = False LCD_LINE_1 = 0x80 LCD_LINE_2 = 0xC0 LCD_LINE_3 = 0x94 LCD_LINE_4 = 0xD4 E_PULSE = 0.00005 E_DELAY = 0.00005 # Main # Will display starting message first # Then, depending on which button is pressed, will print out something differenet def main(): #Set up pins for GPIO output GPIO.setmode(GPIO.BCM) #Use BCM GPIO numbers GPIO.setup(LCD_E,GPIO.OUT) GPIO.setup(LCD_RS,GPIO.OUT) GPIO.setup(LCD_D4,GPIO.OUT) GPIO.setup(LCD_D5,GPIO.OUT) GPIO.setup(LCD_D6,GPIO.OUT) GPIO.setup(LCD_D7,GPIO.OUT) #Set up buttons for GPIO input GPIO.setup(BTN1, GPIO.IN) GPIO.setup(BTN2, GPIO.IN) #Initialize LCD Display lcd_init() #Display introductory message to_write = [LCD_FILLER, str_format_left("Raspberry Pi"), str_format_left("GPIO Test"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(5) #run infinite loop that displays different messages for different button presses while True: if (GPIO.input(BTN1) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 1"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(1) if (GPIO.input(BTN2) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 2"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(1) #Function: str_format_left # Taking in a string, will return it with enough padding for the LCD display def str_format_left(s): return s = s.ljust(LCD_WIDTH, " ") #Function: lcd_write_lines # Takes in a list of 4 strings to be written out to each line in the LCD def lcd_write_lines(message): lcd_byte(LCD_LINE_1,LCD_CMD) lcd_string(message[0]) lcd_byte(LCD_LINE_2,LCD_CMD) lcd_string(message[1]) lcd_byte(LCD_LINE_3,LCD_CMD) lcd_string(message[2]) lcd_byte(LCD_LINE_4,LCD_CMD) lcd_string(message[3]) #Function: lcd_init() # Initializes LCD display def lcd_init(): #init display lcd_byte(0x33,LCD_CMD) lcd_byte(0x32,LCD_CMD) lcd_byte(0x28,LCD_CMD) lcd_byte(0x0C,LCD_CMD) lcd_byte(0x06,LCD_CMD) lcd_byte(0x01,LCD_CMD) #Function: lcd_string # Will print out to a set line in the LCD display def lcd_string(message): for i in range(LCD_WIDTH): lcd_byte(ord(message[i]),LCD_CHR) #Function: lcd_byte # Send byte to data pins # bits = data # mode = True for character # False for command def lcd_byte(bits,mode): GPIO.output(LCD_RS,mode) #High bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits&0x10==0x10: GPIO.output(LCD_D4, True) if bits&0x20==0x20: GPIO.output(LCD_D5, True) if bits&0x40==0x40: GPIO.output(LCD_D6, True) if bits&0x80==0x80: GPIO.output(LCD_D7, True) #Toggle 'Enable' pin time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY) #Low bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits&0x01==0x01: GPIO.output(LCD_D4, True) if bits&0x02==0x02: GPIO.output(LCD_D5, True) if bits&0x04==0x04: GPIO.output(LCD_D6, True) if bits&0x08==0x08: GPIO.output(LCD_D7, True) #Toggle 'Enable' pin time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY) #start the program if __name__ == '__main__': main()
#!/bin/python import math import os import random import re import sys # Complete the powerSum function below. def powerSum(X, N): return recursion(X,N,1) def recursion(X,N,num): if pow(num,N)==X: return 1 elif pow(num,N)<X: return recursion(X,N,num+1) + recursion(X-pow(num,N),N,num+1) elif pow(num,N)>X: return 0 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') X = int(raw_input()) N = int(raw_input()) result = powerSum(X, N) fptr.write(str(result) + '\n') fptr.close() # I needed help for this one. I suck at recursion : (
def func(number): if number // 10 == 0: return f"{number}" if number // 10 != 0: return f"{number % 10}{func(number // 10)}" number_entered = int(input("Введите число: ")) print(int(func(number_entered)))
"""A simple python module to add a retry function decorator""" import functools import itertools import logging import signal import time from decorator import decorator class _DummyException(Exception): pass class MaximumRetriesExceeded(Exception): pass class MaximumTimeoutExceeded(Exception): pass def _timeout(msg): def __internal_timeout(signum, frame): raise MaximumTimeoutExceeded(msg) return __internal_timeout def retry( exceptions=(Exception,), interval=0, max_retries=10, success=None, timeout=-1): """Decorator to retry a function 'max_retries' amount of times :param tuple exceptions: Exceptions to be caught for retries :param int interval: Interval between retries in seconds :param int max_retries: Maximum number of retries to have, if set to -1 the decorator will loop forever :param function success: Function to indicate success criteria :param int timeout: Timeout interval in seconds, if -1 will retry forever :raises MaximumRetriesExceeded: Maximum number of retries hit without reaching the success criteria :raises TypeError: Both exceptions and success were left None causing the decorator to have no valid exit criteria. Example: Use it to decorate a function! .. sourcecode:: python from retry import retry @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0) def foo(bar): if bar < 0: raise ArithmeticError('testing this') return bar foo(5) # Should return 5 foo(-1) # Should raise ArithmeticError foo(0) # Should raise MaximumRetriesExceeded """ if not exceptions and success is None: raise TypeError( '`exceptions` and `success` parameter can not both be None') # For python 3 compatability exceptions = exceptions or (_DummyException,) _retries_error_msg = ('Exceeded maximum number of retries {} at ' 'an interval of {}s for function {}') _timeout_error_msg = 'Maximum timeout of {}s reached for function {}' @decorator def wrapper(func, *args, **kwargs): signal.signal( signal.SIGALRM, _timeout( _timeout_error_msg.format(timeout, func.__name__))) run_func = functools.partial(func, *args, **kwargs) logger = logging.getLogger(func.__module__) if max_retries < 0: iterator = itertools.count() else: iterator = range(max_retries) if timeout > 0: signal.alarm(timeout) for num, _ in enumerate(iterator, 1): try: result = run_func() if success is None or success(result): return result except exceptions: logger.exception( 'Exception experienced when trying function {}'.format( func.__name__)) if num == max_retries: raise logger.warning( 'Retrying {} in {}s...'.format( func.__name__, interval)) time.sleep(interval) else: raise MaximumRetriesExceeded( _retries_error_msg.format( max_retries, interval, func.__name__)) return wrapper
# Load csv with no additional arguments data = pd.read_csv("vt_tax_data_2016.csv") # Print the data types print(data.dtypes) # Create dict specifying that 0s in zipcode are NA values null_values = {'zipcode':0} # Load csv using na_values keyword argument data = pd.read_csv("vt_tax_data_2016.csv", na_values=null_values) # View rows with NA ZIP codes print(data[data.zipcode.isna()])
#-*- coding: utf-8 -*- from scipy.special import j1 def f(x): return j1(2*x) a = 0 b = 10 funa = f(a) funb = f(b) if ( funa * funb > 0.0): print "Dotajaa intervaalaa [%s, %s] saknju nav"%(a,b) sleep(1); exit() else: print "Dotajaa intervaalaa sakne(s) ir!" deltax = 0.0001 while ( fabs(b-a) > deltax ): x = (a+b)/2; funx = f(x) if ( funa*funx < 0. ): b = x else: a = x print "Funkcijas saknes vertiba ir: ", x
x = 5 if x < 10: print('Smaller') if x > 20: print('Bigger') print('Finis') if x == 5: print('Equals 5') if x > 3: print('Ģreater than 3') if x > 5 : print('Ģreater than 5') if x >= 5: print('Ģreater than or Equals') if x <6: print('Less than 6') if x <= 5: print('Less than or Equals 5') if x!= 6: print('Not equal 6') if x == 5: print('Is 5') print('Is Still 5') print('Third 5') print('Afterwards 5') print('Before 6') if x == 6: print('Is 6') print('Is Still 6') print('Third 6') print('Afterwards 6') x = 5 if x > 2: print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5): print(i) if i > 2: print('Bigger than 2') print('Done with i',i) print('All Done') x = 42 if x > 1: print('More than one') if x < 100: print('Less than 100') print('All done') x = 4 if x > 2: print('Bigger') else: print('Smaller') print('All done') if x < 2: print('small') elif x < 10: print('Medium') else: print('LARGE') print('All done') if x < 2: print('Bellow 2') elif x >= 2: print('Two or more') else: print('Something else') astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print('First', istr) astr = '123' try: istr = int(astr) except: istr = -1 print('Second', istr) rawstr = input('Ēnter a number:') try: ival = int(rawstr) except: ival = -1 if ival > 0: print('Nice work') else: print('Not a number')
def bank(a, years): i = 0 while i !=years: a = a * 1.1 i = i + 1 return(a) a = int(input('skolko deneg polozhit? ')) years = int(input("na skolko let? ")) print("za ", years, "goda u tebia budet ", bank(a, years), "deneg")
# bubble sort per le liste list = [] swapped = True num = int(input("How many element do you want to sort?: ")) for i in range(num): val = float(input("Enter next element: ")) list.append(val) while swapped: swapped = False for i in range(len(list)-1): if list[i] > list[i+1]: swapped = True list[i],list[i+1] = list[i+1],list[i] print("Sorted: ") print(list)
def Fib(n): if n < 1: return None if n < 3: return 1 return Fib(n -1) + Fib(n - 2) print("Serie Fibonacci del numero 6:\n") print(Fib(6))
max = -999999999 number = int(input("Enter the value or -1 to stop while: ")) while number != -1 : if number > max : max = number number = int(input("Enter the value or -1 to stop while: ")) print("The largest number is ", max)
# calcola il massimo tra due numeri interi passati come input numero_1 = input('Inserire il primo numero intero:\n') numero_2 = input('Inserire il secondo numero intero: \n') #confronto if numero_1 >= numero_2: print('Il massimo e\' = ' + str(numero_1)) else: print('Il massimo e\' = ' + str(numero_2))
def divisione(a,b): try: risultato = a / b print("Il risultato della divisione = " + str(risultato)) except ZeroDivisionError: print("Non posso dividere per 0") divisione(10,0)
# ciclo while contatore = 0 if contatore <= 10: print(contatore) contatore = contatore + 1 while contatore <= 10: print(contatore) contatore = contatore + 1 # ciclo infinito #while 15 == 15: # print("ciclo infinito!")
# Il risultato è = 1 perché non entra nel while in quanto i = 0, però poi # passa nel ramo else per forza e i si incrementa a +1 quindi i = 1 i=0 while i !=0: i = i - 1 else: i = i + 1 print(i)
my_list=(1,2,3,4,5,6,7,8,9,10) for i in my_list: print(i) for num in range(0,10): print(num+1)
#Print reverse of a string def reverse(strng): if len(strng) == 1: return strng[0] return strng[-1] + reverse(strng[:-1]) #Return true if string is palindrome (same from start or end example - tacocat) def isPalindrome(strng): if len(strng) == 1: return True if strng[0] == strng[-1]: return isPalindrome(strng[1:-1]) return False #returns trues if any of the array elements returns true when sent to callback functions #example arr[2,4,6] false #arr[8,9] true 9 is odd def isOdd(num): if num%2==0: return False else: return True def someRecursive(arr, cb): if len(arr) == 0: return False if not(cb(arr[0])): return someRecursive(arr[1:], cb) return True