text
stringlengths
37
1.41M
sentence = "We are learning how to program in python. I find python programming fun" print(sentence.count("python")) x ="never" reverse_string = "" result = reverse_string.join(reversed(x)) print(result) name= "Cynthia" print("my name is", name) print(name[::-1]) sentence = "We are learning how to program in python. I find python programming fun" print(sentence.count("python")) #function that reverses all the words in a sentence which contains a particular letter.
# evaluate as long as the test expresssion is true #while True: #print("its true") i=10 while i>0: print(i) i-=1
numbers = [1, 2, 3, 4, 5] for each_item in numbers: # iterate over a sequence if each_item%2==0: print(each_item,"is even") else: print(each_item, "is odd") else: print("last item reached") for i in range(1,101): if i%3==0 and i%5==0: print("fizzBuzz") elif i%3==0: print("fizz") elif i%5==0: print("buzz") else: print(i)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 函数作为返回值 # 通常情况下,求和的函数是这样定义的: def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax # 如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办? # 可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def my_sum(): ax = 0 for n in args: ax = ax + n return ax return my_sum f = lazy_sum(1, 3, 5, 7, 9) print(f) print(f()) # 闭包 # 全部都是9!原因就在于返回的函数引用了变量i,但它并非立刻执行。等到3个函数都返回时,它们所引用的变量i已经变成了3,因此最终结果为9。 def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) # 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量 def count(): def f(j): def g(): return j * j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) def count(): def f(j): def g(): return j * j return g return list(map(lambda i: f(i), range(1, 4))) f1, f2, f3 = count() print(f1()) print(f2()) print(f3())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] # 从索引0开始取,直到索引3为止,但不包括索引3 print(L[:3]) print(L[-2:-1]) print(L[:-2])
"""A python linked list implementation.""" from typing import Iterable from data_structures.node import BaseNode class LinkedListNode(BaseNode): """A node for use in linked lists. While this node is usable with arbitrary data values, it also implements rich comparison operators which allow for easy comparison with other nodes which carry comparable value data types. Attributes ---------- value : Any The data this node holds. """ def __init__(self, value): """The constructor for the LinkedListNode. Parameters ---------- value : Any The data this node will hold after initialization. """ super().__init__(value) self._next_node = None @property def next_node(self): """A reference to the next node in the linked list, if one exists. Properties are used in lieu of getters and setters in `Python` to provide custom implementation where necessary. Here, we've made next_node a property so that we can ensure that only other LinkedListNode objects are set. """ return self._next_node @next_node.setter def next_node(self, new_node): """Sets the value of the this node's next node pointer. Parameters ---------- new_node : Optional[LinkedListNode] The new node to point this node at. Raises ------ TypeError : If the new_node is not a LinkedListNode or None. """ if isinstance(new_node, LinkedListNode) or new_node is None: self._next_node = new_node else: raise TypeError("The {0}.next_node must also be an instance of {0}".format(LinkedListNode)) def __str__(self): """The informal representation of this node. This method is called via `str` or `print` and should provide a human readable representation of the object. """ if self.next_node: return "[{} | -]-->".format(self.value, self.next_node.value) else: return "[{} | -]--> None".format(self.value, self.next_node.value) def __repr__(self): """Returns the 'official' string representation of this node. This method's goal is to provide an unambiguous description of the object in question. """ if self.next_node: return "LinkedListNode(value={}, next_node=LinkedListNode({}))".format(self.value, self.next_node.value) else: return "LinkedListNode(value={}, next_node=None)".format(self.value) class LinkedList: """A singly linked list.""" def __init__(self, values=()): """The constructor for this LinkedList Parameters ---------- values : Optional[Sequence] A list, tuple, or set of values to initialize this LinkedList with. """ self._head = None if isinstance(values, Iterable) and values: # Coerce to a list, in case of a weird container type (this makes sure it's iterable). values = list(values) # Since we have some values, fencepost. # Set the head node to a new list and create a generic node pointer that we can advance. self.head = LinkedListNode(values[0]) current_node = self.head # Loop through the remaining values. for v in values[1:]: # Construct a new node for each value. current_node.next_node = LinkedListNode(v) # And advance our generic node pointer. current_node = current_node.next_node elif isinstance(values, Iterable): pass # We didn't get passed anything, construct an empty LinkedList else: raise TypeError("{} object is not iterable".format(values)) @property def head(self): """A reference to the first node in this linked list, if one exists.""" return self._head @head.setter def head(self, new_node): if isinstance(new_node, LinkedListNode) or new_node is None: self._head = new_node else: raise TypeError("The head value of a LinkedList may only be a LinkedListNode or None") def _get(self, index): """This is a 'private' method for getting the LinkedListNode at a particular index.""" if not isinstance(index, int): raise IndexError("{} is not a valid index".format(index)) if index >= len(self) or index < 0: raise IndexError("Valid indices are in the range 0:{}, inclusive. " "You requested {}".format(len(self) - 1, index)) node = self.head for i in range(index): node = node.next_node return node def insert(self, index, value): """Inserts a value at the given index into the linked list. Parameters ---------- index : int The index to construct the new node at. value : Any The value to construct the new node with. Raises ------ IndexError : If the given index is not an integer or is outside the range of the linked list indices [0 to len(self)] """ if not isinstance(index, int): raise IndexError("{} is not a valid index".format(index)) if index: # Grab the immediately preceding node. previous = self._get(index - 1) # Construct a new node and set its next node pointer to what the preceding node was pointing at. new_node = LinkedListNode(value) new_node.next_node = previous.next_node # Finally, set the preceding node's next pointer to point at the newly constructed node. previous.next_node = new_node else: # We want to insert at the head= new_node = LinkedListNode(value) new_node.next_node = self.head self.head = new_node def append(self, value): """Appends a value to the end of the list Parameters ---------- value : Any Value to append """ self.insert(len(self), value) def pop(self, index=None): """Removes a node at the given index and returns its value. Parameters ---------- index : int The index of the node to be removed. Raises ------ IndexError : If the given index is not an integer or is outside the range of the linked list indices [0 to len(self)] """ # if index is None: return self.pop(0) elif not isinstance(index, int): raise IndexError("{} is not a valid index".format(index)) if not index: # We want to pop the first value. node = self._get(0) self.head = node.next_node return node.value # Otherwise normal operations. # Grab the immediately preceding node. previous = self._get(index - 1) # Two cases: Either the immediately preceding node has a next_node value if previous.next_node: # In which case, grab it node = previous.next_node # Set the previous node's next pointer to point at the grabbed nodes next node (even if it is None) previous.next_node = node.next_node # Then return the grabbed node's value return node.value else: # Otherwise we're off by exactly one raise IndexError("You requested an index value one larger than the length of the LinkedList.") def print_list(self): """Prints out the value of each node in the linked list.""" for value in self: print(value) def reverse(self): """Reverses the order of the nodes in place.""" # Grab a reusable reference to the 'previous' node previous_node = self.head # But check to make sure if it's valid if previous_node: # If so, grab a reference to the next node and call it the current one. current_node = previous_node.next_node else: # Otherwise our list is empty and we're done. return # Now, if our list has more than one node, we need to traverse it. # While we have a reference to the current node, while current_node: # Grab a reference to the next one in line so we don't lose it. temp = current_node.next_node # Reset the current node's pointer to point back at the previous node. current_node.next_node = previous_node # We're now done with the previous node, so advance its pointer up one. previous_node = current_node # Then move our current node pointer up one as well. current_node = temp # Finally, deal with the head node, which is now our tail, so point it at nothing. self.head.next_node = None # previous_node is holding on to our new head node, so set it. self.head = previous_node def count(self, value): """Counts the number of nodes in the list whose value is equal to the given value. Parameters ---------- value : Any The value to check for in the nodes of the list. Returns ------- int : The number of nodes whose value is equal to the given value. """ count = 0 for val in self: if val == value: count += 1 return count def index(self, value): """Returns the lowest index for of the first item in the linked list whose value is equal to the given value. Parameters --------- value : Any The value we want to find the index of. Returns ------- int : The lowest zero-based index of the given value in the LinkedList, if present. Raises ------ ValueError : If the given value is not present in the LinkedList """ for idx, val in enumerate(self): if val == value: return idx raise ValueError('{} is not present in the LinkedList'.format(value)) def extend(self, other): """Appends the given iterable to the current LinkedList in place.""" tail = self._get(len(self) - 1) tail.next_node = LinkedList(other).head def sorted(self, method='bubble_sort'): if method == 'bubble_sort': self._bubble_sort() elif method == 'insertion_sort': self._insertion_sort() else: raise NotImplementedError() def _bubble_sort(self): #raise NotImplementedError() current_node = self.head # grab a reference to the next node so we don't lose it if current_node: tmp = current_node.next_node while temp: current_node.value > tmp.value: def _insertion_sort(self): raise NotImplementedError() def __len__(self): count = 0 node = self.head while node: count += 1 node = node.next_node return count def __iter__(self): node = self.head while node: yield node.value node = node.next_node def __contains__(self, value): for v in self: if v == value: return True return False def __add__(self, other): if isinstance(other, Iterable): return LinkedList([value for value in self] + [value for value in other]) raise ValueError("Can only concatenate a LinkedList with another Iterable container-type.") def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): return self.__add__(other) def __mul__(self, value): if isinstance(value, int): return LinkedList([value for value in self]*value) raise ValueError("Multiplication with a LinkedList is only supported for integers") def __rmul__(self, value): return self.__mul__(value) def __imul__(self, value): return self.__mul__(value) def __repr__(self): current_node = self.head out = 'LinkedList(' while current_node: out += str(current_node.value) + ', ' current_node = current_node.next_node out += ')' return out
class Node: def __init__(self,k): self.k=k self.next=None class LinkedList: def __init__(self): self.head=None def PrintList(self): temp=self.head while temp is not None: print(temp.k) temp=temp.next def Push(self,k): if self.head is None: self.head=Node(k) else: newNode=Node(k) newNode.next=self.head self.head=newNode def Pop(self): ret=self.head self.head=self.head.next return ret def Search(self,k): temp=self.head while temp is not None: if temp.k==k: print(k,end=' ') return True temp=temp.next return False class HashTable: def __init__(self): self.ht=[None]*30 def HashMap(self,k): x=33 l=len(k) charList=[b for b in k] PolynomialAccumulation=ord(charList[0]) for i in range(1,l): PolynomialAccumulation+=x*(ord(charList[i])) return PolynomialAccumulation def CompressionMap(self,i): value=i%30 return value def Insert(self,key): self.key=key v=self.HashMap(key) value=self.CompressionMap(v) if self.ht[value] is None: ll=LinkedList() self.ht[value]=ll ll.Push(key) else: self.ht[value].Push(key) def Search(self,key): v=self.HashMap(key) value=self.CompressionMap(v) if self.ht[value] is None: return False else: return self.ht[value].Search(key) def Keys(self): for i in range(30): if self.ht[i] is not None: self.ht[i].PrintList() def main(): table=HashTable() f=open("spellis.dict") for line in f: for word in line.split(): table.Insert(word) isValid=input("Enter a word to check for spelling") if (table.Search(isValid) is True): print("is a valid word") else: print("Not found in our dictionary. Did you mean: ") for i in range(0,len(isValid)): for charInt in range(97,123): if isValid[i] != chr(charInt): newWord=isValid[:i]+str(chr(charInt))+isValid[i+1:] table.Search(newWord) if __name__=='__main__': main()
#jumlah huruf pd kata a="okebos" print(len(a)) #array satu tipe b=[10,9,8,7] print(b[0]) print(b[1]) #array beda tipe c=["siap",10] print(c[0]) print(c[1]) #array kosong diisi d=[] d.append(100) d.append("seratus") print(d[0],d[1]) #menyisipkan data pd array e=[0,1,2,3,4] e.insert(e[0],100) #menjadi didepan index nya print(e) #menghapus f=[0,1,2,3] del(f[2]) print(f) #string sebagai list g="sayaoke" print(g[0]) #panjang list h=["aku","kamu"] print(len(h)) #list dalam list mhs=[[67021,"andi"],[67022,"roy"],[67023,"budi"]] print(len(mhs)) #banyyak data print(mhs[0]) #data keseluruhan print(mhs[0][1]) #data terperinci #membalikan urutan i=[3,2,1] i.reverse() print(i) #mengurutkan ascending j=[3,1,2,4] j.sort() print(j) #mengurutkan descending j=[3,1,2,4] j.sort() j.reverse() print(j) #menyalin k=[10,20] l=k k.append(7) print(k) print(l) #agar data variabel baru salinan awal m=list(k) k.append(30) print(k) print(m) #dictionary-key & value (tipe data key dan value bebas termasuk list) dosen={1001:"boy", 1002:"indra"} #key 1001 dan 1002 #value boy dan indra print(dosen[1001]) print(dosen.keys()) #melihat key yang ada print(dosen.values()) #melihat value yang ada #update data dosen.update({1003:"ike"}) print(dosen) #menghapus data del dosen[1002] print(dosen) type(4.0) #mengetahui tipe data
#Sign your name: Caleb Hews # 1.) Write a program that asks someone for their name and then prints their name to the screen? # name=input("What is your name?") # print("Hello",name) # 2. Write a a program where a user enters a base and height and you print the area of a triangle. # base=int(input("What is the Base of the Triangle?")) # height=int(input("What is the Height of the Triangle")) # area=base*height/2 # print("The area is",area) # 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference. # radius=int(input("What is the Radius of the circle?")) # circumference=radius*2*3.14 # print("The Circmference is: ",circumference) # 4. Ask a user for an integer and then print the square root. # print("This is your square root calculator!") # number=int(input("Give me a number.")) # root=number**.5 # print("The square root of",number,"is", root) # 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma. # Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next. print("May the Mass x Acceleration be with you.") mass=int(input("What is your Mass?")) acceleration=int(input("What is the Acceleration?")) force=mass*acceleration print("Your Force is: ",force) print("Get it?")
"""Class to create and connect to the database""" import mysql.connector from config import DB_NAME class Sql: """Create and use the database""" def __init__(self, user, password, host): self.user = str(user) self.password = str(password) self.host = str(host) def create_db(self, database): """Create the database""" cnx = self.connect_db() cursor = cnx.cursor() self.database = str(database) try: cursor.execute( "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME)) print("Database {} created successfully.".format(DB_NAME)) except mysql.connector.Error as err: print("Failed creating database: {}".format(err)) exit(1) def connect_db(self): """Etablsih the connection to the database""" try: cnx = mysql.connector.connect( user=self.user, password=self.password, host=self.host ) return cnx except mysql.connector.errors.ProgrammingError: return False def create_tables(self): """Create tables in database""" cnx = self.connect_db() cursor = cnx.cursor() use_db = ("USE {}".format(DB_NAME)) cursor.execute(use_db) try: with open('createdb.sql', 'r') as file: query = file.read() cursor.execute(query) cursor.close() except: pass
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 20:31:16 2020 @author: pavdemesh """ def calc_months(starting_salary): left = 1 right = 10000 counter_steps = 0 while left <= right: # Increase the counter of bisection searches by 1 counter_steps += 1 # Define the mid point for bisection search mid = left + (right - left) // 2 # print(f"left: {left}, right: {right}, mid: {mid}") # Calculate the amount of the down payment # By multiplying total_cost by the percentage of the down payment total_cost = 1_000_000 portion_down_payment = 0.25 amount_down_payment = total_cost * portion_down_payment # print(amount_down_payment) # Calculate the monthly return rate given the annual return rate annual_return_rate = 0.04 monthly_return_rate = annual_return_rate / 12 # print(monthly_return_rate) # Define the semi_annual_raise semi_annual_raise = 0.07 # Reset all values to rheir initial state current_savings = 0 monthly_salary_saved = 0 annual_salary = starting_salary # Define the required number of months num_of_months = 36 # Calculate the savings amount after 36 months # The savings rate is the (mid) of (left and right) for month in range(1, num_of_months + 1): # Calculate the monthly salary savings: # Divide the annual by 12 to get monhly salary # Multiply the monthly salary with the mid == percent to be saved monthly_salary_saved = annual_salary / 12 * mid / 10000 # Increase current savings by monthly return (revenue) from existing savings # Plus monthly salary current_savings += current_savings * monthly_return_rate + monthly_salary_saved # If month divisible by 6 - increase annual salary by semi_annual_raise if month % 6 == 0: annual_salary += annual_salary * semi_annual_raise # Check resulting savings against the amount of down payment # If the savings amount lies within USD 100 of required downpayment # Print appropriate message and return the savings rate as deciaml if -100 <= (current_savings - amount_down_payment) <= 100: best_savings_rate = round(mid / 10_000, 4) print("Best savings rate: ", best_savings_rate) print("Steps in bisection search: ", counter_steps) return # If savings amount too big: search the left half: lesser values elif (current_savings - amount_down_payment) > 100: right = mid - 1 # Else search the right half else: left = mid + 1 # If no savings rate found - print appropriate message print("It is not possible to pay the down payment in three years.") return calc_months(int(input("Enter the starting salary: ")))
# -*- coding: utf-8 -*- import re patron = re.compile("^\d*$") class Pila: """ Representa una pila con operaciones de apilar, desapilar y verificar si está vacía. """ def __init__(self): """ Crea una pila vacía. """ # La pila vacía se representa con una lista vacía self.items=[] def apilar(self, x): """ Agrega el elemento x a la pila. """ # Apilar es agregar al final de la lista. self.items.append(x) def desapilar(self): """ Devuelve el elemento tope y lo elimina de la pila. Si la pila está vacía levanta una excepción. """ try: return self.items.pop() except IndexError: print ("la pila esta vacia") raise ValueError("La pila está vacía") def es_vacia(self): """ Devuelve True si la lista está vacía, False si no. """ return self.items == [] variables=[] posicion= 0 def postfijo(lista): p=Pila() tam=len(lista) bandera=True for x in range(tam): var=lista[x] if (esOperador(var)==True): p.apilar(int(operar(lista[x],p.desapilar(),p.desapilar()))) else: if (esVariable(var)==True): if (buscar(var)==True): var=variables[posicion+1] p.apilar(int(var)) else: print('no encontro', var) return False else: if (esNumero(var)==True): p.apilar(int(var)) else: print('caracter invalido comprobo todo para', var) return False return p.desapilar() def esOperador(v): if v=="+": return True if v=="-": return True if v=="/": return True if v=="*": return True return False def esNumero(v): try: v = int(v) return True except ValueError: return False #if type(v) != int: # raise TypeError, v+ "v debe ser del tipo int" # return False # else: # return True def esVariable(v): if(esNumero(v)==False): try: if(len(v)==1): if ord(v)>=65 and ord(v)<=90: return True else: return False else: print ("ay mama") return False except ValueError: return False def operar(o, y, x): if o=="+": z=x+y if o=="-": z=x-y if o=="*": z=x*y if o=="/": z=x/y return z def agregarVariable(var,val): variables.append(var) variables.append(val) def buscar(v): tam=len(variables) for i in range(tam): if v == variables[i]: posicion=i return True return False def comprobar(lista): tam=len(lista) print (tam) if lista[tam-1]=='='or lista[tam-1]=="=\r": if esVariable(lista[tam-2])==True: if(postfijo(lista[0:tam-2])==False): return False else: agregarVariable(lista[tam-2], postfijo(lista[0:tam-2])) else: return "algún dato es erroneo" else: print "no se iguala a nada" def start (): f=open('prueba1.txt','r') lista=[y.split(' ') for y in [x.strip('\n') for x in (f.readlines())]] print (lista) for i in range(len(lista)): if (comprobar(lista[i])==False): break else: print (variables) start()
cases = int(input()) data=list() for case in range(cases): line = input() tupla = line.split(" ") tuplaMod=(int(tupla[0]), tupla[1]) data.append(tuplaMod) data.sort(key=lambda x: x[0]) texto=str() for case in range(cases): texto+=data[case][1] print(texto)
from . import helpers class SinglyLinkedListNode(object): """ A node for a SinglyLinkedList Each node contains a data field ("_value") and a reference ("_next") to the next node in the list. """ def __init__(self, value=None): self._value = value self._next = None def get_value(self): return self._value def set_value(self, value): self._value = value def get_next(self): return self._next def set_next(self, node): self._next = node class SinglyLinkedList(object): """ A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list. """ def __init__(self): self._head = None self._tail = None self._next = None self._len = 0 def __len__(self): return self._len def __iter__(self): next_elt = self._head while next_elt: tmp_next_elt = next_elt next_elt = next_elt.get_next() yield tmp_next_elt def __next__(self): while self._next: tmp_next_elt = self._next self._next = self._next.get_next() return tmp_next_elt raise StopIteration def __str__(self): list_elements = [str(elt.get_value()) for elt in self] return f"{list_elements}" def _append(self, node): if not self._head: self._head = node self._tail = node self._next = node self._len += 1 else: self._tail.set_next(node) self._tail = node self._len += 1 def _pop(self): if self._len == 0: raise IndexError prev = None cur = self._head for node in self: prev = cur cur = node prev.set_next(None) ret = self._tail self._tail = prev self._len -= 1 return ret def pop(self): return self._pop().get_value() def append(self, value): self._append(SinglyLinkedListNode(value)) def reverse(self): if self._len == 0: return self prev = None cur = self._head nxt = self._head.get_next() self._head, self._tail = self._tail, self._head while cur: cur.set_next(prev) prev = cur cur = nxt if nxt: nxt = nxt.get_next() return self
#""" #Assignment 2 - Erewhon Mobile Data Plans #October 18, 2018 #Name..: Laura Whalen #ID....: W0415411 #""" __AUTHOR__ = "Laura Whalen <W0415411@nscc.ca>" def main(): # input data = int(input("Enter data usage (Mb): ")) # processing and output def data_plans(): if data <= 200: print("Total charge is: $20.00") elif data > 1000: print("Total charge is: $118.00") elif data > 200 or data <= 500: charge = 0.105 total = (data * charge) print("Total charge is: ${0:.2f}".format(total)) elif data > 500 or date <= 1000: charge = 0.110 total = (data * charge) print("Total charge is: ${0:.2f}".format(total)) data_plans() if __name__ == "__main__": main()
#Assignment 4 - BattleShips #Name..: Laura Whalen #ID....: W0415411 print("Let's play Battleship!\nYou have 30 missiles to fire to sink all 5 ships.\n") map_file = open("map.txt") #hide the grid target_grid = [] #where values are stored for r in map_file: r = r.replace("\n","") columns_as_list = r.split(",") target_grid.append(columns_as_list) #variables missiles = 30 row_nums = [[chr(32) for x in range(1,11)] for y in range (1,11)] #where guesses will be stored successful_hits = 0 #loop to play game while missiles > 0: emptyspace = " "*3 for i in range (65,75): emptyspace += chr(i) emptyspace += (" ") emptyspace = emptyspace print(emptyspace) n = 1 for l in row_nums: space = " " for entry in l: space += str(entry) space += " " print("{0:2d}{1}".format(n,space)) n += 1 #error checking keep_going = "Y" while keep_going == "Y": target_guess = input("\nChoose your target (Ex. A1): ") target_guess = target_guess.upper() if target_guess == "" or target_guess[0] == " " or target_guess[1:] == " ": print("\nInvalid! Try again") elif ord(target_guess[0]) < 65 or ord(target_guess[0]) > 74: print("\nInvalid! Try again") elif not target_guess[1:].isnumeric(): print("\nInvalid! Try again") elif int(target_guess[1:]) < 1 or int(target_guess[1:]) > 10: print("\nInvalid! Try again") else: row = int(target_guess[1:])-1 column = ord(target_guess[0])-65 if row_nums[row][column] == "O" or row_nums[row][column] == "X": print("\nYou already shot this! Try again!") else: keep_going = "N" #store hits / misses, and print to screen if target_grid[row][column] == "1" : print("\n!!! HIT !!!") row_nums[row][column] = "X" successful_hits += 1 else : print("\nMISS") row_nums[row][column] = "O" missiles -= 1 print("You have {0} missiles remaining!\n".format(missiles)) if successful_hits == 17 and missiles >= 0: print("YOU SANK MY ENTIRE FLEET!\nYou had 17 of 17 hits, which sank all the ship\nYou won, congratulations!") break elif successful_hits < 17 and missiles == 0: print("\nGAME OVER!\nYou had {0} of 17 hits, but didn't sink all the ships.\nBetter luck next time.".format(successful_hits)) break else: continue map_file.close()
# range, for and while loops, breaks, cont. # range(start, stop, step) # it will range from the start to one before the stop # range(0, 10) has the default step of always 1 # range(0, 10, -1) will range from 10 -> 1 range(8, 0, -2) # 8, 6, 4, 2 # doing range(8, 0, 2) will not do anything ######################################################################## """ You use loops when you iterate something multiple times. When you know the number of times an action is to be repeated, use a for loop. If you don't, use a while loop. """ for letter in "python": print(letter) # will print python's letter each on it's own line # for loops are sometimes called for each loops # adding a "/n" prints a new line? for num in range(2, 10, 2): # first determine your range to be 2, 4, 6, 8 print(num*2) # while loops are a number based on something that changes (input) # every for loop can be written as a while loop but not vice versa # while (): whatever is inside the parenthesis is a boolean # below it you put changes to your booleans # while True: would print forever def range2(start, stop, step): while(start < stop): print(start) start = start + step range2(2, 10, 2) def game(): userInput = input("Do you want to continue?") while (userInput == "yes"): print("You are continuing.") userInput = ("Do you want to continue?") for x in range(6): # the range of 6 is 0, 1, 2, 3, 4, 5 print(x) x = 0 while x<6: print(x) x += 1 # tell the while loop to start at a number and use the < to stop it ########################################################################## for letter in "python": if letter == "t": continue # when you do this, it's skips the below statement & restarts print(letter) for letter in "python": if letter == "t": break # the loop will stop forever when it reaches t print(letter) # anything indented to the right of "for" or "while" will be broken out of def findEs(str): # never put quotes in a parameter, it is made for variables numE= 0 for letter in str: if letter == "e": numE= numE+1 return print(numE) findEs("eeeeeeee")
# try and except # if an error is encounterd, a try block code execution is stopped and... # transferred down to the except block # use try and except for runtime errors # example - divide by zero def meanUser(num, denominator): try: answer = num/denominator print(answer) except: print('bad user') # if you put bad code in your except statement...ERROR finally: print('hi there')
# Day 15 - turtle events # review modules first import turtle import random # instead of importing the way above.. you can ##from turtle import * # the star means everything and all ##from random import * # it makes a difference in terms of how you use them # if you import the new way, you use them this way ##myrand = Random() ##print(randrange(1,3)) # you don't need to say random. anymore ## ##myturtle = Turtle() ############################################################################## # TURTLE EVENTS # an event is when something occurs such as a keypress or mouseclick event turtle.setup(600,400) wn = turtle.Screen() wn.bgcolor("light blue") tess = turtle.Turtle() tess.speed(10) myrand = random.Random() # create a random number generator # keypress handlers (functions to handle keypress events) def moveforward(): tess.forward(30) def turnleft(): tess.left(30) def turnright(): tess.right(30) shapes = ["circle", "triangle", "turtle", "arrow"] def costume(): num = myrand.randrange(len(shapes)) tess.shape(shapes[num]) tess.shapesize(random.random() * 5) def teleport(): tess.penup() tess.goto(random.randrange(-300,300),random.randrange(-200,200)) # connects the keypresses to the keypress handlers we defined wn.onkey(moveforward, "Up") # up arrow wn.onkey(turnright, "r") wn.onkey(turnleft,"l") wn.onkey(teleport, "Escape") # move to a random location on the screen wn.onkey(costume, "c") # change what the turtle looks like to a circle twice as big # at the end of your program needs... wn.listen() # change the costume function to make the turtle change to randomly chosen shape # and a randomly chosen size # the shape needs to be either circle,triangle, turtle, arrow # the size can be any floating point number between 0 and 2
#Day 2 - Variables and Expressions # finish chapters 3 and 4 by Friday # a variable is an identifier (a name) that points to a value myname = "Madison" mynumber = 27 # Rules to variable naming: a variable can only be made up of letters, # numbers, and an underscore _ # a variable must start with a letter # variables are case-sensitive # do meaningful variable names num1 = 3 Num1 = 4 # these are two different variables, so just stick to lowercase # 3number as a variable would break the syntax rules # variables keep their value until you change it to something else print(myname) # I can change its value myname = "Ms. Madison" print(myname) # it will print both names num1 = 10 num2 = 20 print(num1 + num2) # even though I defined num1 as 3 earlier in my code, it will use my most # recent assignment of num1 # a runtime error would be if you divided by zero or said something undefined # ex. of a syntax error: using & instead of + for addition # ex. of a syntac error: forgetting a parentheses in print( ) # variables have data types associated with them based upon the value they store num3 = 25.2 # 25.2 is a floating point number print(num3) print(type(num3)) # an integer, denoted by int, is a different class (no decimal) num1 = 5 num2 = 6 result = num1/num2 print(result) print(type(result)) print(type(num1)) # num1 is an integer, num 2 is an integer, but result is a float # python follows normal rules for order of operations (PEMDAS) # () then ** then / * than + - myname = "Queen" mynum = 27 # result = myname + mynum # cannot print(result) becuase you can't add two different types RUNTIME ERROR print(type(myname)) print(type(mynum)) mynum = "33" # makes mynum a string print(type(mynum)) result = myname + mynum print(result) # it prints Queen33
# Day 31 - classes that interact with each other # chapters 13, 16, and 21 cover this week's material class Student: def __init__(self, name, gpa, idnum): self.name = name self.gpa = gpa self.idnum = idnum def __eq__(self, other): return self.idnum == other.idnum def __str__(self): return self.idnum + " is named " + self.name + " with gpa of " + str(self.gpa) class Teacher: def __init__(self, aname, alist): self.name = aname self.students = alist def showfirst(self): # print out the first student print(self.students[0]) def gpaAvg(self): total = 0 for stud in self.students: total += stud.gpa avg = total / len(self.students) return avg # outside of any class # create teacher t1 with name "McDaniel" t1 = Teacher("McDaniel", []) # create student s1 with name "Cara" 3.9 "3332222" s1 = Student("Cara", 3.9, "3332222") # make Cara first in McDaniel's class t1.students.append(s1) t1.showfirst() # add another student to McDaniel's class s2 = Student("Madison", 3.8, "2996969") t1.students.append(s2) # write a method for the teacher class called gpaAverage that computes the... # average gpa of all this teacher's students print(t1.gpaAvg()) studentlist = [] studentlist.append(Student('Peter',2.5,'1111111')) studentlist.append(Student('Kelly',3.0,'2222222')) mcdaniel = Teacher("Prof McD", studentlist) studentlist = [] studentlist.append(Student('George',3.4,'2333233')) studentlist.append(Student('Ringo', 3.2, '3333224')) smith = Teacher('Prof Smith',studentlist) # print out all the students in mcdaniel's class # write an if statement that determines which of these mcdaniel or smith has... # the highest avg gpa students if (mcdaniel.gpaAvg() > smith.gpaAvg()): print('McDaniel students are smarter') elif (smith.gpaAvg() > mcdaniel.gpaAvg()): print('McDaniel students need to work harder') else: print('Same') # print out the gpa of the last student in prof smith's class print(smith.students[len(smith.students)-1].gpa) # how to tell if 2 students are the same student s8 = Student('Joe',3.1,'333') s9 = Student('Joe',3.8,'444') s10 = Student('Joe',3.8,'444') print(s8==s9) print(s9==s10) # use the __eq__ method to determine equality # this can also be done with these: # __lt__ aka less than # __gt__ aka greaterthan # __ge__ aka >= # __le__ aka <=
# Exam 3 Review # TRY AND EXCEPT # some good exceptions- # division by zero # operations on incompatible types # accessing a list item, dict value, or object attribute that doesn't exist # using an identifier that has not been defined # trying to access a file that doesn't exist #---------------------------------------------------------------------------- # API - Application Programming Interface # some entity develops this and us, as a user, we can interact with their code # we can write code, without having to know how theirs works # used to present information to other developers or process data # they are useful bc their code can stay private, while we are still able to... # extract data from Applications that are already made for us # ex. Uber uses Google Maps' API # we build off of another application # the request module is simpler than urllib # get data from the web using apis/json (be able to explain this!) # we send a request, then we are returned a JSON object # they will turn that object into a dictionary # requests.get() makes a call to the api and gets info you want at the url.. # you pass in, returns a STRING # .json() puts that info in a form we can understand & manipulate in python # type of value you did JSON to will be dictionary #----------------------------------------------------------------------------- # Big - O # relationship b/w how much data you have and time it takes # constant # logarithmic # log linear # linear..... # Linear Search - O(n) # not as efficient, unsorted or sorted lists # Binary Search - O(logn) # efficient, must be sorted list # if list is even, searches one with lower index # Bubble sort(On^2) # Insertion sort O(n^2) # Selection sort O(n^2) # Merge sort O(nlogn) # Quick sort O(nlogn) #--------------------------------------------------------------------------- # OOP - Object Oriented Programming # Classes and objects # the definition of the idea we are coding, it's the blueprint # attributes - fields of data # methods - functions that an instance of the class can perform # object - instance of class # init is a constructor # self must be put in params for all methods
# Last Day Notes # aliases v. clones num = 22 # this is not an object, just an integer (called a primitive) mylist = [1,2,3,4] # this is an object num2 = num # makes a copy and stores it in num2 mylist2 = mylist # makes an alias (a pointer to the same area of memory) mylist2[1] = 99 num2 = 44 print(num) # num is still 22 print(mylist) # this is changed when you change mylist2 # try this... create a dictionary from a list of words and numbers w word... # as a key and num as a value fr = open('words.txt','r') stuff = fr.read() mylist = stuff.split('\n') fr.close() mylist = ['joe',22,'fred',25,'martha',33,'tom',18] mydict = {} for num in range(len(mylist)-1): if num%2 == 0: mydict[mylist[num]] = mylist[num + 1] print(mydict)
# day 23 - Try and Except # an exception is another name for a runtime error # you can handle these errors in your code # before try... except review break and continue for num in range(50): if num % 7 == 0: continue # go back to start of loop if num % 25 == 0: break # exits loop print(num) print("Done!") # try except uses break and continue to handle the possibilty of exceptions... # occurring age = 0 while age < 18: try: age = input('enter your age') age = int(age) if age < 18: print("no admittance") except: print("Your answer must be a positive integer") age = 0 print("welcome") # very useful with files in case they are not there try: myfile = open("gradesss.csv","r") data = myfile.read() print(data) myfile.close() except: print("unable to find file") # nonexistent items in a dictionary mydict = {1:45,2:99} try: print(mydict[8]) except: print("key not found in dictionary") # finally is a way to end the try...except block and wrap things up # finally code is executed whether the try or except block happened myfile = open("grades.csv") try: print(3/0) except: print("exception occurred") finally: myfile.close() import random total = 0 rand = random.Random() for num in random.randrange(1,100): try: if num % 10 == 7: continue if num in [70,71,72,73,74,75,76,78,79]: break total += num except: total = 0 print(total)
idade = int(input("Digite sua idade (ex. 32): ")) while idade < 0 or idade > 150: idade = int(input("Digite sua idade (ex. 32): ")) salario = float(input("Digite seu salário (ex. 2100,50): ")) while salario < 0: salario = float(input("Digite seu salário (ex. 2100,50): ")) genero = input("Informe seu genero (ex. M, F, ou outro): ") while genero != "M" and genero != "F" and genero != "outro": genero = str(input("Informe seu genero (ex. M, F, ou outro): ")) print(idade, salario, genero)
numero = int(input("Digite um número: ")) contador = 1 soma = 0 while contador <= numero: soma = soma + contador contador = contador + 1 print(soma) # Exemplo 1: # input: 4 # output: 10
# Faça um programa que leia 10 números do usuário # e os coloque corretamente no dicionário D abaixo. D = {'pares': [], 'impares': []} for i in range(10): numero = int(input("Digite um número: ")) if numero % 2 == 0: D['pares'].append(numero) else: D['impares'].append(numero) print(D)
import random numero_aleatorio = random.randint(1, 40) numero_aleatorio_menos = numero_aleatorio - 3 numero_aleatorio_mais = numero_aleatorio + 3 numero = int(input("Digite um número de 1 a 40: ")) while numero != numero_aleatorio: if numero > numero_aleatorio_menos and numero < numero_aleatorio_mais: print("Você está quente!") numero = int(input("Digite um número de 1 a 40: ")) print(numero, "- Você acertou!") # numero aleatorio entre 1 e 40 # peça número para usuário # dizer se está quente ou frio
x = 0 y = 10 while x < y: if x % 2 == 0: print(x) else: print(y) x = x + 1 y = y - 1 print(x, y)
alunos = {'nomes': ['Ayrton', 'Dandara', 'Felipe', 'Gustavo', 'Jeferson'], 'cpf': [], 'idades': [25, 20, 50, 19, 32]} for chave in alunos: # "lista" é o "valor" da "chave" do dicionário "alunos" lista = alunos[chave] print(lista) for elemento_da_lista in lista: print(elemento_da_lista)
camisas = int(input("Quantas camisas? ")) calcas = int(input("Quantas calças? ")) parmeias = int(input("Quantos pares de meias? ")) total = (camisas * 12) + (calcas * 20) + (parmeias * 5.50) print("Seu total é R$" + str(total))
while True: genero = input("Informe seu gênero: ") if genero == "M" or genero == "F" or genero == "outro": break else: print("Genero inválido.")
si = float(input("Si: ")) v = float(input("t: ")) t = float(input("v: ")) s = si + v * t print(s)
################################################################## '''''' '''''' ''' This file is to Generate the negative samples, with the sample size and form as the training and testing data 1. The negative samples are generated by the random method. 2. The negatiev samples should not have any element in commone with the training or testing samples. ''' '''''' '''''' ############################################################################# import os import json import random import copy ########################################################################### ''' Generate_random_negative: a function to generate negative samples with the same pattern and size of the input data. By negative samples, we mean the randomly generated samples, and they are not in the data. Input: data: a list of core paires, which is the output of the module of FrameConstraint sample_size: the size of the negative samples need to be generated Output: negative_samples: a list of randomly generated cores, with the element in the form of [['ALA','GLU'], ['TYR','MET'], -1, -1] The length of the negative sampels equals to the sample size *****************Important to know*********************** When we generate the negative samples, we have to use the training samples as the reference to decide whether the randomly generated samples are negative or not. The testing samples can not be used because the testing samples are samples that we pretend don't know when we build this model. ''' def Generate_random_negative(data, sample_size): TripleSingle = [['TYR', 'Y'], ['LYS', 'K'],['ASP', 'D'], ['ASN', 'N'], ['TRP', 'W'], ['PHE', 'F'], ['GLN', 'Q'], ['GLU', 'E'], ['PRO', 'P'], ['GLY', 'G'], ['THR', 'T'],['SER', 'S'], ['ARG', 'R'], ['HIS', 'H'], ['LEU', 'L'], ['ILE', 'I'], ['CYS', 'C'], ['ALA', 'A'], ['MET', 'M'], ['VAL', 'V']] AA = [] for aa in TripleSingle: AA.append(aa[0]) Ab_Ag = [] for parepi in data: Ab_Ag.append([parepi[0], parepi[1]]) Ab_length = len(Ab_Ag[0][0]) Ag_length = len(Ab_Ag[0][1]) negative_samples = [] while len(negative_samples) < sample_size: r_Ab_r_Ag = [] while r_Ab_r_Ag == []: r_Ab = With_replacement_sample(AA, Ab_length) r_Ag = With_replacement_sample(AA, Ag_length) r_Ab_r_Ag = [r_Ab, r_Ag] if r_Ab_r_Ag in Ab_Ag: r_Ab_r_Ag = [] negative_samples.append([r_Ab, r_Ag, -1, -1]) return negative_samples def With_replacement_sample(population, size): sample = [] while len(sample) < size: sample.extend(random.sample(population,1)) return sample ############################################################### def main(): # Set the working directory and the saving directory wd = '/home/leo/Documents/Database/Pipeline_New/Complexes/Cores' # we want to generate 10 negative samples for n in range(10): sd = '/home/leo/Documents/Database/Pipeline_New/Complexes/Negative_cores/'+'Sample_'+str(n) for i in range(1, 7): for j in range(1,7): for k in [0]: for h in [1]: train_name ='training_' + str(i)+'_'+str(j)+'_'+str(k)+'_'+str(k)+'_1_2_'+str(h)+'perchain' test_name = 'testing_' + str(i)+'_'+str(j)+'_'+str(k)+'_'+str(k)+'_1_2_'+str(h)+'perchain' print('working on '+ train_name + '\n' + test_name) # Save the core aa os.chdir(wd) with open(train_name, 'r') as f: data = json.load(f) with open(test_name, 'r') as f: testing_data = json.load(f) # Generate the negative samples negative_testing_samples = Generate_random_negative(data, len(testing_data)) negative_training_samples = Generate_random_negative(data, len(data)) # Save the negative samples os.chdir(sd) with open(test_name+'_negative', 'w') as f: json.dump(negative_testing_samples, f) with open(train_name + '_negative', 'w') as f: json.dump(negative_training_samples, f) #################################################################### #if __name__ == '__main__': # main() #os.chdir('/home/leo/Documents/Database/Pipeline_New/Complexes/Negative_cores/Sample_5') #with open('training_1_1_0_0_1_2_1perchain_negative', 'r') as f: # training_1_1 = json.load(f) #len(training_1_1) #################################################################### ''' sd: the saving directory ''' sd = '/home/leo/Documents/Database/Pipeline_New/Latest/Negative_cores' def Negative_the_latest(sd): # Get the training set by combining all the previous for i in range(1,5): for j in range(1, 5): train_name = 'training_'+str(i)+'_'+str(j)+'_0_0_1_2_1perchain' test_name = 'testing_'+str(i)+'_'+str(j)+'_0_0_1_2_1perchain' os.chdir('/home/leo/Documents/Database/Pipeline_New/Cores') with open(train_name, 'r') as f: train_old = json.load(f) with open(test_name, 'r') as f: test_old = json.load(f) train = copy.deepcopy(train_old) train.extend(test_old) os.chdir('/home/leo/Documents/Database/Pipeline_New/Latest/cores') with open(test_name, 'r') as f: test_new = json.load(f) # Generate the negative samples for n in range(10): save_directory = sd + '/sample_'+str(n) print('Generating '+ test_name) negative_test = Generate_random_negative(train, len(test_new)) print('Generating '+ train_name) negative_train = Generate_random_negative(train, len(train)) # Same the negative samples os.chdir(save_directory) save_name_test = test_name + '_negative' save_name_train = train_name + '_negative' with open(save_name_test, 'w') as f: json.dump(negative_test, f) with open(save_name_train, 'w') as f: json.dump(negative_train, f) #Negative_the_latest(sd) #os.chdir('/home/leo/Documents/Database/Pipeline_New/Negative_Cores/Sample_0') #with open('training_1_1_0_0_1_2_1perchain_negative', 'r') as f: # train = json.load(f) #len(train) ''' Need to take a look at the negative samples, make sure they have nothing in common with the real cores ''' #def Check(): # # Set the working directory and the saving directory # wd = '/home/leo/Documents/Database/Pipeline_New/Cores' # # we want to generate 10 negative samples # for n in range(10): # sd = '/home/leo/Documents/Database/Pipeline_New/Negative_Cores/'+'Sample_'+str(n) # for i in range(1, 5): # for j in range(1, 5): # for k in [1, 0]: # for h in [1, 2, 3]: # # name = str(i)+'_'+str(j)+'_'+str(k)+'_'+str(k)+'_1_2_'+str(h)+'perchain' # # # Save the core aa # os.chdir(wd) # with open('training_'+name, 'r') as f: # positive_training_data = json.load(f) # # with open('testing_'+name, 'r') as f: # positive_testing_data = json.load(f) # # # Save the negative samples # os.chdir(sd) # save_name = name + '_negative' # with open('testing_'+save_name, 'r') as f: # negative_testing_data = json.load( f) # with open('training_'+save_name, 'r') as f: # negative_training_data = json.load(f) # # # Check # res1 = Subcheck(positive_training_data, negative_testing_data) # res2 = Subcheck(positive_training_data, negative_training_data) # # if res1 and res2 and len(positive_testing_data)== len(negative_testing_data): # print(' Correct') # else: # print(print(name+'\n not correct')) # # os.chdir(wd) # with open('training_'+name, 'r') as f: # positive_training_data = json.load(f) # # with open('testing_'+name, 'r') as f: # positive_testing_data = json.load(f) # # # Save the negative samples # os.chdir(sd) # save_name = name + '_negative' # with open('testing_'+save_name, 'r') as f: # negative_testing_data = json.load( f) # with open('training_'+save_name, 'r') as f: # negative_training_data = json.load(f) # # # Check # res1 = Subcheck(positive_training_data, negative_testing_data) # res2 = Subcheck(positive_training_data, negative_training_data) # # if res1 and res2 and len(positive_testing_data)== len(negative_testing_data): # print(' Correct') # else: # print(print(name+'\n not correct')) # # #def Subcheck(data, sub_data): # res = True # pool = [x[:2] for x in data] # for sub in sub_data: # if sub[:] in pool: # res = False # break # return res # # #Check()
class Word(): def __init__(self, word): self.word = word self.phone = [] self.syns = [] self.pos = '' def __str__(self): ret = '' ret += self.word + ': ' ret += self.pos + ', ' ret += ' '.join(self.phone) + ', ' ret += '[' + ', '.join(self.syns[:3]) + '...]' return ret
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.firsst = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amount) # @classmethod # def set_raise_amt(cls, amount): # cls.raise_amount = amount # @classmethod # def from_string(cls, emp_str): # first, last, pay = emp_str.split('-') # return cls(first, last, pay) # @staticmethod # def is_workday(day): # if day.weekday() == 5 or day.weekday() == 6: # return False # return True class Developer(Employee): raise_amount = 1.10 def __init__(self, first, last, pay, prog_lang): super().__init__(first, last, pay) self.prog_lang = prog_lang class Manager(Employee): def __init__(self, first, last, pay, employees=None): super().__init__(first, last, pay) if employees is None: self.employees = [] else: self.employees = employees def add_emp(self, emp): if emp not in self.employees: self.employees.append(emp) def remove_emp(self, emp): if emp in self.employees: self.employees.remove(emp) def print_emps(self): for emp in self.employees: print ('--> ', emp.fullname()) dev1 = Developer('Corey', 'Schafer', 50000, 'Python') dev2 = Developer('Test', 'User', 60000, 'C++') mgr1 = Manager('Sue', 'Smith', 90000, [dev1]) print(mgr1.email) mgr1.add_emp(dev2) mgr1.remove_emp(dev1) mgr1.print_emps() #print(dev1.email) #print(dev1.prog_lang) # import datetime # my_date = datetime.date(2016, 7, 10) # print(Employee.is_workday(my_date)) # emp_str_1 = 'John-Doe-70000' # emp_str_2 = 'Steve-Smith-60000' # emp_str_3 = 'Jane-Doe-100000' # new_emp_1 = Employee.from_string(emp_str_1) # print(new_emp_1.email) # print(new_emp_1.pay)
b=int(input("enter no:")) a=1 n=2 print(a) while n<=b: print(n,end='/') a=(n/(n+1)) n=n+1 print('=',a)
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data print("check tensorflow version: ", tf.__version__) # tensorflow 交叉熵 import numpy as np import matplotlib.pyplot as plt mnist = input_data.read_data_sets("MNIST_data", one_hot=True) batch_size = 100 n_batch = mnist.train.num_examples // batch_size x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) prediction = tf.nn.softmax(tf.matmul(x, W) + b) # 损失函数 # loss = tf.reduce_mean(tf.square(y - prediction)) 使用二次代价函数 # 这里输出层已经经过一次softmax,对于已经softmax转换过的预测值不能再使用这个函数!!! loss =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction)) #使用交叉熵 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) init = tf.global_variables_initializer() correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): # 获得一个批次的图片和标签,每个批次是100张,每个批次不重复 batch_xs,batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys}) acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels}) print("Iter " + str(epoch) + ".Testing Accuracy" + str(acc)) ''' # 使用二次代价函数 Iter 0.Testing Accuracy0.8305 Iter 1.Testing Accuracy0.8708 Iter 2.Testing Accuracy0.8819 Iter 3.Testing Accuracy0.8886 Iter 4.Testing Accuracy0.8944 Iter 5.Testing Accuracy0.8969 Iter 6.Testing Accuracy0.8986 Iter 7.Testing Accuracy0.9021 Iter 8.Testing Accuracy0.903 Iter 9.Testing Accuracy0.9047 Iter 10.Testing Accuracy0.9064 Iter 11.Testing Accuracy0.9072 Iter 12.Testing Accuracy0.9083 Iter 13.Testing Accuracy0.9096 Iter 14.Testing Accuracy0.9099 Iter 15.Testing Accuracy0.9106 Iter 16.Testing Accuracy0.9114 Iter 17.Testing Accuracy0.9119 Iter 18.Testing Accuracy0.9136 Iter 19.Testing Accuracy0.9135 Iter 20.Testing Accuracy0.9139 #使用交叉熵 Iter 0.Testing Accuracy0.8443 Iter 1.Testing Accuracy0.8947 Iter 2.Testing Accuracy0.9019 Iter 3.Testing Accuracy0.9065 Iter 4.Testing Accuracy0.9087 Iter 5.Testing Accuracy0.9111 Iter 6.Testing Accuracy0.9129 Iter 7.Testing Accuracy0.9132 Iter 8.Testing Accuracy0.9148 Iter 9.Testing Accuracy0.9171 Iter 10.Testing Accuracy0.9185 Iter 11.Testing Accuracy0.918 Iter 12.Testing Accuracy0.9184 Iter 13.Testing Accuracy0.9199 Iter 14.Testing Accuracy0.9189 Iter 15.Testing Accuracy0.9214 Iter 16.Testing Accuracy0.9204 Iter 17.Testing Accuracy0.9209 Iter 18.Testing Accuracy0.9212 Iter 19.Testing Accuracy0.9223 Iter 20.Testing Accuracy0.9217 '''
import jsonParsing building = raw_input("Enter building name or number: ") level = raw_input("Enter level: ") maps = jsonParsing.mapParser() maps.setMap(building, level) for i in range(maps.numElements): print maps.getLocationName(i)
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. """ unique_calls_to = [] num_calls_from_080 = 0 num_calls_from_080_to_080 = 0 for record in calls: if "(080)" in record[0]: # calling number is from Bangalore num_calls_from_080 += 1 # if fixed line, extract area code which is in brackets # if mobile number extract area code which is first four digits if starting with [7,8,9] # # We can ignore telemarketers (area code 140) because they never receive calls # this will either extract digits in parenthesis or the entire number (10 digits) area_code = record[1][record[1].find("(")+1:record[1].find(")")] if len(area_code) is 10: area_code = area_code[0:4] if area_code not in unique_calls_to: unique_calls_to.append(area_code) if "080" == area_code: # called number is also Bangalore based num_calls_from_080_to_080 += 1 unique_calls_to.sort() print("The numbers called by people in Bangalore have codes:") print(*unique_calls_to, sep="\n") """ Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ percent = 100. * num_calls_from_080_to_080/float(num_calls_from_080) print("{} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.".format(round(percent,2))) """ Reviewer comments: You can convert a list into a set simply by doing set(list_name) later. So if you convert your unique_calls_to list to a set, all the duplicate values will get removed. And you can do this outside of the loop, right at the end, which separates out the need for this check and thereby saves on efficiency since converting a list to a set is not that computationally expensive either compared to the somewhat quadratic complexity you get now (more on this in the analysis file review) """
class Shape(): def area(self): return 0 class Square: def __init__(self,cd): self.cd=cd def area(self,): a=1 return a a=Square(0) a.area() print(a)
# coding: utf-8 # In[187]: # Importing Pandas,Numpy and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns get_ipython().magic('matplotlib inline') # # Question Phase # For this project I come up one question that I'll address in following analysis: # # Q: What's the difference(characteristics) of those people who survived against those didn't? # # Data Wrangling Phase # In[188]: # Load the data into notebook and show the first 5 records for glimpse df = pd.read_csv('titanic-data.csv') df.head() # In[51]: # Take a look at some attributes information df.info() # From above we can see that ticket column is irrelevant to our intention, and cabin column contains so many missing value that it hardly contribute to our final goal (Age column also has the same issue but not that many). So for this project I'd like to take out ticket and cabin column. # # As for those missing values in the data, I plan to use the median of Age to fill those NAs in Age column for the ease of following analysis. And just ignore those 2 NAs in Embarked since there is no way to say which location those 2 people embarked upon the ship. # In[189]: # Execute data cleansing and check df.drop(['Ticket','Cabin'], axis=1) df['Age'] = df['Age'].fillna(df['Age'].median()) df.head() # # Explore & Analysis Phase # I believe the number of women and children(age under 18) who survived is greater than the number of men since women and children should be allowed to escape first for the common practice in accidents. # # And I think the number of survivors in 1st class should be more than those in 2nd and 3rd class respectively since 1st class cabin is closer to the deck. # In[190]: # df now only contains those records with value in Age column! Below codes gives the descriptive statistic result # to get an overview of the processed data df.loc[:,['Age', 'SibSp', 'Parch', 'Fare']][df.Survived==1].describe() # In[191]: df.loc[:,['Age', 'SibSp', 'Parch', 'Fare']][df.Survived==0].describe() # From above we can tell those survivors are about 2 years younger than victims on average, and they spen more for tickets (maybe they were in the 1st class. We'll check about that later), and those who with less relatives are more likely to survive. # # I'll start checking on Sex, Age, Pclass, SibSp, and Parch against survival data (as well as cross check) to tell whether these features affect the odds of survival. # Now let's look into the 1D visualizations for Survived, Pclass, and Sex respectively # In[196]: sns.countplot(x="Survived", data=df) sns.plt.title('Survived Data (1 means survive)') # Number of victims is much higher than survivors # In[199]: sns.countplot(x="Pclass", data=df) sns.plt.title('Count in terms of Pclass') # More people in class than the total of class 1 and 2 # In[198]: sns.countplot(x="Sex", data=df) sns.plt.title('Count in terms of Sex') # In[211]: A lot more men on board than women # In[161]: # To plot the survival data versus Sex Survived_sex = pd.crosstab(df.Sex, df.Survived) Survived_sex.rename(columns={0:'Dead',1:'Survived'},inplace=True) # Add the y label back Survived_sex.plot.bar(figsize=(5,5)).set_ylabel("Number of People") plt.title('Survival Comparision between Sex') # As we can see from above chart, there were a lot more women than men who survived from this tragedy, that may because the "lady and children go first" rule in tragedy. # In[162]: # To plot the survival data versus Age in order to look into the age difference between survivors and victims Survived_age_pclass = pd.crosstab(df.Age, df.Survived) Survived_age_pclass.rename(columns={0:'Dead',1:'Survived'},inplace=True) Survived_age_pclass.plot.line(figsize=(15,6)).set_ylabel("Number of People") plt.title('Survival over age') # It seems people whose age between 20 and 30 are less likely to survive, let's look deeper into the data. # In[91]: # Base on the above chart, try to get a summary from those victims who age between 20 and 30 where people are less # likely to survive df.loc[:,['Pclass', 'Age', 'SibSp', 'Parch', 'Fare']][(df['Age'] >= 20) & (df['Age'] <= 30) & (df['Survived']==0)].describe() # In[164]: # Plot the survival data against selected group to break down the data Survived_age_class = pd.crosstab(df.Pclass[(df['Age'] >= 20) & (df['Age'] <= 30)], df.Survived[(df['Age'] >= 20) & (df['Age'] <= 30)]) Survived_age_class.rename(columns={0:'Dead',1:'Survived'},inplace=True) # Add rot parameter for better reading Survived_age_class.plot.bar(figsize=(10,6), rot=0).set_ylabel("Number of People") # Add some explanation plt.title('Survival among Pclass (Only include passengers age between 20 and 30)') # Seen from the above table and charts, people are less likely to survive not only when their age between 20 and 30, but also when they were in class 3. A simple guess is there were a lot of young immigrants who can only afford a class 3 ticket, trying to get to the state side(This is merely a hypothesis, an additional survey is required to prove it but it beyonds the scope of this project). # # Next I'd like to check the survival rate on children, and since there isn't a column states whether someone is children(age under 18) or not, we need a function to tell if a record was a child or not. And we need a new column to store the information # In[201]: def Child_Classifier(age): # return Children if the person is a child, and Adult otherwise if age < 18: return 'Children' else: return 'Adult' # In[202]: # Create a new column to store the info df['Child'] = df['Age'].apply(Child_Classifier) df.head() # Next I'd like to check # In[203]: # Plot the survival data against selected group to break down the data Children_Sur = pd.crosstab(df.Child, df.Survived) Children_Sur.rename(columns={0:'Dead',1:'Survived'},inplace=True) Children_Sur.plot.bar(figsize=(10,5), rot=0).set_ylabel("Number of People") plt.title('Children Survival Data') # The casualty rate for Adult is much higher than Children group # In[125]: # Now we can check the survival rate over class in terms of whether someone is child, this time I chose to use # another way to plot the data for simplicity sns.factorplot('Pclass',data=df[df.Survived==0],hue='Child',kind='count') # From above we can know that children victims are from class 3 # In[204]: def Alone_Passenger(family): no_of_sipsp, no_of_parch = family no_of_relatives = no_of_sipsp + no_of_parch # Return 'Alone' if alone, 'Have relatives' otherwise if no_of_relatives == 0: return 'Alone' else: return 'Have relatives' # In[205]: # Create a new column to store the alone info, and this time we need to specify axis for apply since there're # 2 columns involved df['Alone'] = df[['SibSp','Parch']].apply(Alone_Passenger, axis = 1) df.head() # In[207]: Alone_Sur = pd.crosstab(df.Alone, df.Survived) Alone_Sur.rename(columns={0:'Dead',1:'Survived'},inplace=True) Alone_Sur.plot.bar(figsize=(10,6),rot=0).set_ylabel("Number of People") plt.title('Family Survival Data') # In[210]: Class_Alone_Sur = pd.crosstab(df.Alone, df.Pclass) #Children_Sur.rename(columns={0:'Dead',1:'Survived'},inplace=True) Class_Alone_Sur.plot.bar(figsize=(10,6),rot=0).set_ylabel("Number of People") plt.title('Alone VS Family') # We can know from above chart that a lot more alone passengers (without any relative on board the ship) lost their lives than those with relative(s), whilst this difference is not that big for survivors. # Code Reference for the project: # # 1. http://pandas.pydata.org/pandas-docs/stable/10min.html#getting # 2. https://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe # 3. http://www.cnblogs.com/jasonfreak/p/5441512.html # 4. http://pandas.pydata.org/pandas-docs/stable/missing_data.html # 5. http://pandas.pydata.org/pandas-docs/stable/visualization.html # # Conclusion # As we can see from above analysis, more women than men survived in this tragedy. And people who age at around 20 and 30 have a lower survival rate than other age groups. # # Children in class 3 also have a higher casualty than those in class 1 and 2, and the same for those people who traveled alone (versus those men with relative(s). The analysis reveals that most of them are in class 3, it might because young immigrants often travel alone. # # Due to some demography info not provided in this dataset, some further analysis are yet to be performed. My analysis only look into some simple statistic into the data. I would like to use logistic regression to build a model and see what features affect the survival rate and try to predict what kind of passenger is more likely to survive. # In[ ]:
def login(): user = input("Username: ") pwd = input("Password: ") if user == "admin" and pwd == "111": showMenu() else: print("Wrong username or password") login() def showMenu(): print("---- Welcome to Shop -----") print("1. Vat Calculator") print("2. Price Calculator") menuSelect() def menuSelect(): userSelected = int(input("Please choose >>")) if userSelected == 1: print("Total Price included VAT =", vatCalculator(int(input("Please enter Total Price: ")))) thankyou() elif userSelected == 2: priceCalculator() else: print("!!!Please select 1 or 2!!!") showMenu() def vatCalculator(totalPrice): vat = 7 result = totalPrice + (totalPrice * vat / 100) return result def priceCalculator(): price1 = int(input("First Product Price: ")) price2 = int(input("Second Product Price: ")) print("Total Price included VAT =", vatCalculator(price1 + price2)) thankyou() def thankyou(): print("Thank you for shopping with us!") login()
#Recordar que en binario comienza en 1---2----4---8---16---32---64---124--256--512---1024 #funcion shift >>,<< #10 es 1010 #a>>1 ,es 101 a=10 b=a>>1 print('Valor entero: {} ,con shift a la derecha: {}'.format(a,b)) print('Valor binario: {},con shift a la derecha: {}'.format(bin(a),bin(b)))
#Permite saber los parametros de una llamada class Callee: def __call__(self, *pargs, **kargs): # Intercept instance calls print('Called:', pargs, kargs) varCalle=Callee() varCalle(1,5,9,s=12,m=122) class Comparacion: data = 'queso' def __gt__(self, other): # 3.X and 2.X version return len(self.data) > len(other) def __lt__(self, other): return len(self.data) < len(other) varComparacion=Comparacion() print(varComparacion < 'hamburgesa') class Truth: def __bool__(self): return True varTruth=Truth() if varTruth: print('yes!') class Life: def __init__(self, name='unknown'): print('Hello ' + name) self.name = name def live(self): print(self.name) def __del__(self): print('Goodbye ' + self.name) lilo = Life('lilo') lilo.live() lilo = 'stich' #Python y OOP tres grandes conceptos. # Inheritance # Encapsulation # Polymorphism #Mangling, FOR Pseudoprivate Attributes #VALID FOR VAR,METHOD,ATRIB INSIDE A CLASS>> __X CONVERTS INTO automatically -> _ClassName__X #UNBOUND AND BOUND METHOD Objects #UNBOUND # object1 = Spam() # t = Spam.doit #CLASS.METHOD # t(object1, 'howdy') #CLASS.METHOD(INSTANCE,ARGUMENT/S) #BOUND # object1 = Spam() # x = object1.doit # x('hello world') #CLASS.METHOD(ARGUMENT/S) class Product: def __init__(self, val): # Bound methods self.val = val #Mangling def __method(self, arg): return self.val * arg def method2(self, arg): return self.val - arg def method3(self, arg): return self.val + arg pobject = Product(2) m=[[],[],[]] actions = [pobject._Product__method,pobject.method2,pobject.method3] [m[x].append(i(j)) for x,i in enumerate(actions) for j in range(10) ] print(m) #factory function, sirve para llamar todo tipo de clases con dif argumentos def factory(aClass, *pargs, **kargs): # Varargs tuple, dict return aClass(*pargs, **kargs) # Call aClass (or apply in 2.X only) pobject2=factory(Product,2) print(pobject2.val)
# Static and Class Methods , en primera instancia sin decoradores.con palabras staticmethod y classmethod #1.METODO ESTATICO, no tengo la necesidad de pasarle como argumento la variable o self a el metodo deseado. # class Spam: # numInstances = 0 # def __init__(self): # Spam.numInstances = Spam.numInstances + 1 # def printNumInstances(): # print("Number of instances created: %s" % Spam.numInstances) # printNumInstances = staticmethod(printNumInstances) # class Sub(Spam): # def printNumInstances(): # Override a static method # print("Extra stuff...") # But call back to original # Spam.printNumInstances() # printNumInstances = staticmethod(printNumInstances) # a=Sub() # b=Sub() # b.printNumInstances() #2.METODO DE CLASE /METODO ESTATICO, definidos ej: smeth = staticmethod(smeth) #3.Metodos CLASE/ESTATICO con decoradores, @staticmethod - @classmethod #cls for the first argument to class methods. #self for the first argument to instance methods. #metodo super(), para llamar las superclases de la clase. class Mx1: def __init__(self): print('estas en MX1') Mx1.imeth(self,self._numero) super().__init__() print('saliste en MX1') def imeth(self, x): print([self, x*x]) class Mx2: def __init__(self): print('estas en MX2') Mx2.imeth(self,self._numero) #No es necesario definir de esta manera , super(Mx2,self).__init__().Cuando ya tenemos object como base super().__init__() print('saliste en MX2') def imeth(self, x): print([self, x+x]) class Methods(Mx2,Mx1): def __init__(self): self._numero=0 @property def imeth(self): #no es necesario instanciarlo, de esta manera super(Methods,self).__init__() .pero es buena practica super().__init__() #tambien podria llamar a todos los metodos imeth() #super().imeth() print('Estas en Methods en MX') return print([self, self._numero]) @imeth.setter def imeth(self, value): print("setter method called") self._numero=value @staticmethod def smeth(x): print([x]) @classmethod def cmeth(cls, x): print([cls.__name__, x]) # smeth = staticmethod(smeth) # cmeth = classmethod(cmeth) #Instancia normal, con decoradores x=Methods() x.imeth=10 x.imeth #Metodo estatico, sin pasar instancia Methods.smeth(55) #Metodo de clase, donde como primer argumento le paso el nombre de la clase base como cls, similar a self para instancias. Methods.cmeth(21) #Como cambiar una instancia de superclase en el runtime #class C(X), en este caso la clase X sera cambiada por el nombreClaseSuper.Entonces class C(nombreClaseSuper) # nombreClase.__bases__ = (nombreClaseSuper,) #para llamar a la primera base de la clase nombreClase.__bases__[0].metodo(self)
#Tuples #Interactive CODE #This function shows the output of the data regardless of the arguments def imprime(dato,*kwargs): print(dato,*kwargs) miTupla=(1,2,3,2,2) imprime(len(miTupla)) #Adicion temporal de dos elementos a la tupla imprime(miTupla+(6,7)) #Mustra la posicion del elemento 2 solo una vez #tambien muestra la cantidad de veces que el elemento se repite imprime(miTupla.index(2),miTupla.count(2)) miTupla = (2,) + miTupla[1:] imprime(miTupla) #La tupla no tiene la funcion append ni pop asociada pero al contener una lista en la posicion 2 #se puede hacer uso de las funciones de listas miTupla = 'spam', 3.0, [11, 22, 33] miTupla[2].append(22) imprime(miTupla)
#INVV-investigar libreria tkinter #eventualmente podria existir un parametro sin *,para usar una funcion osea def example(function,*args,**kwargs) #*args >>> Non-Keyword Arguments , **dict >>> keywords arguments def func(*args,**dict): return [args,dict.items()] diccionario1=dict(kills=8,deaths=5,assist=4) print(func(1,2,3,**diccionario1)) lista1 = [1, [2, [3, 4], 5], 6, [7, 8]] #funcion suma el contenido de una lista sin importar si tiene sublistas.. def sumTree(l1): tot=0 for l in l1: if not isinstance(l,list): tot+=l print(tot) else: tot+=sumTree(l) return tot print(sumTree(lista1)) #Modificacion de cantidad de recursiones permitidas #sys.getrecursionlimit(), 1000 por default # sys.setrecursionlimit(cantidad),permite incrementar la funcion # help(sys.setrecursionlimit) # lectura de documentacion. #Funcion para llamar de manera indirecta a otra pormedio de sus argumentos def echo(m): print(m) def indirect(func, arg): func(arg) indirect(echo, 'Argument call!') #Nombres de variables contenidas en una funcion en especifica(ej:sumTree) print(sumTree.__code__.co_varnames) #Numero de parametros de una funcion. print(sumTree.__code__.co_argcount) #Anotaciones en python parametro: <esperado>, def funcion()->tipo de dato que retorna la funcion #podria establecerse ademas un default value ejemplo: vars: int=6.No es valido para (*)starred expression def anotacionesPrueba(*vars: int) -> int: return sum(vars) print(anotacionesPrueba(1,2,3)) print(anotacionesPrueba.__annotations__) #Anonymous function >>> Lambda #Similarmente en lambda se puede utilizartambien default values def Caballeros(): title = 'Sir' action = (lambda x='Anonymous': title + ' ' + x) return action act = Caballeros() print(act(),act('Camilo')) #Cada elemento x va siendo imprimido despues de utilizar la funcion map showall = lambda x: [print(ele) for ele in x] t = showall(['spam\n', 'toast\n', 'eggs\n']) #Concatenacion de funciones con lambda print(list(filter(lambda x:x>1,range(-5,5)))) from tkinter import Button, mainloop,Frame #Clase para manejo de caracteristicas de ventana tkinter class App(Frame): def __init__(self, master=None): super().__init__(master) self.pack() x = Button( text='Presiona', border=5, height=3, width=10, background='red', command=(lambda:print('Depana '*10,))) #Configuracion de ventana myapp=App() myapp.master.title("Primer interfaz con Tkinter") myapp.master.maxsize(1000, 400) #Enpaqueta el contenido del boton x.pack() # Inicia el programa,en modo consola es opcional. # myapp.mainloop()
# In this assignment you will write a Python program that expands on https://www.py4e.com/code3/urllinks.py. # The program will use urllib to read the HTML from the data files below, extract the href= values from the # anchor tags, scan for a tag that is in a particular position from the top and follow that link, repeat the # process a number of times, and report the last name you find.from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = 'http://py4e-data.dr-chuck.net/known_by_Kael.html' #to repeat 7 times# for i in range(7): html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('a') count = 0 print(url) for tag in tags: count = count +1 #make it stop at position 3# if count>18: break url = tag.get('href', None) print(url)
from collections import deque class MarsRover: RIGHT_ROTATION_DICT = { 'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N' } LEFT_ROTATION_DICT = { 'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N' } def __init__(self, plateau_width: int, plateau_height: int, x: int, y: int, direction: str): self._plateau_width = plateau_width + 1 self._plateau_height = plateau_height + 1 self._x = x self._y = y self._direction = direction self.move = "" @property def x(self): return self._x @property def y(self): return self._y @property def direction(self): return self._direction @direction.setter def direction(self, value): if value not in ['N', 'W', 'E', 'S']: print(f"{value} is wrong! Chosen direction not correct! Please chose from: N, E, W, S") else: self._direction = value def rover_move(self, move): if move == "M": if self.direction == "N": self._y += 1 elif self.direction == "E": self._x += 1 elif self._direction == "W": self._x -= 1 elif self._direction == "S": self._y -= 1 def return_rover_to_previous_position(self): if self.direction == "N": self._y -= 1 elif self.direction == "S": self._y += 1 elif self.direction == "E": self._x -= 1 elif self.direction == "W": self._x += 1 def left_rotate(self): self.direction = self.LEFT_ROTATION_DICT[self._direction] def right_rotate(self): self.direction = self.RIGHT_ROTATION_DICT[self.direction] @staticmethod def print_final_output(output): return f"{output[0][0]} {output[0][1]} {output[0][2]}" def main(): def check_valid_coordinates(x, y, width, height): if (0 <= x < width) and (0 <= y < height): return True return False plateau_width = int(input("Please insert plateau width:")) plateau_height = int(input("Please insert plateau height:")) # TODO Please use only one of the moves lists/arrays provided at a time and put a comment on the others, while you are testing the code! ''' Please use only one of the moves lists/arrays provided at a time and put a comment on the others, while you are testing the code! ''' # moves = [["LMLMLMLMM"], ["MMRMMRMRRM"]] moves = [['RMMMLMMLMM'], ['MMRMMRMRRM']] # moves = ["MMRMMRMRRM"] # moves = [['MMRMM'], ['MMRMMRMRRM']] # moves = ["MMRMMRMRRM"] # moves = ["LLLMMMLMMLMLM"] moves = deque(moves) final_output = [] while moves: x_coordinate = int(input("Please insert the X coordinate:")) y_coordinate = int(input("Please insert the Y coordinate:")) if not check_valid_coordinates(x_coordinate, y_coordinate, plateau_width, plateau_height): print("The chosen coordinates are out of the plateau field." + '\n' f"Please choose X less than " f"{plateau_width} and Y less than {plateau_height}") continue direction = input("Please insert direction from: N, W, E, S") if direction not in ["N", "E", "W", "S"]: print(f"{direction} is wrong! Chosen direction not correct! Please choose from: N, E, W, S") continue mars_rover = MarsRover(plateau_width, plateau_height, x_coordinate, y_coordinate, direction) move_lines = moves.popleft() for move in move_lines[0]: if move == "M": mars_rover.rover_move(move) elif move == "L": mars_rover.left_rotate() elif move == "R": mars_rover.right_rotate() if not check_valid_coordinates(mars_rover.x, mars_rover.y, plateau_width, plateau_height): mars_rover.return_rover_to_previous_position() final_output.append([mars_rover.x, mars_rover.y, mars_rover.direction]) print(mars_rover.print_final_output(final_output)) final_output = [] if __name__ == '__main__': main()
# -*- coding: utf-8 -*- RAT = "rat" OX = "ox" TIGER = "tiger" RABBIT = "rabbit" DRAGON = "dragon" SNAKE = "snake" HORSE = "horse" GOAT = "goat" MONKEY = "monkey" ROOSTER = "rooster" DOG = "dog" PIG = "pig" ANIMALS = [ RAT, OX, TIGER, RABBIT, DRAGON, SNAKE, HORSE, GOAT, MONKEY, ROOSTER, DOG, PIG, ] def round(index): return ANIMALS[index % len(ANIMALS)]
#!/bin/python3 import math import os import random import re import sys """ Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. """ def miniMaxSum(arr): min_element = min(arr) max_element = max(arr) arr.remove(max_element) min_sum = sum(arr) arr.append(max_element) arr.remove(min_element) max_sum = sum(arr) print(min_sum, max_sum) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
import numpy as np from util_funcs import * import matplotlib.pyplot as plt """Implement multi-class classification using Logistic Regression and One-vs-Rest method.""" # Todo: # Read data from .mat format # Implement LR class # Implement one-vs-rest method. class LogisticRegression: def __init__(self, X, num_classes=1): # self.theta = np.random.randn(X.shape[1], num_classes) * 0.1 self.theta = np.zeros((X.shape[1], num_classes), dtype='float') def fit(self, X, y, num_iterations=1000, learning_rate=1): losses = [] for i in range(num_iterations): loss, grad = compute_cost(X, y, self.theta, lambd=1) self.theta = update_parameters(self.theta, grad, learning_rate) if (i % 20 == 0): losses.append(loss) return losses if __name__ == "__main__": np.random.seed(1) np.set_printoptions(suppress=True) # X, y = load_mat_data('ex3data1.mat') X, y = load_txt_data('ex2data2.txt') fig, ax = plt.subplots() ax = plotData(X, y, ax) # one = np.ones((X.shape[0], 1)) # X = np.concatenate((one, X), axis=1) X = map_feature(X[:, 0, np.newaxis], X[:, 1, np.newaxis]) lr = LogisticRegression(X) losses = lr.fit(X, y) ax = plot_decision_boundary(X, y, lr.theta, ax) ax.legend(['y = 1', 'y = 0'], loc='upper right') plt.title('Decision boundary') plt.show()
# A simple Python program to introduce a linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): count = self.head while (count): print(count.data, end= " ") count = count.next # Code execution starts here if __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node("Đầu tiên") second = Node("Thứ hai") third = Node("Thứ ba") ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ ''' llist.printList()
from tkinter import* import sqlite3 import tkinter.messagebox class ATM1(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Select Language",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=480,y=150) #========================= BUTTON =================================================================== button1 = Button(self.mOffsets,font=('bold italic',20),text="English",bg="yellow",fg="blue",height=1,width=20,command=CALL2) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="हिन्दी",bg="yellow",fg="blue",height=1,width=20) button2.place(x=1005,y=500) button9 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button9.place(x=1005,y=600) #==============================================enter pin for withdraw===================================================== class ATM2(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() #========================================================================== lblInfo=Label(self.mOffsets ,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets ,font=('arial',40),text="Please Enter Your Pin",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=430,y=150) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets ,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=520,y=320) button1 = Button(self.mOffsets ,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL3) button1.place(x=1005,y=500) button2 = Button(self.mOffsets ,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #===========================================================main menu two===================================================== class ATM3(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('arial',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Select Transaction",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=450,y=150) #========================= BUTTON =================================================================== button1 = Button(self.mOffsets,font=('bold italic',20),text="DEPOSIT",bg="yellow",fg="blue",height=1,width=20,command=CALL16) button1.place(x=30,y=300) button2 = Button(self.mOffsets,font=('bold italic',20),text="TRANSFER",bg="yellow",fg="blue",height=1,width=20,command=CALL14) button2.place(x=30,y=400) button3 = Button(self.mOffsets,font=('bold italic',20),text="PIN CHANGE",bg="yellow",fg="blue",height=1,width=20,command=CALL7) button3.place(x=30,y=500) button4 = Button(self.mOffsets,font=('bold italic',20),text="CHANGE ACC. DETAIL",bg="yellow",fg="blue",height=1,width=20,command=CALL15) button4.place(x=30,y=600) button5 = Button(self.mOffsets,font=('bold italic',20),text="FAST CASH",bg="yellow",fg="blue",height=1,width=20) button5.place(x=1005,y=300) button6 = Button(self.mOffsets,font=('bold italic',20),text="CASH WITHDRAWAL",bg="yellow",fg="blue",height=1,width=20,command=CALL4) button6.place(x=1005,y=400) button7 = Button(self.mOffsets,font=('bold italic',20),text="BALANCE INQ.",bg="yellow",fg="blue",height=1,width=20,command=CALL11) button7.place(x=1005,y=500) button8 = Button(self.mOffsets,font=('bold italic',20),text="ACC. DETAIL CHECK",bg="yellow",fg="blue",height=1,width=20,command=CALL20) button8.place(x=1005,y=600) #================================================= Quit Button =================================================== button9 = Button(self.mOffsets,font=('bold italic',20),text="CANCEL",bg="yellow",fg="blue",height=1,width=20,command = exit1) button9.place(x=510,y=600) #=========================================================withdraw current and saving========================================================= class ATM4(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) button1 = Button(self.mOffsets,font=('bold italic',20),text="From Current",bg="yellow",fg="blue",height=1,width=20,command = CALL5) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="From Saving",bg="yellow",fg="blue",height=1,width=20,command = CALL5) button2.place(x=1005,y=500) #======================================================withdraw amount============================================================ class ATM5(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY WITHDRAW",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=430,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Pin Number :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="Withdrawal Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password10,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=430,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount10,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=430,y=420) button1 = Button(self.mOffsets,font=('bold italic',20),text="Withdraw",bg="yellow",fg="blue",height=1,width=20,command=Update3) button1.place(x=1005,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command=CALL6) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command=exit1) button2.place(x=1005,y=600) #==========================================================withdraw transaction process======================================================== class ATM6(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) #=========================================================pin change process======================================================= class ATM7(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="YOU CAN CHANGE YOUR PIN",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=310,y=150) #========================= BUTTON =================================================================== lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No.:",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=390) lblInfo1=Label(self.mOffsets,font=('arial',30),text="New Pin :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=490) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Renter New : \nPin",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=590) entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account5,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=320,y=400) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password5,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=320,y=500) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=320,y=600) button1 = Button(self.mOffsets,font=('bold italic',20),text="Submit",bg="yellow",fg="blue",height=1,width=20,command = Update1) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL8) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #===================================================pin changed sucessfull============================================================== class ATM8(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Pin Has Changed ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=420,y=150) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Log In With New Pin",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=360,y=280) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #=======================================================deposite transaction process========================================================== class ATM10(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your amount has been deposited in your account",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=130,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #======================================================balance inquiary process=========================================================== class ATM11(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Balance Inquery ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=480,y=130) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Please Enter Your Pin Number : ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=100,y=300) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Your Transaction is being processed .... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=100,y=410) lblInfo1=Label(self.mOffsets,font=('arial',30),text="your current Account balance is :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=100,y=510) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password21,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=780,y=310) entry4=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount23,bd=10,insertwidth=8,bg="yellow",justify='left') entry4.place(x=480,y=600) button1 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = Update5) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #==================================================registration form=============================================================== class ATM12(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="REGISTRATION FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=400,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="First Name :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',30),text="Password :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) lblInfo4=Label(self.mOffsets,font=('arial',30),text="Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo4.place(x=50,y=608) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account1,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Firstname1,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password1,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) entry4=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount1,bd=10,insertwidth=8,bg="yellow",justify='left') entry4.place(x=420,y=620) button1 = Button(self.mOffsets,font=('bold italic',20),text="Submit",bg="yellow",fg="blue",height=1,width=20,command = Insert) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #========================================================registration successfull========================================================= class ATM13(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',30),text="REGISTRATION SUCCESSFULL",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=385,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Please Again Log In",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=500,y=250) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #==================================================transfer form=============================================================== class ATM14(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY TRANSFER",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=450,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="From Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="To Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',30),text="Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account13,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account14,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount15,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) button1 = Button(self.mOffsets,font=('bold italic',20),text="Transfer",bg="yellow",fg="blue",height=1,width=20,command = Update4) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL18) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #============================================detail change============================================================= class ATM15(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="DETAILED UPDATION FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=300,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Old Acc. No.:",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="First Name :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',30),text="Password :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account3,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Firstname3,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password3,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) button1 = Button(self.mOffsets,font=('bold italic',20),text="Update",bg="yellow",fg="blue",height=1,width=20,command = Update) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button2.place(x=1005,y=600) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=700) #=============================================Deposit menu======================================================= class ATM16(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="MONEY DEPOSIT FORM",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=370,y=150) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="Deposit Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account7,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=430,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount7,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=430,y=420) button1 = Button(self.mOffsets,font=('bold italic',20),text="Deposit",bg="yellow",fg="blue",height=1,width=20,command=Update2) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command=CALL10) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="No",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #=======================================================Transfer transaction process========================================================== class ATM18(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your Transaction is being processed",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=270,y=200) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Please Wait ..... ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=530,y=300) lblInfo1=Label(self.mOffsets,font=('arial',40),text="Your amount has been transfered in another account",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=130,y=400) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #======================================================Services process=========================================================== class ATM19(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="WELCOME TO STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=200,y=50) lblInfo1=Label(self.mOffsets,font=('arial',20),text="Welcome to State Bank Of India. State Bank Of India Is Most Popular Bank Of India.",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=170,y=200) lblInfo1=Label(self.mOffsets,font=('arial',20),text="We Are Providing Many Facilites Like Money Transfer,Cash Withdrwal,Mini Statement, ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=160,y=240) lblInfo1=Label(self.mOffsets,font=('arial',20),text="Balance Inquiry,Cash Deposit,you Can Also Open Your Account.you Can Change Your Pin,\n Update your Account Detail. ",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=140,y=280) button1 = Button(self.mOffsets,font=('bold italic',20),text="Log In",bg="yellow",fg="blue",height=1,width=20,command = CALL1) button1.place(x=1005,y=500) button2 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button2.place(x=1005,y=600) #==================================================registration form=============================================================== class ATM20(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(self.mOffsets,font=('bold italic ',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo=Label(self.mOffsets,font=('bold italic ',40),text="Account Details",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=500,y=130) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Enter Your Pin :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=208) lblInfo1=Label(self.mOffsets,font=('arial',30),text="Account No. :",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=50,y=308) lblInfo2=Label(self.mOffsets,font=('arial',30),text="First Name :",fg="white",bg="blue",bd=10,anchor='w') lblInfo2.place(x=50,y=408) lblInfo3=Label(self.mOffsets,font=('arial',30),text="Password :",fg="white",bg="blue",bd=10,anchor='w') lblInfo3.place(x=50,y=508) lblInfo4=Label(self.mOffsets,font=('arial',30),text="Amount :",fg="white",bg="blue",bd=10,anchor='w') lblInfo4.place(x=50,y=608) #========================= BUTTON =================================================================== entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password25,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=220) entry1=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Account26,bd=10,insertwidth=8,bg="yellow",justify='left') entry1.place(x=420,y=320) entry2=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Firstname27,bd=10,insertwidth=8,bg="yellow",justify='left') entry2.place(x=420,y=420) entry3=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Password28,bd=10,insertwidth=8,bg="yellow",justify='left') entry3.place(x=420,y=520) entry4=Entry(self.mOffsets,font=('arial',24,'bold'),textvar=Amount29,bd=10,insertwidth=8,bg="yellow",justify='left') entry4.place(x=420,y=620) button1 = Button(self.mOffsets,font=('bold italic',20),text="Check",bg="yellow",fg="blue",height=1,width=20,command = Update6) button1.place(x=1005,y=400) button2 = Button(self.mOffsets,font=('bold italic',20),text="Procced",bg="yellow",fg="blue",height=1,width=20,command = CALL13) button2.place(x=1005,y=500) button3 = Button(self.mOffsets,font=('bold italic',20),text="Cancel",bg="yellow",fg="blue",height=1,width=20,command = exit1) button3.place(x=1005,y=600) #===================================================function call=============================================== def CALL1(): atm = ATM1(root) def CALL2(): atm = ATM2(root) def CALL3(): atm = ATM3(root) def CALL4(): atm = ATM4(root) def CALL5(): atm = ATM5(root) def CALL6(): atm = ATM6(root) def CALL7(): atm = ATM7(root) def CALL8(): atm = ATM8(root) def CALL9(): atm = ATM9(root) def CALL10(): atm = ATM10(root) def CALL11(): atm = ATM11(root) def CALL12(): atm = ATM12(root) def CALL13(): atm = ATM13(root) def CALL14(): atm = ATM14(root) def CALL15(): atm = ATM15(root) def CALL16(): atm = ATM16(root) def CALL17(): atm = ATM17(root) def CALL18(): atm = ATM18(root) def CALL19(): atm = ATM19(root) def CALL20(): atm = ATM20(root) #==============================================================main menu===================================== root = Tk() root.geometry("1400x900+0+0") root.title("STATE BANK OF INDIA") root.configure(bg='blue') #==========================================create table ========================================================= db=sqlite3.connect('ATM.db') cursor=db.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS ATMDATA(AccountNumber TEXT,FirstName TEXT,Password TEXT,Amount TEXT)") db.commit() #========================================insert data in table ========================================================== Account1=StringVar() Firstname1=StringVar() Password1=StringVar() Amount1=StringVar() def Insert(): Account2=Account1.get() Firstname2=Firstname1.get() Password2=Password1.get() Amount2=Amount1.get() ins=sqlite3.connect('ATM.db') with ins: cursor=ins.cursor() cursor.execute('INSERT INTO ATMDATA(AccountNumber,FirstName,Password,Amount) VALUES(?,?,?,?)',( Account2,Firstname2,Password2,Amount2)) db.close() #=======================================================update data in tabble ============================================= Account3=StringVar() Firstname3=StringVar() Password3=StringVar() def Update(): Account4=Account3.get() Firstname4=Firstname3.get() Password4=Password3.get() up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET FirstName = ? ,Password = ? WHERE AccountNumber = ?",(Firstname4,Password4,Account4)) up.commit() #================================================update pin ================================================================== Account5=StringVar() Password5=StringVar() def Update1(): Account6=Account5.get() Password6=Password5.get() up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Password = ? WHERE AccountNumber = ?",(Password6,Account6)) up.commit() #================================================Deposit money ================================================================== Account7=StringVar() Amount7=StringVar() def Update2(): Account8=Account7.get() Amount8=Amount7.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE AccountNumber = ?",(Account8,)) row=cursor.fetchone() Amount9=int(row[3])+int(Amount8) up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE AccountNumber = ?",(int(Amount9),Account8)) up.commit() #================================================Withdraw money ================================================================== Password10=StringVar() Amount10=StringVar() def Update3(): Password11=Password10.get() Amount11=Amount10.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE Password = ?",(Password11,)) row=cursor.fetchone() Amount12=int(row[3])-int(Amount11) up=sqlite3.connect('ATM.db') cursor=up.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE Password = ?",(int(Amount12),Password11)) up.commit() #================================================Transfer money ================================================================== Account13=StringVar() Account14=StringVar() Amount15=StringVar() def Update4(): Account16=Account13.get() Account17=Account14.get() Amount18=Amount15.get() #===============================================from account======================================================== up2=sqlite3.connect('ATM.db') cursor=up2.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE AccountNumber = ?",(Account16,)) row=cursor.fetchone() Amount19=int(row[3])-int(Amount18) up3=sqlite3.connect('ATM.db') cursor=up3.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE AccountNumber = ?",(int(Amount19),Account16)) up3.commit() #===============================================to account===================================================== up4=sqlite3.connect('ATM.db') cursor=up4.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE AccountNumber = ?",(Account17,)) row=cursor.fetchone() Amount20=int(row[3])+int(Amount18) up5=sqlite3.connect('ATM.db') cursor=up5.cursor() cursor.execute("UPDATE ATMDATA SET Amount = ? WHERE AccountNumber = ?",(int(Amount20),Account17)) up5.commit() #================================================Balance inq. ================================================================== Password21=StringVar() Amount22=StringVar() Amount23=StringVar() def Update5(): Password24=Password21.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE Password = ?",(Password24,)) row=cursor.fetchone() Amount22=row[3] Amount23.set(Amount22) #================================================Account Detail ================================================================== Password25=StringVar() Account26=StringVar() Firstname27=StringVar() Password28=StringVar() Amount29=StringVar() def Update6(): Password34=Password25.get() up1=sqlite3.connect('ATM.db') cursor=up1.cursor() cursor.execute("SELECT * FROM ATMDATA WHERE Password = ?",(Password34,)) row=cursor.fetchone() Account30=row[0] Account26.set(Account30) Firstname31=row[1] Firstname27.set( Firstname31) Password32=row[2] Password28.set(Password32) Amount33=row[3] Amount29.set(Amount33) #===================================main menu ==================================================================== def exit1(): tkinter.messagebox.showinfo('window Title','Do you want to close') answer = tkinter.messagebox.askquestion('Question 1','Yes for Quit and NO for Continue') if answer == 'yes': root.destroy() lblInfo=Label(root,font=('arial',50),text="STATE BANK OF INDIA",fg="white",bg="blue",bd=10,anchor='w') lblInfo.place(x=320,y=20) lblInfo1=Label(root,font=('arial',40),text="Please Select Banking",fg="white",bg="blue",bd=10,anchor='w') lblInfo1.place(x=420,y=150) #========================= BUTTON =================================================================== button1 = Button(root,font=('bold italic',20),text="SERVICES",bg="blue",fg="white",height=1,width=20,command = CALL19) button1.place(x=30,y=300) button2 = Button(root,font=('bold italic',20),text="MINI STATEMENT",bg="blue",fg="white",height=1,width=20,command = CALL20) button2.place(x=30,y=400) button3 = Button(root,font=('bold italic',20),text="REGISTRATION",bg="blue",fg="white",height=1,width=20,command = CALL12) button3.place(x=30,y=500) button4 = Button(root,font=('bold italic',20),text="QUICK CASH",bg="blue",fg="white",height=1,width=20) button4.place(x=30,y=600) button5 = Button(root,font=('bold italic',20),text="BANKING",bg="blue",fg="white",height=1,width=20,command = CALL1) button5.place(x=1005,y=300) button6 = Button(root,font=('bold italic',20),text="BALANCE INQ.",bg="blue",fg="white",height=1,width=20,command = CALL1) button6.place(x=1005,y=400) button7 = Button(root,font=('bold italic',20),text="TRANSFER",bg="blue",fg="white",height=1,width=20,command = CALL1) button7.place(x=1005,y=500) button8 = Button(root,font=('bold italic',20),text="PIN GENERATION",bg="blue",fg="white",height=1,width=20) button8.place(x=1005,y=600) #================================================= Quit Button =================================================== button9 = Button(root,font=('bold italic',20),text="Cancel",bg="blue",fg="white",height=1,width=20,command = exit1) button9.place(x=510,y=600) root.mainloop()
# import the python testing framework import unittest, math # our "unit" # this is what we are running our test on def reverseList(array): for index in range(math.floor(len(array)/2)): array[index], array[len(array)-index-1] = array[len(array)-index-1], array[index] return array def isPalindrome(word): palindromeFlag = True for index in range(math.floor(len(word)/2)): if word[index] != word[len(word)-index-1]: palindromeFlag = False return palindromeFlag def coin(cents): change = [] change.append(math.floor(cents/25)) cents %= 25 change.append(math.floor(cents/10)) cents %= 10 change.append(math.floor(cents/5)) cents %= 5 change.append(math.floor(cents)) return change def factorial(number): if number <= 1: return 1 return number*factorial(number-1) def fib(number): if number == 1: return 0 if number == 2: return 1 return fib(number-2)+fib(number-1) # our "unit tests" # initialized by creating a class that inherits from unittest.TestCase class reverseListTest(unittest.TestCase): def test1(self): return self.assertEqual(reverseList([1,3,5]), [5,3,1]) def test2(self): return self.assertEqual(reverseList([2,4,-3]), [-3,4,2]) def test3(self): return self.assertEqual(reverseList([2,4,-3,5]), [5,-3,4,2]) class isPalindromeTest(unittest.TestCase): def test1(self): return self.assertEqual(isPalindrome("racecar"), True) def test2(self): return self.assertEqual(isPalindrome("rabbit"), False) def test3(self): return self.assertEqual(isPalindrome("mirror"), False) def test4(self): return self.assertEqual(isPalindrome("mom"), True) def test5(self): return self.assertEqual(isPalindrome("hannah"), True) class coinTest(unittest.TestCase): def test1(self): return self.assertEqual(coin(87), [3,1,0,2]) def test2(self): return self.assertEqual(coin(92), [3,1,1,2]) def test3(self): return self.assertEqual(coin(99), [3,2,0,4]) def test4(self): return self.assertEqual(coin(23), [0,2,0,3]) def test5(self): return self.assertEqual(coin(43), [1,1,1,3]) class factorialTest(unittest.TestCase): def test1(self): return self.assertEqual(factorial(1), 1) def test2(self): return self.assertEqual(factorial(0), 1) def test3(self): return self.assertEqual(factorial(2), 2) def test4(self): return self.assertEqual(factorial(3), 6) def test5(self): return self.assertEqual(factorial(4), 24) def test6(self): return self.assertEqual(factorial(5), 120) class fibTest(unittest.TestCase): def test1(self): return self.assertEqual(fib(1), 0) def test2(self): return self.assertEqual(fib(2), 1) def test3(self): return self.assertEqual(fib(3), 1) def test4(self): return self.assertEqual(fib(4), 2) def test5(self): return self.assertEqual(fib(5), 3) def test6(self): return self.assertEqual(fib(6), 5) def test7(self): return self.assertEqual(fib(7), 8) def test8(self): return self.assertEqual(fib(8), 13) def test9(self): return self.assertEqual(fib(9), 21) def test10(self): return self.assertEqual(fib(10), 34) if __name__ == '__main__': unittest.main() # this runs our tests
import re def contains_gold(bags): containing_gold = set() def search_for_gold(bag_colour='shiny gold'): for bag in bags: if bag_colour in bags[bag]: containing_gold.add(bag) search_for_gold(bag) search_for_gold() return len(containing_gold) def quantity_of_gold(bags): def search_for_gold(bag_colour='shiny gold'): count = 1 for inner_bag in bags[bag_colour]: multiplier = bags[bag_colour][inner_bag] count += multiplier * search_for_gold(inner_bag) return count return search_for_gold() - 1 def load_data(file_path): with open(file_path) as f: return_bags = {} for line in f: line = line.replace('bags', '') line = line.replace('bag', '') line = line.replace('.', '') line_split = re.split(',|contain', line) bags = [bag.strip() for bag in line_split] current_bag = {} for bag in bags[1:]: if bag == 'no other': return_bags[bags[0]] = {} continue bag_parts = bag.split(' ', 1) current_bag[bag_parts[1]] = int(bag_parts[0]) return_bags[bags[0]] = current_bag return return_bags data = load_data('advent-of-code-2020/data/day_7_input.txt') contains_gold_answer = contains_gold(data) print('Answer contains gold -> {}'.format(contains_gold_answer)) quantity_of_gold_answer = quantity_of_gold(data) print('Answer quantity of gold -> {}'.format(quantity_of_gold_answer))
import argparse from cache import Cache, Query from memoria import Memoria """ Entrada: um arquivo .txt, obtido dos argumentos, com as instruções Saída: outro arquivo .txt, com os resultados das instruções, opcional (padrão=out.txt) """ def main(): # Lê os argumentos para obter nome dos arquivos de entrada e saída parser = argparse.ArgumentParser() parser.add_argument("arq_entrada", help="Nome arquivo entrada") parser.add_argument( "-s", "--arquivo-saida", action="store", type=str, dest="arq_saida", help="(Opcional) Nome arquivo saída", default="out.txt" ) args = parser.parse_args() # Inicialização do sistema cache = Cache() memoria = Memoria() # Leitura e Processamento qtd_misses = 0 qtd_hits = 0 qtd_reads = 0 qtd_writes = 0 linhas_lidas = [] #Para impressão na saída with open(args.arq_entrada, "r") as in_file: for line in in_file.readlines(): # Tratamento da linha temp = ' '.join(line.split()) #Junta espaços múltiplos info = temp.split(' ') #Separa por espaços # Extrai as informações endereco = int(info[0]) op = int(info[1]) assert ((op == 0) or (op == 1)) == True if (op == 1): dado = info[2] qtd_writes += 1 elif (op == 0): qtd_reads += 1 # Processamento if (op == 1): result = "W" hit_or_miss, palavra = cache.busca(endereco) bloco = cache.read_bloco(endereco) if (hit_or_miss == Query.MISS): # Se o bloco estiver sujo, escreve o dado na memória if bloco.get_sujo(): memoria.write_bloco(bloco) # Lê o bloco da memória para a cache cache.write_from_memory(endereco, memoria.get_bloco(endereco)) # Escreve o dado no bloco da cache e marca como sujo. cache.write_from_input(endereco, dado) elif (op == 0): hit_or_miss, palavra = cache.busca(endereco) if (hit_or_miss == Query.MISS): result = "M" qtd_misses += 1 # Busca o bloco na cache bloco = cache.read_bloco(endereco) # Se o bloco estiver sujo, escreve o dado na memória if bloco.get_sujo(): memoria.write_bloco(bloco) # Lê da memória para a cache e marca o bit como não sujo. cache.write_from_memory(endereco, memoria.get_bloco(endereco)) else: result = "H" qtd_hits += 1 # Armazenamento para impressão na saída line = line.strip() #Remove o newline do final da linha linhas_lidas.append((line.strip(),result)) # Saída with open(args.arq_saida, "w") as out_file: out_file.write(f"READS: {qtd_reads}\n") out_file.write(f"WRITES: {qtd_writes}\n") out_file.write(f"HITS: {qtd_hits}\n") out_file.write(f"MISSES: {qtd_misses}\n") out_file.write(f"HIT RATE: {float(qtd_hits) / qtd_reads}\n") out_file.write(f"MISS RATE: {float(qtd_misses) / qtd_reads}\n") out_file.write("\n") for pair in linhas_lidas: out_file.write(f"{pair[0]} {pair[1]}\n") if __name__ == "__main__": main()
#!/usr/local/bin/python from time import time fn = 'files/3-1.txt' def read_and_split_file_lines(filename): """Splits input into lines""" with open(filename) as f: lines = f.readlines() split_lines = [line.strip() for line in lines] vectors_1 = split_lines[0].split(',') vectors_2 = split_lines[1].split(',') return vectors_1, vectors_2 def read_directives(list): """Separates vector into direction and distance stored in tuple""" directives = [] for vector in list: direction = vector[0].lower() distance = int(vector[1:]) directives.append([direction, distance]) return directives def perform_directives(dir_list): """Runs the directive from list of tuples""" position = [0,0] position_list = [] for directive in dir_list: if directive[0] == 'r': for i in range(directive[1]): position = (position[0], position[1] + 1) position_list.append(position) elif directive[0] == 'l': for i in range(directive[1]): position = (position[0], position[1] - 1) position_list.append(position) elif directive[0] == 'u': for i in range(directive[1]): position = (position[0] + 1, position[1]) position_list.append(position) else: for i in range(directive[1]): position = (position[0] - 1, position[1]) position_list.append(position) print(f"Length of wire: {len(position_list)}") return position_list def test_for_equivalents(positions_1, positions_2): shared_positions = [] spos_index_1 = [] spos_index_2 = [] for position in positions_1: if position in positions_2: shared_positions.append(position) spos_index_1.append(positions_1.index(position)) spos_index_2.append(positions_2.index(position)) return shared_positions, spos_index_1, spos_index_2 def find_shortest_distance(shared_list): shortest = False for position in shared_list: distance = abs(position[0]) + abs(position[1]) if not shortest or abs(distance) < shortest: shortest = abs(distance) return shortest def find_earliest_shared(ind1, ind2): sum_ind = [] for i in range(len(ind1)): sum_ind.append(ind1[i] + ind2[i]) print(min(sum_ind)+2) start = time() dir_1, dir_2 = read_and_split_file_lines(fn) directives_1 = read_directives(dir_1) directives_2 = read_directives(dir_2) pos1 = perform_directives(directives_1) pos2 = perform_directives(directives_2) shared, sind_1, sind_2 = test_for_equivalents(pos1, pos2) shortest = find_shortest_distance(shared) print(shortest) find_earliest_shared(sind_1, sind_2) end = time() print(f"Time: {end - start}") """ file_lines = read_and_split_file_lines(fn) vectors_1 = write_line_to_list(file_lines[0]) vectors_2 = write_line_to_list(file_lines[1]) """
# # consider this previously common Python code # f = None # try: # f = open('some_file.txt') # # do stuff with f like read the file # finally: # if f: # f.close() # # The above code can be changed to read like this with the 'with' keyword # # allows you to not have to write try/finally blocks everywhere you want to access some # # resource whose connection needs to be closed, connections like those to files and databases. # with open('some_file.txt') as f: # pass # # do stuff with f like read the file # # f is now scoped only to the with block # # The with keyword expects two "dunder" methods on the object created with the "with". # # These objects are Context managers and the methods are named __enter__ and __exit__ # # __enter__ only takes in arg self to set up data (context) necessary # # __ exit__ takes in type (of exception raised), value (the actual exception expression) # # itself, and traceback (stacktrace of the exception raised) # class WithLogger: # def __enter__(self): # print("2. In __enter__") # return self # def __exit__(self, type, value, traceback): # print("4. In __exit__", type, value) # return True # print("1. Before with") # with WithLogger() as logger: # print("3. In with block") # print("5. After with") # # Prints... # # 1. Before with # # 2. In __enter__ # # 3. In with block # # 4. In __exit__ None None # # 5. After with # print("Before with") # with WithLogger() as logger: # raise Exception("OMG!") # print("After with") # # Prints... # # 1. Before with # # 2. __enter__ # # 4. __exit__ <class 'Exception'> OMG! # # 5. After with # # When you return True from the __exit__ method, your code indicates to the Python # # runtime that everything is ok. If you return False, then Python will continue raising # # the error for other try blocks to intercept and handle.
# # Lists # friends = ['derek', 'kyle', 'robby', 'gabe'] # print(friends[1]) # print(friends[-1]) # print(friends[:-1]) # print(friends[1:]) # print(friends[::2]) # # functions that mutate the list # supplies = ['crayons', 'pencil', 'paper', 'Kleenex', 'eraser'] # supplies.append('markers') # print(supplies) # supplies.remove('pencil') # print(supplies) # supplies.sort() # print(supplies) # # sorts with capital letters first # supplies.sort(key=str.lower) # print(supplies) # # applies this function to each item for sorting purposes # # functions that don't mutate original copy # colors = ['red', 'orange', 'blue', 'pink'] # alphabetical = sorted(colors) # reversed_colors = list(reversed(colors)) # print(colors) # print(alphabetical) # print(reversed_colors) # # Tuples # # Just like lists except are immutable # a = (1, 3, 2, 6, 4, 8, 7, 5) # b = ('apple', 'banana', 'orange', 'grape', 'pear') # # sort alphabetically with sorted() which will automatically cast to a list # alpha_b = tuple(sorted(b)) # print(alpha_b) # # functions can return tuples of data with the return statement # scores = (92, 59, 80, 77, 89, 95, 100, 91) # def min_max(nums): # return min(nums), max(nums) # (lowest, highest) = min_max(scores) # print(lowest) # print(highest) # # declare a single item tuple with a trailing comma # single = (1,) # other_single = ('a',) # # Ranges # # a set of integers: range(start, end, step) end is exclisive # items = ['a', 'b', 'c'] # for i in range(len(items)): # print(i, items[i]) # # dictionaries # book = { # 'title': 'Goodnight Moon', # 'rating': 7642, # 'stars': 4.8, # 'author': { # 'first_name': 'Margaret', # 'last_name': 'Wise Brown' # }, # 'pictures': ['goodnightmoon1.png', 'goodnightmoon2.png'], # } # print(len(book)) # del book['stars'] # print(book) # book['stars'] = 4.8 # print(book) # for i in book: # print(i, book[i]) # # Dict function parameter options # pond = dict(depth=10, area='210 square feet', fish=['Mary', 'Bob', 'Carlos']) # print(pond) # alligators = dict([ # ('lifespan', 50), # ('length', 3.4), # ('species', ['American Alligator', 'Chinese Alligator']), # ]) # print(alligators) # keys = ['name', 'homeruns', 'rbis', 'hits'] # values = ['Babe Ruth', 850, 5551, 7612] # player = dict(zip(keys, values)) # print(player) # print(dir(player)) # # Set # # A group of elements in which each is unique # # Work with sets using operators &, |, -, ^ # # | or union() combines the two sets # # & or intersection() returns the elements found in both sets # # - or difference() returns the elements not found in the second set # # ^ or symmetric_difference() returns the elements found in exactly one set # a = set('banana') # b = set('scarab') # print(a.union(b)) # print(a.intersection(b)) # print(a.difference(b)) # print(a.symmetric_difference(b)) # fruit = ['apple', 'banana', 'grape', 'orange', 'banana', 'apple', 'pear'] # fruit = set(fruit) # print(fruit) # # e-commerce example # purchase_emails = ['bob@gmail.com', 'sam@yahoo.com', 'riley@email.com'] # support_emails = ['joe@live.com', 'bob@gmail.com', 'sam@yahoo.com'] # print('Users who made a purchase and also called the help desk') # print(set(purchase_emails) & set(support_emails)) # # Blog hashtag example # posts = [ # {'title': 'All About Lists', 'tags': ('fun', 'informative', 'lists')}, # {'title': 'Tuple Trouble', 'tags': ('fun', 'tuples')}, # {'title': 'Sparkling Sets', 'tags': ('informative', 'numbers')}, # ] # all_tags = [] # for i in range(len(posts)): # print(posts[i]['tags']) # all_tags.extend(posts[i]['tags']) # all_tags = list(set(all_tags)) # print(sorted(all_tags)) # # Custom sorting # users = [ # {'id': 14235, 'display_name': 'JoeSmith', 'email': 'joe.smith@email.com'}, # {'id': 32451, 'display_name': 'BobJones', 'email': 'bobjones@yahoo.com'}, # {'id': 52243, 'display_name': 'AlexChen', 'email': 'alexchen1@gmail.com'}, # ] # def sorter(user): # return user['display_name'] # users.sort(key=sorter) # print(users) # print(sorted(users, key=sorter, reverse=True))
'''Determine Body Mass Index (BMI)''' import sys import speaking import docx #----------------------------------------------------------------------- print(f"\n----------Program Start----------\n") #----------------------------------------------------------------------- print(f"Hello! Welcome...\n") print(f"I can tell you your BMI if you are " "ready to give me some basic information about yourself. " "Additionally, If you give me your blood Pressure measurement," "I can provide you with some essential advise on keeping healthy.\n") print(f"\npress q to quit") print(f"\nFirst, let me get to know you...\n") f_name = input("What is your name: ") #----------------------------------------------------------------------- # Capture name and age #----------------------------------------------------------------------- if f_name.lower() == 'q': sys.exit() while True: try: age = int(input("\nHow old are you? ")) break except ValueError: print(f"\nI do not recognize that as a valid age. Please enter" "your age.") continue #----------------------------------------------------------------------- # Set the loop for collecting weight and height measurements #----------------------------------------------------------------------- status0 = True while status0: try: print(f"\nHey {f_name.title()}! would you like to see how useful" " I can be? Enter (1) or (2)\n") proceed = int(input(f"YES(1) or NO(2): ")) options1, options2 = [1, 2,], ['q'] ##try: if proceed in options1: if proceed == 1: print(f"\nLet's begin with your weight...") print(f"\nWhat unit would you like to use? ") print(f"Please press q to quit\n") print(f"\t--kg/m-- or --lbs/feet--") print(f"\t (1) or (2) \n") ## while True: try: prompt = "Please enter (1) for kg or (2) for lbs: " unit = int(input(prompt)) if unit in options1: if unit == 1: weight_unit = 'kg' height_unit = 'm' weight = float(input(f"\nPlease enter your weight in kilograms: ")) height = float(input(f"\nPlease enter your height in meters: ")) bmi = (weight)/(height**2) print(f"\nHere are your details: ") print(f"\n\tName: {f_name.title()}\n\tAge: {age}\n\tWeight: {weight}{weight_unit}\n\tHeight: {height}{height_unit}\n") print(f"\t---------\n\tBMI: {round(bmi, 2)}kg/m2\n\t----------") #break if unit == 2: weight_unit = 'lbs' height_unit = 'feet' weight = float(input(f"\nPlease enter your weight in pounds: ")) height = float(input(f"\nPlease enter your height in feet: ")) weight_in_kilos = weight/2.205 height_in_meters = height/3.281 bmi = (weight_in_kilos)/(height_in_meters**2) print(f"Here are your details: ") print(f"\n\tName: {f_name.title()}\n\tAge: {age}\n\tWeight: {weight}{weight_unit}\n\tHeight: {height}{height_unit}\n") print(f"\t---------\n\tBMI: {round(bmi, 2)}kg/m2\n\t----------") #break else: print(f"Incorrect input. Please try again.\n") continue except: print(f"Oops, that is not a valid input. Please re-try.") elif proceed == 2: print(f"Sad to see you leave :( Goodbye and have a healthy" " day.") status0 = False elif proceed not in options1: if proceed > 2: print(f"Invalid input.") except: print(f"\nInvalid input.\n") break if proceed == 2: sys.exit() #----------------------------------------------------------------------- # Request of blood pressure data #----------------------------------------------------------------------- status1 = True while status1: try: print(f"\nWould you like to add your blood pressure? " "It would help me give you a comprehensive advice") options = [1, 2] bp_option = int(input(f"\nYes(1) or No(2): ")) if bp_option in options: if bp_option == 1: print("Ok\n") sbp = int(input("Please enter your systolic blood pressure: ")) dbp = int(input("Please enter your diastolic blood pressure: ")) break if bp_option == 2: print(f"\nOk") sbp = 0 dbp = 0 status1 = False except: print(f"\nPlease select or enter a valid response") #----------------------------------------------------------------------- # BMI and Blood Pressure notes/advice categorised #----------------------------------------------------------------------- file = docx.Document("BMI and BP.docx") #-------------------------------------------------- # Underweight #-------------------------------------------------- underweight_no_bp = file.paragraphs[1].text underweight_hypertensive = file.paragraphs[3].text underweight_normotensive = file.paragraphs[5].text what_to_do = file.paragraphs[25].text #-------------------------------------------------- # Normal #-------------------------------------------------- normal_no_bp = file.paragraphs[7].text normal_hypertensive = file.paragraphs[9].text normal_normotensive = file.paragraphs[11].text what_to_do = file.paragraphs[25].text #-------------------------------------------------- # Overweight #-------------------------------------------------- overweight_no_bp = file.paragraphs[13].text overweight_hypertensive = file.paragraphs[15].text overweight_normotensive = file.paragraphs[17].text what_to_do = file.paragraphs[25].text #-------------------------------------------------- # Obese #-------------------------------------------------- obese_no_bp = file.paragraphs[19].text obese_hypertensive = file.paragraphs[21].text obese_normotensive = file.paragraphs[23].text what_to_do = file.paragraphs[25].text #-------------------------------------------------- #-------------------------------------------------- #----------------------------------------------------------------------- # Display and read health advice based on BMI and Blood Pressure #----------------------------------------------------------------------- if bmi < 18.5: print(f"\nHi {f_name.title()}...\n") print(f"\nYour BMI is {round(bmi, 2)} kg/m2; and your blood pressure is {sbp}/{dbp} mmHg\n") if (sbp + dbp) < 230: speaking.speak(underweight_normotensive, what_to_do) elif (sbp + dbp) == 0: speaking.speak(underweight_no_bp, what_to_do) else: speaking.speak(underweight_hypertensive, what_to_do) elif bmi < 24.9: print(f"\nHi {f_name.title()}...\n") print(f"\nYour BMI is {round(bmi, 2)} kg/m2; and your blood pressure is {sbp}/{dbp} mmHg\n") if (sbp + dbp) < 230: speaking.speak(normal_normotensive, what_to_do) elif (sbp + dbp) == 0: speaking.speak(normal_no_bp, what_to_do) else: speaking.speak(normal_hypertensive, what_to_do) elif bmi < 30: print(f"\nHi {f_name.title()}...\n") print(f"\nYour BMI is {round(bmi, 2)} kg/m2; and your blood pressure is {sbp}/{dbp} mmHg\n") if (sbp + dbp) < 230: speaking.speak(overweight_normotensive, what_to_do) elif (sbp + dbp) == 0: speaking.speak(overweight_no_bp, what_to_do) else: speaking.speak(overweight_hypertensive, what_to_do) elif bmi >= 30: print(f"\nHi {f_name.title()}...\n") print(f"\nYour BMI is {round(bmi, 2)} kg/m2; and your blood pressure is {sbp}/{dbp} mmHg\n") if (sbp + dbp) < 230: speaking.speak(obese_normotensive, what_to_do) elif (sbp + dbp) == 0: speaking.speak(obese_no_bp, what_to_do) else: speaking.speak(obese_hypertensive, what_to_do) #----------------------------------------------------------------------- print(f"\n----------Program End----------\n") #-----------------------------------------------------------------------
import sys def read_array(filename): f = open(filename, 'r') matrix = [] for line in f: line = line[:-1] points = line.split(' '); matrix.append(points) #print points f.close(); return matrix def array_to_file(twoDArray, filename): f = open('out.txt', 'w') for i in range(0, len(twoDArray)): for j in range(0,len(twoDArray[i])): f.write(str(twoDArray[i][j]) + " ") f.write("\n") def main(): matrix = read_array(sys.argv[1]) print matrix array_to_file([[0,1,2,3],[4,5,6],[7,8,10]], sys.argv[2]) if __name__ == "__main__": sys.exit(main())
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): if not self.root: self.root = Node(new_val) else: return self.insert_helper(new_val, self.root) def insert_helper(self, new_val, node): if new_val < self.root.value: if node.left: self.insert_helper(new_val, node.left) else: node.left = Node(new_val) elif new_val > self.root.value: if node.right: self.insert_helper(new_val, node.right) else: node.right = Node(new_val) def search(self, find_val): if self.root is None: return False else: return self.preorder_search(self.root, find_val) def preorder_search(self, start, find_val): """Helper method - use this to create a recursive search solution.""" if start: if start.value == find_val: return True else: return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val) return False # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print (tree.search(4)) # Should be False print (tree.search(6))
from collections import Counter text = "A December squall came in search of him and"\ " knocked his door. Yes, It was her. She came in like a "\ "swift stormy wind leaving no room for doubt or fear to crawl "\ "back in. All of a sudden a hidden thought came alive. "\ "It stole a glance at all the busyness of everyday life."\ "It asked for words to set it free, words to wear so that it"\ "can escape from his lips. It asked for his voice so that it "\ "can embrace the moment and sway it with glee. But, we’ve been"\ "so trapped in all these social mazes. Pathways that restrict"\ "you to talk about exactly what’s going on inside you."\ "Sly protocols that make you tweak the words. "\ "Yes, It happened to him as well. We all have forgotten how "\ words = text.split() counter = Counter(words) top_ten = counter.most_common(10) print(top_ten)
expense = [300,500,700,859,123,235,634] def double(dollars): return dollars * 2 new_expense = list(map(double, expense)) print(new_expense) ''' we can also run this list through for loop. but map is much easier for x in expense: print(x*2) '''
def isprimal(n): for i in range(2, n): if n % i == 0: return False return True def primals(n): # res = [] # ! for i in range(2, n): if isprimal(i): yield i # res.append(i) # return res def mytest(n): prims = primals(n) # res = [] for i in prims: yield -i # res.append(-i) # return res n = input("Enter a number: ") prims = mytest(int(n)) for i in prims: print(i)
# Create a dictionary containing some information # about yourself. The keys should include name, age, country of birth, favorite language. # # Write a function that will print something like the following as it executes: # # My name is Anna # My age is 101 # My country of birth is The United States # My favorite language is Python # Copy # There are two steps to this process, building a dictionary and then gathering # all the data from it. Write a function that can take in and print out any dictionary keys and values. # # Note: The majority of data we will manipulate as web developers will be hashed in a dictionary using # key-value pairs. Repeat this assignment a few times to really get the hang of unpacking dictionaries, as it's a very common requirement of any web application. dictn = {"name": "priyan", "age": 27,"country": "India", "fav-language": "python" } print("my name is ", dictn["name"]) print("my age is ", dictn["age"]) print("my country of birth is ", dictn["country"]) print("my favourite language is ", dictn["fav-language"])
from Employee1 import Employee class Manager (Employee): #this is the basic constructor. As this class is a sub-class of Employee, first calls Employee's constructor #and initializes that part of the object # and all other values are assigned as per parameters passed. def __init__(self, first_name, last_name, ssn, salary, title, amt_bonus_indollars): Employee.__init__(self, first_name, last_name, ssn, salary) self.title = title self.amt_bonus_indollars = amt_bonus_indollars #
__author__ = 'priyanka.' from functools import total_ordering @total_ordering class Employee: """ One object of class Employee represents one employee's first name, last name, social security number and his salary """ #this is the basic constructor. Here the current Employee's firstname, lastname, social security number and salary values get assigned #as per the parameters def __init__(self, first_name, last_name, ssn, salary): self.firstName = first_name self.lastName = last_name self.ssn = ssn self.salary = salary #the __str__( ) method is used to convert a Employee object # into a string def __str__(self): return "The employee's first and last name as %s %s and with ssn %s has a salary of %d $ " % (self.firstName, self.lastName, self.ssn, self.salary) #This method gives hike to salary of current Employee's object. def giveRaise(self, percentRaise): self.salary = self.salary + (self.salary * (percentRaise / 100)) emp1 = Employee('priya', 'pramod', '123123412', 5000) emp2 = Employee('priya', 'pramod', '231123424', 6000) emp3 = Employee('kelu', 'pramod', '444777656', 7000) emp4 = Employee('mano', 'naga', '786678776', 4444 ) print(emp1.firstName) print(emp2.firstName) print(emp1 == emp2)# print(emp3 < emp2)# print(emp2 < emp3)# print(emp4 < emp3)#
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Roger TX (425144880@qq.com) # @Link : https://github.com/paotong999 import random def confict(state, pos): nextY = len(state) if pos in state: return True '''判断斜线''' for i in range(nextY): if nextY-pos == i-state[i]: return True if nextY+pos == i+state[i]: return True return False def queens(num, state=()): if num-1 == len(state): for i in range(num): if not confict(state, i): yield (i,) else: for pos in range(num): if not confict(state, pos): for result in queens(num, state+(pos,)): yield (pos,) + result for i in list(queens(8)): print (i)
from itertools import count from math import sqrt def main(): with open("input", "r") as file: minPresents = int(file.readline()) // 10 def calcPresents(house): presents = 0 for elve in range(1, int(sqrt(house)) + 1): if house % elve == 0: presents += elve presents += house // elve return presents for house in range(minPresents//6, minPresents // 2): if calcPresents(house) > minPresents: print(house) break if __name__ == "__main__": main()
from collections import defaultdict def main(): graph = defaultdict(lambda: {}) weights = {} with open("input", "r") as file: for line in file.readlines(): parts = line.strip().split(" -> ") root, weight = parts[0].split(" ") weights[root] = int(weight[1:-1]) if len(parts) > 1: for child in parts[1].split(", "): graph[root][child] = 0 def calcWeights(cur): subTreeWeights = [] for next in graph[cur].keys(): weight = calcWeights(next) graph[cur][next] = weight subTreeWeights.append(weight) weight = weights[cur] + sum(subTreeWeights) return weight def getCorrectedWeight(cur, expectedWeight): subTrees = sorted(graph[cur].items(), key=lambda x: x[1]) if subTrees[0][1] != subTrees[1][1]: return getCorrectedWeight(subTrees[0][0], subTrees[1][1]) elif subTrees[-2][1] != subTrees[-1][1]: return getCorrectedWeight(subTrees[-1][0], subTrees[-2][1]) else: curWeigth = weights[cur] dif = expectedWeight - curWeigth - sum(graph[cur].values()) return curWeigth + dif print(getCorrectedWeight("eugwuhl", calcWeights("eugwuhl"))) if __name__ == "__main__": main()
dic={} a=input("enter your favourite language") b=input("enter your favourite language") c=input("enter your favourite language") d=input("enter your favourite language") dic["shubham"]=a dic["shivam"]=b dic["saurabh"]=c dic["sonia"]=d print(dic)
class Animals: def __init__(self, age, weight, alive, name): self.age = age self.weight = weight self.alive = alive self.name = name def birthday(self): self.age += 1 class Insects(Animals): def __init__(self, longevity, initialSpeed): self.longevity = longevity self.initialSpeed = initialSpeed def getNumberOfLegs(self): return 6 def getSpeed(self): return self.age * self.initialSpeed def death(self, attacked, attacker): if self.age > self.longevity: self.alive = False elif attacked: if self.getSpeed() < attacker.getSpeed(): self.alive = False class Birds(Animals): def __init__(self, canFly, needsToEat, maxAge): self.canFly = canFly self.needsToEat = needsToEat self.maxAge = maxAge def getSpeed(self): if self.canFly: if self.weight > 10: return 5 elif self.weight > 5: return 10 return 50 return 1 def eat(self, attacked): if self.getSpeed() > attacked.getSpeed(): self.needsToEat = 0 def death(self) : if self.age > self.maxAge or self.needsToEat > 10 : self.alive = False
import string import random import pyperclip class Credential: """ Class that generate new instances of user credentials. """ credential_list = [] def save_credential(self): """ function to save user details """ Credential.credential_list.append(self) def delete_credential(self): """ Function to remove user details """ Credential.credential_list.remove(self) def generate_password(size=8, char=string.ascii_uppercase+string.ascii_lowercase+string.digits): """ Generate password """ generate_pass=''.join(random.choice(char) for _ in range(size)) return generate_pass @classmethod def find_by_email(cls,number): """ Method to search user by email """ for credential in cls.credential_list: if credential.email == number: return credential @classmethod def credential_exist(cls,number): """ Method to check if user exists """ for credential in cls.credential_list: if credential.email == number: return True @classmethod def display_credential(cls): """ Method to display user credentials """ return cls.credential_list @classmethod def copy_email(cls,number): """ class method to copy user email """ credential_found = Credential.find_by_email(number) pyperclip.copy(credential_found.email) def __init__(self,email,platform,password): self.email = email self.platform = platform self.password = password
# Problem # # You're watching a show where Googlers (employees of Google) dance, and then each dancer is # given a triplet of scores by three judges. Each triplet of scores consists of three # integer scores from 0 to 10 inclusive. The judges have very similar standards, so it's # surprising if a triplet of scores contains two scores that are 2 apart. No triplet of # scores contains scores that are more than 2 apart. # # For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, 8) are # surprising. (7, 6, 9) will never happen. # # The total points for a Googler is the sum of the three scores in that Googler's triplet of # scores. The best result for a Googler is the maximum of the three scores in that Googler's # triplet of scores. Given the total points for each Googler, as well as the number of # surprising triplets of scores, what is the maximum number of Googlers that could have had # a best result of at least p? # # For example, suppose there were 6 Googlers, and they had the following total points: 29, # 20, 8, 18, 18, 21. You remember that there were 2 surprising triplets of scores, and you # want to know how many Googlers could have gotten a best result of 8 or better. # # With those total points, and knowing that two of the triplets were surprising, the # triplets of scores could have been: def search(totals, p): combos = [] current_combo = [] for c in range(len(totals)): combos.append(list()) for i in range(11): for j in range(11): for k in range(11): current_combo = [i, j, k] # print("Trying Googler #%d, Combo %s" % ((c+1), str(current_combo))) if (sum(current_combo) == totals[c] and max(current_combo) >= p and abs(current_combo[0]-current_combo[1])<=2 and abs(current_combo[0]-current_combo[2])<=2 and abs(current_combo[1]-current_combo[2])<=2): try: combos[c].append(tuple(current_combo)) # print("len of combos: %d" %len(combos)) # print("Googler #%d - Appending score: %s" % ((c+1), str(current_combo))) except: # print("C=%d and Length of combo list: %d" % (c, len(combos))) combos.append(list()) combos[c].append(tuple(current_combo)) # print("Googler #%d - Extending List, appending score: %s" % ((c+1), str(current_combo))) k+=1 j+=1 i+=1 return combos def NumberOfAllSurprises(combos): all_surprises=0 winning_scores=[] num_blank_scores = 0 # print("Combos: %s" % str(combos)) # print("len of combos= %d" %len(combos)) for c in range(len(combos)): winning_scores.append(list()) if len(combos[c]) ==0: num_blank_scores +=1 for score in combos[c]: # print("googler %d - trying score: %s" % ((c+1), str(score))) if (abs(score[0]-score[1])<=1 and abs(score[0]-score[2])<=1 and abs(score[1]-score[2])<=1): winning_scores[c].append(tuple(score)) continue if (combos[c] and (len(winning_scores[c]) == 0)): all_surprises+=1 # print("winning scores: %s, blank scores: %d, all surprises: %d" % (str(winning_scores), num_blank_scores, all_surprises)) return all_surprises filePrefix = 'B-small-attempt0' fin = open(filePrefix + '.in', 'r') fout = open(filePrefix + '.out', 'w') T = int(fin.readline()) combs = [] for i in range(T): N, S, p, *t = [int(x) for x in fin.readline().split()] # print("N=%d" %N) combos = search(t, p) # print("Number of Googlers: %d" %len(combos)) # for googler in combos: # print("Len of scores: %d" % len(googler)) all_surprises=NumberOfAllSurprises(combos) # print("All Surprises = %d" % all_surprises) if all_surprises > S: deduction = all_surprises-S else: deduction = 0 non_empty_scores = 0 for googler in combos: if len(googler)>0: non_empty_scores +=1 # print("Non-empty scores: %d" % non_empty_scores) if non_empty_scores - deduction <= 0: answer = 0 else: answer = non_empty_scores-deduction print("Case #%d: %d" % ((i+1), answer)) fout.write("Case #%d: %d\n" % ((i+1), answer))
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def findLen(self, head): result = 0 return result def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ """ find list size """ if head is None: return head size = 0 cur = head while cur is not None: size += 1 if cur.next is None: if k % size == 0: return head else: cur.next = head cur = head break cur = cur.next move = size - (k % size) for i in range(move - 1): cur = cur.next head = cur.next cur.next = None return head def makeList(l): a = None for val in l: if a is None: a = ListNode(val) cur = a else: cur.next = ListNode(val) cur = cur.next return a def printList(head): while head is not None: print(head.val, end=' ') head = head.next print('') sol = Solution() l = [1, 2, 3, 4, 5] head = makeList(l) printList(head) for i in range(6): print('rotate -->', i) head = makeList(l) rotate = sol.rotateRight(head, i) printList(rotate) print('-----') l = [] head = makeList(l) printList(head) rotate = sol.rotateRight(head, 3) printList(rotate) l = [3] head = makeList(l) printList(head) print('rotate -->', 5) rotate = sol.rotateRight(head, 5) printList(rotate) print('-----')
#!/usr/bin/env python # coding: utf-8 # # Project - Wrangle and Analyze data # # Tasks in this project are as follows: # # Data wrangling, which consists of: # # Gathering data # # Assessing data # # Cleaning data # # Storing, analyzing, and visualizing wrangled data # # Reporting on 1) data wrangling efforts and 2) data analyses and visualizations # ## Introduction # The dataset that I will be wrangling (and analyzing and visualizing) is the tweet archive of Twitter user @dog_rates, also known as WeRateDogs. WeRateDogs is a Twitter account that rates people's dogs with a humorous comment about the dog. These ratings almost always have a denominator of 10. The numerators, though? Almost always greater than 10. 11/10, 12/10, 13/10, etc. Why? Because "they're good dogs Brent." WeRateDogs has over 4 million followers and has received international media coverage. # # Wrangling of data is done in three steps: # 1. Gather # 2. Assess # 3. Clean # Below all the steps are explained and shown in detail # ## Gather # Data can be gathered from many sources and in many ways. In this projext I will gather data using three ways. # 1. File on hand. In this case I alreday have the file and just need to open it using Pandas DataFrame. # 2. Downloading a file programmatically from a given url using request(). # 3. Gathering data from a specfic website/archive using API. # In[191]: # Import necessary packages import pandas as pd import requests import os import json import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import re # In[192]: #Open file 'twitter-archive-enhanced.csv' into a pandas DataFrame twitter_archive=pd.read_csv('twitter-archive-enhanced.csv') twitter_archive.head() # In[193]: # Download the file programmatically using request() image_url='https://d17h27t6h515a5.cloudfront.net/topher/2017/August/599fd2ad_image-predictions/image-predictions.tsv' response=requests.get(image_url) response.content # As we can see the contents of the response variable are in bytes format. To make the contents in human readable format we have to write the contents of the response variable in a file with mode as 'write binary'. # When we open the file into a pandas DataFrame, the contents become human readable. # # In[194]: #Write response.content into a file with mode as 'write binary(wb)' with open(os.path.join(image_url.split('/')[-1]),mode='wb') as file: file.write(response.content) # In[195]: # Read file into a pandas DataFrame image_df=pd.read_csv('image-predictions.tsv',sep='\t') image_df.head() # # ## Disclaimer: The tweets which have been deleted from twitter archive- I will be filling those with Null values # In[196]: # Authenticate your credentials ''' import tweepy consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) ''' # In[197]: #Gather data from Twitter API using tweepy package. ''' id_list=list(twitter_archive.tweet_id) data={} data['tweet']=[] for id_of_tweet in id_list: try: tweet = api.get_status(id_of_tweet,tweet_mode='extended',parser=tweepy.parsers.JSONParser()) favourites_count =tweet['user']['favourites_count'] retweet_count=tweet['retweet_count'] day_of_the_week=tweet['created_at'].split()[0] month=tweet['created_at'].split()[1] except: favourites_count =None retweet_count=None day_of_the_week=None month=None data['tweet'].append({'tweet_id':id_of_tweet, 'favourites_count':favourites_count, 'retweet_count':retweet_count, 'day_of_the_week':day_of_the_week, 'month':month}) ''' # In[198]: # Write the json object(dictnary) into a file ''' with open('tweet_json.txt', 'w') as outfile: json.dump(data, outfile) ''' # In[199]: # Read the file into a pandas DataFrame tweet_id=[] favourites_count=[] retweet_count=[] day_of_the_week=[] month=[] with open('tweet_json.txt') as json_file: data = json.load(json_file) for p in data['tweet']: retweet_count.append(p['retweet_count']) favourites_count.append(p['favourites_count']) tweet_id.append(p['tweet_id']) day_of_the_week.append(p['day_of_the_week']) month.append(p['month']) # In[200]: twitter_api=pd.DataFrame({'tweet_id':tweet_id, 'favourites_count':favourites_count, 'retweet_count':retweet_count, 'day_of_the_week':day_of_the_week, 'month':month}) twitter_api.head() # ## Assess # The second step in data wrangling process is assessing the data. Once the data has been gathered, it has to be inspected for two things # 1. Quality : Data that has quality issues has issues with content like missing, duplicate or incorrect data. This type of data is called dirty data. # 2. Tidiness : Data that has tidiness issues has specific structural issues. These structural issues slow down the process of cleaning and visualising data. This type of data is called messy data. Data to be tidy it has to satisfy 3 critera. # a. Each variable forms a column. # b. Each observation forms a row. # c. Each observational unit forms a table # # Data can be both dirty and messy. # # Data can be assessed for these two issues in two ways # 1. Visual # 2. Programmatic # # These assessments are then documented so that the cleaning process becomes easier. Only the observation is written down and not how to clean the data. # ### Visual Assessment # Visual Assessment is done simply by going through the dataset and catching anything that looks wrong. Visual assessment in python is difficult as large datasets are collasped by python. Visual assessment is better carried out in Google docs or sheets. # In[201]: #Visual assessment of twitter_archive_enhanced.csv dataset twitter_archive # In[202]: #Visual assessment of image_predictions.tsv dataset image_df # In[203]: # Visual assessment of tweet_json.txt dataset twitter_api # ### Programmatic Assessment # Programmatic assessment means using python functions such as info(), describe() or sample() to find dirty or untidy data. # Common functions are # 1. info() # 2. describe() # 3. values_count() # 4. isnull() # 5. sample() # In[204]: twitter_archive.info() # In[205]: image_df.info() # In[206]: twitter_api.info() # In[207]: twitter_archive.describe() # In[208]: twitter_api.describe() # In[209]: twitter_archive.sample(5) # In[210]: image_df.sample(5) # In[211]: twitter_archive['rating_numerator'].value_counts() # In[212]: twitter_archive['name'].value_counts() # In[213]: twitter_archive['source'].value_counts() # In[214]: image_df['p1_dog'].value_counts() # In[215]: image_df['p2_dog'].value_counts() # In[216]: image_df['p3_dog'].value_counts() # In[217]: twitter_api['day_of_the_week'].value_counts() # In[218]: twitter_api['month'].value_counts() # In[219]: sum(twitter_archive.duplicated()) # In[220]: sum(twitter_api.duplicated()) # In[221]: sum(image_df.duplicated()) # ### Quality # # #### `twitter_archive table` # - rating_denominator has values more than 10 # - for tweet_id 887517139158093824 name is 'such' # - name column has 'O' instead of O'Malley # - Erroneous datatpes (timestamp, retweeted_status_timestamp) # - Decimal values such 13.5 are interpreted as 5. # - name column has names such as 'a' ,'the' ,'an' # - html tags in source column # - missing values have None instead of Nan # # # #### `image_predictions table` # - smallcase names in p1,p2 and p3 # - names have '_' or '-' instead of space between them # - missing data (2075 instead of 2356) # - ambigous column names (p1,p1_conf,p1_dog) # # #### `json_tweet table` # - missing values in favourites_count,retweet_count,day_of_the_week and month # # ### Tidiness # # #### `twitter_archive table` # - instead of seperate column for each dog stage(doggo,floofer,pupper,puppo) single column called dog_stage # # #### `json_tweet table` # - should be joined with twitter archive table as it contains the information regarding the tweets. # # #### `image_predictions table` # - can be joined with twitter archive table as single column for dog_breed # ## Clean # The final step of data wrangling process is data cleaning.There are three steps in data cleaning. # # 1. Define- In words define the approach to clean data # 2. Code- Code to clean data # 3. Test-Test whether your code has worked properly or not # # In[222]: # Make copies of tables twitter_archive_clean=twitter_archive.copy() image_df_clean=image_df.copy() twitter_api_clean=twitter_api.copy() # ### Missing data # **Quality Issue-1** # # All the tables have columns which have missing data. # `twitter_archive table` has columns like in_reply_to_status_id, in_reply_to_user_id etc that have missing data. This either means that that data does not exsist at all or there was some issues while retriving the data. Getting this data is impossible and hence it will remain as it is. # `image_predictions table` has only 2075 records whereas there are supposed to be 2356. It means that the data was lost while it was being documented. Retrieving this data is almost impossible. # `json_tweet table` also has missing data. These tweets have been deleted from the twitter archive. To make joining of twitter_archive and json_tweet tables easier I will drop the coressponding tweet_id from twitter_archive table # **Define** # # Drop rows from `twitter_archive and json_tweet table` of tweet_id that have missing data in `json_tweet table` # **Code** # In[223]: #Create list of tweet_id's that have missing data missing_tweet_list=list(twitter_api_clean[twitter_api_clean['favourites_count'].isnull()]['tweet_id']) missing_tweet_list # In[224]: #Drop rows from twitter_archive and json_tweet tables for tweet_id in missing_tweet_list: twitter_archive_clean=twitter_archive_clean.drop(twitter_archive_clean[twitter_archive_clean.tweet_id==tweet_id].index) twitter_api_clean=twitter_api_clean.drop(twitter_api_clean[twitter_api_clean.tweet_id==tweet_id].index) # **Test** # In[225]: # Check the number of rows in both datasets twitter_archive_clean.shape,twitter_api_clean.shape # **Quality Issue-2** # # **image_predictions table** # # **smallcase names in p1,p2 and p3** # # **names have '_' or '-' instead of space between them** # **Define** # # Capitalize the words and replace '-','_' with blank space in p1,p2,p3 # **Code** # # In[226]: # Replace '_' and '-' with blank space and capitalise the words in p1 p1_clean=[] for name in image_df_clean.p1: if '_' in name: s=name.split('_') var=" ".join(s) elif '-' in name: s=name.split('-') var=" ".join(s) else: var=name p1_clean.append(var.title()) image_df_clean.p1=p1_clean # In[227]: # Replace '_' and '-' with blank space and capitalise the words in p2 p2_clean=[] for name in image_df_clean.p2: if '_' in name: s=name.split('_') var=" ".join(s) elif '-' in name: s=name.split('-') var=" ".join(s) else: var=name p2_clean.append(var.title()) image_df_clean.p2=p2_clean # In[228]: # Replace '_' and '-' with blank space and capitalise the words in p3 p3_clean=[] for name in image_df_clean.p3: if '_' in name: s=name.split('_') var=" ".join(s) elif '-' in name: s=name.split('-') var=" ".join(s) else: var=name p3_clean.append(var.title()) image_df_clean.p3=p3_clean # **Test** # In[229]: image_df_clean.head() # **Define** # # Extract the 'pupper','doggo','puppo','floofer' keywords from the text to form a single column 'dog_stage' and drop the remaining columns. # **Code** # In[230]: #Extract the dog stage keywords from the text column twitter_archive_clean['dog_stage'] = twitter_archive_clean['text'].str.extract('(doggo|floofer|pupper|puppo)',expand=False) # In[231]: #Drop the previous columns twitter_archive_clean=twitter_archive_clean.drop(['pupper','doggo','puppo','floofer'],axis=1) # **Test** # In[232]: twitter_archive_clean.head() # In[233]: twitter_archive_clean.shape # **Tidiness Issue-2** # # **All 3 tables should be merged together** # **Define** # # Merge the `twitter_archive and json_tweet tables and 'image_predictions table` # **Code** # In[234]: #Merge twitter_archive and json_tweet tables twitter_archive_clean=twitter_archive_clean.join(twitter_api_clean.set_index('tweet_id'), on='tweet_id') # In[235]: #Merge twitter_archive and imgae_predictions tables twitter_archive_clean=twitter_archive_clean.join(image_df_clean.set_index('tweet_id'), on='tweet_id') # **Test** # In[236]: twitter_archive_clean.head() # In[237]: twitter_archive_clean.info() # ### Quality # **Quality Issue-3** # # **twitter_archive table** # # **rating_denominator in twitter_archive table has values more than 10. It should be 10 only.** # **Define** # # Assign all values of rating_denominator in twitter_archive to be 10. # **Code** # In[238]: # Assign all values of rating_denominator to be 10 twitter_archive_clean['rating_denominator']=10 # **Test** # In[239]: twitter_archive_clean['rating_denominator'].value_counts() # **Quality Issue-4** # # **twitter_archive table** # # **name column has names such as 'a' ,'the' ,'an','such' etc** # # **name column has 'O' instead of O'Malley** # **Define** # # Change the names such as 'a','an','the' to NaN # # Change O to O'Malley in name column # # All the incorrect names are in lowercase # **Code** # In[240]: #Create list of all lowercase names lower_name_list=[] for name in twitter_archive_clean.name: if name is not None: if name.islower() and name not in lower_name_list: lower_name_list.append(name) lower_name_list # In[241]: # Replace thses names by NaN twitter_archive_clean.replace(lower_name_list,np.NaN,inplace=True) # In[242]: # Replace O with O'Malley twitter_archive_clean.replace('O',"O'Malley",inplace=True) # **Test** # In[243]: # Check for any lowercase names twitter_archive_clean.name.value_counts() # In[244]: # Check whether name O'Malley is correctly reflected twitter_archive_clean[twitter_archive_clean['name']=="O'Malley"]['name'] # **Quality Issue-5** # # **twitter_archive table** # # **Erroneous datatpes (timestamp, retweeted_status_timestamp)** # **Define** # # Convert timestamp and retweeted_status_timestamp from string to Datetime datatype # **Code** # In[245]: # Convert above columns to Datetime twitter_archive_clean.timestamp = pd.to_datetime(twitter_archive_clean.timestamp) twitter_archive_clean.retweeted_status_timestamp = pd.to_datetime(twitter_archive_clean.retweeted_status_timestamp) # **Test** # In[246]: twitter_archive_clean.info() # **Quality Issue-6** # # **twitter_archive table** # # **decimal values such as 13.5 extracted as 5** # **Define** # # Extract the decimal ratings correctly. # **Code** # In[247]: # Obtain all text, indices, and ratings for tweets that contain a decimal in the numerator of rating decimals_text = [] decimals_index = [] decimals = [] for i, text in twitter_archive_clean['text'].iteritems(): if bool(re.search('\d+\.\d+\/\d+', text)): decimals_text.append(text) decimals_index.append(i) decimals.append(re.search('\d+\.\d+', text).group()) # Print the text to confirm presence of ratings with decimals decimals_text # In[248]: # Print the index of text with decimal ratings decimals_index # In[249]: # Change contents of 'rating_numerator' twitter_archive_clean.loc[decimals_index[0],'rating_numerator'] = float(decimals[0]) twitter_archive_clean.loc[decimals_index[1],'rating_numerator'] = float(decimals[1]) twitter_archive_clean.loc[decimals_index[2],'rating_numerator'] = float(decimals[2]) twitter_archive_clean.loc[decimals_index[3],'rating_numerator'] = float(decimals[3]) twitter_archive_clean.loc[decimals_index[4],'rating_numerator'] = float(decimals[4]) # **Test** # In[250]: # Check contents of row with index 40 to ensure the rating is corrected twitter_archive_clean.loc[45] # In[251]: # Check contents of row with index 40 to ensure the rating is corrected twitter_archive_clean.loc[340] # **Quality Issue-7** # # **twitter_archive table** # # **None in columns instead of NaN** # **Define** # # Replace None with NaN in all the columns to maintian uniformity # **Code** # In[252]: # Replace None with NaN in all columns twitter_archive_clean.replace('None',np.NaN,inplace=True) # **Test** # In[253]: twitter_archive_clean.sample(5) # **Quality Issue-8** # # **twitter_archive table** # # **Ambiguous columns names such as p1,conf_p1,p1_dog** # **Define** # # Change ambiguous column names to meaning full names # **Code** # In[254]: #Rename column nanmes twitter_archive_clean.rename(columns={'p1':'prediction1(p1)', 'conf_p1':'confidence_p1', 'p1_dog':'is_p1_dog', 'p2':'prediction2(p2)', 'conf_p2':'confidence_p2', 'p2_dog':'is_p2_dog', 'p3':'prediction3(p3)', 'conf_p3':'confidence_p3', 'p3_dog':'is_p3_dog'},inplace=True) # **Test** # In[255]: # List column names twitter_archive_clean.columns # **Quality Issue-9** # # **twitter_archive table** # # retweeted_status is not NaN # # **Define** # # Drop rows where retweeted_status is not NaN # # **Code** # In[256]: # Drop rows where retweet status is not null twitter_archive_clean = twitter_archive_clean[np.isnan(twitter_archive_clean.retweeted_status_id)] # In[257]: # Drop null columns twitter_archive_clean = twitter_archive_clean.drop(['retweeted_status_id', 'retweeted_status_user_id', 'retweeted_status_timestamp'], axis=1) # **Test** # In[258]: twitter_archive_clean.info() # ## Storing # In[259]: # Store twitter_archive table to a csv file twitter_archive_clean.to_csv('twitter_archive_master.csv',index=False) # ## Visualisation # # In[260]: # Read twitter table from csv file twitter_df=pd.read_csv('twitter_archive_master.csv') twitter_df.head() # **Visulaisation -1** # # Plot of how retweets and favourites_count differs on a particular day of the week. # In[261]: # Get the number of retweets for each day of the week retweet=twitter_df.groupby('day_of_the_week')['retweet_count'].sum() retweet # In[262]: # Store the no. of retweets in a seperate list retweet_count=[retweet[1],retweet[5],retweet[6],retweet[4],retweet[0],retweet[2],retweet[3]] retweet_count # In[263]: # Define lables label=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] label # In[264]: # Plot graph with apt lables plt.figure(figsize=(15,8)) index = np.arange(len(label)) plt.bar(index, retweet_count,color='yellow',alpha=0.5); plt.xlabel('Day of the Week', fontsize=14) plt.ylabel('No. of retweets(in lakhs)', fontsize=14) plt.xticks(index, label) plt.title('Day V/S Retweet Count',fontsize=14) plt.show() # In[265]: # Get the number of favourites count for each day of the week fav=twitter_df.groupby('day_of_the_week')['favourites_count'].sum() fav # In[266]: # Store the no. of favourites count in a seperate list fav_count=[fav[1],fav[5],fav[6],fav[4],fav[0],fav[2],fav[3]] fav_count # In[267]: # Plot graph with apt lables plt.figure(figsize=(15,8)) index = np.arange(len(label)) plt.bar(index, fav_count,color='blue',alpha=0.3); plt.xlabel('Day of the Week', fontsize=14) plt.ylabel('No. of favourites count(in lakhs)', fontsize=14) plt.xticks(index, label) plt.title('Day V/S Favourites Count',fontsize=14) plt.show() # **Observation** # # As we can see from the two graphs that maximum number of retweets happen on Wednesday. Since the count is in lakhs(millions) the difference is quite significant. # # Similarly the maximum number of favourites takes place on Monday. Here also the difference in count is quite significant # **Visualisation-2** # # Plot of how retweets and favourites count differ with month. # In[268]: # Get the number of favourites count for each month of the year fav=twitter_df.groupby('month')['favourites_count'].sum() fav # In[269]: # Store the no. of favourites count in a seperate list fav_count=[fav[4],fav[3],fav[7],fav[0],fav[8],fav[5],fav[6],fav[1],fav[-1],fav[-2],fav[-3],fav[2]] fav_count # In[270]: #Create Labels label=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] label # In[271]: # Plot graph with apt lables plt.figure(figsize=(15,8)) index = np.arange(len(label)) plt.bar(index, fav_count,color='green',alpha=0.3); plt.xlabel('Month', fontsize=14) plt.ylabel('No. of favourites count(in lakhs)', fontsize=14) plt.xticks(index, label) plt.title('Month V/S Favourites Count',fontsize=14) plt.show() # In[272]: # Get the number of retweets for each month retweet=twitter_df.groupby('month')['retweet_count'].sum() retweet # In[273]: # Store the no. of retweet count in a seperate list retweet_count=[retweet[4],retweet[3],retweet[7],retweet[0],retweet[8],retweet[5],retweet[6], retweet[1],retweet[-1],retweet[-2],retweet[-3],retweet[2]] retweet_count # In[274]: # Plot graph with apt lables plt.figure(figsize=(15,8)) index = np.arange(len(label)) plt.bar(index, retweet_count,color='red',alpha=0.5); plt.xlabel('Month', fontsize=14) plt.ylabel('No. of retweets(in lakhs)', fontsize=14) plt.xticks(index, label) plt.title('Month V/S Retweet Count',fontsize=14) plt.show() # **Observation** # # As we can see from the two graphs that the activity on twitter or in this case for the account @WeRateDogs is more during the month of January, December, June and July compared to months of March, April, August and September. This may be because they are the holiday months and people have more time to dedicate to social media. It is highest in January and December because most parts of the world experience winter season during that time and people tend to stay indoors during time compared to June and July. # **Visualisation-3** # # Plot to see the relationship between retweet count ad favourites count # In[275]: plt.figure(figsize=(15,8)) plt.scatter(y=twitter_df['favourites_count'], x=twitter_df['retweet_count']); plt.xlabel('Retweet Count',fontsize=14) plt.ylabel('Favourites Count',fontsize=14) plt.title('Retweet Count V/S Favourites Count',fontsize=14) plt.show() # In[276]: import seaborn as sns # In[277]: # Plot scatterplot of retweet vs favorite count sns.lmplot(x="retweet_count", y="favourites_count", data=twitter_archive_clean, size = 5, aspect=1.3, scatter_kws={'alpha':1/5}) plt.title('Favorite vs. Retweet Count') plt.xlabel('Retweet Count') plt.ylabel('Favorite Count'); # **Observation** # # Retweet count and favourites count are positively co-related. # ## Conclusion # Data wrangling is an important step in the Data Analysis process. Data warngling itself has three steps Gather, Assess and Clean. Gathereing relevant data is important otherwise our finds and observations will not come out correctly. Assessing the data for dirty or untidy data and then cleaning and documenting these process id helpful to get correct insights. # # ## Limitations # Real world data is messy and untidy. Gathering itself is a painful process. Assessing data was the toughest pat because there are so many discrepancies and one cannot address all of them. Cleaning the data was also difficult but with the help of stackoverflow and python documentations I was able to complete the project # ## Achnowledgment # - https://stackoverflow.com # - https://pythonspot.com # - https://docs.python.org/3/ # In[ ]:
class Spot: def __init__(self, name, info=""): self.name = name self.info = info self.next_spots = {} self.characters = [] def connect(self, next_spot, direction): self.next_spots[direction] = next_spot def show(self): print(self.name) print("-" * len(self.name)) print(self.info) for character in self.characters: character.about() for direction in self.next_spots: print("🏃 The " + self.next_spots[direction].name + " is " + direction + '.') def move(self, direction): if direction in self.next_spots: return self.next_spots[direction] else: print(">>> You can't go that way.\n") return self def add_characters(self, *characters): for c in characters: self.characters.append(c) # \|/-*-/|\ links # opposites = { # "east": "west", # "west": "east", # "south": "north", # "north": "south", # "southeast": "northwest", # "southwest": "northeast", # "northeast": "southwest", # "northwest": "southeast" # }
import VigenereCipher while True: try: cryptanalysis = int(input("Entrer 1 si vous voulez calculer l'indice de coincidence d'un texte :")) except ValueError: print("Veuillez présenter un choix correct.") if cryptanalysis == 1: try: cipher = str(input("Enter le message en question :")) except ValueError: print("Veuillez entrer un message correct.") print("L'indice de coincidence de votre message est de ", VigenereCipher.cryptanalysis(cipher)) continue try: key = str(input('Présenter la clé à utiliser :')) except ValueError: print('Veuillez présenter une clé correcte !') try: action = int(input('Entrer 0 pour chiffrer un message et 1 pour déchiffrer :')) except ValueError: print("Veuillez demander une action correcte.") if action == 0: try: message = str(input('Entrer le texte à chiffrer :')) except ValueError: print("Veuiller présenter un message correct !") print("Votre message chiffré est : ", VigenereCipher.encrypt(message, key)) elif action == 1: try: message = str(input('Entrer le texte à déchiffrer :')) except ValueError: print("Veuillez présenter un message correct.") print("Votre message déchiffré est", VigenereCipher.decrypt(message, key)) else: print("Action non reconnu.")
""" http://rosalind.info/problems/iprb/ Given: Three positive integers k, m, and n, representing a population containing k+m+n organisms: k individuals are homozygous dominant for a factor, m are heterozygous, and n are homozygous recessive. Return: The probability that two randomly selected mating organisms will produce an individual possessing a dominant allele (and thus displaying the dominant phenotype). Assume that any two organisms can mate. """ import common from math import factorial sample_data = "2 2 2" sample_output = "0.78333" def prob(inp): # k homozygous dominant (YY) # m heterozygous (Yy) # n homozygous recessive (yy) k, m, n = [float(x) for x in inp.split(" ")] N = k + m + n Nm = N - 1.0 p = (k/N) # YY chosen first p += (m/N) * ( (k/Nm) + (0.75*(m-1)/Nm) + (0.5*(n/Nm)) ) # Yy first p += (n/N) * ( (k/Nm) + (0.5*(m/Nm)) ) #yy first return "%.5f" % p common.test(prob, sample_data, sample_output) common.runit(prob)
import os import re def preprocess(document): """This function converts non-alphabetic characters to whitespace, lowercases all letters, and collapses all subsequent whitespace down to a single space. It returns a string of the preprocessed document""" document = re.sub(r'\W+', ' ', document) document = re.sub(r'\d+', ' ', document) document = re.sub(r'\s+', ' ', document) document = document.lower() return document def parse_documents_from_directory(direct): """This function takes a directory as an argument and traverses each text file in the directory. With each text file, it will preprocess it. It returns a dictionary of all the names of the preprocessed documents mapped to their corresponding preprocessed text. The dictionary that is returned can then be used to implement an initial strategy.""" files = os.listdir(direct) preprocessed_documents = {} for file in files: if file.endswith('.txt'): file_d = open("{}/{}".format(direct, file), 'r', encoding='utf8') document = file_d.read() preprocessed_documents[file] = preprocess(document) file_d.close() return preprocessed_documents def parse_actual_results(actual_test_results): test_results_file = open(actual_test_results, 'r') test_contents = test_results_file.read() test_contents = test_contents.splitlines() actual = {} for line in test_contents: elements = tuple(line.split(',')) actual[elements[0]] = elements[1] test_results_file.close() return actual
class Bank: def __init__(self): self.accounts = {} def insert(self, account): if self.accounts.has_key(account.get_person_id()): print ("Account exists") return False self.accounts[account.get_person_id()] = account def remove(self, person_id): if not self.accounts.has_key(person_id): print ("Account does not exist") return False self.accounts.pop(person_id) return True def get_account_by_id(self, person_id): if not self.accounts.has_key(person_id): print ("Account does not exist") return False return self.accounts[person_id]
#!/usr/bin/env python # Default color levels for the color cube cubelevels = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] # Generate a list of midpoints of the above list snaps = [(x+y)/2 for x, y in zip(cubelevels, [0]+cubelevels)[1:]] print(snaps) def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """ # Using list of snap points, convert RGB value to cube indexes r, g, b = map(lambda x: len(tuple(s for s in snaps if s<x)), (r, g, b)) print(r) print(g) print(b) # Simple colorcube transform return r*36 + g*6 + b + 16 print(rgb2short(0xff, 0x00, 0xaf));
def addToEach(value,aList): result = [] for item in aList: result = result + [ item + value ] return result #def addToEach(value,aList): # result = [] # for item in aList: # result.append(item + value) # return result def test_addToEach_1(): assert addToEach(1,[3,4,5])==[4,5,6] def test_addToEach_10(): assert addToEach(10,[3,4,5])==[13,14,15]
"""Do this now: Write a function to get a valid age from a user Write two lines of main code to show its use """ MAXIMUM_AGE = 130 def main(): """Program for getting ages.""" age = get_valid_age() print(f"You are {age} years old!") def get_valid_age(): """Get a valid age between 0 and MAXIMUM_AGE.""" age = int(input("Age: ")) while age < 0 or age > MAXIMUM_AGE: print("Invalid age") age = int(input("Age: ")) return age main()
#!/usr/bin/python """ //[]------------------------------------------------------------------------[] //| | //| Problema dos Monges e Canibais | //| Version 1.0 | //| | //| Copyright 2015-2020, Marcos Vinicius Teixeira | //| All Rights Reserved. | //| | //[]------------------------------------------------------------------------[] // // OVERVIEW: mong_cabib.py // ======== // Source file for solve the Cannibals and Missionaries Problem. #[ M, C, L] # L = [-1,1] onde -1 lado direito e 1 lado esquerdo # Estado inicial [3,3,-1] # Estado final [0,0,1] """ class FIFOQueue(): """A First-In-First-Out Queue.""" def __init__(self): self.A = []; self.start = 0 def append(self, item): self.A.append(item) def __len__(self): return len(self.A) - self.start def pop(self): e = self.A[self.start] self.start += 1 return e def __contains__(self, item): return item in self.A[self.start:] def valid(state): ret = True dm = state[0] dc = state[1] lado = state[2] em = 3-dm ec = 3-dc if dm < 0 or dm > 3: ret = False if dc < 0 or dc > 3: ret = False if dc > dm and dm != 0: ret = False if ec > em and em != 0: ret = False return ret def generate_children(state): lista = [] monges = state[0] canibais = state[1] lado = state[2] inv_lado = lado*-1 # Leva 1 canibal testado = [monges,canibais + lado,inv_lado] if valid(testado): lista.append(testado) # Leva 2 canibais testado = [monges,canibais + 2*lado,inv_lado] if valid(testado): lista.append(testado) # Leva 1 monge e 1 canibal testado = [monges+lado,canibais + lado,inv_lado] if valid(testado): lista.append(testado) # Leva 1 monge testado = [monges+lado,canibais,inv_lado] if valid(testado): lista.append(testado) # Leva 2 monges testado = [monges+2*lado,canibais,inv_lado] if valid(testado): lista.append(testado) return lista def breadth_first_search(initial,final): initial_state = initial frontier = FIFOQueue() # explored list explored = [] path = [] father = dict() frontier.append(initial_state) while len(frontier) > 0: state = frontier.pop() if state == final: return state if state not in explored: explored.append(state) children = generate_children(state) for child in children: father['%d%d%d'%(child[0],child[1],child[2])] = state frontier.append(child) if __name__ == '__main__': print breadth_first_search([3,3,-1],[0,0,1])
import wikipedia from topicblob import TopicBlob # get random wikipeida summaries wiki_pages = [ "Facebook", "New York City", "Barack Obama", "Wikipedia", "Topic Modeling", "Python (programming language)", "Snapchat", ] def main(): texts = [] for page in wiki_pages: text = wikipedia.summary(page) # print(text) texts.append(text) tb = TopicBlob(texts, 20, 20) counter = 0 for page in wiki_pages: print("Stats for "+page) print(tb.df.iloc[counter]) counter += 1 print("") print("#################Sims EXAMPLE##################") print("Showing sim docs for doc number 0 *Facebook") sims = tb.get_sim(0) print(sims) print("#################Ranked Search EXAMPLE##################") print("Doing ranked search for the word 'president'") search = tb.ranked_search_docs_by_words("president") print(search) print("#################Topic Search EXAMPLE##################") print("Doing topic search for the word 'python'") topic_search = tb.search_docs_by_topics("python") print(topic_search) if __name__ == "__main__": main()
# # # Utils # # import re import os.path import mimetypes from urllib.parse import urlparse def splitext(path): """ Split file into name and extension with support for .tar.gz / .tar.bz2 extensions Parameters ----------- path: str File path Returns -------- name: str File name extension: str File extension """ for ext in [".tar.gz", ".tar.bz2"]: if path.endswith(ext): return path[:-len(ext)], path[-len(ext):] return os.path.splitext(path) def lines(file_path, strip=True): """ Read file line by line Parameters ----------- file_path: str File path strip: bool Whether or not strip spaces from each line Yields --------- line: str Read line. """ with open(file_path) as f: for line in f: if strip: line = line.strip() yield line def guess_extension(content_type): """ Guess extension Parameters ----------- content_type: str MIME type Returns -------- str Extension or None if not found """ if content_type == "text/plain": ext = ".txt" else: ext = mimetypes.guess_extension(content_type) if ext == ".htm": ext = ".html" elif ext == ".jpe": ext = ".jpg" return ext def get_valid_filename(s): s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s) def filename_from_url(url): """ Get filename from url Parameters ------------ url: str Url to get filename Returns --------- str Filename """ parsed = urlparse(url) last_path = os.path.basename(parsed.path) if not last_path: last_path = "index.html" return get_valid_filename(last_path)
from queue import PriorityQueue import math class WayPointsProblem: def __init__(self, inputGrid, startPos, goalPos, cylinders, boundaryPoints): self.grid = inputGrid self.start = (startPos[0], startPos[1]) self.startAlt = startPos[2] self.goal = (goalPos[0], goalPos[1]) self.goalAlt = goalPos[2] self.obstacles = [i for i in cylinders if i[4] >= min(self.startAlt, self.goalAlt)] self.boundary = boundaryPoints #print(inputGrid[25][13]) def getStartState(self): ''' Gets the starting state for the search state is (x, y, cost, (x_direction, y_direction)) ''' if not self.valid(self.start[0], self.start[1]): print("ERROR: Start state is not valid!") if not self.valid(self.goal[0], self.goal[1]): print("ERROR: End state is not valid!") if self.obstacle(self.start[0], self.start[1]): print("ERROR: Start state is an obstacle or out of bounds!") if self.obstacle(self.goal[0], self.goal[1]): print("ERROR: End state is an obstacle or out of bounds!") return [(self.start[0], self.start[1], 0, (1, 1)), (self.start[0], self.start[1], 0, (1, -1)), (self.start[0], self.start[1], 0, (-1, 1)), (self.start[0], self.start[1], 0, (-1, -1))] def valid(self, x, y): return x >= 0 and x < len(self.grid) and y >= 0 and y < len(self.grid[0]) def getSuccessors(self, state): ''' Gets the successors of the search problem with constraints added by jump point search ''' x, y, cost, direction = state next_diagonal = [] if self.valid(x, y) and not self.obstacle(x + direction[0], y + direction[1]): next_diagonal = [(x + direction[0], y + direction[1], cost + math.sqrt(2), direction)] if self.obstacle(x, y + direction[1]) and not self.obstacle(x, y + 2 * direction[1]): next_diagonal.append((x + direction[0], y + direction[1], cost + math.sqrt(2), (-direction[0], direction[1]))) if self.obstacle(x + direction[0], y) and not self.obstacle(x + 2 * direction[0], y): next_diagonal.append((x + direction[0], y + direction[1], cost + math.sqrt(2), (direction[0], -direction[1]))) return self.search_horizontal(state, direction[0]) + self.search_vertical(state, direction[1]) + next_diagonal def obstacle(self, x, y): ''' Determines if there is an obstacle at a specific point ''' if not self.valid(x, y): return True; return self.grid[x][y] > 0 and (self.grid[x][y] == 1 or self.grid[x][y] > self.startAlt) def search_horizontal(self, state, hdir): ''' jump point search horizontal search ''' x, y, cost, direction = state nodes = []; a = [] while self.valid(x + hdir, y): if self.obstacle(x + hdir, y): return nodes if (x + hdir, y) == self.goal: return [(x + hdir, y, cost + 1, "END")] if self.obstacle(x + hdir, y - 1) and not self.obstacle(x + hdir * 2, y - 1): nodes.append((x + hdir, y, cost + 1, (hdir, -1))) if self.obstacle(x + hdir, y + 1) and not self.obstacle(x + hdir * 2, y + 1): nodes.append((x + hdir, y, cost + 1, (hdir, 1))) cost = cost + 1 x = x + hdir a = nodes[:] return nodes def search_vertical(self, state, vdir): ''' jump point search vertical search ''' x, y, cost, direction = state nodes = []; while self.valid(x, y + vdir): if self.obstacle(x, y + vdir): return nodes if (x, y + vdir) == self.goal: return [(x, y + vdir, cost + 1, "END")] if self.obstacle(x - 1, y + vdir) and not self.obstacle(x - 1, y + vdir * 2): nodes.append((x, y + vdir, cost + 1, (-1, vdir))) if self.obstacle(x + 1, y + vdir) and not self.obstacle(x + 1, y + vdir * 2): nodes.append((x, y + vdir, cost + 1, (1, vdir))) cost = cost + 1 y = y + vdir return nodes def isGoalState(self, state): ''' checks if we found out goal ''' x, y, cost, direction = state return x == self.goal[0] and y == self.goal[1] def heuristic(self, state): ''' heuristic for A-star ''' x, y, cost, direction = state return math.sqrt((self.goal[0] - x) * (self.goal[0] - x) + (self.goal[1] - y) * (self.goal[1] - y)) def aStarSearch(problem): q = PriorityQueue(); visited = set() for i in problem.getStartState(): if problem.valid(i[0], i[1]) and not problem.obstacle(i[0], i[1]): q.put((0, (i, []))) while(not q.empty()): priority, item = q.get() expand, directions = item if problem.isGoalState(expand): expand = (expand[0], expand[1], expand[2], expand[3]) return directions + [(expand[0], expand[1])], expand[2] if (expand[0], expand[1], expand[3]) in visited: continue; visited.add((expand[0], expand[1], expand[3])) for successor in problem.getSuccessors(expand): q.put((successor[2] + problem.heuristic(successor), (successor, directions+[(expand[0], expand[1])]))) print("Path Not Found!") return ([], -1) def smooth(path, problem): ''' takes a path found by jump point search and smooths it ''' if len(path) < 2: print('ERROR: Path must have at least 2 points for smoothing to work!') return None waypoints = [(path[0][0], path[0][1])] for i in range(len(path) - 1): x0, y0, x1, y1 = path[i][0], path[i][1], path[i + 1][0], path[i + 1][1] if x1 - x0 == 0: xdiff = 0 else: xdiff = int((x1 - x0) / abs(x1 - x0)) if y1 - y0 == 0: ydiff = 0 else: ydiff = int((y1 - y0) / abs(y1 - y0)) dirx = [1, -1, 0, 0] diry = [0, 0, 1, -1] while(x0 != x1): for j in range(4): if problem.obstacle(x0 + dirx[j], y0 + diry[j]) and problem.valid(x0 + dirx[j], y0 + diry[j]): if ((x0, y0) != waypoints[len(waypoints) - 1]): waypoints.append((x0, y0)) x0 += xdiff y0 += ydiff waypoints.append((path[len(path) - 1][0], path[len(path) - 1][1])) smoothedPoints = waypoints[:] for i in range(len(waypoints) - 2): x0, y0, x1, y1 = waypoints[i][0], waypoints[i][1], waypoints[i + 1][0], waypoints[i + 1][1] x2, y2 = waypoints[i + 2][0], waypoints[i + 2][1] if (y1 - y0) * (x2 - x1) == (x1 - x0) * (y2 - y1): smoothedPoints[i + 1] = None waypoints = [] prev, totalDistance = None, 0 for i in smoothedPoints: if i is not None: if prev is not None: totalDistance += dist(prev, i) prev = i waypoints.append(i) altitudePoints = [(waypoints[0][0], waypoints[0][1], problem.startAlt)] partialDistance = problem.startAlt for i in range(1, len(waypoints)): partialDistance += (problem.goalAlt - problem.startAlt) * dist(waypoints[i-1], waypoints[i]) / totalDistance altitudePoints.append((waypoints[i][0], waypoints[i][1], partialDistance)) print(altitudePoints) return altitudeSmooth(altitudePoints, problem) def dist(p1, p2): return math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])) def intersect(ellipse, point1, point2): ''' checks if a line between two points intersects an ellipse assumes we are uniformly increasing the altitude ''' h, k, a, b, altitude = ellipse x0, y0, altitude0 = point1 x1, y1, altitude1 = point2 m = (y1 - y0) / (x1 - x0) c = y0 - m * x0 epsilon = c - k delta = c + m * h discriminant = a*a + m*m + b*b - delta * delta - k * k + 2 * delta * k if discriminant < 0: return False xans0 = (h*b*b - m*a*a*epsilon + a*b*math.sqrt(discriminant)) / (a*a*m*m + b*b) xans1 = (h*b*b - m*a*a*epsilon - a*b*math.sqrt(discriminant)) / (a*a*m*m + b*b) yans0 = (xans0 - x0) * m + y0 yans1 = (xans1 - x0) * m + y0 ansCoords = [] if xans0 >= min(x0, x1) and xans0 <= max(x0, x1): ansCoords.append((xans0, yans0)) if xans1 >= min(x0, x1) and xans1 <= max(x0, x1): ansCoords.append((xans1, yans1)) if ansCoords == []: return False if altitude0 < altitude1: point = min(ansCoords, key = lambda p: dist(p, (x0, y0))) else: point = min(ansCoords, key = lambda p: dist(p, (x1, y1))) if (altitude1 - altitude0) / dist((x0, y0), (x1, y1)) * dist((x0, y0), point) + altitude0 <= altitude: return True return False def intersectLine(linePoint1, linePoint2, point1, point2): ''' determines if two line segements intersect ''' point1 = (point1[0], point1[1]) point2 = (point2[0], point2[1]) if linePoint1 == point1 or linePoint2 == point1 or linePoint1 == point2 or linePoint2 == point2: return False return ccw(linePoint1, point1, point2) != ccw(linePoint2, point1, point2) and ccw(linePoint1, linePoint2, point1) != ccw(linePoint1, linePoint2, point2) def ccw(point1, point2, point3): ''' determines if points are counter-clockwise ''' return (point3[1] - point1[1]) * (point2[0] - point1[0]) > (point2[1] - point1[1]) * (point3[0] - point1[0]) def altitudeSmooth(altitudePoints, problem): ''' shortens the path by not considering some obstacles that are not present at a specific altitude ''' smoothPoints = [altitudePoints[0]] i = 0 while (i < len(altitudePoints) - 1): ioriginal = i for j in range(len(altitudePoints) - 1, i, -1): #there is guaranteed to be a valid j that is greater than i, namely i + 1 valid = True for k in problem.obstacles: if intersect(k, altitudePoints[i], altitudePoints[j]): valid = False for k in range(len(problem.boundary)): if intersectLine(problem.boundary[k], problem.boundary[(k + 1) % len(problem.boundary)], altitudePoints[i], altitudePoints[j]): valid = False if valid: smoothPoints.append(altitudePoints[j]) i = j break; if i == ioriginal: print("Altitude Smoothing Failed!") j = i + 1 print(altitudePoints[i], altitudePoints[j]) for k in range(len(problem.boundary)): if intersectLine(problem.boundary[k], problem.boundary[(k + 1) % len(problem.boundary)], altitudePoints[i], altitudePoints[j]): print(problem.boundary[k], problem.boundary[(k + 1) % len(problem.boundary)]) return altitudePoints return smoothPoints
""" Task 1 String calculation: The method can take two numbers, separated by commas, and will return their sum. For example "1,2" would return 3. Task 2 The method can take up to two numbers, separated by commas, and will return their sum. For example "" or "1", where an empty string will return 0. """ import pytest from operators.add_string import add_string @pytest.mark.parametrize( "input_data, expected", [ ("3,5", 8), ("-2,4", 2), ("6,9", 15), ("3+1j,9", 12+1j), ("", 0), ("1", 1), pytest.param("3,5", 10, marks=pytest.mark.xfail( strict=True, reason='incorrect sum')), ]) def test_sum_numbers(input_data, expected): assert add_string(input_data) == expected
import random name = "구도" english_name = "Gu" # pyformat print("안녕하세요, {}입니다. My name is {}".format(name,english_name)) # f-string print(f"안녕하세요, {name}입니다. My name is {english_name}") numbers = list(range(1,46)) lotto = random.sample(numbers,6) print(f"오늘의 행운의 번호는 {sorted(lotto)} 입니다.")
print() print("//// Part 3: Perform Financial Calculations \\\\\\\\") """ Perform financial calculations using functions. 1. Define a new function that will be used to calculate present value. a. This function should include parameters for `future_value`, `remaining_months`, and the `annual_discount_rate` b. The function should return the `present_value` for the loan. 2. Use the function to calculate the present value of the new loan given below. a. Use an `annual_discount_rate` of 0.2 for this new loan calculation. """ # Given the following loan data, you will need to calculate the present value for the loan new_loan = { "loan_price": 800, "remaining_months": 12, "repayment_interval": "bullet", "future_value": 1000, } new_loan["annual_discount_rate"] = 0.2 # Add a key called 'annual_discount_rate' and assign it a value of 20 percent (or 0.2) # @TODO: Define a new function that will be used to calculate present value. # This function should include parameters for `future_value`, `remaining_months`, and the `annual_discount_rate` # The function should return the `present_value` for the loan. def calculate_present_value(remaining_months, future_value, annual_discount_rate): present_value = future_value / (1 + (annual_discount_rate / 12)) ** remaining_months return(present_value) present_value = calculate_present_value(new_loan["remaining_months"], new_loan["future_value"], new_loan["annual_discount_rate"]) # @TODO: Use the function to calculate the present value of the new loan given below. # Use an `annual_discount_rate` of 0.2 for this new loan calculation. print(f"The Present Value of this Loan is: ${present_value: .2f}") print()
import numpy as np # Define a main() function that transpose matrix and # create view array containing only 2nd and 4th row. def main(): arr = np.arange(1, 16).reshape(3, 5) arr_transpose = arr.T print(arr_transpose) second_and_forth_row_arr = arr_transpose[[1, 3], :] print(second_and_forth_row_arr) # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
import unittest from convert import CurrencyConverter class TestCurrencyConverterClass(unittest.TestCase): def test_get_current_rates(self): """Test get_current_rates()""" CurrencyConverter.get_current_rates() self.assertEqual(type(CurrencyConverter.current_rates), dict) #def test_currencies_available(self): #"""Test currencies_available()""" #test the print function # def test_get_currency_code(self): # """Test get_currency_code""" # CurrencyConverter.get_current_rates() # self.assertEqual(type(CurrencyConverter.get_currency_code()), str) def test_get_currency_rate(self): """Test get_currency_rates()""" CurrencyConverter.get_current_rates() self.assertEqual(type(CurrencyConverter.get_currency_rate("CAD")), float) self.assertEqual(type(CurrencyConverter.get_currency_rate("USD")), float) self.assertEqual(type(CurrencyConverter.get_currency_rate("GBP")), float) self.assertEqual(type(CurrencyConverter.get_currency_rate("AUD")), float) def test_convert(self): """Test convert""" self.assertEqual(len(CurrencyConverter.convert(self,1000,1.5,1.2)), 7) self.assertEqual(CurrencyConverter.convert(self,1000,1.5,1.2), "1250.00")
# !/usr/bin/env python # -- coding:utf-8 -- ''' 习题7-9 ''' def tr(srcstr, dststr, string,case=False): ''' 一个字符翻译程序 功能类似于 Unix 中的 tr 命令 ''' assert len(srcstr) == len(dststr) ,'srcstr length must be equal to dststr' # 替换字符串 arr = list(string) length = len(arr) if case: srcstr = srcstr.lower() for i in range(length): try: tmp = arr[i] if case: # 区分大小写 tmp = tmp.lower() j = srcstr.index(tmp) arr[i] = dststr[j] except: # 当字符不存在于 原来的字符串的时候 ,继续循环 continue return ''.join(arr) if __name__ == '__main__': print tr('12','23','1231231342') print tr('','','1231231342') print tr('123','1','1231231342') print tr('12','23','1231231342') print tr('Ab','cC','abdcd',True)
# -- coding: utf-8 -- # 对列表的解析 squared = [x ** 2 for x in range(4)] ''' print squared 结果: [0,1,4,9] ''' sqdEvens = [x ** 2 for x in range(8) if not x % 2] ''' print squared 结果: [0, 4, 16, 36] ''' print sqdEvens
'''@file character.py contains the character target normalizer''' def normalize(transcription, alphabet): '''normalize a transcription Args: transcription: the transcription to be normalized as a string Returns: the normalized transcription as a string space seperated per character''' #make the transcription lower case and put it into a list normalized = list(transcription.lower()) #replace the spaces with <space> normalized = [character if character != ' ' else '<space>' for character in normalized] #replace the end of line with <eol> #replace the spaces with <space> normalized = [character if character != '\n' else '<eol>' for character in normalized] #replace unknown characters with <unk> normalized = [character if character in alphabet else '<unk>' for character in normalized] return ' '.join(normalized)
#Python Text RPG# #The Dream Hero# #Imports# import os import sys import time import random import textwrap screen_width = 100 ## Player Setup ## class player: def __init__(self): self.name = '' self.location = 'b2' self.hp = 0 self.mp = 0 self.role = ' ' self.inventory = '' #self.stm = 0 #self.attack = 0 #self.defense = 0 #self.int = 0 #self.luck = 0 self.game_over = False myPlayer = player() ## Title Screen ## def title_screen_selections(): option = input("> ") if option.lower() == ("play"): start_game() elif option.lower() == ("help"): help_menu() elif option.lower() ==("home"): title_screen() elif option.lower() == ("quit"): sys.exit() while option.lower() not in ['play', 'help', 'quit']: print("Please enter a valid command.") option = input("> ") if option.lower() == ("play"): start_game() elif option.lower() ==("home"): title_screen() elif option.lower() == ("help"): help_menu() elif option.lower() == ("quit"): sys.exit() def title_screen(): os.system("cls") os.system("mode con cols=100 lines=11") title = "The Dream Hero".upper() welcome = "Welcome to '{}' a TextRPG!".format(title) print("#" * 100) print(title.center(100)) print("#" * 100) print("=" * 100) print(welcome.center(100)) print("=" * 100) print(("- Play -".upper()).center(100)) print(("- Help -".upper()).center(100)) print(("- Quit -".upper()).center(100)) print("lachance.n copyright2018".rjust(100)) title_screen_selections() ## Help Menu ## def help_menu(): os.system("cls") os.system("mode con cols=100 lines=8") welcome = "#Help Menu!#".upper() print("#" * 100) print(welcome.center(100)) print("#" * 100) print(("-Type the commands to perform them-".upper()).center(100)) print(("-Use 'up', 'down', 'left', 'right', to move around.-".upper()).center(100)) print(("-Use 'look' to inspect things-".upper()).center(100)) print(("-Type 'home' to go back-".upper()).center(100)) title_screen_selections() ## Game Over ## def game_over(): os.system("cls") os.system("mode con cols=100 lines=8") welcome = "#You beat the game!#".upper() print("#" * 100) print(welcome.center(100)) print("#" * 100) print(("-Congratulations!-".upper()).center(100)) print(("-You are now The Dream Hero!-".upper()).center(100)) print(("-I hope you enjoyed this basic game I made :)-".upper()).center(100)) print(("-Type 'home' to go play again-".upper()).center(100)) print("lachance.n copyright2018".rjust(100)) title_screen_selections() #Inventory INVENTORY = [] ITEMS = [] home_Item = "A note: 'A place where those seeking adventure depart from.' 'Just don't fall in.'" harbor_Item = "A note: 'Why would everyone leave without me?' 'I guess I will go for a walk in the woods..'" forest_Item = "A note: 'The sacred Volcano to the East might be the perfect place to be alone.'" volcano_Item = "A burnt note: 'This looks like a perfect spot to rest my head and think.'" ### MAP ### #|1|2|3|4|5|##Player starts at b2 #------------ #| | | | | |a #----------- #| | | | | |b #------------ #| | | | | |c #----------- #| | | | | |d #----------- ############ ZONENAME = '' DESCRIPTION = 'description' EXAMINATION = 'inspect' ITEM = 'pick up' SOLVED = False UP = 'up', 'north' DOWN = 'down','south' LEFT = 'left', 'west' RIGHT = 'right', 'east' #For Puzzles if I add them solved_places = {'a1': False, 'a2': False, 'a3': False, 'a4': False, 'a5': False, 'b1': False, 'b2': False, 'b3': False, 'b4': False, 'b5': False, 'c1': False, 'c2': False, 'c3': False, 'c4': False, 'c5': False, 'd1': False, 'd2': False, 'd3': False, 'd4': False, 'd5': False} #Actual Map# zonemap = { 'a1': { ZONENAME: "Town Market", DESCRIPTION: 'This is where the Town folk come to get their food.', EXAMINATION: 'The market seems to only have food.' ' All the merchants are gone.', SOLVED: False, ITEM: '', UP: '', DOWN: 'b1', LEFT: '', RIGHT: 'a2', }, 'a2': { ZONENAME: "Town Hall", DESCRIPTION: 'A place where Town decsions are made.', EXAMINATION: 'It seems to be unusually empty.\n' 'Where did everyone go?', SOLVED: False, ITEM: '', UP: '', DOWN: 'b2', LEFT: 'a1', RIGHT: 'a3', }, 'a3': { ZONENAME: "Town North Gate", DESCRIPTION: 'The Northern Entrance of the Town', EXAMINATION: 'There is no need to leave from this gate.\n' 'It leads to nothing.', SOLVED: False, ITEM: '', UP: '', DOWN: 'b3', LEFT: 'a2', RIGHT: 'a4', }, 'a4': { ZONENAME: "Town Pub", DESCRIPTION: 'A place to get some grub and an ale.', EXAMINATION: 'The Barkeep seems to be missing.', SOLVED: False, ITEM: '', UP: '', DOWN: 'b4', LEFT: 'a3', RIGHT: 'a5', }, 'a5': { ZONENAME: "Town Library", DESCRIPTION: 'Where the nerds hang out.', EXAMINATION: 'The librarian is missing.\n' 'The books still remain.\n' 'There seems to be a book left open.', SOLVED: False, ITEM: '', UP: '', DOWN: 'b5', LEFT: 'a4', RIGHT: '', }, 'b1': { ZONENAME: "Neighbor", DESCRIPTION: 'Your bestfriend lives here', EXAMINATION: 'Your friend seems to not be home right now.\n' 'A candle is burning, they may be close by.', SOLVED: False, ITEM: '', UP: 'a1', DOWN: 'c1', LEFT: '', RIGHT: 'b2', }, 'b2': { ZONENAME: 'Home', DESCRIPTION: 'This is your home.', EXAMINATION: 'Nothing has changed.', SOLVED: False, ITEM: home_Item, UP: 'a2', DOWN: 'c2', LEFT: 'b1', RIGHT: 'b3', }, 'b3': { ZONENAME: "Town South Gate", DESCRIPTION: 'The Southern Gate of the Town', EXAMINATION: 'This will be you to un-explored territories.', SOLVED: False, ITEM: '', UP: 'a3', DOWN: 'c3', LEFT: 'b2', RIGHT: 'b4', }, 'b4': { ZONENAME: "Town Square", DESCRIPTION: 'A gathering place for the Town Folk', EXAMINATION: 'It appears to be empty.\n' 'There are a few dogs walking around.\n' 'Maybe the dogs know where the Town Folk went.', SOLVED: False, ITEM: '', UP: 'a4', DOWN: 'c4', LEFT: 'b3', RIGHT: 'b5', }, 'b5': { ZONENAME: "Town Church", DESCRIPTION: 'A place of prayer.', EXAMINATION: 'There appears texted painted across the wall' "'The end is upon us...'\n" "'If only there was someone to save us.'", SOLVED: False, ITEM: '', UP: 'a5', DOWN: 'c5', LEFT: 'b4', RIGHT: '', }, 'c1': { ZONENAME: "Foggy Forest", DESCRIPTION: 'A creepy wooded area', EXAMINATION: 'This place seems like it might be important later.', SOLVED: False, ITEM: forest_Item, UP: 'b1', DOWN: 'd1', LEFT: '', RIGHT: 'c2', }, 'c2': { ZONENAME: "Soul Swamp", DESCRIPTION: 'The resting place of souls', EXAMINATION: 'The swamp appears to not have any souls in it.\n' 'This very unsual...', SOLVED: False, ITEM: '', UP: 'b2', DOWN: 'd2', LEFT: 'c1', RIGHT: 'c3', }, 'c3': { ZONENAME: "Grassy Field", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'b3', DOWN: 'd3', LEFT: 'c2', RIGHT: 'c4', }, 'c4': { ZONENAME: "Dry Desert", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'b4', DOWN: 'd4', LEFT: 'c3', RIGHT: 'c5', }, 'c5': { ZONENAME: "Hot Volcano", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: volcano_Item, UP: 'b5', DOWN: 'd5', LEFT: 'c4', RIGHT: '', }, 'd1': { ZONENAME: "Light House", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'c1', DOWN: '', LEFT: '', RIGHT: 'd2', }, 'd2': { ZONENAME: "Broken Bridge", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'c2', DOWN: '', LEFT: 'd1', RIGHT: 'd3', }, 'd3': { ZONENAME: "Rocky Beach", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'c3', DOWN: '', LEFT: 'd2', RIGHT: 'd4', }, 'd4': { ZONENAME: "Harbor", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: harbor_Item, UP: 'c4', DOWN: '', LEFT: 'd3', RIGHT: 'd5', }, 'd5': { ZONENAME: "Tall Cliff", DESCRIPTION: 'description', EXAMINATION: 'inspect', SOLVED: False, ITEM: '', UP: 'c5', DOWN: '', LEFT: 'd4', RIGHT: '', } } ## Game Interactivity ## def print_map(): os.system("cls") os.system("mode con cols=100 lines=20") print("\n") print(" ### MAP! ### ".center(100)) print("#|1|2|3|4|5|##".center(100)) print("#------------#".center(100)) print("#| | | | | |a#".center(100)) print("#------------#".center(100)) print("#| | | | | |b#".center(100)) print("#------------#".center(100)) print("#| | | | | |c#".center(100)) print("#------------#".center(100)) print("#| | | | | |d#".center(100)) print("#------------#".center(100)) print("##############".center(100)) print("\n") def print_character_inventory(): class_stats1 = "Warrior: HP=150, MP=50\n" class_stats2 = "Mage: HP=50, MP=150\n" class_stats3 = "Paladin: HP=75, MP=75\n" os.system("cls") os.system("mode con cols=100 lines=20") print("=" * 100) if myPlayer.role == 'warrior': for character in class_stats1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) elif myPlayer.role == 'mage': for character in class_stats2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) elif myPlayer.role == 'paladin': for character in class_stats2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) print("Inventory: \n") if home_Item in INVENTORY: print("\n".join(str(x) for x in INVENTORY)) elif INVENTORY == []: print("You have no items in your inventory.") print("=" * 100) time.sleep(.5) print("Type 'exit' to leave your inventory\n") exit = input("> ") if exit == 'exit': os.system("cls") os.system("mode con cols=100 lines=20") while exit != 'exit': print("That wasn't 'exit'") print("Type 'exit' to leave your inventory\n") exit = input("> ") if exit == 'exit': os.system("cls") os.system("mode con cols=100 lines=10") def print_location(): location = zonemap[myPlayer.location][ZONENAME] print('\n' + ("#" * (4 + len(location)))) print("# " + str(location) + " #") print("# " + zonemap[myPlayer.location][DESCRIPTION] + " #") print("# " + myPlayer.location + " #") print("#" * (4 + len(location))) def print_character_stats(): class_stats1 = "Warrior: HP=150, MP=50\n" class_stats2 = "Mage: HP=50, MP=150\n" class_stats3 = "Paladin: HP=75, MP=75\n" class_def1 = "The Warrior is battle hardened and always ready for blood\n" class_def2 = "The Mage has seen many conflicts, but approaches with an intellectual strategy.\n" class_def3 = "The Paladin is a protector of many, and will let noting stand in his way in being such.\n" print("-" * 100) for character in class_stats1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) for character in class_stats2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) for character in class_stats3: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.03) for character in class_def1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.06) for character in class_def2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.06) for character in class_def3: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.06) print("-" * 100) def prompt(): acceptable_actions = ['move', 'go', 'walk', 'quit', 'examine', 'inspect', 'search', 'look', 'location', 'title', 'home', 'map', 'inventory', 'bag', 'self', 'pick up', 'item'] print("\n" + "=" * 100) print("What would you like to do?") print("Type 'options' for what you can do.") action = input("> ") if action.lower() == 'options': print(acceptable_actions) action = input("> ") while action.lower() not in acceptable_actions and not 'options': print("Unknown action, try again.\n") action = input("> ") if action.lower() == 'quit': sys.exit() elif action.lower() in acceptable_actions[:2]: player_move(action.lower()) elif action.lower() in acceptable_actions[4:7]: player_examine(action.lower()) elif action.lower() in acceptable_actions[8]: print_location() elif action.lower() in acceptable_actions[9:10]: title_screen_selections() elif action.lower() in acceptable_actions[11]: print_map() elif action.lower() in acceptable_actions[12:14]: print_character_inventory() elif action.lower() in acceptable_actions[15:16]: item_pick_up() def player_move(myAction): ask = "Where would you like to move to?\n" dest = input(ask) if dest.lower() in ['up', 'north']: destination = zonemap[myPlayer.location][UP] if destination == '': print("I am sorry, but you cannot go that way.") dest = input(ask) else: movement_handler(destination) elif dest.lower() in ['down', 'south']: destination = zonemap[myPlayer.location][DOWN] if destination == '': print("I am sorry, but you cannot go that way.") dest = input(ask) else: movement_handler(destination) elif dest.lower() in ['right', 'east']: destination = zonemap[myPlayer.location][RIGHT] if destination == '': print("I am sorry, but you cannot go that way.") dest = input(ask) else: movement_handler(destination) elif dest.lower() in ['left', 'west']: destination = zonemap[myPlayer.location][LEFT] if destination == '': print("I am sorry, but you cannot go that way.") dest = input(ask) else: movement_handler(destination) def movement_handler(destination): print("\n" + "you've arrived at the, {}.".format(destination)) myPlayer.location = destination print_location() def player_examine(action): examination = zonemap[myPlayer.location][EXAMINATION] if zonemap[myPlayer.location][SOLVED]: print("You have already exhausted this zone") else: print('\n' + ("#" * (4 + len(examination)))) print(zonemap[myPlayer.location][EXAMINATION]) print("#" * (4 + len(examination))) def item_pick_up(): item = zonemap[myPlayer.location][ITEM] if item != '': INVENTORY.append(item) myPlayer.inventory = INVENTORY print('\n' + ("#" * (4 + len(item)))) print(zonemap[myPlayer.location][ITEM]) print("#" * (4 + len(item))) else: print("There does not appear to be an item here.") #Game functionality# def start_game(): character_create() intro() welcome_home() while myPlayer.game_over is False: prompt() if home_Item and harbor_Item and forest_Item and volcano_Item in INVENTORY: myPlayer.game_over = True time.sleep(2) os.system("cls") os.system("mode con cols=100 lines=5") print("It was all just a dream..") time.sleep(2) game_over() def character_create(): self = myPlayer warriorStatement1 = 'A warrior huh? I guess it is true what they say, you do enjoy killing.\n' warriorStatement2 = 'I guess in a time like now that is a good thing.\n' mageStatement1 = 'I should have expected you to train to be a mage.\n' mageStatement2 = 'The role that intellect plays in your life has always been obvious.\n' paladinStatement1 = 'A mix between battle ready and intellect?\n' paladinStatement2 = 'This does seem like the perfect mix for you.\n' valid_class = ["warrior", "mage", "paladin"] os.system("mode con cols=100 lines=20") os.system('cls') #What is your name question1 = "Tell me?\n" question1added = "What is your name?\n" for character in question1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in question1added: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.04) player_name = input("> ") myPlayer.name = player_name statement1 = 'I am glad you still remember who you are.' #Assign class question2 = "Forgive me {},\nWhat class did you train to become during your time away?\n".format(myPlayer.name) question2added = "(You can choose 'warrior', 'mage', 'paladin')\n" for character in question2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in question2added: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.01) print_character_stats() player_role = input("> ") if player_role.lower() in valid_class: myPlayer.role = player_role.lower() while player_role.lower() not in valid_class: player_role = input("> ") if player_role in valid_class: myPlayer.role = player_role.lower() #Class Stats if myPlayer.role == 'warrior': for character in warriorStatement1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in warriorStatement2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) time.sleep(1.0) self.hp = 150 self.mp = 50 elif myPlayer.role == 'mage': for character in mageStatement1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in mageStatement2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) time.sleep(1.0) self.hp = 50 self.mp = 150 elif myPlayer.role == 'paladin': for character in paladinStatement1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in paladinStatement2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) time.sleep(1.0) self.hp = 75 self.mp = 75 def welcome_home(): os.system('cls') os.system("mode con cols=100 lines=7") statement1 = "Welcome back home, {} the {}.\n".format(myPlayer.name, myPlayer.role) statement2 = 'Hopefully your time away from The Town has served you well.\n' for character in statement1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in statement2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.07) speech1 = "You haven't changed a bit.\n" speech2 = "I know it has been quite sometime..\n" speech3 = "Hopefully you remember your way...\n" for character in speech1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in speech2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in speech3: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.06) speech4 = "Good luck {}, this place needs you now more than ever.".format(myPlayer.name) for character in speech4: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.06) time.sleep(0.85) os.system("mode con cols=100 lines=20") os.system('cls') print("#" * 100) print("You awaken in your bed.".center(100)) print("It was all just a dream.".center(100)) print("#" * 100) def intro(): #Intro to the universe os.system('cls') os.system("mode con cols=100 lines=10") lore1 = 'The Town was once a lively place and home to many.\n' lore2 = 'Now there seems to have been something that caused eveyone to disappear.\n' lore3 = 'The Town is a nexus and has always been such.\n' lore4 = 'It is possible that something wanted to dismantle the uptopia.\n' lore5 = 'It is your destiny {} to save The Town, your home.\n'.format(myPlayer.name) lore6 = 'There is no need to worry {} this is why you trained to be a {}'.format(myPlayer.name, myPlayer.role) for character in lore1: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in lore2: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in lore3: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in lore4: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) for character in lore5: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) time.sleep(.8) for character in lore6: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.08) time.sleep(1.2) #Start Game title_screen()